contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
sequencelengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1288
E
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4 3 5 1 4 OutputCopy1 3 2 5 1 4 1 5 1 5 InputCopy4 3 1 2 4 OutputCopy1 3 1 2 3 4 1 4 NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3]
[ "data structures" ]
// LUOGU_RID: 102287254 // #pragma GCC optimize("O3,unroll-loops") // #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #include <bits/stdc++.h> #include <ext/rope> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/hash_policy.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/trie_policy.hpp> #include <ext/pb_ds/priority_queue.hpp> using namespace std; using namespace __gnu_cxx; using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>; using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>; // template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>; template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>; #define ll long long #define i128 ll #define ld long double #define ui unsigned int #define ull unsigned long long #define pii pair<int, int> #define pll pair<ll, ll> #define pdd pair<ld, ld> #define vi vector<int> #define vvi vector<vector<int>> #define vll vector<ll> #define vvll vector<vector<ll>> #define vpii vector<pii> #define vpll vector<pll> #define lb lower_bound #define ub upper_bound #define pb push_back #define pf push_front #define eb emplace_back #define fi first #define se second #define rep(i, a, b) for(int i = a; i < b; ++i) #define per(i, a, b) for(int i = a; i > b; --i) #define each(x, v) for(auto& x: v) #define len(x) (int)x.size() #define elif else if #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define mst(x, a) memset(x, a, sizeof(x)) #define lowbit(x) (x & (-x)) #define bitcnt(x) (__builtin_popcountll(x)) #define endl "\n" mt19937 rng( chrono::steady_clock::now().time_since_epoch().count() ); #define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a) struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } size_t operator()(pair<uint64_t,uint64_t> x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1); } }; const i128 ONE = 1; istream &operator>>(istream &in, i128 &x) { string s; in >> s; bool minus = false; if (s[0] == '-') { minus = true; s.erase(s.begin()); } x = 0; for (auto i : s) { x *= 10; x += i - '0'; } if (minus) x = -x; return in; } ostream &operator<<(ostream &out, i128 x) { string s; bool minus = false; if (x < 0) { minus = true; x = -x; } while (x) { s.push_back(x % 10 + '0'); x /= 10; } if (s.empty()) s = "0"; if (minus) out << '-'; reverse(s.begin(), s.end()); out << s; return out; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const set<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) { os << p.first << " " << p.second; return os; } ll gcd(ll x,ll y) { if(!x) return y; if(!y) return x; int t = __builtin_ctzll(x | y); x >>= __builtin_ctzll(x); do { y >>= __builtin_ctzll(y); if(x > y) swap(x, y); y -= x; } while(y); return x<<t; } ll lcm(ll x, ll y) { return x * y / gcd(x, y); } ll exgcd(ll a, ll b, ll &x, ll &y) { if(!b) return x = 1, y = 0, a; ll d = exgcd(b, a % b, x, y); ll t = x; x = y; y = t - a / b * x; return d; } ll max(ll x, ll y) { return x > y ? x : y; } ll min(ll x, ll y) { return x < y ? x : y; } ll Mod(ll x, int mod) { return (x % mod + mod) % mod; } ll pow(ll x, ll y, ll mod){ ll res = 1, cur = x; while (y) { if (y & 1) res = res * cur % mod; cur = ONE * cur * cur % mod; y >>= 1; } return res % mod; } ll probabilityMod(ll x, ll y, ll mod) { return x * pow(y, mod-2, mod) % mod; } vvi getGraph(int n, int m, bool directed = false) { vvi res(n); rep(_, 0, m) { int u, v; cin >> u >> v; u--, v--; res[u].emplace_back(v); if(!directed) res[v].emplace_back(u); } return res; } vector<vpii> getWeightedGraph(int n, int m, bool directed = false) { vector<vpii> res(n); rep(_, 0, m) { int u, v, w; cin >> u >> v >> w; u--, v--; res[u].emplace_back(v, w); if(!directed) res[v].emplace_back(u, w); } return res; } const ll LINF = 0x1fffffffffffffff; const ll MINF = 0x7fffffffffff; const int INF = 0x3fffffff; const int MOD = 1000000007; const int MODD = 998244353; const int N = 1e6 + 10; class SegmentTree { public: struct STNode { STNode () : left(nullptr), right(nullptr), val(0), maxval(0), minval(0), lazy(0), mlazy(LINF) {} STNode* left; STNode* right; ll val; ll maxval; ll minval; ll lazy; ll mlazy; }; STNode* root; SegmentTree() { root = new STNode(); } ~SegmentTree() {} void assign(STNode* node, int l, int r, int start, int end, ll x) { if (l == start && r == end) { node->val = 0; node->maxval = 0; node->minval = 0; node->lazy = 0; node->mlazy = x; return; } pushdown(node); int mid = l+r>>1; if (end <= mid) { assign(node->left, l, mid, start, end, x); } elif (start > mid) { assign(node->right, mid+1, r, start, end, x); } else { assign(node->left, l, mid, start, mid , x); assign(node->right, mid+1, r, mid+1, end, x); } pushup(node, mid-l+1, r-mid); } void add(STNode* node, int l, int r, int start, int end, ll x){ if (l == start && r == end) { node->lazy += x; return; } pushdown(node); int mid = l+r>>1; if (end <= mid) { add(node->left, l, mid, start, end, x); } elif (start > mid) { add(node->right, mid+1, r, start, end, x); } else { add(node->left, l, mid, start, mid , x); add(node->right, mid+1, r, mid+1, end, x); } pushup(node, mid-l+1, r-mid); } ll querySum(STNode* node, int l, int r, int start, int end) { if (l == start && r == end) { return node->val + node->lazy * (r-l+1) + \ (node->mlazy == LINF ? 0 : node->mlazy * (r-l+1)); } pushdown(node); int mid = l+r>>1; ll res; if (end <= mid) { res = querySum(node->left, l, mid, start, end); } elif (start > mid) { res = querySum(node->right, mid+1, r, start, end); } else { res = querySum(node->left, l, mid, start, mid) + querySum(node->right, mid+1, r, mid+1, end); } pushup(node, mid-l+1, r-mid); return res; } ll queryMax(STNode* node, int l, int r, int start, int end) { if (l == start && r == end) { return node->maxval + node->lazy + \ (node->mlazy == LINF ? 0 : node->mlazy); } pushdown(node); int mid = l+r>>1; ll res; if (end <= mid) { res = queryMax(node->left, l, mid, start, end); } elif (start > mid) { res = queryMax(node->right, mid+1, r, start, end); } else { res = max(queryMax(node->left, l, mid, start, mid), queryMax(node->right, mid+1, r, mid+1, end)); } pushup(node, mid-l+1, r-mid); return res; } ll queryMin(STNode* node, int l, int r, int start, int end) { if (l == start && r == end) { return node->minval + node->lazy + \ (node->mlazy == LINF ? 0 : node->mlazy); } pushdown(node); int mid = l+r>>1; ll res; if (end <= mid) { res = queryMin(node->left, l, mid, start, end); } elif (start > mid) { res = queryMin(node->right, mid+1, r, start, end); } else { res = min(queryMin(node->left, l, mid, start, mid), queryMin(node->right, mid+1, r, mid+1, end)); } pushup(node, mid-l+1, r-mid); return res; } void pushdown(STNode* node) { if (node->left == nullptr) { node->left = new STNode(); } if (node->right == nullptr) { node->right = new STNode(); } if (node->mlazy != LINF) { node->left->lazy = 0; node->left->val = 0; node->left->maxval = 0; node->left->minval = 0; node->right->lazy = 0; node->right->val = 0; node->right->maxval = 0; node->right->minval = 0; node->left->mlazy = node->mlazy; node->right->mlazy = node->mlazy; node->mlazy = LINF; } if (node->lazy) { node->left->lazy += node->lazy; node->right->lazy += node->lazy; node->lazy = 0; } } void pushup(STNode* node, int ln, int rn) { node->val = node->left->val + node->left->lazy * ln + \ (node->left->mlazy == LINF ? 0 : node->left->mlazy * ln) + \ node->right->val + node->right->lazy * rn + \ (node->right->mlazy == LINF ? 0 : node->right->mlazy * rn); node->maxval = max(node->left->maxval + node->left->lazy + \ (node->left->mlazy == LINF ? 0 : node->left->mlazy), node->right->maxval + node->right->lazy + \ (node->right->mlazy == LINF ? 0 : node->right->mlazy)); node->minval = min(node->left->minval + node->left->lazy + \ (node->left->mlazy == LINF ? 0 : node->left->mlazy), node->right->minval + node->right->lazy + \ (node->right->mlazy == LINF ? 0 : node->right->mlazy)); } }; void solve() { int n, m; cin >> n >> m; vi a(m); each(i, a) cin >> i; vi pos(n+1); vi mn(n+1); vi mx(n+1); rep(i, 1, n+1) mn[i] = mx[i] = i, pos[i] = i + m; SegmentTree st; rep(i, 1, n+1) st.add(st.root, -1, N, pos[i], pos[i], 1); int cur = m; each(i, a) { mn[i] = 1; mx[i] = max(mx[i], st.querySum(st.root, -1, N, 0, pos[i])); st.add(st.root, -1, N, pos[i], pos[i], -1); pos[i] = cur--; st.add(st.root, -1, N, pos[i], pos[i], 1); } rep(i, 1, n+1) { mx[i] = max(mx[i], st.querySum(st.root, -1, N, 0, pos[i])); cout << mn[i] << " " << mx[i] << endl; } } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; // cin >> t; while (t--) { solve(); } return 0; }
cpp
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
[ "constructive algorithms", "math", "ternary search" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define all(v) ((v).begin()), ((v).end()) #define siz(v) ((int)((v).size())) #define clr(v, d) memset(v, d, sizeof(v)) #define rep(i, v) for (int i = 0; i < siz(v); ++i) #define fo(i, n) for (int i = 0; i < (int)(n); ++i) #define fp(i, j, n) for (long long i = (j); i <= (long long)(n); ++i) #define fn(i, j, n) for (int i = (j); i >= (int)(n); --i) #define fvec(i, vec) for (auto i : vec) #define pb push_back #define MP make_pair #define mine(x, y, z) min(x, min(y, z)) #define maxe(x, y, z) max(x, max(y, z)) #define F first #define S second typedef unsigned long long ull; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef pair<ll,ll> pll; typedef pair<int,int> pi; typedef vector<pll> vp; typedef vector< long long> vll; typedef vector<double> vd; typedef vector<vi> vvi; typedef vector<vd> vvd; typedef vector<string> vs; typedef tree< ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; #define setp(item) cout<<fixed<<setprecision(item); ll gcd(ll a, ll b) { return ((b == 0) ? a : gcd(b, a % b)); } ll lcm(ll a,ll b){return (a*b)/gcd(a,b);} const ll OO = 1e18, mod = 1e9+7,mod2=1e9+9, N =1e6+5,M=30,MOD=998244353; void solve(int inde) { ll n,m,p;cin>>n>>m>>p; vll a(n),b(m); ll st=0,en=0; fo(i,n){ cin>>a[i]; if(a[i]%p!=0)st=i; } fo(i,m){ cin>>b[i]; if(b[i]%p!=0)en=i; } // vll res(n+m-1); // fo(i,n){ // fo(j,m){ // res[i+j]+=a[i]*b[j]; // } // } // // fvec(item,res)cout<<item<<" "; cout<<en+st<<'\n'; } int main() { //freopen("input.txt","rt",stdin); //freopen("output.txt","wt",stdout); ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); ll t=1; // cin>>t; ll index=1; while (t--){ solve(index++); } return 0; }
cpp
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3 1 3 2 -100 2 3 OutputCopy3 InputCopy5 2 1 4 3 5 2 2 2 3 4 OutputCopy19 InputCopy2 2 1 -3 0 OutputCopy0
[ "data structures", "divide and conquer", "implementation", "sortings" ]
#include<bits/stdc++.h> using namespace std; long long n,a[200005],ans; pair<long long,long long>q[200005]; int main() { cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) { long long x; cin>>x; q[i]=make_pair(x,a[i]); } sort(a+1,a+n+1); sort(q+1,q+n+1); for(int i=1;i<=n;i++) ans+=(lower_bound(a+1,a+n+1,q[i].second)-a-n+i-1)*q[i].second; cout<<ans; }
cpp
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve(){ int n, m, k; // n is elements, m is place in line, k is number of people to control cin >> n >> m >> k; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; if (k >= (m - 1)){ int ans = 0; for (int i = 0; i < m; i++){ ans = max(ans, a[i]); ans = max(ans, a[n - 1 - i]); } cout << ans << '\n'; return; } int lp = k; int rp = n - 1; int invols = m - k - 1; int best = 0; int cb = INT_MAX; vector<int> sols; sols.clear(); for (int i = 0; i <= k; i++){ best = 0; cb = INT_MAX; for (int j = 0; j <= invols; j++){ best = max(a[lp + j], a[rp - (invols - j)]); cb = min(cb, best); } lp--; rp--; sols.push_back(cb); } cout << *max_element(begin(sols), end(sols)) << '\n'; } int main(){ ios::sync_with_stdio(0); cin.tie(0); ll t = 1; cin >> t; while (t--) solve(); return 0; }
cpp
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
#include <bits/stdc++.h> #define range(i,n) for(int i= 0; i < (n); i++) typedef long long int ll; #define arr(a,n) for(int i=0;i<(n);i++) cin>>a[i]; #define pb push_back #define mp make_pair #define F first #define S second #define all(x) x.begin(), x.end() #define int ll #define in insert #define endl '\n' using namespace std; signed main() { ios::sync_with_stdio(false); cin.tie(0); int testcase=1; cin>>testcase; for(int test=0;test<testcase;test++) { int n; cin>>n; int a[n]; arr(a,n); vector<int>b((2*n)+1,-1); vector<int>ans(2*n); queue<int> q; range(i,n){ ans[2*i]=a[i]; b[a[i]]=i; } int flag=0; for(int i=2*n;i>0;i--){ if(b[i]==-1){ q.push(i); } else{ if(q.empty()){ // cout<<-1; flag=1; break; } ans[2*b[i]+1]=q.front(); q.pop(); } } if(flag) cout<<-1; else{ for(int i=1;i<2*n;i+=2){ for(int j=i+2;j<2*n;j+=2){ if(ans[i]>ans[j] && ans[j]>ans[i-1] && ans[j-1]<ans[i]){ swap(ans[i],ans[j]); } } } range(i,2*n) cout<<ans[i]<<" "; } cout<<endl; } return 0; }
cpp
1288
F
F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15 RRB UB 3 2 2 2 1 2 1 1 2 1 1 1 OutputCopy35 BUURRU InputCopy3 1 3 4 5 RRR B 2 1 1 1 3 1 OutputCopy-1 InputCopy3 1 3 4 5 URU B 2 1 1 1 3 1 OutputCopy14 RBB
[ "constructive algorithms", "flows" ]
#include<bits/stdc++.h> using namespace std; const int N = 443; int n1, n2, m, r, b; string s1, s2; int u[N]; int v[N]; struct edge { int y, c, f, cost; edge() {}; edge(int y, int c, int f, int cost) : y(y), c(c), f(f), cost(cost) {}; }; int bal[N][N]; int s, t, oldS, oldT, V; vector<int> g[N]; vector<edge> e; void add(int x, int y, int c, int cost) { g[x].push_back(e.size()); e.push_back(edge(y, c, 0, cost)); g[y].push_back(e.size()); e.push_back(edge(x, 0, 0, -cost)); } int rem(int num) { return e[num].c - e[num].f; } void add_LR(int x, int y, int l, int r, int cost) { int c = r - l; if(l > 0) { add(s, y, l, cost); add(x, t, l, cost); } if(c > 0) { add(x, y, c, cost); } } int p[N]; int d[N]; int pe[N]; int inq[N]; bool enlarge() { for(int i = 0; i < V; i++) { d[i] = int(1e9); p[i] = -1; pe[i] = -1; inq[i] = 0; } d[s] = 0; queue<int> q; q.push(s); inq[s] = 1; while(!q.empty()) { int k = q.front(); q.pop(); inq[k] = 0; for(auto z : g[k]) { if(!rem(z)) continue; if(d[e[z].y] > d[k] + e[z].cost) { p[e[z].y] = k; pe[e[z].y] = z; d[e[z].y] = d[k] + e[z].cost; if(!inq[e[z].y]) { q.push(e[z].y); inq[e[z].y] = 1; } } } } if(p[t] == -1) return false; int cur = t; while(cur != s) { e[pe[cur]].f++; e[pe[cur] ^ 1].f--; cur = p[cur]; } return true; } void add_edge(int x, int y) { add(x, y + n1, 1, r); add(y + n1, x, 1, b); } void impose_left(int x) { if(s1[x] == 'R') { add_LR(oldS, x, 1, m, 0); } else if(s1[x] == 'B') { add_LR(x, oldT, 1, m, 0); } else { add(oldS, x, m, 0); add(x, oldT, m, 0); } } void impose_right(int x) { if(s2[x] == 'R') { add_LR(x + n1, oldT, 1, m, 0); } else if(s2[x] == 'B') { add_LR(oldS, x + n1, 1, m, 0); } else { add(oldS, x + n1, m, 0); add(x + n1, oldT, m, 0); } } void construct_bal() { for(int i = 0; i < n1; i++) { for(auto z : g[i]) { if(e[z].y >= n1 && e[z].y < n1 + n2) bal[i][e[z].y - n1] += e[z].f; } } } void find_ans() { int res = 0; string w = ""; for(auto x : g[s]) if(rem(x)) { cout << -1 << endl; return; } for(int i = 0; i < m; i++) { if(bal[u[i]][v[i]] > 0) { bal[u[i]][v[i]]--; res += r; w += "R"; } else if(bal[u[i]][v[i]] < 0) { bal[u[i]][v[i]]++; res += b; w += "B"; } else w += "U"; } cout << res << endl << w << endl; } int main() { cin >> n1 >> n2 >> m >> r >> b; cin >> s1; cin >> s2; for(int i = 0; i < m; i++) { cin >> u[i] >> v[i]; u[i]--; v[i]--; } oldS = n1 + n2; oldT = oldS + 1; s = oldT + 1; t = s + 1; V = t + 1; for(int i = 0; i < n1; i++) impose_left(i); for(int i = 0; i < n2; i++) impose_right(i); for(int i = 0; i < m; i++) add_edge(u[i], v[i]); add(oldT, oldS, 100000, 0); while(enlarge()); construct_bal(); find_ans(); }
cpp
1295
F
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3 1 2 1 2 1 2 OutputCopy499122177 InputCopy2 42 1337 13 420 OutputCopy578894053 InputCopy2 1 1 0 0 OutputCopy1 InputCopy2 1 1 1 1 OutputCopy1 NoteThe real answer in the first test is 1212.
[ "combinatorics", "dp", "probabilities" ]
//#pragma GCC optimize("Ofast", "unroll-loops") //#pragma GCC target("sse", "sse2", "sse3", "ssse3", "sse4", "avx") #include <bits/stdc++.h> #define int long long #define ll long long #define ull unsigned long long #define clr(f, n) memset(f, 0, sizeof(int) * (n)) #define cpy(f, g, n) memcpy(f, g, sizeof(int) * (n)) #define rev(f, n) reverse(f, f + n) #define YES puts("YES") #define NO puts("NO") #define Yes puts("Yes") #define No puts("No") #define edl puts("") #define mc cerr<<"qwq\n" #define error goto gg #define def gg: #define rd(x) x=read() #define opl(x) printf("%lld",x) #define opls(x) printf("%lld ",x) #define opd(x) printf("%d",x) #define opds(x) printf("%d ",x) #define ver(x) for(int i=head[x];i;i=nxt[i]) #define up(i,x,y) for(int i=x,i##end=y;i<=i##end;++i) #define pu(i,x,y) for(int i=x,i##end=y;i>=i##end;--i) #define ft(x) for(int i=head[x];i;i=nxt[i]) #define upn up(i,1,n) #define upm up(j,1,m) #define pun pu(i,n,1) #define pum pu(j,m,1) #define up_(x) up(i,1,x) #define pu_(x) pu(j,x,1) #define ep emplace_back #define fp for(auto to: #define pf ) #define pii pair<int,int> #define pis pair<int,string> #define psi pair<string,int> #define mkp make_pair #define fi first #define se second #define mii map<int,int> #define mis map<int,string> #define msi map<string,int> #define mvi map<vector<int>,int> #define miv map<int,vector<int>> #define rdn rd(n) #define rdm rd(m) #define rdk rd(k) #define pb push_back #define edge1 int head[maxn],to[maxn<<1],nxt[maxn<<1],tot;\ void add(int a,int b)\ {\ to[++tot]=b;nxt[tot]=head[a];head[a]=tot;\ } #define edge2 int head[maxn],to[maxn<<1],nxt[maxn<<1],tot,w[maxn<<1];\ void add(int a,int b,int c)\ {\ to[++tot]=b;nxt[tot]=head[a];head[a]=tot;w[tot]=c;\ } #define Mod998 const int mod=998244353;\ int qpow(int a,int b=mod-2)\ {\ int ans=1;\ while(b)\ {\ if(b&1)ans=1ll*ans*a%mod;\ a=1ll*a*a%mod;\ b>>=1;\ }\ return ans;\ }\ void Add(int &a,int b)\ {\ a+=b;if(a>=mod)a-=mod;\ }\ void Sub(int &a,int b)\ {\ a-=b;if(a<0)a+=mod;\ }\ int Mul(int a,int b)\ {\ return 1ll*a*b%mod;\ }\ int Frac(int a,int b)\ {\ return 1ll*a*qpow(b)%mod;\ } #define Mod1e9 const int mod=1e9+7;\ int qpow(int a,int b=mod-2)\ {\ int ans=1;\ while(b)\ {\ if(b&1)ans=1ll*ans*a%mod;\ a=1ll*a*a%mod;\ b>>=1;\ }\ return ans;\ }\ void Add(int &a,int b)\ {\ a+=b;if(a>=mod)a-=mod;\ }\ void Sub(int &a,int b)\ {\ a-=b;if(a<0)a+=mod;\ }\ int Mul(int a,int b)\ {\ return 1ll*a*b%mod;\ }\ int Frac(int a,int b)\ {\ return 1ll*a*qpow(b)%mod;\ } #define DSU int fa[maxn];\ int find(int x)\ {\ return fa[x]==x?fa[x]:fa[x]=find(fa[x]);\ }\ void merge(int x,int y)\ {\ int fx=find(x),fy=find(y);\ if(fx==fy)return;\ fa[fx]=fy;\ }\ void S(int x)\ {\ up(i,1,x)fa[i]=i;\ } using namespace std; int n, m, k; int read() { int s = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { s = s * 10 + ch - '0'; ch = getchar(); } return s * f; } void print(int x) { if(x<0)putchar('-'),x=-x; if(x>9)print(x/10); putchar(x%10+'0'); } #define inf 1000000000000000000ll ll Max(ll a=-inf,ll b=-inf,ll c=-inf,ll d=-inf,ll e=-inf,ll f=-inf,ll g=-inf,ll h=-inf) { return max(max(max(a,b),max(c,d)),max(max(e,f),max(g,h))); } ll Min(ll a=inf,ll b=inf,ll c=inf,ll d=inf,ll e=inf,ll f=inf,ll g=inf,ll h=inf) { return min(min(min(a,b),min(c,d)),min(min(e,f),min(g,h))); } #undef inf void chkmin(int &x,int y) { if(x>y)x=y; } void chkmax(int &x,int y) { if(x<y)x=y; } /* #define ls ((x<<1)) #define rs ((x<<1)|1) #define mid ((l+r)>>1) void pushup(int x) { //do sth } void build(int x,int l,int r) { if(l==r) { //do sth return; } build(ls,l,mid);build(rs,mid+1,r); pushup(x); } void update(int x,int l,int r,int ql,int qr) { if(ql<=l&&r<=qr) { //do sth return; } if(ql<=mid)update(ls,l,mid,ql,qr); if(mid<qr)update(rs,mid+1,r,ql,qr); pushup(x); } void query(int x,int l,int r,int ql,int qr) { if(ql<=l&&r<=qr) { //do sth return; } if(ql<=mid) { query(ls,l,mid,ql,qr); } if(mid<qr) { query(rs,mid+1,r,ql,qr); } return; } */ int l[55],r[55]; int v[2020]; Mod998; const int maxn=50001; int C(int m,int n) { int p=1,q=1; upn { p*=(m-i+1);p%=mod; q*=(n-i+1);q%=mod; } return p*qpow(q)%mod; } int dp[55]; signed main() { int T=1; while(T--) { rdn; upn rd(l[i]),rd(r[i]),r[i]++; upn v[++m]=l[i],v[++m]=r[i]; sort(v+1,v+m+1);int q=unique(v+1,v+m+1)-v-1; m=q; upn { l[i]=lower_bound(v+1,v+m+1,l[i])-v; r[i]=lower_bound(v+1,v+m+1,r[i])-v; } dp[0]=1; pu(i,m-1,0) { int len=v[i+1]-v[i]; pu(j,n,1) { // cout<<i<<" "<<l[j]<<" "<<r[j];edl; if(l[j]<=i&&r[j]>i) { pu(t,j-1,0) { // cout<<dp[t]<<" "<<j-t,edl; Add(dp[j],dp[t]*C(len+(j-t)-1,(j-t))%mod); if(!(l[t]<=i&&r[t]>i)) { break; } } } } } int w=dp[n];//opl(w);edl; up(i,1,n)w*=qpow(v[r[i]]-v[l[i]]),w%=mod; opl(w);edl; } } /* When you are coding,remember to: - clear the arrays if a problem has many tasks. - pay attention to some special cases(n=0,1). - Don't code before think completely. - ... */
cpp
13
B
B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES
[ "geometry", "implementation" ]
#include <bits/stdc++.h> #define int long long using namespace std; struct point{ int x,y; }; struct line{ point p1,p2; }a[4]; int len_line_pow(line a){//求线段长度的平方 return (a.p1.x-a.p2.x)*(a.p1.x-a.p2.x)+(a.p1.y-a.p2.y)*(a.p1.y-a.p2.y); } bool check_same_point(point p1,point p2){//判断两点是否相同 return p1.x==p2.x&&p1.y==p2.y; } bool check_one_line(line a,point p){//判断三点共线 return (a.p1.y-p.y)*(a.p2.x-p.x)==(a.p2.y-p.y)*(a.p1.x-p.x); } bool check_5_point(line a,point p){//判断p是不是在a的1/5点和4/5线之间 a.p1.x*=5,a.p2.x*=5,a.p1.y*=5,a.p2.y*=5; p.x*=5,p.y*=5; point p1={a.p1.x+(a.p2.x-a.p1.x)/5,a.p1.y+(a.p2.y-a.p1.y)/5}; point p4={a.p1.x+(a.p2.x-a.p1.x)/5*4,a.p1.y+(a.p2.y-a.p1.y)/5*4}; double d=sqrt((double)len_line_pow({p1,p4})); double d1=sqrt((double)len_line_pow({p,p1})); double d4=sqrt((double)len_line_pow({p,p4})); return fabs(d-d1-d4)<1e-7; } bool check(line l,line r,line m){ //条件1:两线有唯一共同端点 int x=check_same_point(l.p1,r.p1); if(check_same_point(l.p1,r.p2)){ x++; swap(r.p1,r.p2); } if(check_same_point(l.p2,r.p1)){ x++; swap(l.p1,l.p2); } if(check_same_point(l.p2,r.p2)){ x++; swap(l.p1,l.p2); swap(r.p1,r.p2); } if(x!=1){ return false; } // cout<<"T1:OK"<<"\n"; //条件2:夹角不是钝角,可以是直角 if(len_line_pow(l)+len_line_pow(r)<len_line_pow({l.p2,r.p2})){ // cout<<"T2:FALSE"<<"\n"; // cout<<len_line_pow(l)<<"+"<<len_line_pow(r)<<">"<<len_line_pow({l.p2,r.p2})<<"\n"; return false; } // cout<<"T2:OK"<<"\n"; //条件3:第3线两端点与前两线共线 if(check_one_line(l,m.p1)&&check_one_line(r,m.p2)){ ; }else if(check_one_line(l,m.p2)&&check_one_line(r,m.p1)){ swap(m.p1,m.p2); }else{ return false; } // cout<<"T3:OK"<<"\n"; //条件4:第3线两端点必须在两线分别的1/5点和4/5线之间 if(check_5_point(l,m.p1)&&check_5_point(r,m.p2)){ // cout<<"T4:OK"<<"\n"; return true; }else{ return false; } } signed main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T; cin>>T; while(T--){ for(int i=1;i<=3;i++){ cin>>a[i].p1.x>>a[i].p1.y>>a[i].p2.x>>a[i].p2.y; } bool flag=false; for(int i=1;i<=3&&!flag;i++){ for(int j=1;j<=3&&!flag;j++){ if(i==j){ continue; } for(int k=1;k<=3&&!flag;k++){ if(k==j||k==i){ continue; } // cout<<i<<" "<<j<<" :"<<k<<"\n"; flag|=check(a[i],a[j],a[k]); } } } cout<<(flag?"YES":"NO")<<"\n"; } return 0; }
cpp
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
#include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define scl(n) cin>>n; #define scc(c) cin>>c; #define fr(i,n) for (ll i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) #define pfl(x) printf("%lld\n",x) #define pb push_back #define debug cout<<"I am here"<<endl; #define pno cout<<"NO"<<endl #define pys cout<<"YES"<<endl #define l(s) s.size() #define asort(a) sort(a,a+n) #define all(x) (x).begin(), (x).end() #define dsort(a) sort(a,a+n,greater<int>()) #define vasort(v) sort(v.begin(), v.end()); #define vdsort(v) sort(v.begin(), v.end(),greater<int>()); #define uniquee(x) x.erase(unique(x.begin(), x.end()),x.end()) #define pn cout<<endl; #define md 1000000007 #define inf 1e18 #define ps cout<<" "; #define Pi acos(-1.0) #define mem(a,i) memset(a, i, sizeof(a)) #define tcas(i,t) for(ll i=1;i<=t;i++) #define pcas(i) cout<<"Case "<<i<<": "<<"\n"; #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) #define N 100006 int main() { fast; ll t; ll m,n,c,d,i,j,k,x,y,z,l,q,r; string s,s1, s2, s3, s4; ll cnt=1,ans=0,sum1=0, sum2=0; scl(n); ll a[n], b[n]; fr(i,n)cin>>a[i]; fr(i,n)cin>>b[i]; fr(i, n)if( (a[i]==1 and b[i]==0) ) sum1++; else if (a[i]==0 and b[i]==1) sum2++; //cout<<sum1<<" "<<sum2<<endl; if(sum1==sum2 and sum1==0)cout<<-1<<endl; else { ll val=sum1; if(sum1==0)cnt=-1; else fr1(i, N)if(sum2>=sum1)sum1=val*i, cnt=i;else break; cout<<cnt<<endl; } return 0; }
cpp
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
#include<iostream> using namespace std; int main() { int n,i; cin>>n; if(n%2) { cout<<"NO"<<endl; return 0; } pair<int,int>a[n],p,temp; for(i=0;i<n;i++)cin>>a[i].first>>a[i].second; p={a[0].first+a[n/2].first,a[0].second+a[n/2].second}; for(i=1;i<n/2;i++){temp={a[i].first+a[i+n/2].first,a[i].second+a[i+n/2].second};if(p!=temp){cout<<"NO"<<endl;return 0;}} cout<<"YES"<<endl; }
cpp
1311
E
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3 5 7 10 19 10 18 OutputCopyYES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO NotePictures corresponding to the first and the second test cases of the example:
[ "brute force", "constructive algorithms", "trees" ]
// LUOGU_RID: 101656980 // just for fun #include <bits/stdc++.h> #define rep(i, x, y) for (int i = (x); i <= (y); i+=1) #define epr(i, x) for (int i = head[x]; i; i = nxt[i]) #define per(i, x, y) for (int i = (x); i >= (y); i-=1) #define DC int T = gi <int> (); while (T--) #define eb emplace_back #define ep emplace #define pb push_back #define mp make_pair #define fi first #define se second using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair <int, int> PII; typedef pair <LL, int> PLI; typedef pair <int, LL> PIL; typedef pair <LL, LL> PLL; template <typename T> inline T gi() { T x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();} while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return f * x; } template <typename T> inline void chkmax(T &x, const T &y) {x = x > y ? x : y;} template <typename T> inline void chkmin(T &x, const T &y) {x = x < y ? x : y;} const int N = 5003, M = N << 1, INF = 0x3f3f3f3f; int n, d; int cnt[N]; vector <int> vec[N]; inline void solve() { n = gi <int> (), d = gi <int> (); int cc = 0, mn = 0, mx = 1ll * n * (n - 1) / 2, mxd = 0; rep(i, 0, n) cnt[i] = 0, vec[i].clear(); rep(i, 0, 20) { cnt[i] = min(n - cc, 1 << i); mn += min(n - cc, 1 << i) * i; cc += min(n - cc, 1 << i); if (cc == n) {mxd = i; break;} } if (d < mn || d > mx) return (void)puts("NO"); puts("YES"); int dlt = d - mn, pp = mxd; per(i, mxd, 1) { int o = cnt[i]; rep(j, 1, o - 1) { --cnt[i]; int now = i; while (dlt && cnt[now]) ++now, --dlt; ++cnt[now], chkmax(pp, now); if (!dlt) break; } if (!dlt) break; } int oid = 0; rep(i, 0, pp) rep(j, 1, cnt[i]) vec[i].eb(++oid); rep(i, 1, pp) { int zz = 0, oc = 0; rep(j, 1, cnt[i]) { printf("%d ", vec[i - 1][zz]); if (oc == 0) ++oc; else oc = 0, ++zz; } } puts(""); } int main() { //freopen(".in", "r", stdin); freopen(".out", "w", stdout); DC solve(); return !!0; }
cpp
1313
E
E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5];
[ "data structures", "hashing", "strings", "two pointers" ]
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #define AquA cin.tie(0);ios_base::sync_with_stdio(0); #define fs first #define sc second #define p_q priority_queue #define int long long using namespace std; vector<int> findz(string a){ int n=a.size(); vector<int> re(n); re[0]=n; int l=0,r=0; vector<int> z; int flag=0; for(int i=1;i<n;i++){ if(i+re[i-l]<r){ re[i]=re[i-l]; } else{ l=i; if(i>r){ r=i; } while(r<n && a[r]==a[r-l]){ r++; } re[i]=r-l; } if(flag){ z.push_back(re[i]); } if(a[i]=='$'){ flag=1; } } return z; } struct BIT{ int n; vector<int> bt; void init(int x){ n=x; bt.resize(n+1); } void update(int x,int y){ for(;x>0;x-=x&(-x)){ bt[x]+=y; } } int query(int x){ int ans=0; for(;x<=n;x+=(x&-x)){ ans+=bt[x]; } return ans; } }; signed main(){ AquA; int n,m; cin >> n >> m; string a,b,s; cin >> a >> b >> s; auto w=s+"$"+a; auto z1=findz(w); w=b+"$"+s; reverse(w.begin(),w.end()); auto z2=findz(w); reverse(z2.begin(),z2.end()); for(auto &h:z1){ if(h==m){ h--; } } for(auto &h:z2){ if(h==m){ h--; } } BIT bt,bt2; bt.init(m); bt2.init(m); int ans=0; int l=0,r=0; auto add=[&](int x,int y){ bt.update(x,y*x); bt2.update(x,y); }; for(int i=0;i<n;i++){ while(l<i){ add(z2[l],-1); l++; } while(r<n && r-i<=m-2){ add(z2[r],1); r++; } if(z1[i]==0){ continue; } ans+=bt.query(m-z1[i])+bt2.query(m-z1[i])*(z1[i]-m+1); } cout << ans << "\n"; return 0; }
cpp
1290
E
E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5 2 4 1 5 3 OutputCopy1 3 6 8 11 InputCopy6 1 2 4 5 6 3 OutputCopy1 3 6 8 12 17 NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11.
[ "data structures" ]
#include <bits/stdc++.h> #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2") #define int long long using namespace std; namespace IO { char ibuf[(1 << 20) + 1], *iS, *iT; #if ONLINE_JUDGE #define gh() (iS == iT ? iT = (iS = ibuf) + fread(ibuf, 1, (1 << 20) + 1, stdin), (iS == iT ? EOF : *iS++) : *iS++) #else #define gh() getchar() #endif #define reg register inline long long read () { reg char ch = gh(); reg long long x = 0; reg char t = 0; while (ch < '0' || ch > '9') t |= ch == '-', ch = gh(); while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = gh(); return t ? ~(x - 1) : x; } inline void write(long long x) { if (x < 0) { x = ~(x - 1); putchar('-'); } if (x > 9) write(x / 10); putchar(x % 10 + '0'); } } using IO::read; using IO::write; const int maxn(2e5 + 500); int n, a[maxn], p[maxn], b[maxn]; inline int max (const int &x, const int &y) { return x < y ? y : x; } struct SGT { struct SGTNode { int v, mx, se, ct, len, tg, fl; } tr[maxn << 2]; #define ls (p << 1) #define rs (p << 1 | 1) inline void pushup (int p) { tr[p].v = tr[ls].v + tr[rs].v, tr[p].len = tr[ls].len + tr[rs].len; if (tr[ls].mx == tr[rs].mx) { tr[p].mx = tr[ls].mx, tr[p].ct = tr[ls].ct + tr[rs].ct; tr[p].se = max(tr[ls].se, tr[rs].se); } else if (tr[ls].mx > tr[rs].mx) { tr[p].mx = tr[ls].mx, tr[p].ct = tr[ls].ct; tr[p].se = max(tr[ls].se, tr[rs].mx); } else { tr[p].mx = tr[rs].mx, tr[p].ct = tr[rs].ct; tr[p].se = max(tr[ls].mx, tr[rs].se); } } // inline void pushmin (int p, int v) { // if (tr[p].mx <= v) return; // tr[p].v += (v - tr[p].mx) * tr[p].ct; // tr[p].mx = tr[p].tg = v; // } inline void pushmin (int p, int v) { tr[p].v += tr[p].ct * v; tr[p].mx += v; tr[p].tg += v; } inline void pushadd (int p, int v) { tr[p].v += v * tr[p].len; tr[p].mx += v, tr[p].se += v; tr[p].fl += v; } inline void pushdown (int p) { if (tr[p].fl) { pushadd(ls, tr[p].fl); pushadd(rs, tr[p].fl); tr[p].fl = 0; } if (tr[p].tg) { int tp = max(tr[ls].mx, tr[rs].mx); if (tr[ls].mx == tp) pushmin(ls, tr[p].tg); if (tr[rs].mx == tp) pushmin(rs, tr[p].tg); tr[p].tg = 0; } } inline void build (int l, int r, int p) { tr[p].tg = tr[p].fl = tr[p].len = tr[p].ct = tr[p].v = 0, tr[p].mx = tr[p].se = -1; if (l == r) return; const int mid = (l + r) >> 1; build(l, mid, ls); build(mid + 1, r, rs); pushup(p); } inline void updadd (int s, int t, int l, int r, int p, int v) { if (s > t) return; if (s <= l && r <= t) { pushadd(p, v); return; } pushdown(p); const int mid = (l + r) >> 1; if (s <= mid) updadd(s, t, l, mid, ls, v); if (mid < t) updadd(s, t, mid + 1, r, rs, v); pushup(p); } inline void updmin (int s, int t, int l, int r, int p, int v) { if (s > t) return; if (tr[p].mx <= v) return; if (s <= l && r <= t && tr[p].se <= v) { pushmin(p, v - tr[p].mx); return; } pushdown(p); const int mid = (l + r) >> 1; if (s <= mid) updmin(s, t, l, mid, ls, v); if (mid < t) updmin(s, t, mid + 1, r, rs, v); pushup(p); } inline void assign (int s, int l, int r, int p, int v) { if (l == r) { tr[p].mx = tr[p].v = v; tr[p].ct = tr[p].len = 1; return; } pushdown(p); const int mid = (l + r) >> 1; if (s <= mid) assign(s, l, mid, ls, v); else assign(s, mid + 1, r, rs, v); pushup(p); } inline int qry (int s, int t, int l, int r, int p) { if (s <= l && r <= t) return tr[p].len; pushdown(p); const int mid = (l + r) >> 1; int res = 0; if (s <= mid) res += qry(s, t, l, mid, ls); if (mid < t) res += qry(s, t, mid + 1, r, rs); return res; } } T; signed main() { n = read(); for (int i = 1; i <= n; i++) a[i] = read(), p[a[i]] = i; for (int o = 0; o < 2; ++o) { T.build(1, n, 1); for (int i = 1; i <= n; i++) { T.assign(p[i], 1, n, 1, i + 1); T.updadd(p[i] + 1, n, 1, n, 1, 1); int t = T.qry(1, p[i], 1, n, 1); T.updmin(1, p[i] - 1, 1, n, 1, t); b[i] += T.tr[1].v; } for (int i = 1; i <= n; i++) p[i] = n - p[i] + 1; } for (int i = 1; i <= n; i++) write(b[i] - i * (i + 2)), puts(""); } // I love WHQ!
cpp
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might 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.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #define ll long long using namespace std; using namespace __gnu_pbds; typedef pair<int, int> node; typedef tree<node, null_type, less<node>,rb_tree_tag, tree_order_statistics_node_update> ordered_set; const int N=3e5+5; const ll MOD=1e9+7,MAX=1e18; const double ep=1e-6, pi=3.14159265359; long long inv(long long a, long long b=MOD){ return 1<a ? b - inv(b%a,a)*b/a : 1; } int dx[8] = { 1, 0, -1, 0, -1, 1, -1, 1 }; int dy[8] = { 0, 1, 0, -1, -1, 1, 1, -1 }; ll n,m=0,k; void fastio() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } vector<int>graph[N]; int ask(int a,int b) { cout<<"? "<<a<<" "<<b<<'\n'; cout.flush(); int x; cin>>x; return x; } bool vis[N],taken[N]; void dfs(int x) { vis[x]=1; for(auto i:graph[x]) { if(!vis[i])dfs(i); } } void fn() { cin>>n; for(int i=1;i<n;i++) { int a,b; cin>>a>>b; graph[a].push_back(b); graph[b].push_back(a); } vector<int>leafs,v2; for(int i=1;i<=n;i++) { if(graph[i].size()==1) { leafs.push_back(i); } } while(leafs.size()>1) { int a=leafs.back(); leafs.pop_back(); int b=leafs.back(); leafs.pop_back(); if(vis[b]) { leafs.push_back(a); } else { int x=ask(a,b); vis[x]=1; if(x==a) { cout<<"! "<<a<<'\n'; return; } if(x==b) { cout<<"! "<<b<<'\n'; return; } if(!taken[x])v2.push_back(x),taken[x]=1; if(!vis[a]||b==x)dfs(a); if(!vis[b])dfs(b); vis[x]=0; } } if(leafs.size()&&!taken[leafs[0]]) { v2.push_back(leafs[0]); } leafs=v2; cout.flush(); while(leafs.size()>1) { int a=leafs.back(); leafs.pop_back(); int b=leafs.back(); leafs.pop_back(); if(vis[b]) { leafs.push_back(a); } else { int x=ask(a,b); leafs.push_back(x); vis[x]=1; if(!vis[a]||b==x)dfs(a); if(!vis[b])dfs(b); } } cout<<"! "<<leafs[0]<<'\n'; cout.flush(); } int main() { fastio(); int t=1; //cin>>t; while(t--)fn(); return 0; }
cpp
1284
C
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853 OutputCopy1 InputCopy2 993244853 OutputCopy6 InputCopy3 993244853 OutputCopy32 InputCopy2019 993244853 OutputCopy923958830 InputCopy2020 437122297 OutputCopy265955509 NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.
[ "combinatorics", "math" ]
#include <iostream> #include <vector> #include <queue> #include <unordered_map> #include <unordered_set> #include <map> #include <set> #include <cmath> #include <algorithm> #include <functional> using namespace std; #define int long long void solve() { int n,mod; cin>>n>>mod; vector<int> fact(n+1,1); for(int i=2;i<=n;i++)fact[i]=(fact[i-1]*i)%mod; int rez=0LL; for(int i=1;i<=n;i++) { ///permutari restu, poz in care se afla, de la cat la cat rez+=((((fact[n-i]*(n-i+1))%mod)*(n-i+1)%mod)*fact[i])%mod; rez%=mod; //cout<<rez; } cout<<rez; } main() { auto sol=[](bool x)->string { if(x)return "YES"; return "NO"; }; int tt=1; //cin>>tt; while(tt--) { solve(); cout<<'\n'; } }
cpp
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4 OutputCopy6 InputCopy3 5 OutputCopy10 InputCopy42 1337 OutputCopy806066790 InputCopy100000 200000 OutputCopy707899035 NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
[ "combinatorics", "math" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <functional> using namespace std; using namespace __gnu_pbds; // less<int> -> increasing order, greater<int>->decreasing order, less_equal<int> -> work as multiset typedef tree<pair<long long int, long long int>, null_type, less<pair<long long int, long long int>>, rb_tree_tag, tree_order_statistics_node_update> pbds; // find_by_order(index) -> iterator of element at x // order_of_key(key) -> all element strictly less than key. typedef long long ll; typedef long double ld; typedef vector<ll> v64; typedef vector<int> v32; typedef vector<pair<ll, ll>> vp64; typedef vector<vector<ll>> vv64; #define forauto(v) \ for (auto i : v) \ { \ cout << i << " "; \ } \ cout << ln; #define fori(n) for (ll i = 0; i < n; i++) #define fori1(n) for (ll i = 1; i <= n; i++) #define forj1(n) for (ll j = 1; j <= n; j++) #define forj(n) for (ll j = 0; j < n; j++) #define forsn(i, s, n) for (ll i = s; i < n; i++) #define ln "\n" #define pb push_back #define m1e9 998244353 #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define sz(x) ((ll)(x).size()) #define fast_cin() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL) const ll N = 2e5 + 5; ll fact[N], invfact[N]; ll power(ll x, ll y) { ll res = 1; x = x % m1e9; while (y > 0) { if (y & 1) { res = (res * x) % m1e9; } y = y >> 1; x = (x * x) % m1e9; } return res; } ll modinv(ll n) { return power(n, m1e9 - 2); } void f() { fact[0] = 1; invfact[0] = 1; fori1(N) { fact[i] = (fact[i - 1] * i) % m1e9; invfact[i] = modinv(fact[i]); } } ll NCR(ll n, ll r) { if (n < r) { return 0; } if (r < 0) { return 0ll; } if (r == 0 or r == n) return 1ll; return ((fact[n] * invfact[r] % m1e9) * invfact[n - r]) % m1e9; } void solve() { ll n, m; cin >> n >> m; /* n= 6 m= 10 1 2 3 4 5 6 ct -> n-1 equal pair -> n-2 */ ll ans = NCR(m, n - 1); ans = (ans * (n - 2)) % m1e9; ans = (ans * power(2, n - 3)) % m1e9; cout<<ans<<ln; } int main() { fast_cin(); ll t = 1; f(); while (t--) { solve(); } return 0; }
cpp
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might 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.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> PII; typedef pair<double, double> PDD; const int N = 1e6 + 10; vector<int>h[N]; int ask(int u, int v) { cout << "? " << u << " " << v << '\n'; int t; cin >> t; return t; } int ans, st[N]; int p[10], ok; void dfs(int u, int d) { if (ok)return; p[d] = u; st[u] = 1; if (d == 3) { int x = ask(p[1], p[3]); dfs(x,1); return; } for (auto j : h[u]) { if (st[j])continue; dfs(j, d + 1); return; } } int d[N]; int main() { // std::ios::sync_with_stdio(false); // cin.tie(0); // cout.tie(0); // cout<<fixed<< setprecision(2); int n; cin >> n; int l=1; queue<int>q; for (int i = 1; i < n; i++) { int a, b; cin >> a >> b; h[a].push_back(b); h[b].push_back(a); d[a]++; d[b]++; } for(int i=1;i<=n;i++){ if(d[i]==1)q.push(i); } int ans=0; while(q.size()>1){ auto t=q.front();q.pop(); auto v=q.front();q.pop(); int d1=ask(t,v); if(d1==t||d1==v){ ans=d1; break; }else{ for(auto j:h[t]){ d[j]--; if(d[j]==1)q.push(j); } for(auto j:h[v]){ if(--d[j]==1)q.push(j); } } } if(!ans)ans=q.front(); cout<<"! "<<ans; return 0; }
cpp
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
//This is coded by VIDYARTH GS //#include <bits/stdc++.h> #include <iostream> #include <complex> #include <queue> #include <set> #include <unordered_set> #include <list> #include <chrono> #include <random> #include <iostream> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <map> #include <unordered_map> #include <stack> #include <iomanip> #include <fstream> #ifndef ONLINE_JUDGE #define debug(x) cerr<<#x<<" "<<x<<"\n"; #else #define debug(x) #endif using namespace std; typedef long long ll; typedef long double ld; typedef pair<int,int> p32; typedef pair<ll,ll> p64; typedef pair<double,double> pdd; typedef vector<ll> v64; typedef vector<int> v32; typedef vector<vector<int> > vv32; typedef vector<vector<ll> > vv64; typedef vector<vector<p64> > vvp64; typedef vector<p64> vp64; typedef vector<p32> vp32; typedef map<int,int> mii; typedef map<int,v32> miv; ll MOD = 998244353; double eps = 1e-12; #define rep(i,e) for(ll i = 0; i < e; i++) #define repFR(i,s,e) for(ll i = s; i < e; i++) #define repR(i,s) for(ll i = s; i >= 0; i--) #define repRR(i,s,e) for(ll i = s; i >= e; i--) #define ln "\n" #define dbg(x) cout<<#x<<" = "<<x<<ln #define mp make_pair #define pb push_back #define ff first #define ss second #define INF 2e18 #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) #define all(x) (x).begin(), (x).end() #define sz(x) ((ll)(x).size()) void solve(){ //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int n; cin>>n; v32 arr1(n),arr2(n); rep(i,n){ cin>>arr1[i]; } rep(i,n){ cin>>arr2[i]; } int cnt1 = 0; int cnt2 = 0; rep(i,n){ if(arr1[i] == 1 && arr2[i] == 0){ cnt1++; } if(arr1[i] == 0 && arr2[i] == 1){ cnt2++; } } if(cnt1 == 0){ cout<<-1<<"\n"; return; } int ans = ceil((cnt2+1)/(float)cnt1); cout<<ans; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif #ifndef ONLINE_JUDGE freopen("Error.txt","w",stderr); #endif fast_cin(); solve(); return 0; }
cpp
1313
D
D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.
[ "bitmasks", "dp", "implementation" ]
// LUOGU_RID: 97931742 #include <cstdio> #include <cstring> #include <algorithm> using std::max; const int MAXN = 1e5 + 5; int n, m, k; int vis[MAXN << 1]; int f[1000]; int tot; struct Seg { int x, id; Seg() {} Seg(const int& X, const int& I) { x = X, id = I; } bool operator< (const Seg& A) const { return x == A.x ? id < A.id : x < A.x; } } seg[MAXN << 1]; int main() { scanf("%d %d %d", &n, &m, &k); for (int i = 1; i <= n; ++i) { int l, r; scanf("%d %d", &l, &r); seg[++tot] = Seg(l, i); seg[++tot] = Seg(r + 1, -i); } std::sort(seg + 1, seg + tot + 1); memset(f, 0xcf, sizeof(f)); f[0] = 0; for (int i = 1; i <= tot; ++i) { int len = 0, p; if (i < tot) len = seg[i + 1].x - seg[i].x; if (seg[i].id > 0) { for (int k = 0; k < 8; ++k) { if (!vis[k]) { vis[p = k] = seg[i].id; break; } } for (int k = (1 << 8) - 1; k >= 0; --k) { if (k >> p & 1) f[k] = f[k ^ 1 << p] + len * __builtin_parity(k); else f[k] = f[k] + len * __builtin_parity(k); } } else { for (int k = 0; k < 8; ++k) { if (vis[k] == -seg[i].id) { vis[p = k] = 0; break; } } for (int k = 0; k < 1 << 8; ++k) { if (k >> p & 1) f[k] = 0xcfcfcfcf; else f[k] = max(f[k], f[k ^ 1 << p]) + len * __builtin_parity(k); } } } printf("%d\n", f[0]); return 0; }
cpp
1290
E
E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5 2 4 1 5 3 OutputCopy1 3 6 8 11 InputCopy6 1 2 4 5 6 3 OutputCopy1 3 6 8 12 17 NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11.
[ "data structures" ]
#include <bits/stdc++.h> #define int long long using namespace std; const int maxn=150005,inf=1e18; int n,a[maxn],pos[maxn]; struct vl {int sum,mx,sc,cnt; vl(){sum=0;mx=sc=-inf;cnt=0;} }; inline vl merge(vl a,vl b) { vl ret; ret.sum=a.sum+b.sum; ret.mx=max(a.mx,b.mx); ret.sc=-inf; ret.cnt=0; if(a.mx!=ret.mx)ret.sc=max(ret.sc,a.mx); else ret.cnt+=a.cnt; if(b.mx!=ret.mx)ret.sc=max(ret.sc,b.mx); else ret.cnt+=b.cnt; if(a.sc!=ret.mx)ret.sc=max(ret.sc,a.sc); if(b.sc!=ret.mx)ret.sc=max(ret.sc,b.sc); return ret; } vl val[maxn<<2]; int tag[maxn<<2],add[maxn<<2],len[maxn<<2]; inline void pushup(int i) { val[i]=merge(val[i<<1],val[i<<1|1]); len[i]=len[i<<1]+len[i<<1|1]; } inline void pushtgmin(int i,int v) { if(v>=val[i].mx)return; val[i].sum-=(val[i].mx-v)*val[i].cnt; val[i].mx=v; tag[i]=min(tag[i],v); return; } inline void pushtgadd(int i,int v) { add[i]+=v; val[i].sum+=len[i]*v; if(tag[i]!=inf)tag[i]+=v; if(val[i].mx!=-inf)val[i].mx+=v; if(val[i].sc!=-inf)val[i].sc+=v; } inline void pushdown(int i) { pushtgadd(i<<1,add[i]); pushtgadd(i<<1|1,add[i]); add[i]=0; pushtgmin(i<<1,tag[i]); pushtgmin(i<<1|1,tag[i]); tag[i]=inf; } void update(int i,int l,int r,int L,int R,int v) { if(L>R)return; if(L<=l&&r<=R){pushtgadd(i,v);return;} int mid=l+r>>1;pushdown(i); if(L<=mid)update(i<<1,l,mid,L,R,v); if(R>mid)update(i<<1|1,mid+1,r,L,R,v); pushup(i); } void calcmin(int i,int l,int r,int L,int R,int v) { //if(i==1)printf("#%d %d %d\n",L,R,v); if(r<L||l>R||L>R)return; if(L<=L&&r<=R&&val[i].sc<v){pushtgmin(i,v);return;} if(l==r)return; int mid=l+r>>1;pushdown(i); calcmin(i<<1,l,mid,L,R,v); calcmin(i<<1|1,mid+1,r,L,R,v); pushup(i); } void build(int i,int l,int r) { len[i]=0; val[i].cnt=val[i].sum=0; val[i].mx=val[i].sc=-inf; tag[i]=inf;add[i]=0; if(l==r)return; int mid=l+r>>1; build(i<<1,l,mid); build(i<<1|1,mid+1,r); } int query(int i,int l,int r,int p) { if(l==r)return val[i].sum; int mid=l+r>>1; pushdown(i); if(p<=mid)return query(i<<1,l,mid,p); else return query(i<<1|1,mid+1,r,p); } void modify(int i,int l,int r,int p,int v) { if(l==r) { val[i].cnt=1; val[i].mx=v; val[i].sc=-inf; val[i].sum=v; len[i]=1; return; } int mid=l+r>>1; pushdown(i); if(p<=mid)modify(i<<1,l,mid,p,v); else modify(i<<1|1,mid+1,r,p,v); pushup(i); } int c[maxn]; int num[maxn]; void uadd(int p,int v){while(p<=n){c[p]+=v;p+=p&-p;}} int ask(int p){int ret=0;while(p){ret+=c[p];p-=p&-p;}return ret;} int sum[maxn]; signed main() { scanf("%lld",&n); for(int i=1;i<=n;i++) scanf("%lld",&a[i]); for(int i=1;i<=n;i++) pos[a[i]]=i,num[a[i]]=ask(a[i]),uadd(a[i],1); build(1,1,n); for(int i=1;i<=n;i++) { update(1,1,n,pos[i]+1,n,1); calcmin(1,1,n,1,pos[i]-1,num[i]); modify(1,1,n,pos[i],i); int S=0; //for(int j=1,x;j<=n;j++) // if(a[j]<=i) // printf("%d ",(x=query(1,1,n,j))),S+=x; // putchar('\n'); //printf("%d\n",val[1].sum); sum[i]+=val[1].sum; } reverse(a+1,a+1+n); memset(c,0,sizeof c); for(int i=1;i<=n;i++) pos[a[i]]=i,num[a[i]]=ask(a[i]),uadd(a[i],1); build(1,1,n); for(int i=1;i<=n;i++) { update(1,1,n,pos[i]+1,n,1); calcmin(1,1,n,1,pos[i]-1,num[i]); modify(1,1,n,pos[i],i); // int S=0; // for(int j=n,x;j>=1;j--) // if(a[j]<=i) // printf("%d ",i-(x=query(1,1,n,j))+1),S+=x; // putchar('\n'); //printf("%d\n",val[1].sum); sum[i]-=i*i-val[1].sum; } for(int i=1;i<=n;i++) printf("%lld\n",sum[i]); // putchar('\n'); return 0; }
cpp
1307
G
G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3 1 2 2 2 3 2 1 3 3 5 0 1 2 3 4 OutputCopy3.0000000000 4.0000000000 4.5000000000 5.0000000000 5.5000000000
[ "flows", "graphs", "shortest paths" ]
#include <bits/stdc++.h> using namespace std; using i64=long long; using u64=unsigned long long; using db=double; using pii=pair<int,int>; using vi=vector<int>; template<typename T> inline T read(){ T x=0,f=0;char ch=getchar(); while(!isdigit(ch)) f|=(ch=='-'),ch=getchar(); while(isdigit(ch)) x=x*10+(ch-'0'),ch=getchar(); return f?-x:x; } #define rdi read<int> #define rdi64 read<i64> #define fi first #define se second #define pb push_back const int N=55; const i64 INFl=4e18; int n,m,q; struct Edge{int to,nxt,f,w;}e[N*N*4]; int head[N],tot=1; void add_e(int x,int y,int f,int w){ e[++tot]={y,head[x],f,w};head[x]=tot; e[++tot]={x,head[y],0,-w};head[y]=tot; } i64 dis[N];int pre[N]; bool spfa(int n,int S,int T){ static int inq[N]; queue<int> q; fill(dis+1,dis+n+1,INFl); dis[S]=0,q.push(S),inq[S]=1; while(!q.empty()){ int x=q.front(); q.pop(),inq[x]=0; for(int i=head[x];i;i=e[i].nxt){ int y=e[i].to; if(e[i].f&&dis[y]>dis[x]+e[i].w){ dis[y]=dis[x]+e[i].w,pre[y]=i; if(!inq[y]) inq[y]=1,q.push(y); } } } return dis[T]!=INFl; } vector<pair<int,i64>> cv; void calc(int n,int S,int T){ int sf=0;i64 sc=0; while(spfa(n,S,T)){ int x=T;i64 fl=INFl; while(x!=S) fl=min(fl,(i64)e[pre[x]].f),x=e[pre[x]^1].to; x=T,sf+=fl,sc+=fl*dis[T]; while(x!=S) e[pre[x]].f-=fl,e[pre[x]^1].f+=fl,x=e[pre[x]^1].to; cv.pb({sf,sc}); } } db query(int x){ db ret=INFl; for(auto cur:cv) ret=min(ret,1.*(cur.se+x)/cur.fi); return ret; } int main(){ #ifdef LOCAL freopen("1.in","r",stdin); freopen("1.out","w",stdout); #endif n=rdi(),m=rdi(); for(int i=1;i<=m;i++){ int x=rdi(),y=rdi(),w=rdi(); add_e(x,y,1,w); } calc(n,1,n); q=rdi(); while(q--){ int x=rdi(); cout<<fixed<<setprecision(7)<<query(x)<<'\n'; } return 0; }
cpp
1325
E
E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3 1 4 6 OutputCopy1InputCopy4 2 3 6 6 OutputCopy2InputCopy3 6 15 10 OutputCopy3InputCopy4 2 3 5 7 OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.
[ "brute force", "dfs and similar", "graphs", "number theory", "shortest paths" ]
#include <bits/stdc++.h> using namespace std; const int MN=8e4; int N, at=170, dist[MN], ans = MN; bool pvis[1001], vis[MN]; set<int> start; vector<int> prime, vals, adj[MN]; unordered_map<int, int> ind; // (value, index it maps to) queue<pair<int, pair<int, int> > > next1; // (distance, (node, parent)) void bfs(int j){ memset(vis, 0, sizeof(vis)); next1.push({0, {j, j}}); while (!next1.empty()) { int d = next1.front().first; int x = next1.front().second.first; int p = next1.front().second.second; next1.pop(); if(adj[x].size()<=1 || vis[x]) continue; vis[x]=1; dist[x] = d; bool skip=0; for (int i: adj[x]) if (i != p || skip) { if (vis[i]) ans = min(ans, dist[i] + dist[x] + 1); else next1.push({d + 1, {i, x}}); } else skip = 1; } adj[j].clear(); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); prime.reserve(170); prime.push_back(1); for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.push_back(i); for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; } cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x; for (int j=1; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0; while (x%prime[j] == 0) { x /= prime[j]; cnt++; } if (cnt%2 == 1) vals.push_back(prime[j]); } if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; } vals.push_back(x); if (vals.size() == 1) vals.push_back(1); for (int k: vals) if (ind.count(k) == 0) { if (k > 1e3) ind[k] = at++; else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin(); ind[k]=t; start.insert(t); } } adj[ind[vals[0]]].push_back(ind[vals[1]]); adj[ind[vals[1]]].push_back(ind[vals[0]]); } for (int j: start) bfs(j); cout << (ans == MN ? -1 : ans) <<'\n'; }
cpp
1303
F
F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10 2 1 1 1 2 1 2 2 1 1 1 2 3 1 2 1 2 2 2 2 2 2 1 2 3 2 4 2 1 5 OutputCopy2 4 3 3 4 4 4 2 2 4
[ "dsu", "implementation" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; int dx[4] = {-1, 0, 0, 1}; int dy[4] = { 0,-1, 1, 0}; int n,m,Q,a[305][305],x[2000005],y[2000005],c[2000005],ans[2000005]; vector <int> vec[305][305]; int pre[2000005]; int fa[4000005]; int getf(int x){ if(x == fa[x]) return x; return fa[x] = getf(fa[x]); } void merge(int x,int y,int id){ x = getf(x); y = getf(y); if(x == y) return; fa[x] = y; pre[id] --; } unordered_map <int,int> mp[1000005]; int get_id(int col,int tx,int ty){ return mp[col][(tx - 1) * m + ty]; } int read(){ int x = 0; char ch; ch = getchar(); while(!isdigit(ch)) ch = getchar(); while(isdigit(ch)){ x = x * 10 + ch - '0'; ch = getchar(); } return x; } int lc[2000005],lcc = 0; int main(){ int tot = 0; n = read(); m = read(); Q = read(); if(n * m == 1){ for(int i = 1;i <= Q;i ++) printf("1\n"); return 0; } for(int i = 1;i <= n;i ++){ for(int j = 1;j <= m;j ++){ mp[0][(i - 1) * m + j] = ++ tot; } } for(int i = 1;i <= Q;i ++){ x[i] = read(); y[i] = read(); c[i] = read(); lc[++ lcc] = c[i]; } sort(lc + 1,lc + 1 + lcc); lcc = unique(lc + 1,lc + 1 + lcc) - lc - 1; for(int i = 1;i <= Q;i ++){ c[i] = lower_bound(lc + 1,lc + 1 + lcc,c[i]) - lc; if(mp[c[i]].find((x[i] - 1) * m + y[i]) == mp[c[i]].end()) mp[c[i]][(x[i] - 1) * m + y[i]] = ++ tot; } for(int i = 1;i <= tot;i ++) fa[i] = i; pre[0] = 1; for(int i = 0;i <= n + 1;i ++) a[i][0] = a[i][m + 1] = -1; for(int i = 0;i <= m + 1;i ++) a[0][i] = a[n + 1][i] = -1; c[0] = c[Q + 1] = -1; for(int i = 1;i <= Q;i ++){ pre[i] = pre[i - 1]; if(c[i] != c[i - 1]) pre[i] = 0; vec[x[i]][y[i]].push_back(c[i]); if(a[x[i]][y[i]] == c[i]) continue; a[x[i]][y[i]] = c[i]; pre[i] ++; for(int d = 0;d < 4;d ++){ int tx = x[i] + dx[d]; int ty = y[i] + dy[d]; if(a[tx][ty] == c[i]) merge(get_id(c[i],tx,ty),get_id(c[i],x[i],y[i]),i); } } for(int i = 1;i <= tot;i ++) fa[i] = i; pre[0] = n * m; for(int i = 1;i <= n;i ++){ for(int j = 1;j <= m;j ++){ for(int d = 0;d < 4;d ++){ int tx = i + dx[d]; int ty = j + dy[d]; if(a[tx][ty] == a[i][j]) merge(get_id(a[tx][ty],tx,ty),get_id(a[i][j],i,j),0); } } } for(int i = Q;i >= 1;i --){ if(c[i] != c[i + 1]) pre[0] -= pre[i]; ans[i] = pre[0] + pre[i]; //cout << i << " : " << pre[0] << ' ' << pre[i] << endl; vec[x[i]][y[i]].pop_back(); int col = vec[x[i]][y[i]].size() ? vec[x[i]][y[i]][vec[x[i]][y[i]].size() - 1] : 0; if(a[x[i]][y[i]] == col) continue; a[x[i]][y[i]] = col; pre[0] ++; for(int d = 0;d < 4;d ++){ int tx = x[i] + dx[d]; int ty = y[i] + dy[d]; if(a[tx][ty] == col) merge(get_id(col,tx,ty),get_id(col,x[i],y[i]),0); } } for(int i = 1;i <= Q;i ++) printf("%d\n",ans[i]); return 0; }
cpp
1288
B
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1 0 1337 NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
[ "math" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; using namespace std; const ll mod = 998244353; const int mm = 2e5 + 10; void solve(){ ll a,b; cin>>a>>b; ll ans=0; for(int i=10;i-1<=b;i*=10){ ans+=a; }cout<<ans<<'\n'; } int main(){ std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int t; cin>>t; while(t--){ solve(); } }
cpp
1313
C2
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "data structures", "dp", "greedy" ]
#include <iostream> #include <stack> using namespace std; #define int long long int ans[500005]; int n, a[500005]; int suml[500005]; int sumr[500005]; stack<int> st; signed main(){ scanf("%lld", &n); st.push(0); a[0] = -999999999; for(int i = 1; i <= n; i++) scanf("%lld", &a[i]); for(int i = 1; i <= n; i++){ while(a[st.top()] > a[i]) st.pop(); suml[i] = suml[st.top()] + a[i] * (i - st.top()); st.push(i); } while(!st.empty()) st.pop(); st.push(n + 1); a[n + 1] = -999999999; for(int i = n; i >= 1; i--){ while(a[st.top()] > a[i]) st.pop(); sumr[i] = sumr[st.top()] + a[i] * (st.top() - i); st.push(i); } int maxn = -999999999, id; for(int i = 1; i <= n; i++){ if(suml[i] + sumr[i] - a[i] > maxn){ maxn = suml[i] + sumr[i] - a[i]; id = i; } } int minn = a[id]; for(int i = id - 1; i >= 1; i--){ minn = min(minn, a[i]); ans[i] = minn; } minn = a[id]; for(int i = id + 1; i <= n; i++){ minn = min(minn, a[i]); ans[i] = minn; } ans[id] = a[id]; for(int i = 1; i <= n; i++) printf("%lld ", ans[i]); return 0; }
cpp
1299
D
D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8 1 2 0 2 3 1 2 4 3 2 6 2 3 4 8 3 5 4 5 4 5 5 6 6 OutputCopy2 InputCopy7 9 1 2 0 1 3 1 2 3 9 2 4 3 2 5 4 4 5 7 3 6 6 3 7 7 6 7 8 OutputCopy1 InputCopy4 4 1 2 27 1 3 1 1 4 1 3 4 0 OutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.
[ "bitmasks", "combinatorics", "dfs and similar", "dp", "graphs", "graphs", "math", "trees" ]
#include<bits/stdc++.h> using namespace std; struct edge{ int x,y,z; }t[1000011]; const int mod=1000000007; int n,m,sum,x[200011],y[200011],z[200011],h[200011],f[200011],val[200011],ans,p[11],idx[200011],cnt,g[511][11],son[511][511],idd[41],ss[2][2][511],la,col[200011],dep[200011],vis[41]; bool fl[200011]; queue<int> qx,qy,qz; map<int,int> mp; void link(int a,int b,int c){ cnt++; t[cnt].x=b; t[cnt].y=h[a]; t[cnt].z=c; h[a]=cnt; } int add(int a,int b){ if(a+b>=mod)return a+b-mod; return a+b; } int del(int a,int b){ if(a-b<0)return a-b+mod; return a-b; } int mul(int a,int b){ return ((int)(1ll*a*b%mod)); } int ksm(int a,int b){ int s=1; while(b){ if(b&1)s=mul(s,a); a=mul(a,a); b=(b>>1); } return s; } bool ins(int a){ for(int i=4;i>=0;i--){ if((a&(1<<i))==0)continue; a=a^p[i]; } if(a==0)return 0; for(int i=4;i>=0;i--){ if(a&(1<<i)){ for(int j=4;j>i;j--){ if(p[j]&(1<<i)){ p[j]=p[j]^a; } } p[i]=a; break; } } return 1; } int find(){ int s=0; for(int i=0;i<=4;i++)s=s*32+p[i]; return s; } void dfs(int a){ if(a>=32){ int c=find(); if(!mp[c]){ sum++; mp[c]=sum; int s=0; for(int i=4;i>=0;i--){ g[sum][i]=p[i]; if(p[i]>0)s++; } if(s==0)idd[0]=sum; if(s==1){ for(int i=4;i>=0;i--){ if(p[i]>0){ s=p[i]; break; } } idd[s]=sum; } } return; } dfs(a+1); int ss[11]; for(int i=0;i<=4;i++)ss[i]=p[i]; if(ins(a))dfs(a+1); for(int i=0;i<=4;i++)p[i]=ss[i]; } int getson(int a,int b){ for(int i=0;i<=4;i++)p[i]=g[a][i]; for(int i=0;i<=4;i++){ if(g[b][i]==0)continue; if(!ins(g[b][i]))return 0; } return mp[find()]; } void down(int a,int fa){ fl[a]=1; for(int i=h[a];i;i=t[i].y){ if(t[i].x==1||t[i].x==fa)continue; if(fl[t[i].x]){ vis[dep[a]^dep[t[i].x]^t[i].z]++; }else{ dep[t[i].x]=dep[a]^t[i].z; down(t[i].x,a); } } } int build(int a){ for(int i=0;i<32;i++)vis[i]=0; for(int i=0;i<=4;i++)p[i]=0; dep[a]=0; down(a,0); if(vis[0]>0)return 0; for(int i=1;i<32;i++){ if(vis[i]>2)return 0; if(vis[i]){ if(!ins(i)){ return 0; } } } return mp[find()]; } int main(){ dfs(1); for(int i=1;i<=sum;i++){ for(int j=1;j<=sum;j++){ son[i][j]=getson(i,j); } } scanf("%d%d",&n,&m); for(int i=1;i<=n;i++)f[i]=-1; for(int i=1;i<=m;i++){ scanf("%d%d%d",&x[i],&y[i],&z[i]); if(x[i]>y[i])swap(x[i],y[i]); if(x[i]==1)f[y[i]]=z[i]; link(x[i],y[i],z[i]); link(y[i],x[i],z[i]); } cnt=0; for(int i=1;i<=m;i++){ if(f[x[i]]>=0&&f[y[i]]>=0){ cnt++; idx[cnt]=x[i]; val[cnt]=-1; cnt++; idx[cnt]=y[i]; val[cnt]=f[x[i]]^f[y[i]]^z[i]; f[x[i]]=-1; f[y[i]]=-1; col[x[i]]=build(x[i]); col[y[i]]=col[x[i]]; } } for(int i=1;i<=n;i++){ if(f[i]<0)continue; col[i]=build(i); cnt++; idx[cnt]=i; val[cnt]=-1; } la=0; ss[0][0][idd[0]]=1; for(int i=1;i<=cnt;i++){ for(int j=1;j<=sum;j++){ ss[la^1][0][j]=0; ss[la^1][1][j]=0; } for(int j=1;j<=sum;j++){ ss[la^1][0][j]=add(ss[la^1][0][j],add(ss[la][0][j],ss[la][1][j])); if(col[idx[i]]>0){ int c=son[j][col[idx[i]]]; if(c>0)ss[la^1][1][c]=add(ss[la^1][1][c],ss[la][0][j]); if(val[i]<0)ss[la^1][1][c]=add(ss[la^1][1][c],ss[la][1][j]); else if(val[i]>0){ c=son[j][idd[val[i]]]; if(c>0)ss[la^1][1][c]=add(ss[la^1][1][c],ss[la][1][j]); } } } la=(la^1); } for(int i=1;i<=sum;i++)ans=add(ans,add(ss[la][0][i],ss[la][1][i])); printf("%d\n",ans); }
cpp
1310
C
C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1 abac OutputCopyaba InputCopy19 5 1821 aupontrougevkoffice OutputCopyau NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a".
[ "binary search", "dp", "strings" ]
#include <bits/stdc++.h> #define ms(x, v) memset(x, v, sizeof(x)) #define il __attribute__((always_inline)) #define U(i,l,r) for(int i(l),END##i(r);i<=END##i;++i) #define D(i,r,l) for(int i(r),END##i(l);i>=END##i;--i) using namespace std; typedef unsigned long long ull; typedef long long ll; template <typename T> using BS = basic_string<T>; //const int SZ(1 << 23); //unsigned char buf[SZ], *S, *Q; //#define getchar() ((S==Q)&&(Q=buf+fread(S=buf,1,SZ,stdin)),S==Q?EOF:*S++) template <typename T> void rd(T& s) { int c = getchar(); T f = 1; s = 0; while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) { s = s * 10 + (c ^ 48); c = getchar(); } s *= f; } template <typename T, typename... Y> void rd(T& x, Y&... y) { rd(x), rd(y...); } template <typename T> void pr(T s, bool f = 1) { if (s < 0) { printf("-"); s = -s; } if (!s) return void(f ? printf("0") : 0); pr(s / 10, 0); printf("%d", (signed)(s % 10)); } #define meow(...) fprintf(stderr, __VA_ARGS__) const int N = 1005; int n, m; ll k; char s[N]; // n^2 个子串排序 // 求 LCP 后比较下一位 int lcp[N][N], ord[N][N]; void getLCP() { D (i, n, 1) D (j, n, 1) if (s[i] == s[j]) lcp[i][j] = lcp[i + 1][j + 1] + 1; } pair<int, int> sub[N * N]; int sCnt; bool cmp(pair<int, int> l, pair<int, int> r){ int cp = lcp[l.first][r.first]; if (cp >= l.second - l.first + 1) return l.second - l.first < r.second - r.first; if (cp >= r.second - r.first + 1) return 0; return s[l.first + cp] < s[r.first + cp]; } bool check(int mid) { // 选定代表串大于等于第 mid 个,个数是否满足大于等于 k int term[N]{1}; __int128 f[N]{}; // term[i] = j that ord[i][j] >= mid const __int128 INF = (__int128(0x3f3f3f3f3f3f3f3f) << 64) | 0x3f3f3f3f3f3f3f3f; U (i, 0, n) { term[i] = n + 1; U (j, i + 1, n) if (ord[i + 1][j] >= mid) { term[i] = j; break; } } f[0] = 1; U (p, 1, m) { __int128 g[N]; U (i, 0, n) g[i] = f[i]; ms(f, 0); U (i, 0, n) { f[term[i]] += g[i]; f[term[i]] = min(INF, f[term[i]]); } U (i, 1, n) { f[i] += f[i - 1]; f[i] = min(INF, f[i]); } } return f[n] >= k; } int main() { rd(n, m, k); scanf("%s", s + 1); getLCP(); U (i, 1, n) U (j, i, n) sub[++sCnt] = {i, j}; // int fk = 0; // U (i, 2, sCnt) U (j, 1, i - 1) // if (!cmp(sub[i], sub[j]) && !cmp(sub[j], sub[i])) { // ++fk; // meow("(%d,%d), (%d,%d)\n", sub[i].first, sub[i].second, sub[j].first, sub[j].second); // } // clog << fk << endl << endl; sort(sub + 1, sub + sCnt + 1, cmp); // U (i, 1, sCnt) { // meow("[%d, %d]", sub[i].first, sub[i].second); // U (j, sub[i].first, sub[i].second) meow("%c", s[j]); // meow("\n"); // } // sCnt = unique(sub + 1, sub + sCnt + 1, cmp) - sub - 1; U (i, 1, n) U (j, i, n) ord[i][j] = lower_bound(sub + 1, sub + 1 + sCnt, pair<int, int>{i, j}, cmp) - sub; // clog << sCnt << endl; int l = 0; D (k, 30, 0) if (l + (1 << k) <= sCnt) if (check(l + (1 << k))) l += 1 << k; // clog << l << endl; auto pr = sub[l]; s[pr.second + 1] = 0; puts(s + pr.first); }
cpp
1304
F1
F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp" ]
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> //#include<boost/algorithm/string.hpp> //pragmas #pragma GCC optimize("O3") //types #define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define ll long long int #define ull unsigned long long int #define vec vector<long long int> #define pall pair<long long int, long long int> #define vecpair vector<pair<long long int,long long int>> #define vecvec(a, i, j) vector<vector<long long int>> a (i, vec (j, 0)) #define vecvecvec(a, i, j, k) vector<vector<vector<long long int>>> dp (i + 1, vector<vector<long long int>>(j + 1, vector<long long int>(k + 1, 0))) using namespace std; using namespace __gnu_pbds; //random stuff #define all(a) a.begin(),a.end() #define read(a) for (auto &x : a) cin >> x #define endl "\n" #define print(a) for(auto x : a) cout << x << " "; cout << endl #define sp " " ll INF = 9223372036854775807; typedef tree<long long int, null_type, less<long long int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set; struct custom_hash { static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; #define safe_map unordered_map<long long, int, custom_hash> //debug void __print(int x) {cerr << x;} void __print(long x) {cerr << x;} void __print(long long x) {cerr << x;} void __print(unsigned x) {cerr << x;} void __print(unsigned long x) {cerr << x;} void __print(unsigned long long x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define debug(x...) cerr << "[" << #x << "] = ["; _print(x) #define reach cerr<<"reached"<<endl #else #define debug(x...) #define reach #endif /*---------------------------------------------------------------------------------------------------------------------------*/ ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);} ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3 ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);} bool revsort(ll a, ll b) {return a > b;} void swap(int &x, int &y) {int temp = x; x = y; y = temp;} ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;} void google(int t) {cout << "Case #" << t << ": ";} vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (ll j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;} ll mod_add(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} ll mod_mul(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} ll mod_sub(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} ll mod_div(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N)) void precision(int a) {cout << setprecision(a) << fixed;} ll ceil_div(ll x, ll y){return (x + y - 1) / y;} unsigned long long power(unsigned long long x,ll y, ll p){unsigned long long res = 1;x = x % p; while (y > 0){if (y & 1)res = (res * x) % p;y = y >> 1;x = (x * x) % p;}return res;} unsigned long long modInverse(unsigned long long n,int p){return power(n, p - 2, p);} ll nCr(ll n,ll r, ll p){if (n < r)return 0;if (r == 0)return 1;unsigned long long fac[n + 1];fac[0] = 1;for (int i = 1; i <= n; i++)fac[i] = (fac[i - 1] * i) % p;return (fac[n] * modInverse(fac[r], p) % p* modInverse(fac[n - r], p) % p)% p;} ll accumulate(const vec &nums){ll sum = 0; for(auto x : nums) sum += x; return sum;} ll tmax(ll a, ll b, ll c = 0, ll d = -INF, ll e = -INF, ll f = -INF){return max(a, max(b, max(c, max(d, max(e, f)))));} /*--------------------------------------------------------------------------------------------------------------------------*/ //code starts int main() { fastio(); ll n, m, k; cin >> n >> m >> k; vecvec (forest, 55, 20002); vecvec (dp, 55, 20001); vecvec (pref, 55, 20002); for(ll i = 1; i <= n; i ++) { cin >> forest[i][1]; pref[i][1] = forest[i][1]; for(ll j = 2; j <= m; j ++) { cin >> forest[i][j]; pref[i][j] = pref[i][j - 1] + forest[i][j]; } } // dp[1][] manually for(ll j = 1; j <= m - k + 1; j ++) dp[1][j] = pref[1][j + k - 1] - pref[1][j - 1] + ((n - 1) ? pref[2][j + k - 1] - pref[2][j - 1] : 0); vec lmax(m - k + 2), rmax(m - k + 2); lmax[1] = dp[1][1]; for(ll j = 2; j <= m - k + 1; j ++) lmax[j] = max(lmax[j - 1], dp[1][j]); rmax[m - k + 1] = dp[1][m - k + 1]; for(ll j = m - k; j >= 1; j --) rmax[j] = max(rmax[j + 1], dp[1][j]); for(ll i = 2; i <= n; i ++) { for(ll j = 1; j <= m - k + 1; j ++) { ll cur = pref[i][j + k - 1] - pref[i][j - 1] + pref[i + 1][j + k - 1] - pref[i + 1][j - 1]; if(j - k >= 1) dp[i][j] = max(dp[i][j], cur + lmax[j - k]); if(j + k <= m - k + 1) dp[i][j] = max(dp[i][j], cur + rmax[j + k]); for(ll p = max(1LL, j - k + 1); p <= min(m - k + 1, j + k - 1); p ++) { ll l, r; ll now = dp[i - 1][p] + pref[i][j + k - 1] - pref[i][j - 1] + pref[i + 1][j + k - 1] - pref[i + 1][j - 1]; l = max(j, p), r = min(j + k - 1, p + k - 1); if(l <= r) now -= pref[i][r] - pref[i][l - 1]; dp[i][j] = max(dp[i][j], now); } } lmax[1] = dp[i][1]; for(ll j = 2; j <= m - k + 1; j ++) lmax[j] = max(lmax[j - 1], dp[i][j]); rmax[m - k + 1] = dp[i][m - k + 1]; for(ll j = m - k; j >= 1; j --) rmax[j] = max(rmax[j + 1], dp[i][j]); } cout << lmax[m - k + 1] << endl; } // There is an idea of a Patrick Bateman. Some kind of abstraction. // But there is no real me. Only an entity. Something illusory. // And though I can hide my cold gaze, and you can shake my hand and // feel flesh gripping yours, and maybe you can even sense our lifestyles // are probably comparable, I simply am not there.
cpp
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
#include<bits/stdc++.h> using namespace std; const int N=1e6+10,R=1e6; const int mod=1e9+7,inf=1e9; void solve() { int n,m; cin>>n>>m; vector<vector<int> >a(n,vector<int>(m)); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cin>>a[i][j]; } } long long ans=0; for(int j=0;j<m;j++){ map<int,int>cnt; for(int i=0;i<n;i++){ if((a[i][j]-j-1)%m==0){ int x=(a[i][j]-j-1)/m; if(x>=0&&x<n){ if(i>=x)cnt[i-x]++; else cnt[i-x+n]++; } } } int tmp=n; for(auto [k,v]:cnt)tmp=min(tmp,(n-v)+k); ans+=tmp; } cout<<ans; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T=1; while(T--) { solve(); } return 0; } /* 99 5 2 3 100 101 6 7 x 5 1 1 x x 1 1 1 1 */
cpp
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
#include<bits/stdc++.h> using namespace std; #define int long long typedef int ll; typedef pair<ll,ll> pi; const int N=2e5+10; pi isinter(pi a,pi b) { if (a.first > b.first)swap(a, b); if (a.first == b.first && b.second >= a.second)swap(a, b); // nested if (a.second >= b.second) { return b; } // inter if (a.second >= b.first) { return {max(a.first, b.first), min(a.second, b.second)}; } return {-1e18, -1}; } void solve() { ll n; pi now; cin >> n >> now.first; now.second = now.first; ll t = 0; bool can = true; for (int i = 0; i < n; ++i) { ll time; pi me, bounds; cin >> time >> me.first >> me.second; bounds.first = now.first - (time - t); bounds.second = now.second + (time - t); pi inter = isinter(bounds, me); if (inter.first == -1e18)can = false; now = {max(bounds.first, me.first), min(bounds.second, me.second)}; t = time; } if (can) { cout << "YES" << endl; } else { cout << "NO" << endl; } } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll t = 1; cin >> t; while (t--) { solve(); } }
cpp
1285
F
F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3 13 35 77 OutputCopy1001InputCopy6 1 2 4 8 16 32 OutputCopy32
[ "binary search", "combinatorics", "number theory" ]
#include <bits/stdc++.h> constexpr int N = 1e5 + 10; signed main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::cin >> n; std::vector<std::vector<int>> divs(N); std::vector<int> mu(N); for (int i = 1; i < N; ++i) { mu[i] += i == 1; divs[i].emplace_back(i); for (int j = i * 2; j < N; j += i) { divs[j].emplace_back(i); mu[j] -= mu[i]; } } std::vector<int> a(N); long long res = 0; for (int i = 1; i <= n; ++i) { int x; std::cin >> x; for (int j : divs[x]) { a[j] = 1; } res = std::max(res, 1LL * x); } std::stack<int> sta; std::vector<int> cnt(N); for (int i = N - 1; i; --i) { if (a[i]) { int sum = 0; for (int j : divs[i]) { sum += mu[j] * cnt[j]; } while (!sta.empty()) { if (sum == 0) { break; } int x = sta.top(); res = std::max(res, 1LL * i * x / std::__gcd(i, x)); for (int j : divs[x]) { --cnt[j]; if (i % j == 0) { sum -= mu[j]; } } sta.pop(); } sta.push(i); for (int j : divs[i]) { ++cnt[j]; } } } std::cout << res << '\n'; }
cpp
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6 -100 -200 -300 125 77 -4 OutputCopy9 InputCopy1000000000000 5 -1 0 0 0 0 OutputCopy4999999999996 InputCopy10 4 -3 -6 5 4 OutputCopy-1
[ "math" ]
#include <bits/stdc++.h> using namespace std; #define int long long #define sz(x) (int)((x).size()) #define all(x) (x).begin(), (x).end() #define db(x) cout << "[" << #x << "]: " << x << '\n'; const int INF = 2e18; struct SegmentTree { int merge(const int& left_child, const int& right_child) { int parent; parent = max(left_child, right_child); return parent; } int n; vector<int> tree; vector<int> a; void initialize(const vector<int>& x) { n = sz(x); tree.resize(4 * n + 1); a.resize(n + 1); for (int i = 0; i < n; ++i) { a[i] = x[i]; } } void build(int id, int id_left, int id_right) { if (id_left == id_right) { tree[id] = a[id_left]; return; } int id_middle = (id_left + id_right) / 2; build(2 * id, id_left, id_middle); build(2 * id + 1, id_middle + 1, id_right); tree[id] = merge(tree[2 * id], tree[2 * id + 1]); } void element_update(int id, int id_left, int id_right, int idx, int value) { if (idx < id_left || idx > id_right) { return; } if (id_left == id_right) { tree[id] = value; return; } int id_middle = (id_left + id_right) / 2; element_update(2 * id, id_left, id_middle, idx, value); element_update(2 * id + 1, id_middle + 1, id_right, idx, value); tree[id] = merge(tree[2 * id], tree[2 * id + 1]); } int query(int id, int id_left, int id_right, int query_left, int query_right) { if (id_right < query_left || id_left > query_right) { return -INF; } if (query_left <= id_left && id_right <= query_right) { return tree[id]; } int id_middle = (id_left + id_right) / 2; return merge(query(2 * id, id_left, id_middle, query_left, query_right), query(2 * id + 1, id_middle + 1, id_right, query_left, query_right)); } void build() { build(1, 0, n - 1); } void element_update(int idx, int value) { element_update(1, 0, n - 1, idx, value); } int query(int query_left, int query_right) { return query(1, 0, n - 1, query_left, query_right); } }; const int N = 2e5 + 2; int a[N], x[N], pfx[N], mx[N]; vector<int> nw; SegmentTree st; int t, n, m, h; void solve() { cin >> h >> n; nw.resize(2 * n); int sum = 0; for (int i = 0; i < n; ++i) { cin >> a[i]; a[i] = -a[i]; pfx[i] = (i == 0 ? a[i] : a[i] + pfx[i - 1]); nw[i] = pfx[i]; mx[i] = (i == 0 ? pfx[i] : max(mx[i - 1], pfx[i])); sum += a[i]; } for (int i = n; i < 2 * n; ++i) { nw[i] = nw[i - 1] + a[i % n]; } st.initialize(nw); st.build(); int cur = pfx[0], pos = 0; for (int i = 1; i < n; ++i) { if (pfx[i] > cur) { cur = pfx[i]; pos = i; } } if (h <= mx[n - 1]) { int l = 0, r = n - 1; while (l < r) { int md = (l + r) / 2; if (mx[md] >= h) { r = md; } else { l = md + 1; } } cout << l + 1; exit(0); } int ans = pos, val = cur, diff = h - cur; if (val < h && sum <= 0) { cout << -1; exit(0); } ans += (diff / sum * n); val += ((diff / sum) * sum); diff %= sum; if (diff == 0) { cout << ans + 1; exit(0); } int left = pos + 1, right = pos + n; int offset = nw[pos]; while (left < right) { int middle = (left + right) / 2; if (st.query(left, middle) - offset >= diff) { right = middle; } else { left = middle + 1; } } cout << ans + (left - pos) + 1; cout << '\n'; } int32_t main() { ios::sync_with_stdio(false); cin.tie(0); solve(); return 0; }
cpp
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
// LUOGU_RID: 102109617 #include <bits/stdc++.h> using i64 = long long; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n, h, l, r; std::cin >> n >> h >> l >> r; std::vector<int> a(n); for (int i = 0; i < n; i++) { std::cin >> a[i]; } std::vector<int> dp(h, -1); dp[0] = 0; for (int i = 0; i < n; i++) { std::vector<int> ndp(h, -1); for (int j = 0; j < h; j++) { if (dp[j] != -1) { for (int x = a[i] - 1; x <= a[i]; x++) { int y = (j + x + h) % h; ndp[y] = std::max(ndp[y], dp[j] + (l <= y && y <= r)); } } } std::swap(ndp, dp); } std::cout << *max_element(dp.begin(), dp.end()) << "\n"; return 0; }
cpp
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
#include <bits/stdc++.h> #define speed ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define pb push_back #define mp make_pair #define f first #define s second using namespace std; const int N = 2001; int n, p, cnt = 0, mx = 0; bool f = 1; int main(){ speed; cin >> n; for(int i = 0;i < n;i++){ int d; cin >> d; if(d == 1){ cnt++; mx = max(mx, cnt); }else{ if(f) p = cnt, f = 0; cnt = 0; } } mx = max(mx, cnt+p); cout << mx; return 0; }
cpp
1301
E
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 OutputCopy16 4 4 4 0 InputCopy6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 OutputCopy36 4 16 16 16 InputCopy8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 OutputCopy64 0 16 4 16 4 36 0 NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.
[ "binary search", "data structures", "dp", "implementation" ]
#include<iostream> #include<cstring> #include<vector> #include<algorithm> using namespace std; using LL = long long; const int maxn = 505; int s[4][maxn][maxn], a[maxn][maxn]; int sum(int s[maxn][maxn], int l1, int r1, int l2, int r2){ return s[l2][r2] - s[l2][r1 - 1] - s[l1 - 1][r2] + s[l1 - 1][r1 - 1]; } template<typename T, bool isMin> struct SparseTable2D{ #define v1 vector<T> #define v2 vector<v1> #define v3 vector<v2> #define v4 vector<v3> int n, m, N, M; v4 f; SparseTable2D(int n, int m) : n(n), m(m), N(__lg(n)), M(__lg(m)) { f = v4(N + 1, v3(M + 1, v2(n + 1, v1(m + 1)))); } SparseTable2D(v2 init) : SparseTable2D((int)init.size(), (int)init[0].size()){ for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) f[0][0][i][j] = init[i - 1][j - 1]; for(int i = 0; i <= N; i++){ for(int j = 0; j <= M; j++){ if (i + j){ for(int a = 1; a + (1 << i) - 1 <= n; a++){ for(int b = 1; b + (1 << j) - 1 <= m; b++){ if (isMin){ if (i) f[i][j][a][b] = min(f[i - 1][j][a][b], f[i - 1][j][a + (1 << (i - 1))][b]); else f[i][j][a][b] = min(f[i][j - 1][a][b], f[i][j - 1][a][b + (1 << (j - 1))]); } else{ if (i) f[i][j][a][b] = max(f[i - 1][j][a][b], f[i - 1][j][a + (1 << (i - 1))][b]); else f[i][j][a][b] = max(f[i][j - 1][a][b], f[i][j - 1][a][b + (1 << (j - 1))]); } } } } } } } T query(int x1, int y1, int x2, int y2){ int k1 = __lg(x2 - x1 + 1); int k2 = __lg(y2 - y1 + 1); x2 = x2 - (1 << k1) + 1; y2 = y2 - (1 << k2) + 1; if (isMin) return min(min(f[k1][k2][x1][y1], f[k1][k2][x1][y2]), min(f[k1][k2][x2][y1], f[k1][k2][x2][y2])); else return max(max(f[k1][k2][x1][y1], f[k1][k2][x1][y2]), max(f[k1][k2][x2][y1], f[k1][k2][x2][y2])); } #undef v1 #undef v2 #undef v3 #undef v4 }; int main(){ #ifdef LOCAL freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif cin.tie(0); cout.tie(0); ios::sync_with_stdio(0); auto get = [](char c){ if (c == 'R') return 0; if (c == 'G') return 1; if (c == 'Y') return 2; return 3; }; int n, m, q; cin >> n >> m >> q; for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++){ char c; cin >> c; a[i][j] = get(c); } for(int x = 0; x < 4; x++) for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) s[x][i][j] = (a[i][j] == x) + s[x][i - 1][j] + s[x][i][j - 1] - s[x][i - 1][j - 1]; auto check = [&](int x, int y, int mid){ if (sum(s[0], x - mid + 1, y - mid + 1, x, y) != mid * mid) return false; if (sum(s[1], x - mid + 1, y + 1, x, y + mid) != mid * mid) return false; if (sum(s[2], x + 1, y - mid + 1, x + mid, y) != mid * mid) return false; if (sum(s[3], x + 1, y + 1, x + mid, y + mid) != mid * mid) return false; return true; }; vector<vector<int> > init(n, vector<int>(m)); for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++){ int l = 0, r = min({i, j, n - i, m - j}); while(l < r){ int mid = (l + r + 1) / 2; if (check(i, j, mid)) l = mid; else r = mid - 1; } init[i - 1][j - 1] = r; } SparseTable2D<int, false> st(init); while(q--){ int l1, r1, l2, r2; cin >> l1 >> r1 >> l2 >> r2; int l = 0, r = min(l2 - l1 + 1, r2 - r1 + 1) / 2; while(l < r){ int mid = (l + r + 1) / 2; if (st.query(l1 + mid - 1, r1 + mid - 1, l2 - mid, r2 - mid) >= mid) l = mid; else r = mid - 1; } cout << 4 * r * r << '\n'; } }
cpp
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
// LUOGU_RID: 102570642 #include <bits/stdc++.h> using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; const LL mod = 1e9 + 7; const int N = 100005; int a[N]; int main() { int _; cin >> _; while (_--) { int n, m; cin >> n >> m; int mx = 0; int ok = 0; for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i] == m) ok = 1; mx = max(mx, a[i]); } int ans = max(2, (m + mx - 1) / mx); if (ok) ans = 1; cout << ans << endl; } return 0; }
cpp
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
#include<iostream> using namespace std; int main() { int n,i; cin>>n; if(n%2) { cout<<"NO"<<endl; return 0; } pair<int,int>a[n],p,temp; for(i=0;i<n;i++)cin>>a[i].first>>a[i].second; p={a[0].first+a[n/2].first,a[0].second+a[n/2].second}; for(i=1;i<n/2;i++){temp={a[i].first+a[i+n/2].first,a[i].second+a[i+n/2].second};if(p!=temp){cout<<"NO"<<endl;return 0;}} cout<<"YES"<<endl; }
cpp
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
#include <bits/stdc++.h> #define Source ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL); #define ll long long #define int long long #define ld long double #define Endl '\n' //#define t int t;cin>>t;while(t--) #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define sz(a) (int)(a).size() using namespace std; const int N = 2e5 + 5; const ll mod = 1e9 + 7; int dx[] = {+0, +0, +1, -1, -1, +1, -1, +1}; int dy[] = {+1, -1, +0, +0, +1, -1, -1, +1}; void testCase(int cs) { string s; cin >> s; vector<int>freq(26); vector<vector<int>>v(26,vector<int>(26)); for (int i = 0; i < sz(s); ++i) { for (int j = 0; j < 26; ++j) { v[s[i] - 'a'][j] += freq[j]; } freq[s[i] - 'a']++; } int ans = 0; for (int i = 0; i < 26; ++i) { ans = max(ans, freq[i]); } for (int i = 0; i < 26; ++i) { for (int j = 0; j < 26; ++j) { ans = max(ans, v[i][j]); } } cout << ans << endl; } signed main() { // files(); Source ll t = 1; int cs = 0; // cin >> t; while (t--) { testCase(++cs); } return 0; }
cpp
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
#include<bits/stdc++.h> using namespace std; const int maxn=1e4+10; int arr[maxn]; int main(){ int t; cin>>t; while(t--){ int n,m,k; cin>>n>>m>>k; for(int i=1;i<=n;++i) cin>>arr[i]; if(k>=m) k=m-1; int ans=-1,len1=n-k,len2=len1-(m-k-1); for(int i=1;i<=k+1;++i){ int tmp=0x3f3f3f3f; for(int j=i;j<=i+m-k-1;++j) tmp=min(tmp,max(arr[j],arr[j+len2-1])); ans=max(ans,tmp); } cout<<ans<<endl; } return 0; }
cpp
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define mod 1000000007 int main(){ ios_base::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); int T=1; cin>>T; while(T--) { int ans=0,dis=1; string s; cin>>s; char c; for(int i=0;i<s.size();i++){ if(s[i]=='L'){ dis++; } else{ ans=max(ans,dis); dis=1; c=i; } } ans=max(ans,dis); cout<<ans<<'\n'; } return 0; }
cpp
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2 1 4 4 3 3 5 3 6 5 2 OutputCopy2 1 2 1 1 2 InputCopy4 2 3 1 1 4 1 2 OutputCopy1 1 1 1 InputCopy10 2 10 3 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 OutputCopy3 1 1 2 3 2 3 1 3 1
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
#include<bits/stdc++.h> #define ll long long int #define pa pair<int,int> #define f first #define s second #define sz 200005 #define vec array<int,4> using namespace std; std::vector<int> adj[sz]; int deg[sz],ans[sz],deg1[sz]; int r; map<pa,int>mp; void solve(int node,int par,int clr) { for(int u:adj[node]) { if(u == par) continue; clr = (clr%r)+1; ans[mp[{node,u}]] = (clr)%r+1; solve(u,node,clr); } return; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int test_case = 1; //cin >> test_case; for(int cs = 1;cs <= test_case; cs++) { int n,k; cin >> n >> k; for(int i = 1;i<n;i++) { int a,b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); deg[a]++; deg[b]++; mp[{a,b}]=mp[{b,a}] = i; } for(int i = 1;i<=n;i++) deg1[deg[i]]++; for(int i = n;i >= 1; i--) { deg1[i] += deg1[i+1]; if(deg1[i] <= k) r = i-1; } solve(1,0,0); cout << r <<"\n"; for(int i = 1;i<n;i++) cout << ans[i] <<" "; cout <<"\n"; } return 0; }
cpp
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
#include<bits/stdc++.h> #define ll long long int #define pii pair<ll,ll> using namespace std ; void solve() { ll n,g,b ; cin>>n>>g>>b ; // ll good_days = n/2/g*g + (ll)(ceil(n/2.0) - n/2/g*g); // ll bad_days = ((n/2/g-1)*b) + (ceil(n/2.0) - n/2/g*g != 0 ? b : 0); // ll rem_days = max(0LL,(n-good_days-bad_days)) ; // cout<<good_days+bad_days+rem_days<<endl; // cout<<good_days<<" "<<bad_days<<endl; ll need = (n+1)/2 ; ll total = need/g*(g+b) ; if(need%g == 0) total-=b ; else total+=(need%g) ; cout<<max(n,total)<<endl; } int main(){ ios::sync_with_stdio(0); cin.tie(0); ll T ; cin>>T ; while(T--){ solve() ; } } bool isPowerOfTwo (int x) { return x && (!(x&(x-1))); }
cpp
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; int main() { int num,t; int a[2][1000]; scanf("%d",&t); while(t--) { scanf("%d",&num); for(int j=0;j<2;j++) for(int i=0;i<num;i++) { scanf("%d",&a[j][i]); } sort(a[0],a[0]+num); sort(a[1],a[1]+num); for(int j=0;j<2;j++) { for(int i=0;i<num;i++) { printf(i!=num-1?"%d ":"%d\n",a[j][i]); } } } }
cpp
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; int main() { int64_t x0, y0, ax, ay, bx, by, xs, ys, t; cin >> x0 >> y0 >> ax >> ay >> bx >> by; cin >> xs >> ys >> t; vector<int64_t> x(1, x0), y(1, y0); int64_t LIMIT = (1LL << 62) - 1; while ((LIMIT - bx) / ax >= x.back() && (LIMIT - by) / ay >= y.back()) { x.push_back(ax * x.back() + bx); y.push_back(ay * y.back() + by); } int n = x.size(); int ans = 0; for (int i=0; i<n; i++) { for (int j=i; j<n; j++) { int64_t length = x[j] - x[i] + y[j] - y[i]; int64_t d2l = abs(xs - x[i]) + abs(ys - y[i]); int64_t d2r = abs(xs - x[j]) + abs(ys - y[j]); if (length <= t - min(d2l, d2r)) ans = max(ans, j-i+1); } } cout << ans << endl; }
cpp
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 OutputCopy2 -1 0
[ "bitmasks", "greedy" ]
#include <bits/stdc++.h> #define N 100005 #define wr cout << "Continue debugging\n"; #define all(x) (x).begin(), (x).end() #define ll long long int #define pii pair <int, int> #define pb push_back #define ff first #define ss second using namespace std; int t, cnt[N]; int logs(int x){ int res = 0; while(x > 1){ res++; x /= 2; } return res; } ll powd(int x, int y){ ll res = 1; while(y--){ res *= x; } return res; } int main () { ios::sync_with_stdio(false); cin.tie(0); cin >> t; while (t--){ ll n, m; cin >> n >> m; for (int i = 0; i <= 30; i++){ cnt[i]=0; } for (int i = 1; i <= m; i++){ int x; cin >> x; cnt[logs(x)]++; } ll ans = 0; int res = 0; bool tr = 0; while(n){ if (n%2){ ll x = powd(2, res); for (int i = 30; i >= 0; i--){ ll cur = 0; while(cnt[i] > 0 and x > cur){ cnt[i]--; cur += powd(2, i); } if (x < cur){ cur -= powd(2, i); cnt[i]++; } x -= cur; } if (x){ int idx = -1; for (int i = res+1; i <= 30; i++){ if (cnt[i]){ idx = i; break; } } if (idx == -1){ tr = 1; break; } ans += idx-res; cnt[idx]--; for (int i = idx-1; i >= res; i--){ cnt[i]++; } } } n /= 2; res++; } if (tr) ans = -1; cout << ans << '\n'; } }
cpp
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8 ))((())( OutputCopy6 InputCopy3 (() OutputCopy-1 NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.
[ "greedy" ]
/* God loves You */ #include<bits/stdc++.h> using namespace std; #define Sowrav_Nath ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define f(i,n) for(int i=0;i<int(n);i++) #define f1(i,n) for(int i=1;i<=n;i++) #define rf(i,n) for(int i=int(n)-1;i>=0;i--) #define rf1(i,n) for(int i = n;i>=1;i--) #define saisir(v,x) int x; cin>>x; v.push_back(x); #define le_debut int main #define lol long long int #define endl '\n' #define pb push_back #define un first #define deux second #define oui cout<<"YES"<<endl #define non cout<<"NO"<<endl #define homme cout<<"Bob"<<endl #define femme cout<<"Alice"<<endl #define un_de_minus cout<<"-1"<<endl #define duck cout<<0<<endl; #define reponse cout<<ans<<endl #define ici cout<<"Je suis ici"<<endl const int N = 2*1e5+10; const int M = 1e9+7; void allons_y(){ int n; cin >> n; string s; cin >> s; vector<int>a; int res = 0, ans = 0; f(i,n){ if(s[i] == '(') res++; if(s[i] == ')') res--; while(res < 0 && i < n){ i++; if(s[i] == ')') res--; else { res++; ans += 2; } // cout << res << endl; } // cout << res << " " << i << endl; } res == 0 ? reponse : un_de_minus ; } le_debut(){ Sowrav_Nath int t; t = 1; // cin >> t; while(t--){ // memset(dp,0,sizeof(dp)); allons_y(); } }
cpp
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza OutputCopyYES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO
[ "dfs and similar", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define ll long long ll N = 1000000007; // int dp[200001]; string func(int i,vector<vector<int>> &adj,int pr){ string str=""; str.push_back('a'+i); for(auto ch:adj[i]){ if(ch==pr)continue; str=str+func(ch,adj,i); } return str; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout<<fixed; cout<<setprecision(10); int t; cin>>t; while(t--){ vector<vector<int>> adj(27); string str; cin>>str; vector<bool> present(26,false); vector<vector<int>> vist(26,vector<int>(26,false)); for(int i=0;i<str.size()-1;i++){ int a=str[i]-'a'; int b=str[i+1]-'a'; present[a]=true; present[b]=true; if(vist[a][b])continue; else{ vist[a][b]=true; vist[b][a]=true; adj[a].push_back(b); adj[b].push_back(a); } } int d1=0; int d2=0; int idx=-1; bool flag=true; for(int i=0;i<26;i++){ if(adj[i].size()==0)continue; if(adj[i].size()==2)d2++; else if(adj[i].size()==1){ d1++; idx=i; } else { flag=false; break; } } if(str.size()==1){ d1=2; idx=str[0]-'a'; present[idx]=true; } if(flag && d1==2){ cout<<"YES"<<endl; string str=func(idx,adj,-1); for(int i=0;i<26;i++){ if(!present[i])str.push_back('a'+i); } cout<<str<<endl; }else cout<<"NO"<<endl; } return 0; }
cpp
1287
A
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1 4 PPAP OutputCopy1 InputCopy3 12 APPAPPPAPPPP 3 AAP 3 PPA OutputCopy4 1 0 NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.
[ "greedy", "implementation" ]
#include <bits/stdc++.h> #define ll long long using namespace std; int main() { ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); int t; cin >> t; while(t--){ int n; string s; cin >> n >> s; int cnt = 0; int res = 0; for(int i = n - 1; i >= 0; --i){ if(s[i] == 'P'){ cnt++; } else{ res = max(res, cnt); cnt = 0; } } cout << res << "\n"; } return 0; }
cpp
1290
E
E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5 2 4 1 5 3 OutputCopy1 3 6 8 11 InputCopy6 1 2 4 5 6 3 OutputCopy1 3 6 8 12 17 NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11.
[ "data structures" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define N 200010 #define inf (1e9) ll n; ll a[N]; ll ans[N]; ll pos[N]; struct sgt{ ll sum[N<<2],tag1[N<<2],tag2[N<<2],mx[N<<2],smx[N<<2],cn[N<<2],cnmx[N<<2]; inline void pushup(ll x){ sum[x]=sum[x<<1]+sum[x<<1|1]; cn[x]=cn[x<<1]+cn[x<<1|1]; if(mx[x<<1]==mx[x<<1|1]){ smx[x]=max(smx[x<<1],smx[x<<1|1]); mx[x]=mx[x<<1]; cnmx[x]=cnmx[x<<1]+cnmx[x<<1|1]; } if(mx[x<<1]<mx[x<<1|1]){ mx[x]=mx[x<<1|1]; smx[x]=max(mx[x<<1],smx[x<<1|1]); cnmx[x]=cnmx[x<<1|1]; } if(mx[x<<1]>mx[x<<1|1]){ mx[x]=mx[x<<1]; smx[x]=max(mx[x<<1|1],smx[x<<1]); cnmx[x]=cnmx[x<<1]; } return ; } inline void pushdown(ll x){ if(tag1[x]){ ll u=tag1[x]; if(mx[x<<1]==mx[x<<1|1]){ mx[x<<1]+=u;mx[x<<1|1]+=u; sum[x<<1]+=u*(cnmx[x<<1]);sum[x<<1|1]+=u*(cnmx[x<<1|1]); tag1[x<<1]+=u;tag1[x<<1|1]+=u; }else{ if(mx[x<<1]<mx[x<<1|1]){ mx[x<<1|1]+=u; sum[x<<1|1]+=u*(cnmx[x<<1|1]); tag1[x<<1|1]+=u; }else{ mx[x<<1]+=u; sum[x<<1]+=u*(cnmx[x<<1]); tag1[x<<1]+=u; } } tag1[x]=0; } if(tag2[x]){ ll u=tag2[x]; if(mx[x<<1]==mx[x<<1|1]){ smx[x<<1]+=u;smx[x<<1|1]+=u; sum[x<<1]+=u*(cn[x<<1]-cnmx[x<<1]);sum[x<<1|1]+=u*(cn[x<<1|1]-cnmx[x<<1|1]); tag2[x<<1]+=u;tag2[x<<1|1]+=u; }else{ if(mx[x<<1]<mx[x<<1|1]){ mx[x<<1]+=u; smx[x<<1]+=u;smx[x<<1|1]+=u; sum[x<<1]+=u*(cn[x<<1]);sum[x<<1|1]+=u*(cn[x<<1|1]-cnmx[x<<1|1]); tag2[x<<1]+=u;tag1[x<<1]+=u;tag2[x<<1|1]+=u; }else{ mx[x<<1|1]+=u; smx[x<<1]+=u;smx[x<<1|1]+=u; sum[x<<1]+=u*(cn[x<<1]-cnmx[x<<1]);sum[x<<1|1]+=u*(cn[x<<1|1]); tag2[x<<1]+=u;tag2[x<<1|1]+=u;tag1[x<<1|1]+=u; } } tag2[x]=0; }return ; } inline void update(ll o,ll l,ll r,ll x,ll y,ll z){ if(x<=l&&r<=y){ if(mx[o]<=z)return ; if(z>smx[o]){ sum[o]+=(z-mx[o])*cnmx[o]; tag1[o]+=(z-mx[o]);mx[o]=z; return ; } }pushdown(o); ll mid=(l+r)>>1; if(mid>=x)update(o<<1,l,mid,x,y,z); if(mid<y)update(o<<1|1,mid+1,r,x,y,z); pushup(o); return ; } inline void upd(ll o,ll l,ll r,ll x,ll y){ if(l==r){ sum[o]=mx[o]=y; smx[o]=-inf;cn[o]=cnmx[o]=1; return ; }pushdown(o); ll mid=(l+r)>>1; if(mid>=x)upd(o<<1,l,mid,x,y); else upd(o<<1|1,mid+1,r,x,y); pushup(o); return ; } inline void add(ll o,ll l,ll r,ll x,ll y){ if(x<=l&&r<=y){ sum[o]+=cn[o];mx[o]++;smx[o]++; tag1[o]++;tag2[o]++; return ; } pushdown(o); ll mid=(l+r)>>1; if(mid>=x)add(o<<1,l,mid,x,y); if(mid<y)add(o<<1|1,mid+1,r,x,y); pushup(o); return ; } inline ll ask(ll o,ll l,ll r,ll x,ll y){ if(x>y)return 0; if(x<=l&&r<=y)return cn[o]; pushdown(o); ll an=0;ll mid=(l+r)>>1; if(mid>=x)an+=ask(o<<1,l,mid,x,y); if(mid<y)an+=ask(o<<1|1,mid+1,r,x,y); return an; } inline void build(ll o,ll l,ll r){ sum[o]=tag1[o]=tag2[o]=mx[o]=smx[o]=cn[o]=cnmx[o]=0; if(l==r)return ; ll mid=(l+r)>>1; build(o<<1,l,mid);build(o<<1|1,mid+1,r); return ; } }g; inline void suan(){ for(int i=1;i<=n;i++)pos[a[i]]=i; g.build(1,1,n); for(int i=1;i<=n;i++){ ll o=pos[i]; ll p=g.ask(1,1,n,1,o-1); if(o>1)g.update(1,1,n,1,o-1,p+1); if(o<n)g.add(1,1,n,o+1,n); g.upd(1,1,n,o,i+1); ans[i]+=g.sum[1]; }return ; } int main() { // freopen("test1.in","r",stdin); //freopen(".in","r",stdin); //freopen("test1.out","w",stdout); ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n;for(int i=1;i<=n;i++)cin>>a[i]; suan(); reverse(a+1,a+n+1); suan(); for(int i=1;i<=n;i++)cout<<ans[i]-1ll*i*(i+2)<<'\n'; return 0; }
cpp
1324
A
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4 3 1 1 3 4 1 1 2 1 2 11 11 1 100 OutputCopyYES NO YES YES NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.
[ "implementation", "number theory" ]
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,i,even=0,odd=0; cin>>n; int a[n]; for( i=0;i<n;i++) cin>>a[i]; for(i=0;i<n;i++) { if(a[i]%2==0) even=1; else odd=1; } if(even+odd==1) cout<<"YES"<<endl; else cout<<"NO"<<endl; } }
cpp
1320
E
E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7 1 2 1 3 2 4 2 5 3 6 3 7 3 2 2 4 1 7 1 1 3 2 2 4 3 7 1 1 3 3 3 1 1 4 100 7 100 1 2 3 OutputCopy1 2 1 1 1 1 1
[ "data structures", "dfs and similar", "dp", "shortest paths", "trees" ]
#include<bits/stdc++.h> using namespace std; #define X first #define Y second #define int long long #define sz(a) (int)a.size() #define ll long long const int N = 2e5; const int T = 20; int n, q; vector <int> g[N]; vector <pair <int, int> > g1[N]; int h[N]; int used[N]; int up[T][N]; int tin[N], tout[N]; int timer = 0; bool pred(int a, int b) { return tin[a] <= tin[b] && tout[a] >= tout[b]; } int lca(int a, int b) { if(pred(a, b)) { return a; } for(int j = T - 1; j >= 0; j--) { if(!pred(up[j][a], b)) { a = up[j][a]; } } return up[0][a]; } void dfs(int v, int p = -1) { tin[v] = timer++; for(auto to : g[v]) { if(to == p) { continue; } h[to] = h[v] + 1; up[0][to] = v; dfs(to, v); } tout[v] = timer++; } bool cmp1(int a, int b) { return tin[a] < tin[b]; } int num[N]; int ans_node[N]; pair <int, int> dp_down[N], dp_up[N]; int s[N]; bool cmp(pair <int, int> a, pair <int, int> b) { if(a.X == -1) { return 0; } if(b.X == -1) { return 1; } int k1 = (a.Y + s[a.X] - 1) / s[a.X]; int k2 = (b.Y + s[b.X] - 1) / s[b.X]; if(k1 == k2) { return a.X < b.X; } return k1 < k2; } pair <int, int> best(pair <int, int> a, pair <int, int> b, pair <int, int> c) { if(cmp(a, b) && cmp(a, c)) { return a; } if(cmp(b, a) && cmp(b, c)) { return b; } return c; } void dfs_calc_down(int v) { dp_down[v] = {-1, -1}; for(auto to : g1[v]) { // cout << to.X << '\n'; dfs_calc_down(to.X); pair <int, int> p = dp_down[to.X]; p.Y += to.Y; if(cmp(p, dp_down[v])) { dp_down[v] = p; } } if(used[v] && cmp({used[v] - 1, 0}, dp_down[v])) { dp_down[v] = {used[v] - 1, 0}; } } void dfs_calc_up(int v) { vector <pair <int, int> > pref(sz(g1[v]) + 1, {-1, -1}), suf(sz(g1[v]) + 1, {-1, -1}); for(int i = 0; i < sz(g1[v]); i++) { int to = g1[v][i].X; pair <int, int> p = dp_down[to]; p.Y += g1[v][i].Y; if(cmp(p, pref[i])) { pref[i + 1] = p; } else { pref[i + 1] = pref[i]; } } for(int i = sz(g1[v]) - 1; i >= 0; i--) { int to = g1[v][i].X; pair <int, int> p = dp_down[to]; p.Y += g1[v][i].Y; if(cmp(p, suf[i + 1])) { suf[i] = p; } else { suf[i] = suf[i + 1]; } } if(used[v] && cmp({used[v] - 1, 0}, dp_up[v])) { dp_up[v] = {used[v] - 1, 0}; } if(cmp(dp_down[v], dp_up[v])) { ans_node[v] = dp_down[v].X; } else { ans_node[v] = dp_up[v].X; } for(int i = 0; i < sz(g1[v]); i++) { int to = g1[v][i].X; pair <int, int> p = dp_up[v]; pair <int, int> p1 = pref[i]; pair <int, int> p2 = suf[i + 1]; dp_up[to] = best(p, p1, p2); dp_up[to].Y += g1[v][i].Y; } for(auto to : g1[v]) { dfs_calc_up(to.X); } } vector <int> vertex; int go_to(int l, int r) { if(l == r) { return vertex[l]; } int a = lca(vertex[l], vertex[r]); int l1 = l, r1 = r; while(r1 - l1 > 1) { int midd1 = (l1 + r1) / 2; if(lca(vertex[l], vertex[midd1]) != a) { l1 = midd1; } else { r1 = midd1; } } int b = go_to(l, l1); int c = go_to(l1 + 1, r); if(b != a) { g1[a].push_back({b, h[b] - h[a]}); } if(c != a) { g1[a].push_back({c, h[c] - h[a]}); } vertex.push_back(a); return a; } signed main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); cin >> n; for(int i = 0; i < n - 1; i++) { int a, b; cin >> a >> b; a--; b--; g[a].push_back(b); g[b].push_back(a); } dfs(0); for(int j = 1; j < T; j++) { for(int i = 0; i < n; i++) { up[j][i] = up[j - 1][up[j - 1][i]]; } } cin >> q; while(q--) { int k, m; cin >> k >> m; set <pair <int, int> > st; vector <int> ver1(k), ver2(m); vertex.clear(); for(int i = 0; i < k; i++) { cin >> ver1[i]; ver1[i]--; cin >> s[i]; vertex.push_back(ver1[i]); } for(int i = 0; i < m; i++) { cin >> ver2[i]; ver2[i]--; vertex.push_back(ver2[i]); } sort(vertex.begin(), vertex.end(), cmp1); int lst = go_to(0, sz(vertex) - 1); for(int i = 0; i < sz(ver1); i++) { num[ver1[i]] = i; used[ver1[i]] = i + 1; } for(auto v : vertex) { dp_down[v] = dp_up[v] = {-1, -1}; } dfs_calc_down(lst); dfs_calc_up(lst); for(auto i : vertex) { g1[i].clear(); } for(auto v : ver2) { cout << 1 + ans_node[v] << " "; } for(auto v : vertex) { used[v] = num[v] = 0; } cout << "\n"; } return 0; }
cpp
1286
D
D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2 1 1 100 3 1 0 OutputCopy1 InputCopy3 7 10 0 9 4 86 14 5 100 OutputCopy0 InputCopy4 6 4 50 11 25 50 13 16 50 15 8 50 OutputCopy150902884
[ "data structures", "math", "matrices", "probabilities" ]
// LUOGU_RID: 97675100 #include <bits/stdc++.h> #include <utility> namespace atcoder { namespace internal { // @param m `1 <= m` // @return x mod m constexpr long long safe_mod(long long x, long long m) { x %= m; if (x < 0) x += m; return x; } // Fast modular multiplication by barrett reduction // Reference: https://en.wikipedia.org/wiki/Barrett_reduction // NOTE: reconsider after Ice Lake struct barrett { unsigned int _m; unsigned long long im; // @param m `1 <= m < 2^31` barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {} // @return m unsigned int umod() const { return _m; } // @param a `0 <= a < m` // @param b `0 <= b < m` // @return `a * b % m` unsigned int mul(unsigned int a, unsigned int b) const { // [1] m = 1 // a = b = im = 0, so okay // [2] m >= 2 // im = ceil(2^64 / m) // -> im * m = 2^64 + r (0 <= r < m) // let z = a*b = c*m + d (0 <= c, d < m) // a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im // c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1) < 2^64 * 2 // ((ab * im) >> 64) == c or c + 1 unsigned long long z = a; z *= b; #ifdef _MSC_VER unsigned long long x; _umul128(z, im, &x); #else unsigned long long x = (unsigned long long)(((unsigned __int128)(z)*im) >> 64); #endif unsigned int v = (unsigned int)(z - x * _m); if (_m <= v) v += _m; return v; } }; // @param n `0 <= n` // @param m `1 <= m` // @return `(x ** n) % m` constexpr long long pow_mod_constexpr(long long x, long long n, int m) { if (m == 1) return 0; unsigned int _m = (unsigned int)(m); unsigned long long r = 1; unsigned long long y = safe_mod(x, m); while (n) { if (n & 1) r = (r * y) % _m; y = (y * y) % _m; n >>= 1; } return r; } // Reference: // M. Forisek and J. Jancina, // Fast Primality Testing for Integers That Fit into a Machine Word // @param n `0 <= n` constexpr bool is_prime_constexpr(int n) { if (n <= 1) return false; if (n == 2 || n == 7 || n == 61) return true; if (n % 2 == 0) return false; long long d = n - 1; while (d % 2 == 0) d /= 2; constexpr long long bases[3] = {2, 7, 61}; for (long long a : bases) { long long t = d; long long y = pow_mod_constexpr(a, t, n); while (t != n - 1 && y != 1 && y != n - 1) { y = y * y % n; t <<= 1; } if (y != n - 1 && t % 2 == 0) { return false; } } return true; } template <int n> constexpr bool is_prime = is_prime_constexpr(n); // @param b `1 <= b` // @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g constexpr std::pair<long long, long long> inv_gcd(long long a, long long b) { a = safe_mod(a, b); if (a == 0) return {b, 0}; // Contracts: // [1] s - m0 * a = 0 (mod b) // [2] t - m1 * a = 0 (mod b) // [3] s * |m1| + t * |m0| <= b long long s = b, t = a; long long m0 = 0, m1 = 1; while (t) { long long u = s / t; s -= t * u; m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b // [3]: // (s - t * u) * |m1| + t * |m0 - m1 * u| // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u) // = s * |m1| + t * |m0| <= b auto tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp; } // by [3]: |m0| <= b/g // by g != b: |m0| < b/g if (m0 < 0) m0 += b / s; return {s, m0}; } // Compile time primitive root // @param m must be prime // @return primitive root (and minimum in now) constexpr int primitive_root_constexpr(int m) { if (m == 2) return 1; if (m == 167772161) return 3; if (m == 469762049) return 3; if (m == 754974721) return 11; if (m == 998244353) return 3; int divs[20] = {}; divs[0] = 2; int cnt = 1; int x = (m - 1) / 2; while (x % 2 == 0) x /= 2; for (int i = 3; (long long)(i)*i <= x; i += 2) { if (x % i == 0) { divs[cnt++] = i; while (x % i == 0) { x /= i; } } } if (x > 1) { divs[cnt++] = x; } for (int g = 2;; g++) { bool ok = true; for (int i = 0; i < cnt; i++) { if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) { ok = false; break; } } if (ok) return g; } } template <int m> constexpr int primitive_root = primitive_root_constexpr(m); } // namespace internal } // namespace atcoder #include <cassert> #include <numeric> #include <type_traits> namespace atcoder { namespace internal { #ifndef _MSC_VER template <class T> using is_signed_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int128 = typename std::conditional<std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type; template <class T> using make_unsigned_int128 = typename std::conditional<std::is_same<T, __int128_t>::value, __uint128_t, unsigned __int128>; template <class T> using is_integral = typename std::conditional<std::is_integral<T>::value || is_signed_int128<T>::value || is_unsigned_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using is_signed_int = typename std::conditional<(is_integral<T>::value && std::is_signed<T>::value) || is_signed_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int = typename std::conditional<(is_integral<T>::value && std::is_unsigned<T>::value) || is_unsigned_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using to_unsigned = typename std::conditional< is_signed_int128<T>::value, make_unsigned_int128<T>, typename std::conditional<std::is_signed<T>::value, std::make_unsigned<T>, std::common_type<T>>::type>::type; #else template <class T> using is_integral = typename std::is_integral<T>; template <class T> using is_signed_int = typename std::conditional<is_integral<T>::value && std::is_signed<T>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int = typename std::conditional<is_integral<T>::value && std::is_unsigned<T>::value, std::true_type, std::false_type>::type; template <class T> using to_unsigned = typename std::conditional<is_signed_int<T>::value, std::make_unsigned<T>, std::common_type<T>>::type; #endif template <class T> using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>; template <class T> using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>; template <class T> using to_unsigned_t = typename to_unsigned<T>::type; } // namespace internal } // namespace atcoder #include <cassert> #include <numeric> #include <type_traits> #ifdef _MSC_VER #include <intrin.h> #endif namespace atcoder { namespace internal { struct modint_base {}; struct static_modint_base : modint_base {}; template <class T> using is_modint = std::is_base_of<modint_base, T>; template <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>; } // namespace internal template <int m, std::enable_if_t<(1 <= m)>* = nullptr> struct static_modint : internal::static_modint_base { using mint = static_modint; public: static constexpr int mod() { return m; } static mint raw(int v) { mint x; x._v = v; return x; } static_modint() : _v(0) {} template <class T, internal::is_signed_int_t<T>* = nullptr> static_modint(T v) { long long x = (long long)(v % (long long)(umod())); if (x < 0) x += umod(); _v = (unsigned int)(x); } template <class T, internal::is_unsigned_int_t<T>* = nullptr> static_modint(T v) { _v = (unsigned int)(v % umod()); } static_modint(bool v) { _v = ((unsigned int)(v) % umod()); } unsigned int val() const { return _v; } mint& operator++() { _v++; if (_v == umod()) _v = 0; return *this; } mint& operator--() { if (_v == 0) _v = umod(); _v--; return *this; } mint operator++(int) { mint result = *this; ++*this; return result; } mint operator--(int) { mint result = *this; --*this; return result; } mint& operator+=(const mint& rhs) { _v += rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator-=(const mint& rhs) { _v -= rhs._v; if (_v >= umod()) _v += umod(); return *this; } mint& operator*=(const mint& rhs) { unsigned long long z = _v; z *= rhs._v; _v = (unsigned int)(z % umod()); return *this; } mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); } mint operator+() const { return *this; } mint operator-() const { return mint() - *this; } mint pow(long long n) const { assert(0 <= n); mint x = *this, r = 1; while (n) { if (n & 1) r *= x; x *= x; n >>= 1; } return r; } mint inv() const { if (prime) { assert(_v); return pow(umod() - 2); } else { auto eg = internal::inv_gcd(_v, m); assert(eg.first == 1); return eg.second; } } friend mint operator+(const mint& lhs, const mint& rhs) { return mint(lhs) += rhs; } friend mint operator-(const mint& lhs, const mint& rhs) { return mint(lhs) -= rhs; } friend mint operator*(const mint& lhs, const mint& rhs) { return mint(lhs) *= rhs; } friend mint operator/(const mint& lhs, const mint& rhs) { return mint(lhs) /= rhs; } friend bool operator==(const mint& lhs, const mint& rhs) { return lhs._v == rhs._v; } friend bool operator!=(const mint& lhs, const mint& rhs) { return lhs._v != rhs._v; } private: unsigned int _v; static constexpr unsigned int umod() { return m; } static constexpr bool prime = internal::is_prime<m>; }; template <int id> struct dynamic_modint : internal::modint_base { using mint = dynamic_modint; public: static int mod() { return (int)(bt.umod()); } static void set_mod(int m) { assert(1 <= m); bt = internal::barrett(m); } static mint raw(int v) { mint x; x._v = v; return x; } dynamic_modint() : _v(0) {} template <class T, internal::is_signed_int_t<T>* = nullptr> dynamic_modint(T v) { long long x = (long long)(v % (long long)(mod())); if (x < 0) x += mod(); _v = (unsigned int)(x); } template <class T, internal::is_unsigned_int_t<T>* = nullptr> dynamic_modint(T v) { _v = (unsigned int)(v % mod()); } dynamic_modint(bool v) { _v = ((unsigned int)(v) % mod()); } unsigned int val() const { return _v; } mint& operator++() { _v++; if (_v == umod()) _v = 0; return *this; } mint& operator--() { if (_v == 0) _v = umod(); _v--; return *this; } mint operator++(int) { mint result = *this; ++*this; return result; } mint operator--(int) { mint result = *this; --*this; return result; } mint& operator+=(const mint& rhs) { _v += rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator-=(const mint& rhs) { _v += mod() - rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator*=(const mint& rhs) { _v = bt.mul(_v, rhs._v); return *this; } mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); } mint operator+() const { return *this; } mint operator-() const { return mint() - *this; } mint pow(long long n) const { assert(0 <= n); mint x = *this, r = 1; while (n) { if (n & 1) r *= x; x *= x; n >>= 1; } return r; } mint inv() const { auto eg = internal::inv_gcd(_v, mod()); assert(eg.first == 1); return eg.second; } friend mint operator+(const mint& lhs, const mint& rhs) { return mint(lhs) += rhs; } friend mint operator-(const mint& lhs, const mint& rhs) { return mint(lhs) -= rhs; } friend mint operator*(const mint& lhs, const mint& rhs) { return mint(lhs) *= rhs; } friend mint operator/(const mint& lhs, const mint& rhs) { return mint(lhs) /= rhs; } friend bool operator==(const mint& lhs, const mint& rhs) { return lhs._v == rhs._v; } friend bool operator!=(const mint& lhs, const mint& rhs) { return lhs._v != rhs._v; } private: unsigned int _v; static internal::barrett bt; static unsigned int umod() { return bt.umod(); } }; template <int id> internal::barrett dynamic_modint<id>::bt = 998244353; using modint998244353 = static_modint<998244353>; using modint1000000007 = static_modint<1000000007>; using modint = dynamic_modint<-1>; namespace internal { template <class T> using is_static_modint = std::is_base_of<internal::static_modint_base, T>; template <class T> using is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>; template <class> struct is_dynamic_modint : public std::false_type {}; template <int id> struct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {}; template <class T> using is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>; } // namespace internal } // namespace atcoder #include <algorithm> #ifdef _MSC_VER #include <intrin.h> #endif namespace atcoder { namespace internal { // @param n `0 <= n` // @return minimum non-negative `x` s.t. `n <= 2**x` int ceil_pow2(int n) { int x = 0; while ((1U << x) < (unsigned int)(n)) x++; return x; } // @param n `1 <= n` // @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0` int bsf(unsigned int n) { #ifdef _MSC_VER unsigned long index; _BitScanForward(&index, n); return index; #else return __builtin_ctz(n); #endif } } // namespace internal } // namespace atcoder #include <cassert> #include <vector> namespace atcoder { template <class S, S (*op)(S, S), S (*e)()> struct segtree { public: segtree() : segtree(0) {} segtree(int n) : segtree(std::vector<S>(n, e())) {} segtree(const std::vector<S>& v) : _n(int(v.size())) { log = internal::ceil_pow2(_n); size = 1 << log; d = std::vector<S>(2 * size, e()); for (int i = 0; i < _n; i++) d[size + i] = v[i]; for (int i = size - 1; i >= 1; i--) { update(i); } } void set(int p, S x) { assert(0 <= p && p < _n); p += size; d[p] = x; for (int i = 1; i <= log; i++) update(p >> i); } S get(int p) { assert(0 <= p && p < _n); return d[p + size]; } S prod(int l, int r) { assert(0 <= l && l <= r && r <= _n); S sml = e(), smr = e(); l += size; r += size; while (l < r) { if (l & 1) sml = op(sml, d[l++]); if (r & 1) smr = op(d[--r], smr); l >>= 1; r >>= 1; } return op(sml, smr); } S all_prod() { return d[1]; } template <bool (*f)(S)> int max_right(int l) { return max_right(l, [](S x) { return f(x); }); } template <class F> int max_right(int l, F f) { assert(0 <= l && l <= _n); assert(f(e())); if (l == _n) return _n; l += size; S sm = e(); do { while (l % 2 == 0) l >>= 1; if (!f(op(sm, d[l]))) { while (l < size) { l = (2 * l); if (f(op(sm, d[l]))) { sm = op(sm, d[l]); l++; } } return l - size; } sm = op(sm, d[l]); l++; } while ((l & -l) != l); return _n; } template <bool (*f)(S)> int min_left(int r) { return min_left(r, [](S x) { return f(x); }); } template <class F> int min_left(int r, F f) { assert(0 <= r && r <= _n); assert(f(e())); if (r == 0) return 0; r += size; S sm = e(); do { r--; while (r > 1 && (r % 2)) r >>= 1; if (!f(op(d[r], sm))) { while (r < size) { r = (2 * r + 1); if (f(op(d[r], sm))) { sm = op(d[r], sm); r--; } } return r + 1 - size; } sm = op(d[r], sm); } while ((r & -r) != r); return 0; } private: int _n, size, log; std::vector<S> d; void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); } }; } // namespace atcoder using namespace std; using namespace atcoder; typedef modint998244353 mint; struct mat { mint v[2][2]; }; mat e() { return {1, 0, 0, 1}; } mat mul(mat a, mat b) { return {a.v[0][0] * b.v[0][0] + a.v[0][1] * b.v[1][0], a.v[0][0] * b.v[0][1] + a.v[0][1] * b.v[1][1], a.v[1][0] * b.v[0][0] + a.v[1][1] * b.v[1][0], a.v[1][0] * b.v[0][1] + a.v[1][1] * b.v[1][1]}; } signed main() { cin.tie(nullptr)->sync_with_stdio(false); int n; cin >> n; vector<int> p(n), v(n); vector<mat> wv(n); for (int i = 0, s; i < n; ++i) { cin >> p[i] >> v[i] >> s; mint ps = s / mint(100); wv[i] = {1 - ps, ps, 1 - ps, ps}; } segtree<mat, mul, e> sgt(wv); vector<tuple<int, int, int, int>> tog; for (int i = 1; i < n; ++i) { int w = p[i] - p[i - 1], d = v[i] - v[i - 1]; if (tog.emplace_back(w, v[i] + v[i - 1], i, 1); d > 0) tog.emplace_back(w, d, i, 0); else if (d) tog.emplace_back(w, -d, i, 3); } ranges::sort(tog, [](auto x, auto y) { return 1ll * get<0>(x) * get<1>(y) < 1ll * get<1>(x) * get<0>(y); }); mint ans = 0; for (auto [x, y, p, b] : tog) { mat tmp{0, 0, 0, 0}; tmp.v[b & 1][b >> 1] = wv[p].v[b & 1][b >> 1], sgt.set(p, tmp); ans += x * (sgt.all_prod().v[0][0] + sgt.all_prod().v[0][1]) / y; wv[p].v[b & 1][b >> 1] = 0, sgt.set(p, wv[p]); } return cout << ans.val() << endl, 0; }
cpp
1288
E
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4 3 5 1 4 OutputCopy1 3 2 5 1 4 1 5 1 5 InputCopy4 3 1 2 4 OutputCopy1 3 1 2 3 4 1 4 NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3]
[ "data structures" ]
#include <bits/stdc++.h> typedef long long ll; typedef long double ld; using namespace std; #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> indexed_set; #define endl '\n' #define ilihg ios_base::sync_with_stdio(false);cin.tie(NULL) int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif clock_t time_req=clock(); ilihg; int t=1; // cin>>t; while(t--){ int n,m; cin>>n>>m; vector<int> v(n+1); indexed_set s,p; int r[n+1],l[n+1]; for(int i=1;i<=m;i++){ int k; cin>>k; if(v[k]==0){ r[k]=s.size()-s.order_of_key(k)+k; s.insert(k); v[k]=i; p.insert(i); } else{ r[k]=max(r[k],(int)p.size()-(int)p.order_of_key(v[k])); p.erase(v[k]); p.insert(i); v[k]=i; } } for(int i=1;i<=n;i++){ if(v[i]==0){ l[i]=i; r[i]=s.size()-s.order_of_key(i)+i; r[i]=min(r[i],n); } else{ l[i]=1; r[i]=max(r[i],(int)p.size()-(int)p.order_of_key(v[i])); r[i]=min(r[i],n); } cout<<l[i]<<" "<<r[i]<<endl; } } #ifndef ONLINE_JUDGE cout<<"Time : "<<fixed<<setprecision(6)<<((double)(clock()-time_req))/CLOCKS_PER_SEC<<endl; #endif }
cpp
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
#include <bits/stdc++.h> using namespace std; #define endl '\n' #define ll long long #define Endl '\n' #define ENDL '\n' #define enld '\n' #define bitsN(n) __builtin_popcount(n) #define bitsN_ll(n) __builtin_popcountll(n) #define lz(n) __builtin_clz(n) #define lzll(n) __builtin_clzll(n) #define tz(n) __builtin_ctz(n) #define tzll(n) __builtin_ctzll(n) #define lpn(a, n, x)(lower_bound(a, a + n, x) - a) #define upn(a, n, x)(upper_bound(a, a + n, x) - a) #define lp(a, x)(lower_bound(a.begin(), a.end(), x) - a.begin()) #define up(a, x)(upper_bound(a.begin(), a.end(), x) - a.begin()) #define memset0(a) memset(a, 0, sizeof a) #define memset1(a) memset(a, -1, sizeof a) #define frn(x, n) for (int i = x; i < n; i++) #define max_int INT_MAX #define max_long LLONG_MAX #define pb push_back #define mb make_pair #define mk make_pair #define sortv(v) sort(v.begin(), v.end()) #define reversev(v) reverse(v.begin(), v.end()) #define sorta(a, n) sort(a, a + n); #define sorta1(a, n) sort(a + 1, a + n + 1); #define lop(i, n) for(int i = 0 ; i < n ; i++) #define lop1(i, n) for(int i = 1 ; i <= n ; i++) #define lopn(i, j, n) for(int i = j ; i < n ; i++) #define lopr(i, n, j) for(int i=n;i>=j;i--) #define fixed(x) fixed << setprecision(x) #define F first #define S second #define pll pair<ll, ll> #define ld long double ll __lcm(ll a, ll b) { return (a * b / __gcd(a, b)); } ll lowbit(ll x){ return x & (-x); } ll INF = 1e17; ll mod = 1e9+7; ll power(ll a, ll b){ if (b == 0) return 1; ll p = power(a, b / 2); if (b % 2) return ((a * p)%mod * p)%mod; return (p * p)%mod; } vector<ll> seive() { vector<ll> res; bool p[10009]; p[0] = p[1] = 0; memset(p,1,sizeof(p)); for(int i=2; i*i<=10000; i++) if(p[i]) for(int j=i*i; j<=10000; j+=i) p[j]=0; for(int i=2; i<=10000; i++) if(p[i]) res.pb(i); return res; } // int mx[4] = {1,0,-1,0}; // int my[4] = {0,1,0,-1}; // int mx1[8] = {1,1,0,-1,-1,-1,0,1}; // int my1[8] = {0,1,1,1,0,-1,-1,-1}; // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // double doubleBS(double l, double r) { // ld eps = 1e-6; // double mid, ans=0; // int op = 100; // while(r-l > eps && op--) { // mid = (l+r)/2.0; // if(check(mid)){ // l= mid; // ans= mid; // } // else r= mid; // } // return mid; // lop(j, 200) { // ld mid = (l+r)/2.0; // ld mid2 = mid+eps; // ld t=0, t2=0; // lop(i, n) { // t = max(t, abs(v[i].S-mid)/v[i].F); // t2 = max(t2, abs(v[i].S-mid2)/v[i].F); // } // if(t <= t2) { // ans = min(ans, t); // r = mid; // } else { // l = mid; // ans = min(ans, t2); // } // } // return ans // } map<pll, ll> mp; vector<ll> g[100010]; ll n; void dfs(int node, int p) { for(auto it: g[node]) { } } void solve() { cin>>n; pll a[n]; map<pll, ll> ans; lop(i, n-1) { ll u,v; cin>>u>>v; u--; v--; g[u].pb(v); g[v].pb(u); a[i].F = u; a[i].S = v; } int x=0; vector<pll> vec; for(int i=0; i<n; i++) { if(g[i].size() == 1) vec.pb({i, g[i][0]}); } for(auto [u, v]: vec) { if(mp[{u,v}] || mp[{v,u}]) continue; mp[{u,v}] = 1; mp[{v,u}] = 1; ans[{u,v}] = x; ans[{v,u}] = x++; } lop(i, n-1) { ll u = a[i].F; ll v = a[i].S; if(mp[{u,v}] || mp[{v,u}]) continue; mp[{u,v}] = 1; mp[{v,u}] = 1; ans[{u,v}] = x; ans[{v,u}] = x++; } lop(i, n-1) { cout<<ans[{a[i].F, a[i].S}]<<endl; } } int main() { ll t = 1; ios:: sync_with_stdio(NULL); cin.tie(0); cout.tie(0); // cin >> t; while (t--) { solve(); } return 0; }
cpp
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
#include<bits/stdc++.h> using namespace std; int tt, tc; using ll = long long; void solve() { int n; cin >> n; string s; cin >> s; vector<int> freq(27, INT_MAX); freq[0] = INT_MIN; reverse(s.begin(), s.end()); vector<int> ans; for (char c : s) { int j = c - 'a'; int x = lower_bound(freq.begin(), freq.end(), j) - freq.begin(); ans.push_back(x); freq[x] = j; } reverse(ans.begin(), ans.end()); cout << *max_element(ans.begin(), ans.end()) << "\n"; for (int c : ans) cout << c << " "; } int main() { ios::sync_with_stdio(0); cin.tie(0); tt = 1, tc = 1; // cin >> tt; while (tt--) solve(), tc++; }
cpp
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; using vi = vector<int>; using vb = vector<bool>; using vll = vector<ll>; using vs = vector<string>; #define ALL(v) v.begin(), v.end() #define SORT(v) sort(ALL(v)) #define SZ(v) int(v.size()) #ifdef DLOCAL #include <local.h> #else #define deb(...); #endif void solve() { int n; cin >> n; vi vec(n - 1); for (int i = 0; i < n - 1; ++i) { cin >> vec[i]; } vi ans(n); for (int i = 1; i < n; ++i) { ans[i] = ans[i - 1] + vec[i - 1]; } int lowest = *min_element(ALL(ans)); int inc = abs(lowest - 1); for (int i = 0; i < n; ++i) { ans[i] += inc; } vi sorted = ans; SORT(sorted); for (int i = 0; i < n; ++i) { if (sorted[i] != i + 1) { cout << -1; return; } } for (int i = 0; i < n; ++i) { cout << ans[i] << " "; } } int main() { ios::sync_with_stdio(0); cin.tie(0); //ifstream cin ("puzzle_name.in"); //ofstream cout ("puzzle_name.out"); solve(); return 0; }
cpp
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4 4 LRUD 4 LURD 5 RRUDU 5 LLDDR OutputCopy1 2 1 4 3 4 -1
[ "data structures", "implementation" ]
#include <bits/stdc++.h> #include <bitset> #include <iostream> #define lana_del_rey ios_base::sync_with_stdio(false);cin.tie(NULL) #define ll long long int #define clr(v,d ) memset(v, d, sizeof(v)) #define deb(x) cout<<#x<<"="<<x<<endl using namespace std; const ll Mod = 1000000007; const ll N = 2002000; map<pair<int, int>,int> mp; void solve() { mp.clear(); int n; cin>>n; string s; cin >> s; s = "0" + s; pair<int, int> ans = { -1, 1000000}; pair<int, int> cur = {0, 0}; //LR UD mp[cur] = 0; for (int i = 1; i <= n; i++) { if (s[i] == 'U') { cur.second++; } else if (s[i] == 'L') { cur.first++; } else if (s[i] == 'D') { cur.second--; } else if (s[i] == 'R') { cur.first--; } if (cur.first==0 && cur.second== 0|| mp[cur]) { if (ans.second - ans.first + 1 > i - mp[cur] + 1) { ans.first=mp[cur]+1; ans.second=i; } } mp[cur] = i; } if (ans.first==-1) cout << -1 << endl; else cout << ans.first << " " << ans.second << endl; } int main() { lana_del_rey; int t = 1; cin >> t; while (t--) { solve(); } return 0; }
cpp
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might 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.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
#include <bits/stdc++.h> #define F first #define S second #define pb push_back #define ppb pop_back #define ep insert #define endl '\n' #define elif else if #define pow pwr #define sqrt sqrtt #define int long long typedef unsigned long long ull; using namespace std; const int N=1005; vector<int> adj[N]; int n,dis[N],curnode=1; void dfs(int node,int d,int p){ dis[node]=d; for (auto u:adj[node]){ if (u==p) continue; dfs(u,d+1,node); }return; } void del(int node,int p,int t){ for (int i=0;i<adj[node].size();i++){ if (adj[node][i]==p) continue; if (adj[node][i]==t){ //cout<<node<<endl; for (int j=0;j<adj[t].size()-1;j++){ if (adj[t][j]!=node) continue; swap(adj[t][j],adj[t][adj[t].size()-1]); break; }adj[t].ppb(); return; }del(adj[node][i],node,t); } return; } int32_t main(){ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); cin>>n; for (int i=1;i<n;i++){ int x,y; cin>>x>>y; adj[x].pb(y); adj[y].pb(x); } while (true){ int x,y,z=INT_MIN; for (int i=1;i<=n;i++) dis[i]=INT_MIN; dfs(curnode,0,0); for (int i=1;i<=n;i++){ if (z>=dis[i]) continue; x=i; z=dis[i]; } dfs(x,0,0); z=INT_MIN; for (int i=1;i<=n;i++){ if (z>=dis[i]) continue; y=i; z=dis[i]; } if (x==y){ cout<<"! "<<x<<endl; cout.flush(); return 0; } cout<<"? "<<x<<' '<<y<<endl; cout.flush(); int lca;cin>>lca; if (lca==-1) return 0; del(x,0,lca); del(y,0,lca); curnode=lca; } return 0; }
cpp
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3 3 1 4 3 1 15 2 3 5 OutputCopy1 2 -1 2 1 2 NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
[ "brute force", "dp", "greedy", "implementation" ]
#include<iostream> #include<vector> #include<set> #include<queue> #include<map> #include<algorithm> #include<numeric> #include<cmath> #include<cstring> #include<bitset> #include<iomanip> #include<random> #include<fstream> #include<complex> #include<time.h> #include<stack> using namespace std; #define endl "\n" #define ll long long #define bl bool #define ch char #define vec vector #define vll vector<ll> #define sll set<ll> #define pll pair<ll,ll> #define mkp make_pair #define mll map<ll,ll> #define puf push_front #define pub push_back #define pof pop_front() #define pob pop_back() #define em empty() #define fi first #define se second #define fr front() #define ba back() #define be begin() #define rbe rbegin() #define en end() #define ren rend() #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(),x.rend() #define fo(i,x,y) for(ll i=x;i<=y;++i) #define fa(i,v) for(auto &i:v) #define re return #define rz return 0; #define sz size() #define len length() #define con continue; #define br break; #define ma(a,x) a=max(a,x) #define mi(a,x) a=min(a,x) #define so(v) sort(all(v)) #define rso(v) sort(rall(v)) #define rev(v) reverse(all(v)) #define i(x) for(ll i=0;i<x;++i) #define j(x) for(ll j=0;j<x;++j) #define k(x) for(ll k=0;k<x;++k) #define n(x) for(ll yz=0;yz<x;++yz) #define xx(k) while(k--) #define wh(x) while(x) #define st string #define M 8611686018427387904 #define ze(x) __builtin_ctzll(x) #define z(x) ll x=0 #define in insert #define un(v) v.erase(unique(all(v)),v.en); #define er(i,n) erase(i,n); #define co(x,a) count(all(x),a) #define lo(v,a) lower_bound(v.begin(),v.end(),a) #define up(v,a) upper_bound(v.begin(),v.end(),a) #define dou double #define elif else if #define ge(x,...) x __VA_ARGS__; ci(__VA_ARGS__); #define fix(n,ans) cout<<fixed<<std::setprecision(n)<<ans<<endl; void cc(){ cout<<endl; }; void ff(){ cout<<endl; }; void cl(){ cout<<endl; }; template<class T,class... A> void ff(T a,A... b){ cout<<a; (cout<<...<<(cout<<' ',b)); cout<<endl; }; template<class T,class... A> void cc(T a,A... b){ cout<<a; (cout<<...<<(cout<<' ',b)); cout<<' '; }; template<class T,class... A> void cl(T a,A... b){ cout<<a; (cout<<...<<(cout<<'\n',b)); cout<<endl; }; template<class T,class... A> void cn(T a,A... b){ cout<<a; (cout<<...<<(cout<<"",b)); }; template<class... A> void ci(A&... a){ (cin>>...>>a); }; template<class T>void ou(T v){fa(i,v)cout<<i<<" ";cout<<endl;} template<class T>void oun(T v){fa(i,v)cout<<i;cout<<endl;} template<class T>void ouu(T v){fa(i,v){fa(j,i)cout<<j<<" ";cout<<endl;}} template<class T> void oul(T v){fa(i,v)cout<<i<<endl;} template<class T>void in(T &v){fa(i,v)cin>>i;} template<class T>void inn(T &v){fa(i,v)fa(j,i)cin>>j;} template<class T>void oump(T &v){fa(i,v)ff(i.fi,i.se);} template<class T,class A>void pi(pair<T,A> &p){ci(p.fi,p.se);} template<class T,class A>void po(pair<T,A> &p){ff(p.fi,p.se);} void init(){ ios::sync_with_stdio(false); cin.tie(0); } void solve(); void ori(); ll ck(){ std::random_device seed_gen; std::mt19937 engine(seed_gen()); // [-1.0, 1.0)の値の範囲で、等確率に実数を生成する std::uniform_real_distribution<> dist1(1.0, 100000); i(10000){ // 各分布法に基いて乱数を生成 ll n = dist1(engine); } rz; } bl isup(ch c){ re 'A'<=c&&c<='Z'; } bl islo(ch c){ re 'a'<=c&&c<='z'; } //isdigit mll pr_fa(ll x){ mll mp; for(ll i=2;i*i<=x;++i){ while(x%i==0){ ++mp[i]; x/=i; } } if(x!=1) ++mp[x]; re mp; } ch to_up(ch a){ re toupper(a); } ch to_lo(ch a){ re tolower(a); } #define str(x) to_string(x) #define acc(v) accumulate(v.begin(),v.end(),0LL) #define acci(v,i) accumulate(v.begin(),v.begin()+i,0LL) #define dq deque<ll> int main(){ init(); solve(); rz; } template <typename T>class pnt{ public: T x,y; pnt(T x=0,T y=0):x(x),y(y){} pnt operator + (const pnt r)const { return pnt(x+r.x,y+r.y);} pnt operator - (const pnt r)const { return pnt(x-r.x,y-r.y);} pnt operator * (const pnt r)const { return pnt(x*r.x,y*r.y);} pnt operator / (const pnt r)const { return pnt(x/r.x,y/r.y);} pnt &operator += (const pnt r){ x+=r.x;y+=r.y;return *this;} pnt &operator -= (const pnt r){ x-=r.x;y-=r.y;return *this;} pnt &operator *= (const pnt r){ x*=r.x;y*=r.y;return *this;} pnt &operator /= (const pnt r){ x/=r.x;y/=r.y;return *this;} ll dist(const pnt r){ re (x-r.x)*(x-r.x)+(y-r.y)*(y-r.y); } pnt rot(const dou theta){ T xx,yy; xx=cos(theta)*x-sin(theta)*y; yy=sin(theta)*x+cos(theta)*y; return pnt(xx,yy); } }; istream &operator >> (istream &is,pnt<dou> &r){is>>r.x>>r.y;return is;} ostream &operator << (ostream &os,pnt<dou> &r){os<<r.x<<" "<<r.y;return os;} ll MOD= 1000000007; //#define MOD 1000000007 //#define MOD 10007 //#define MOD 998244353 //ll MOD; ll mod_pow(ll a, ll b, ll mod = MOD) { ll res = 1; for (a %= mod; b; a = a * a % mod, b >>= 1) if (b & 1) res = res * a % mod; return res; } class mint { public: ll a; mint(ll x=0):a(x%MOD){} mint operator + (const mint rhs) const { return mint(*this) += rhs; } mint operator - (const mint rhs) const { return mint(*this) -= rhs; } mint operator * (const mint rhs) const { return mint(*this) *= rhs; } mint operator / (const mint rhs) const { return mint(*this) /= rhs; } mint &operator += (const mint rhs) { a += rhs.a; if (a >= MOD) a -= MOD; return *this; } mint &operator -= (const mint rhs) { if (a < rhs.a) a += MOD; a -= rhs.a; return *this; } mint &operator *= (const mint rhs) { a = a * rhs.a % MOD; return *this; } mint &operator /= (mint rhs) { ll exp = MOD - 2; while (exp) { if (exp % 2) *this *= rhs; rhs *= rhs; exp /= 2; } return *this; } bool operator > (const mint& rhs)const{ return (this->a>rhs.a); } bool operator < (const mint& rhs)const{ return (this->a<rhs.a); } bool operator >= (const mint& rhs)const{ return (this->a>=rhs.a); } bool operator <= (const mint& rhs)const{ return (this->a<=rhs.a);} bool operator == (const mint& rhs)const{ return (this->a==rhs.a);} }; istream& operator>>(istream& is, mint& r) { is>>r.a;return is;} ostream& operator<<(ostream& os, const mint& r) { os<<r.a;return os;} #define pq priority_queue<ll> #define top top() ll sumw(ll v,ll r){ re (v==0?0:sumw(v/10,r)*r+v%10); } #define com complex<dou> struct UFS{ map<st,st> par;map<st,ll>rk,siz; st root(st x){ auto it=par.find(x); if(it==par.en){ par[x]=x;siz[x]=1;re x; } if(par[x]==x)return x; else return par[x]=root(par[x]); } bool same(st x,st y){ return root(x)==root(y); } bool unite(st x,st y){ st rx=root(x),ry=root(y); if(rx==ry) return false; if(rk[rx]<rk[ry]) swap(rx,ry); siz[rx]+=siz[ry]; par[ry]=rx; if(rk[rx]==rk[ry]) rk[rx]++; return true; } ll size(st s){ re siz[s]; } }; //vector<long long> fact, fact_inv, inv; /* init_nCk :二項係数のための前処理 計算量:O(n) */ vll fact,inv,fact_inv; void init_nCk(int SIZE) { fact.resize(SIZE + 5); fact_inv.resize(SIZE + 5); inv.resize(SIZE + 5); fact[0] = fact[1] = 1; fact_inv[0] = fact_inv[1] = 1; inv[1] = 1; for (int i = 2; i < SIZE + 5; i++) { fact[i] = fact[i - 1] * i % MOD; inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD; fact_inv[i] = fact_inv[i - 1] * inv[i] % MOD; } } long long nCk(int n, int k) { return fact[n] * (fact_inv[k] * fact_inv[n - k] % MOD) % MOD; } struct UF{ vll par,rk,siz; UF(ll n):par(n+5,-1),rk(n+5,0){ } ll root(ll x){ if(par[x]<0)return x; else return par[x]=root(par[x]); } bool same(ll x,ll y){ return root(x)==root(y); } bool unite(ll x,ll y){ ll rx=root(x),ry=root(y); if(rx==ry) return false; if(rk[rx]<rk[ry]) swap(rx,ry); par[rx]+=par[ry]; par[ry]=rx; if(rk[rx]==rk[ry]) rk[rx]++; return true; } ll size(ll x){ return -par[root(x)]; } }; /* O(2*10^8) 9*10^18 1LL<<62 4*10^18 ~~(v.be,v.be+n,x); not include v.be+n set.lower_bound(x); ->. *++ ! /%* +- << < == & && +=?: */ //vll dx={-1,-1,-1,0,0,1,1,1},dy={-1,0,1,-1,1,-1,0,1}; //vll dx={-1,0,0,1},dy={0,-1,1,0}; //#define N 11 #define N 105 void solve(){ ge(ll,t); xx(t){ ge(ll,n); vll v(n);in(v); if(n==1){ if(v[0]%2) ff(-1); else { ff(1); ff(1); } }else{ if(v[0]%2==0){ ff(1); ff(1); }else if(v[1]%2==0){ ff(1); ff(2); }else{ ff(2); ff(1,2); } } } }
cpp
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6 -100 -200 -300 125 77 -4 OutputCopy9 InputCopy1000000000000 5 -1 0 0 0 0 OutputCopy4999999999996 InputCopy10 4 -3 -6 5 4 OutputCopy-1
[ "math" ]
// ~BhupinderJ #include <bits/stdc++.h> using namespace std; #define endl "\n" #define spc <<" "<< #define pii pair<int, int> #define vvi vector<vector<int>> #define all(t) t.begin(), t.end() #define int long long const int Mod = 1e9+7; const int N = 1e5+1; void SOLVE(){ int H, n; cin >> H >> n; vector<int> d(n); for(int i=0 ; i<n ; i++){ cin >> d[i]; } int mn = d[0]; for(int i=1 ; i<n ; i++){ d[i] += d[i-1]; mn = min(mn, d[i]); } if(d[n-1] >= 0){ int idx = -1; for(int i=0 ; i<n ; i++){ if(d[i] + H <= 0){ idx = i+1; break; } } cout << idx << endl; }else{ int pH = H + mn, t; if(pH < 0) t = 0; else{ t = pH/abs(d[n-1]); if(pH % abs(d[n-1])) t++; } H += t*d[n-1]; for(int i=0 ; i<n ; i++){ if(d[i] + H <= 0){ cout << t*n + i+1 << endl; return; } } } } signed main(){ ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int T = 1; //cin >> T; while(T--) SOLVE(); }
cpp
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
#include<bits/stdc++.h> #include <ext/random> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define GET(n, i) (((n) >> (i)) bitand 1) #define LAST(n) ((n) bitand (-(n))) #define RANGE(x, y, i, j) (i > -1 and i < x and j > -1 and j < y) #define SET(x, k) (x | (1LL << k)) #define CLEAR(x, k) (x bitand ~ (1LL << k)) #define CHECK(x, k) (x bitand (1LL << k)) #define TOGGLE(x, k) (x ^ (1LL << k)) using LL = int64_t; LL dx [] = {0, 1, 0, -1}; LL dy [] = {1, 0, -1, 0}; LL dxx [] = {0, 1, 0, -1, 1, 1, -1, -1}; LL dyy [] = {1, 0, -1, 0, 1, -1, 1, -1}; const LL mod = 1000000007; #define ordered_set tree<LL, null_type, less<LL>, rb_tree_tag, tree_order_statistics_node_update> __gnu_cxx::sfmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); const LL MAX = 1000; vector<LL> fre(MAX, 0); int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); srand(chrono :: high_resolution_clock :: now().time_since_epoch().count()); LL T = 1; for (LL qq = 0; qq < T; qq++) { LL n, m; cin >> n >> m; vector<LL> a(n, 0), b; unordered_set<LL> ss, bb; for (LL k = 0; k < n; k++) { cin >> a[k]; ss.insert(a[k]); } if (ss.size() < n or n > m) { cout << 0; cout << '\n'; exit(0); } LL res = 1LL; for (LL k = 0; k < n; k++) { for (LL j = k + 1; j < n; j++) { res = res * (abs(a[k] - a[j])); res = res % m; } } cout << res << '\n'; exit(0); } return 0; }
cpp
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3 OutputCopy4 5 9 13 18InputCopy8 0 OutputCopy10 11 12 13 14 15 16 17 InputCopy4 10 OutputCopy-1 NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
[ "constructive algorithms", "greedy", "implementation", "math" ]
#include <bits/stdc++.h> // #pragma GCC optimize(2) #define N 5005 // #define mod 998244353 // #define endl '\n' #define int long long // #define double long double #define fastio \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); using namespace std; int n, m, tmp[N], num[N]; void solve() { cin >> n >> m; for (int i = 1; i <= n; i++) num[i] = i; int ans = 0; for (int i = 1; i <= n; i++) { ans += (i - 1) / 2; if (ans >= m) { num[i] -= (m - ans) * 2; for (int j = i + 1; j <= n; j++) num[j] = num[j - 1] + num[i] * 2; for (int i = 1; i <= n; i++) cout << num[i] << " "; return; } } cout << -1 << endl; } signed main() { // fastio; // freopen("data.in", "r", stdin); int t = 1; // cin >> t; while (t--) solve(); // fclose(stdin); }
cpp
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
#include<bits/stdc++.h> using namespace std; #define pb push_back #define ppb pop_back #define pf push_front #define ppf pop_front #define eb emplace_back #define ef emplace_front #define lowbit(x) (x & (-x)) #define ti chrono::system_clock::now().time_since_epoch().count() #define Fin(x) freopen(x, "r", stdin) #define Fout(x) freopen(x, "w", stdout) #define Fio(x) Fin(x".in"), Fout(x".out"); // #define SGT #define int long long // int main() -> signed // #define PAIR #define ll long long #ifdef PAIR #define fi first #define se second #endif #ifdef SGT #define lson (p << 1) #define rson (p << 1 | 1) #define mid ((l + r) >> 1) #endif const int maxn = 2e5 + 10; int n, a[maxn], ans; set<int> st; mt19937 rnd(ti); void solve(int x){ for(int i = 2; i * i <= x; i++) if(x % i == 0){ st.insert(i); while(x % i == 0) x /= i; } if(x > 1) st.insert(x); } int calc(int x){ int ret = 0; for(int i = 1; i <= n; i++){ int k = a[i] / x * x; ret += min(k ? a[i] - k : n, k + x - a[i]); } return ret; } signed main(){ scanf("%lld", &n), ans = n; for(int i = 1; i <= n; i++) scanf("%lld", &a[i]); for(int _ = 1; _ <= 50; _++){ int i = rnd() % n + 1; solve(a[i]), solve(a[i] + 1), solve(a[i] - 1); } for(int i : st) ans = min(ans, calc(i)); printf("%lld\n", ans); return 0; }
cpp
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native") #pragma GCC optimize("fast-math") #pragma GCC optimize ("unroll-loops,Ofast,O3") #pragma GCC target("avx,avx2,fma") #define file(s) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout) #define all(x) (x).begin(),(x).end() #define int long long #define rs(p) (p<<1|1) #define ls(p) (p<<1) #define pb push_back #define endl '\n' #define sz size() #define F first #define S second #define SlimShady ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); using namespace std; const long double eps = 1e-10; const int MIN = LLONG_MIN; const int M = 2e9 + 100; const int N = 5e4 + 100; const int ZERO = 0; void solve() { int n, k; cin >> n >> k; string a[n + 3], b[k + 3]; for(int i = 0; i < n; ++i) cin >> a[i]; for(int i = 0; i < k; ++i) cin >> b[i]; int m; cin >> m; while(m--) { int i; cin >> i; i--; cout << a[i % n] << b[i % k] << endl; } } signed main () { SlimShady int test = 1; // cin >> test; while(test--) { solve(); } }
cpp
1324
D
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5 4 8 2 6 2 4 5 4 1 3 OutputCopy7 InputCopy4 1 3 2 4 1 3 2 4 OutputCopy0
[ "binary search", "data structures", "sortings", "two pointers" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; template<class T> using ordset = tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>; #define ar array #define ll long long #define ld long double #define sz(x) ((int)x.size()) #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() #define pb push_back #define ppb pop_back #define vll vector<long long int> #define vi vector<int> #define PrintArray(arr) for(int i=0;i<(int)arr.size();i++)cout<<arr[i]<<" ";cout<<"\n"; #define lowerb lower_bound #define upperb upper_bound #define pqi priority_queue<int> #define pqll priority_queue<long long> #define nl '\n'; const long long MAX_SIZE = 1000001; const int MAX_N = 1e5 + 5; const ll MOD1 = 1e9 + 7; const ll MOD2 = 9882999; const ll INF = 1e18; const ld EPS = 1e-9; //----------------------------------------------Code---------------------------------------------------// void solve() { int n; cin >> n; vll a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; vll lhs, rhs; for (int i = 0; i < n; i++) { lhs.pb(a[i] - b[i]); } sort(all(lhs)); ll ans = 0; for (int i = 0; i < n; i++) { int temp = -1, l = i + 1, r = n - 1; while (l <= r) { int mid = (l + r) / 2; if (lhs[mid] + lhs[i] > 0) { temp = mid; r = mid - 1; } else { l = mid + 1; } } if (temp >= 0) { ans += (n - temp); } } cout << ans << nl; } //-----------------------------------------------------------------------------------------------------// int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int tc = 1; // cin >> tc; for (int t = 1; t <= tc; t++) { // cout << "Case #" << t << ": "; solve(); } return 0; }
cpp
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
#include <iostream> #include <vector> #include <algorithm> #include <bits/stdc++.h> #include <iterator> #include <map> using namespace std; bool sortbysec(const pair<char,int> &a, const pair<char,int> &b) { return (a.first > b.first); } bool isPalindrome(string S) { // Stores the reverse of the // string S string P = S; // Reverse the string P reverse(P.begin(), P.end()); // If S is equal to P if (S == P) { // Return "Yes" return true; } // Otherwise else { // return "No" return false; } } bool poss(vector<int> &g1,vector<int> &g2,long long int mid){ long long int sum=0; int j=0; while(j<g1.size()){ if(g1[j]>mid){ sum=sum+g2[j]; } j++; } if(sum<=mid){ return true; } return false; } bool isPrime(long long int n) { if (n <= 1) return false; for (long long int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true; } long long int onesComplement(long long int n) { vector<int> v; // convert to binary representation while (n != 0) { v.push_back(n % 2); n = n / 2; } reverse(v.begin(), v.end()); // change 1's to 0 and 0's to 1 for (int i = 0; i < v.size(); i++) { if (v[i] == 0) v[i] = 1; else v[i] = 0; } // convert back to number representation int two = 1; for (int i = v.size() - 1; i >= 0; i--) { n = n + v[i] * two; two = two * 2; } return n; } static bool sortbysec(const vector<int> &a, const vector<int> &b) { return (a.size() < b.size()); } bool ans23(int n,vector<pair<int,int>> g1){ int j=0; while(j<g1.size()){ if(n<g1[j].first){ return false; } else{ n=n+g1[j].second; } j++; } return true; } int ans(int i,int n,vector<int> &dp,string s, map<char,vector<int>> m1,map<char,int> m2){ if(i>=n){ return 0; } if(dp[i]!=-1){ return dp[i]; } int r=m1[s[i]].size(); if(m2[s[i]]<r){ m2[s[i]]++; int r1=(ans(i+1,n,dp,s,m1,m2)); int r2=2+ans(m1[s[i]][m2[s[i]]-1]+1,n,dp,s,m1,m2); return dp[i]=max(r1,r2); } else{ return dp[i]=ans(i+1,n,dp,s,m1,m2); } } int main(){ int t; cin>>t; int i=0; while(i<t){ int a,b,p; cin>>a>>b>>p; string s; cin>>s; int j=s.length()-2; while(1){ if(s[j]=='B'){ if(p>=b){ while(s[j]=='B'&&j>=0){ j--; } p=p-b; } else{ break; } } if(s[j]=='A'){ if(p>=a){ while(s[j]=='A'&&j>=0){ j--; } p=p-a; } else{ break; } } if(j<0){ break; } } if(j<0){ cout<<1<<"\n"; i++; continue; } if(j>=s.length()-2){ cout<<s.length()<<"\n"; i++; continue; } cout<<j+2<<"\n"; i++; } return 0; }
cpp
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
#include <bits/stdc++.h> // #include "Algorithms.h" #define long long long const int Mod = 1e9 + 7, N = 1e3 + 1; void Solution() { int n; std::cin >> n; std::vector<int> a(n); for (int i = 0; i < n; i++) { std::cin >> a[i]; } int l = 0, r = n; while (l < n && a[l] >= l) l++; while (r > 0 && a[r - 1] >= n - r) r--; if (l > r) { std::cout << "YES\n"; } else { std::cout << "NO\n"; } } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int t = 1; std::cin >> t; while (t--) { Solution(); } return 0; }
cpp
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3 2 1 4 OutputCopy5 InputCopy4 3 1 4 4 OutputCopy6 InputCopy4 3 1 4 1 OutputCopy6 InputCopy5 3 1 4 1 5 OutputCopy11 NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
// LUOGU_RID: 101764554 //#pragma GCC optimize(3) #include<iostream> #include<climits> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<queue> #include<map> #include<set> #include<vector> #include<complex> #include<random> #include<chrono> #define int long long //#define double long double #define invert dsfsdf using namespace std; const long long INF=LLONG_MAX/4ll; const long long mod=998244353; const long long mod2=1000009; const long long mod3=924844033; const double Pai=acos(-1); map< pair<int,pair<int,int> >,int> mp; int n,cnt=0,sign=0,ans=INF; int pri[1000005],a[1000005],h[1000005],vt[1000005],t[1000005],ct[1000005],pos[1000005],sta[1000005],d[1000005]; int sum[30005][705],num[30005][705]; int N=5000; struct edge { int from,to,next,v; }e[100005]; void addedge(int x,int y,int z) { e[++cnt]={x,y,h[x],z},h[x]=cnt; swap(x,y); e[++cnt]={x,y,h[x],z},h[x]=cnt; } int qp(int x,int y) { int res=1; while(y) { if(y&1) y--,res*=x,res%=mod3; y>>=1,x*=x,x%=mod3; } return res; } void init() { for(int i=1;i<=N;i++) { int sq=sqrt(i),fg=1; for(int j=2;j<=sq;j++) if(i%j==0) fg=0; if(fg) pri[++pri[0]]=i; } sum[1][1]=1; for(int i=2;i<=N;i++) { for(int j=1;j<=pri[0];j++) sum[i][j]=sum[i-1][j]; int x=i; for(int j=2;j<=pri[0];j++) { while(x%pri[j]==0) x/=pri[j],sum[i][j]++; } } for(int i=1;i<=N;i++) { int sm=0,sm2=0,sm3=1; // cout<<i<<endl; for(int j=pri[0];j>=1;j--) /*cout<<pri[j]<<" "<<sum[i][j]<<"\n",*/num[i][j]=sum[i][j],ct[i]+=sum[i][j],sm+=pri[j]*sum[i][j]%mod,sm%=mod,sm2^=pri[j]^sum[i][j],sm2%=mod2,sm3*=qp(pri[j],sum[i][j]),sm3%=mod3; mp[{sm3,{sm,sm2}}]=i; // cout<<sm3<<"\n"; } } int LCA(int x,int y) { sign++; for(int i=pri[0];i>=1;i--) { if(num[x][i]!=num[y][i]) { num[sign][i]=min(num[x][i],num[y][i]); for(int j=i-1;j>=1;j--) num[sign][j]=0; break; } else num[sign][i]=num[x][i]; } num[sign][1]=1; int sm=0,sm2=0,sm3=1; for(int i=pri[0];i>=1;i--) ct[sign]+=num[sign][i],sm+=pri[i]*num[sign][i]%mod,sm%=mod,sm2^=pri[i]^num[sign][i],sm2%=mod2,sm3*=qp(pri[i],num[sign][i]),sm3%=mod3; if(mp[{sm3,{sm,sm2}}]) { ct[sign]=0,sign--; return mp[{sm3,{sm,sm2}}]; } // cout<<sm<<" "<<sm2<<" "<<sm3<<endl; // for(int i=pri[0];i>=1;i--) cout<<num[x][i]<<" ";puts(""); // for(int i=pri[0];i>=1;i--) cout<<num[y][i]<<" ";puts(""); // for(int i=pri[0];i>=1;i--) cout<<num[sign][i]<<" ";puts(""); return mp[{sm3,{sm,sm2}}]=sign; } bool cmp(int x,int y) { for(int i=1;i<=pri[0];i++) { if(num[x][i]>num[y][i]) return 0; if(num[x][i]<num[y][i]) return 1; } return 0; } int calc(int x,int y) { return ct[y]-ct[x]; } void Build() { sort(vt+1,vt+N+1); int tp=1; sta[tp]=1,h[1]=0,cnt=0; for(int i=1;i<=N;i++) { if(vt[i]==1) continue; int lca=LCA(vt[i],sta[tp]); if(lca!=sta[tp]) { while(cmp(lca,sta[tp-1])) addedge(sta[tp-1],sta[tp],calc(sta[tp-1],sta[tp])),tp--; if(!cmp(lca,sta[tp-1])) addedge(lca,sta[tp],calc(lca,sta[tp])),sta[tp]=lca; else addedge(lca,sta[tp--],calc(lca,sta[tp--])); } sta[++tp]=vt[i]; } for(int i=1;i<tp;i++) addedge(sta[i],sta[i+1],calc(sta[i],sta[i+1])); } void dfs(int s,int fa,int dep) { d[s]=dep; for(int i=h[s];i;i=e[i].next) { int y=e[i].to; if(y==fa||y==s) continue; // cout<<s<<" "<<y<<endl; dfs(y,s,dep+e[i].v); } } signed main() { scanf("%lld",&n);sign=N; for(int i=1;i<=n;i++) { scanf("%lld",&a[i]); if(a[i]==0) a[i]=1; t[a[i]]++; } for(int i=1;i<=N;i++) vt[i]=i; init(); Build(); // for(int i=1;i<=cnt;i++) { // cout<<e[i].from<<" "<<e[i].to<<" "<<e[i].v<<endl; // } for(int i=1;i<=sign;i++) { int res=0; dfs(i,0,0); for(int j=1;j<=N;j++) res+=t[j]*d[j]/*,cout<<d[j]<<" "*/; // for(int j=1;j<=sign;j++) vis[j]=0; // cout<<res<<endl; ans=min(ans,res); } // for(int i=1;i<=sign;i++) { // int res=1; // for(int j=pri[0];j>=1;j--) res*=qp(pri[j],sum[i][j]),res%=mod3; // cout<<res<<endl; // } printf("%lld",ans); return 0; }
cpp
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
#include <bits/stdc++.h> #include <ext/pb_ds/detail/standard_policies.hpp> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define FIO ios::sync_with_stdio(false); cin.tie(nullptr) #define TC(t) int t; cin >> t; for(int i = 1; i <= t; i++) #define ll long long int #define ull unsigned long long int #define lll __int128 #define lld long double #define loop(i, a, b) for(ll i = a; i <= b; i++) #define loop2(i, b, a) for(ll i = b; i >= a; i--) #define ini(x, y) memset(x, y, sizeof(x)) #define all(x) x.begin(), x.end() #define all2(x) x.rbegin(), x.rend() #define sz(x) (ll)x.size() #define pb push_back #define ppb pop_back #define mp make_pair #define ff first #define ss second #define M 1000000007 #define endl '\n' #define bits(x) __builtin_popcountll(x) #define zrbits(x) __builtin_ctzll(x) #define vl vector<ll> #define pll pair<ll,ll> #define vpll vector<pll> #define uni(x) x.erase(unique(all(x)), x.end()) #define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> #define multi_ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> #define mxheap priority_queue<ll> #define mnheap priority_queue<ll, vector<ll>, greater<ll>> #define mxheap2 priority_queue<pair<ll,ll>> #define mnheap2 priority_queue<pair<ll,ll>, vector<pair<ll,ll>>, greater<pair<ll,ll>>> const int N = 2e5 + 5; const int L = 20; const int MX = 1e9 + 10; const ll INF = 1e18; const int dx[] = {0, -1, 0, 1, -1, -1, 1, 1}; const int dy[] = {1, 0, -1, 0, 1, -1, -1, 1}; using namespace std; using namespace __gnu_pbds; inline ll uceil(ll a,ll b) {return (a % b ? a / b + 1 : a / b);} inline ll mod(ll x) {return ( (x % M + M) % M );} ll ulog(ll val, ll base) {ll cnt = 0; val /= base; while(val) {cnt++; val /= base;} return cnt;} ll power(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a; a = a * a; b >>= 1;} return res;} ll modpow(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a % M; a = a * a % M; b >>= 1;} return res;} #ifdef FARHAN #define deb(x) cerr << #x << " = " << x << endl; #define deb2(x, y) cerr << #x << " = " << x << ", " << #y << " = " << y << endl; #define deb3(x, y, z) cerr << #x << " = " << x << ", " << #y << " = " << y << ", " << #z << " = " << z << endl; #define deb4() cerr << endl; #define done cerr << "Line " << __LINE__ << " is done" << endl; #else #define deb(x) #define deb2(x, y) #define deb3(x, y, z) #define deb4() #define done #endif template<typename T> ostream& operator<<(ostream& os, const vector<T>& v) {for(auto& x : v) os << x << " "; return os;} template<typename T> ostream& operator<<(ostream& os, const set<T>& v) {for(auto& x : v) os << x << " "; return os;} template<typename T, typename S> ostream& operator<<(ostream& os, const pair<T, S>& p) {os << p.first << ' ' << p.second; return os;} template<typename... T> void in(T&... args) {((cin >> args), ...);} template<typename... T> void out(T&&... args) {((cout << args << endl), ...);} template<typename... T> void out2(T&&... args) {((cout << args << " "), ...);} template<typename... T> void out3(T&&... args) {((cout << args << " "), ...); cout << endl;} void solve() { ll n, m, k; cin >> n >> m >> k; ll totpath = 4 * n * m - 2 * (n + m); if(k > totpath) { cout << "NO" << endl; return; } cout << "YES" << endl; vector<pair<ll, char>> ans; // process for(ll i = 1; i < m; i++) { ll mn = min(1LL, k); if(mn) { ans.pb({mn, 'R'}); k -= mn; } if(i == m - 1) break; mn = min(n - 1, k); if(mn) { ans.pb({mn, 'D'}); k -= mn; } mn = min(n - 1, k); if(mn) { ans.pb({mn, 'U'}); k -= mn; } } for(ll i = 1; i < n; i++) { ll mn = min(1LL, k); if(mn) { ans.pb({mn, 'D'}); k -= mn; } if(i == n - 1) break; mn = min(m - 1, k); if(mn) { ans.pb({mn, 'L'}); k -= mn; } mn = min(m - 1, k); if(mn) { ans.pb({mn, 'R'}); k -= mn; } } ll mn = min(m - 1, k); if(mn) { ans.pb({mn, 'L'}); k -= mn; } mn = min(n - 1, k); if(mn) { ans.pb({mn, 'U'}); k -= mn; } mn = min(n - 1, k); if(mn) { ans.pb({mn, 'D'}); k -= mn; } mn = min(m - 1, k); if(mn) { ans.pb({mn, 'R'}); k -= mn; } mn = min(n - 1, k); if(mn) { ans.pb({mn, 'U'}); k -= mn; } mn = min(m - 1, k); if(mn) { ans.pb({mn, 'L'}); k -= mn; } cout << sz(ans) << endl; for(auto e : ans) cout << e << endl; } signed main () { #ifdef FARHAN freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif FIO; // TC(t) solve(); return 0; }
cpp
1294
C
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5 64 32 97 2 12345 OutputCopyYES 2 4 8 NO NO NO YES 3 5 823
[ "greedy", "math", "number theory" ]
// Online C++ compiler to run C++ program online #include <iostream> #define k long long unsigned using namespace std; int main() { int t;cin>>t; while(t--){ k n,a=1,b=1,c=1;cin>>n; for(k i=2;i*i<=n;i++){ if(n%i==0){ a=i; n/=a; break; } } for(k i=2;i*i<=n;i++){ if(n%i==0 && i!=a && n/i!=i && n/i!=a){ b=i; c=n/i; n/=b;n/=c; break; } } if(n==1 && a!=b && a!=c && b!=c){ cout<<"YES \n"<<a<<" "<<b<<" "<<c; } else{ cout<<"NO"; } cout<<endl; } return 0; }
cpp
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3 OutputCopy4 5 9 13 18InputCopy8 0 OutputCopy10 11 12 13 14 15 16 17 InputCopy4 10 OutputCopy-1 NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
[ "constructive algorithms", "greedy", "implementation", "math" ]
#include<bits/stdc++.h> using namespace std; int n,m,t=1; int a[5002]; int main() { for(scanf("%d%d",&n,&m);t<=n && m>=(t-1)/2;++t)a[t]=t,m-=(t-1)/2; if(t>n && m)return 0&puts("-1"); if(m)a[t]=2*t-2*m-1,++t; for(;t<=n;++t)a[t]=n*n+t*n; for(int i=1;i<=n;++i)printf("%d ",a[i]); return 0; }
cpp
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4 4 0 11 6 OutputCopy11 6 4 0InputCopy1 13 OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
[ "brute force", "greedy", "math" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define v(li) vector<ll> #define vp(li) vector<pair<ll, ll>> #define m(li) map<ll, ll> #define s(li) set<ll> #define yes cout<<"YES"<<endl #define no cout<<"NO"<<endl #define ss second #define ff first #define f(i, n) for (ll i = 0; i < n; i++) #define nl cout << "\n" #define vecsort(v) sort(v.begin(), v.end()) #define pb push_back #define mk make_pair void fastio(){ std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); } vector<ll> freq(ll a[],ll n){ ll c=1; v(li) v; for(ll i=0;i<n-1;i++){ if(a[i]==a[i+1]) c++; else{ v.push_back(c); c=1; } } v.push_back(c); return v; } vector<pair<ll,ll>> freqp(ll a[],ll n){ ll c=1; vp(li) v; for(ll i=0;i<n-1;i++){ if(a[i]==a[i+1]) c++; else{ v.push_back(make_pair(c,a[i])); c=1; } } v.push_back(make_pair(c,a[n-1])); return v; } ll power(ll a,ll b){ if(b==0) return 1; ll res=power(a,b/2); if(b%2==0) return res*res; else return res*res*a; } ll powerm(ll a,ll b,ll M){ if(b==0) return 1; ll res=powerm(a,b/2,M); if(b%2==0) return ((res%M)*(res%M))%M; else return (((res%M)*(res%M)%M)*(a%M))%M; } int main(){ fastio(); ll n; cin>>n; ll ma=0; ll a[n]; f(i,n){ cin>>a[i]; if(a[i]>ma){ ma=a[i]; } } //cout<<ma<<endl; ll ind=0; for(ll i=0;i<64;i++){ if(power(2,i)>ma){ ind=i; break; } } //cout<<ind<<endl; ll p[n],s[n]; ll xo=power(2,ind)-1; ll fi; ll st; p[0]=xo^a[0]; s[n-1]=xo^a[n-1]; for(ll i=1;i<n;i++) p[i]=p[i-1]&(xo^a[i]); for(ll i=n-2;i>=0;i--) s[i]=s[i+1]&(xo^a[i]); f(i,n){ if(i==0){ fi=s[i+1]&a[i]; st=a[i]; } else if(i==n-1){ ll x=a[i]&p[i-1]; if(x>fi){ fi=x; st=a[i]; } } else{ ll x=a[i]&p[i-1]&s[i+1]; if(x>fi){ fi=x; st=a[i]; } } } int flag=1; cout<<st<<" "; f(i,n){ if(a[i]==st){ if(flag) flag=0; else cout<<a[i]<<" "; } else cout<<a[i]<<" "; } nl; }
cpp
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
#include<bits/stdc++.h> using namespace std; deque<string>k; int main() { ios_base::sync_with_stdio(NULL); cin.tie(0); cout.tie(0); int n, m, ans = 0; string q = ""; cin >> n >> m; map<string, int>mp; for(int i = 1; i <= n;i++) { string s, t; cin >> s; t = s; reverse(t.begin(), t.end()); if(mp[t] != 0) { mp[t]--; k.push_front(t); k.push_back(s); ans += s.size() * 2; } else if(s == t) { q = s; } else { mp[s]++; } } cout << ans + q.size() << '\n'; for(int i = 0; i < k.size() / 2;i++) { cout << k[i]; } cout << q; for(int i = k.size() / 2; i < k.size();i++) { cout << k[i]; } }
cpp
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
#include "bits/stdc++.h" #define pf printf #define sf scanf #define db double #define ll long long #define siz 20000001 #define MAXN 100001 #define fast ios_base::sync_with_stdio(false);cin.tie(NULL); ll mod=1000000007; ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); } ll powerwithmod(ll a, ll b){ ll res=1; while(b){ if(b&1) res=(res*a)%mod; b>>=1; a=(a*a)%mod; } return res; } using namespace std; int main() { fast; ll n,m; cin>>n>>m; ll arr[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin>>arr[i][j]; } } ll ans=0; for (int i = 0; i < m; i++) { vector<ll>v; for (int j = 0; j < n; j++) { v.push_back(arr[j][i]); } ll x=i+1; map<ll,ll>ma; for (int j = 0; j < v.size(); j++) { ll val=v[j]-x; if(val%m!=0){ continue; } val/=m; if(val>=n) { continue; } if(val>j) { ma[j+n-val]++; } else { ma[j-val]++; } } ll temp=n; for(auto it:ma) { temp=min(it.first+(n-it.second),temp); } ans+=temp; } cout<<ans<<"\n"; return 0; }
cpp
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1 OutputCopy1.000000000000 InputCopy2 OutputCopy1.500000000000 NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
[ "combinatorics", "greedy", "math" ]
#include <bits/stdc++.h> using namespace std; int main() { float n,ans=0; cin>>n; while(n>0) { ans+= 1/n; n--; } cout<<ans<<endl; }
cpp
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int ll ans[100000]; ll depth=0; int main() { ll t; cin>>t; while(t--) { ll n; cin>>n; ll arr[n]; set<ll>s; vector<ll>v(2*n+1); for(int i=0;i<n;i++) { cin>>arr[i]; v[arr[i]]=1; } ll flag=0; ll kk=0; ll ans[2*n]; ll x=-1; // for(int i=1;i<=2*n;i++) // { // cout<<v[i]<<" "; // } // cout<<endl; for(int i=0;i<n;i++) { ++x; flag=0; ll val=arr[i]; ans[x]=arr[i]; for(int j=arr[i]+1;j<=2*n;j++) { if(v[j]==0) { ++x; ans[x]=j; flag=-1; v[j]=1; break; } } if(flag==0) { cout<<-1<<endl; kk=-1; break; } } if(kk==0) { for(auto &it:ans) { cout<<it<<" "; } cout<<endl; } }}
cpp
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
#include <bits/stdc++.h> #define ll long long #define pb push_back using namespace std; int main() { ll n,m;cin>>n>>m; vector<string> vn,vm; for(ll i=0;i<n;i++) { string x;cin>>x;vn.pb(x);} for(ll i=0;i<m;i++) { string x;cin>>x;vm.pb(x);} ll q;cin>>q; while(q--){ ll x;cin>>x; cout<<vn[(x-1+n)%n]<<vm[(x-1+m)%m]<<endl; } }
cpp
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native") #pragma GCC optimize("fast-math") #pragma GCC optimize ("unroll-loops,Ofast,O3") #pragma GCC target("avx,avx2,fma") #define file(s) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout) #define all(x) (x).begin(),(x).end() #define int long long #define ar array #define rs(p) (p<<1|1) #define ls(p) (p<<1) #define pb push_back #define endl '\n' #define sz size() #define F first #define S second #define SlimShady ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); using namespace std; const long double eps = 1e-10; const int MIN = LLONG_MIN; const int M = 2e9 + 100; const int N = 1e5 + 100; void solve() { string s; int mx = 0; cin >> s; int old = -1; for(int i = 0; i < s.sz; ++i) { if(s[i] == 'R') { mx = max(mx, i - old); old = i; } } int n = s.sz; mx = max(mx, n - old); cout << mx << endl; } signed main () { SlimShady int test = 1; cin >> test; while(test--) { solve(); } }
cpp
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n,even=0,odd=0; cin>>n; string s; cin>>s; for(int i=0;i<n;i++){ if(s[i]%2==0){ even++; } else{ odd++; } } int lastindex=n-1; while(s.size()!=0 && s[lastindex]%2==0){ s.pop_back(); lastindex--; } if(odd%2==1){ s.pop_back(); lastindex--; } while(s.size()!=0 && s[lastindex]%2==0){ s.pop_back(); lastindex--; } if(s.size()!=0) cout<<s<<endl; else cout<<-1<<endl; } }
cpp
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; long long t,n,k,i,j; string s,a,b,c; int main() { scanf("%lld",&t); for(j=1;j<=t;j=j+1) { scanf("%lld",&n);cin>>s;a=s;k=1; for(i=2;i<=n;i=i+1) { c=s.substr(0,i-1); if((n-i)%2==1)b=s.substr(i-1,n-i+1)+c; if((n-i)%2==0){reverse(c.begin(),c.end());b=s.substr(i-1,n-i+1)+c;} if(a>b){a=b;k=i;} } cout<<a; printf("\n%lld\n",k); } return 0; }
cpp
1286
B
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3 2 0 0 2 2 0 OutputCopyYES 1 2 1 InputCopy5 0 1 1 3 2 1 3 0 2 0 OutputCopyYES 2 3 2 1 2
[ "constructive algorithms", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
#include <iostream> #include <vector> using namespace std; using ll = long long; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; typedef tree< ll, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; void dfs(ll from, const vector<vector<ll>> &graph, ordered_set &have, const vector<ll> &cnt, vector<ll> &res) { auto it = have.find_by_order(cnt[from]); res[from] = *it; have.erase(it); for (const auto &to: graph[from]) { dfs(to, graph, have, cnt, res); } } ll dfs1(ll from, const vector<vector<ll>> &graph, const vector<ll> &cnt) { ll sz = 1; for (const auto &to: graph[from]) { sz += dfs1(to, graph, cnt); } if (sz <= cnt[from]) { cout << "NO\n"; exit(0); } return sz; } void resolve() { ll n; cin >> n; vector<ll> cnt(n); vector<vector<ll>> graph(n); ll root = 0; for (ll v = 0; v < n; ++v) { ll p, c; cin >> p >> c; --p; cnt[v] = c; if (p != -1) { graph[p].push_back(v); } else { root = v; } } ordered_set have; for (ll i = 1; i <= n; ++i) { have.insert(i); } dfs1(root, graph, cnt); vector<ll> res(n); dfs(root, graph, have, cnt, res); cout << "YES\n"; for (const auto &item: res) { cout << item << ' '; } cout << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); resolve(); return 0; }
cpp
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
#include <bits/stdc++.h> #define ll long long using namespace std; ll lcm(ll a, ll b){ return (a*b)/__gcd(a,b); } void solve(){ ll x; cin>>x; ll res1 = x; ll res2 = 1; ll res = x; for(ll i = 1; i*i <= x; i++){ if(x % i == 0){ if(lcm(i, x/i) == x){ if(res > max(x/i, i)){ res = max(i, x/i); res1 = i; res2 = x/i; } } } } cout<<res1<<" "<<res2<<endl; } int main() { int tc = 1; //cin>>tc; while(tc--){ solve(); } return 0; }
cpp
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
#include <bits/stdc++.h> #include <time.h> #include <random> #include <conio.h> typedef long double ld; typedef long long ll; #define rall(a) a.rbegin(), a.rend() #define all(a) a.begin(), a.end() #define accepdet cout << "YES\n" #define error cout << "NO\n" /// author: University ITMO using namespace std; bool arr(vector < ll > &a) { return is_sorted(a.begin(), a.end());} ll Sum(vector < ll > &a) { return accumulate(a.begin(), a.end(), 0);} ll mod = 1000000007; bool flag = true; ll k = 0, d = 0; ll powing(ll x, ll n) { if (n == 0) return 1; ll r = powing(x, n / 2); r = (r * r) % mod; if (n & 1) r = (r * 2) % mod; return r; } ll summa(ll n) {return n * (n + 1) / 2;} ll fact(ll n) { return n * (n - 1) / 2; } void func() { ll n, Robo = 0, Bionic = 0; cin >> n; vector < ll > a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) { cin >> b[i]; Robo += (!b[i] and a[i] > 0); Bionic += (b[i] > 0 and !a[i]); } if (!Robo) { cout << "-1\n"; return; } cout << Bionic / Robo + 1 << "\n"; } int main() { setlocale(LC_ALL, "Russian"); srand(time(NULL)); ios_base::sync_with_stdio(true); cin.tie(0); cout.tie(0); ll t = 1; //cin >> t; while (t--) { func(); } return 0; }
cpp
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { cin.tie(0);cin.sync_with_stdio(0); cout.tie(0);cout.sync_with_stdio(0); int t= 1; cin >>t ; while (t--) { int a , b , p ; cin >> a >> b >> p ; string s ; cin >> s; int n = s.size() ; vector<ll> cost(n+1 , 0 ); cost[n] =0 ; cost[n-1] = (s[n-2] == 'A' ? a : b) ; int ans = n ; if(cost[n-1] <= p) ans = n-1 ; for(int i = n-2 ; i >= 1; i--) { cost[i] = cost[i+1] ; if(s[i-1] != s[i]) cost[i] += (s[i-1] == 'A' ? a : b) ; if(cost[i] <= p) ans = i ; } cout << ans << "\n" ; } return 0; }
cpp
1310
E
E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function ff of multiset aa as the multiset of number of occurences of every number, that is present in aa.E.g., f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}.Let's define fk(a)fk(a), as applying ff to array aa kk times: fk(a)=f(fk−1(a)),f0(a)=afk(a)=f(fk−1(a)),f0(a)=a. E.g., f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}.You are given integers n,kn,k and you are asked how many different values the function fk(a)fk(a) can have, where aa is arbitrary non-empty array with numbers of size no more than nn. Print the answer modulo 998244353998244353.InputThe first and only line of input consists of two integers n,kn,k (1≤n,k≤20201≤n,k≤2020).OutputPrint one number — the number of different values of function fk(a)fk(a) on all possible non-empty arrays with no more than nn elements modulo 998244353998244353.ExamplesInputCopy3 1 OutputCopy6 InputCopy5 6 OutputCopy1 InputCopy10 1 OutputCopy138 InputCopy10 2 OutputCopy33
[ "dp" ]
#include<bits/stdc++.h> #define ll long long #define gmax(x,y) x=max(x,y) #define gmin(x,y) x=min(x,y) #define F first #define S second #define P pair #define FOR(i,a,b) for(int i=a;i<=b;i++) #define rep(i,a,b) for(int i=a;i<b;i++) #define V vector #define RE return #define ALL(a) a.begin(),a.end() #define MP make_pair #define PB emplace_back #define PF push_front #define FILL(a,b) memset(a,b,sizeof(a)) #define lwb lower_bound #define upb upper_bound #define lc (x<<1) #define rc ((x<<1)|1) #define sz(x) ((int)x.size()) using namespace std; const int mod=998244353; void add(int &x,int y){ x+=y; if(x>=mod)x-=mod; } int dp[2050][2050],n,k,cnt=0; int val[2050],len; bool dfs(int x){ if(len){ V<int> now; FOR(i,1,len)now.PB(val[i]); bool f=1;reverse(ALL(now)); rep(i,1,k-1){ int tv=0;V<int> to; for(auto u:now){ ++tv; FOR(j,1,u)to.PB(tv); if(to.size()*(to.size()+1)/2>n){ f=0;break; } } if(!f)break; reverse(ALL(to)); now=to; int s=0; FOR(i,1,sz(to))s+=to[i-1]*i; if(s>n){ f=0;break; } } if(f)cnt++;else RE 0; } FOR(i,x,n){ val[++len]=i; bool now=dfs(i); --len; if(!now)break; } RE 1; } signed main(){ ios::sync_with_stdio(0); cin.tie(0); cin>>n>>k; if(k==1){ dp[0][0]=1; int sum=0; FOR(i,1,n)FOR(j,i,n){ dp[i][j]=dp[i-1][j-1]; add(dp[i][j],dp[i][j-i]); add(sum,dp[i][j]); } cout<<sum<<'\n'; }else if(k==2){ dp[0][0]=1; int ans=0; FOR(i,1,n)FOR(j,0,n)if(dp[i-1][j]){ int mul=i*(i+1)/2; FOR(k,0,n){ if(j+k*mul>n)break; add(dp[i][j+k*mul],dp[i-1][j]); if(k)add(ans,dp[i-1][j]); } } cout<<ans<<'\n'; }else{ dfs(1); cout<<cnt; } RE 0; }
cpp
1322
B
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2 1 2 OutputCopy3InputCopy3 1 2 3 OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
#include <bits/stdc++.h> using namespace std; //#define int long long typedef pair<int,int> PII; typedef long long LL; const int INF=0x3f3f3f3f; const long long LNF=0x3f3f3f3f3f3f3f3f; const int mod=998244353; const int N=400010,M=N<<1; inline int read(){ int f=1,x=0;char s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();} while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();} return x*f; } int n; int a[N],b[N]; bool check(int x){ for(int i=1;i<=n;++i)b[i]=a[i]%(1<<(x+1)); int l1=1<<x,r1=(1<<(x+1))-1; int l2=(1<<x)+(1<<(x+1)),r2=(1<<(x+2))-1; sort(b+1,b+1+n); int j1=1,j2=1; LL res=0; for(int i=n;i>=1;--i){ while(j1<=n&&b[i]+b[j1]<l1)++j1; while(j2<=n&&b[i]+b[j2]<=r1)++j2; res+=j2-1-j1+1; if(j1<=i&&i<j2)--res; } j1=1,j2=1; for(int i=n;i>=1;--i){ while(j1<=n&&b[i]+b[j1]<l2)++j1; while(j2<=n&&b[i]+b[j2]<=r2)++j2; res+=j2-j1; if(j1<=i&&i<j2)--res; } res>>=1; return res&1; } void solve(){ cin>>n; for(int i=1;i<=n;++i)cin>>a[i]; int res=0; for(int i=0;i<=24;++i)res|=(check(i)<<i); cout<<res<<'\n'; } signed main() { ios::sync_with_stdio(false),cin.tie(nullptr); int Tt=1; //cin>>Tt; while(Tt--){ solve(); } return 0; }
cpp
1286
F
F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3 1 10 100 OutputCopy3 InputCopy3 5 3 -2 OutputCopy2 InputCopy1 0 OutputCopy0 NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed.
[ "brute force", "constructive algorithms", "dp", "fft", "implementation", "math" ]
#include <bits/stdc++.h> #include <immintrin.h> using namespace std; #pragma GCC target("avx2") #pragma GCC optimize("Ofast,unroll-loops") #define ll long long #define int ll #define ull unsigned ll #define ld long double #define rep(a) rep1(i,a) #define rep1(i,a) rep2(i,0,a) #define rep2(i,b,a) for(int i=(b); i<((int)(a)); i++) #define rep3(i,b,a) for(int i=(b); i>=((int)(a)); i--) #define chkmin(a,b) (a=min(a,b)) #define chkmax(a,b) (a=max(a,b)) #define all(a) a.begin(),a.end() #define pii pair<int,int> #define pb push_back #define eb emplace_back #define sort_unique(a) sort(all(a)),a.resize(unique(all(a))-a.begin()) //#define inf 1010000000 #define inf 4000000000000000000 #define eps 1e-9 #define sz(a) ((int)a.size()) #define pow2(x) (1ll<<(x)) #define ceiling(a,b) (((a)+(b)-1)/(b)) #define print0(a) cout << (a) << ' ' #define ykh mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()) #ifdef i_am_noob #define bug(...) cerr << "#" << __LINE__ << ' ' << #__VA_ARGS__ << "- ", _do(__VA_ARGS__) template<typename T> void _do(vector<T> x){for(auto i: x) cerr << i << ' ';cerr << "\n";} template<typename T> void _do(set<T> x){for(auto i: x) cerr << i << ' ';cerr << "\n";} template<typename T> void _do(unordered_set<T> x){for(auto i: x) cerr << i << ' ';cerr << "\n";} template<typename T> void _do(T && x) {cerr << x << endl;} template<typename T, typename ...S> void _do(T && x, S&&...y) {cerr << x << ", "; _do(y...);} #else #define bug(...) 777771449 #endif template<typename T> void print(T && x) {cout << x << "\n";} template<typename T, typename... S> void print(T && x, S&&... y) {cout << x << ' ';print(y...);} const int maxn=1<<20; const int N=1<<20,LG=__lg(N); using u32=uint32_t; void fadd(u32* arr1, u32* arr2, u32* res){ __m256 reg1=_mm256_loadu_ps((float*)arr1),reg2=_mm256_loadu_ps((float*)arr2); __m256i reg3=_mm256_add_epi32((__m256i)reg1,(__m256i)reg2); _mm256_storeu_ps((float*)res,(__m256)reg3); } void fsub(u32* arr1, u32* arr2, u32* res){ __m256 reg1=_mm256_loadu_ps((float*)arr1),reg2=_mm256_loadu_ps((float*)arr2); __m256i reg3=_mm256_sub_epi32((__m256i)reg1,(__m256i)reg2); _mm256_storeu_ps((float*)res,(__m256)reg3); } void ma_u32(u32* arr1, u32* arr2, u32* arr3, u32* res){ __m256 reg1=_mm256_loadu_ps((float*)arr1),reg2=_mm256_loadu_ps((float*)arr2),reg3=_mm256_loadu_ps((float*)arr3); __m256i reg4=_mm256_mullo_epi32((__m256i)reg1,(__m256i)reg2); __m256i reg5=_mm256_add_epi32((__m256i)reg3,reg4); _mm256_storeu_ps((float*)res,(__m256)reg5); } void sos(u32* arr){ for(int i=0; i<3; ++i) for(int j=0; j<N; ++j) if(j>>i&1) arr[j]+=arr[j^(1<<i)]; for(int i=3; i<LG; ++i) for(int j=0; j<N; j+=8) if(j>>i&1) fadd(&arr[j],&arr[j^(1<<i)],&arr[j]); } void sos_rev(u32* arr){ for(int i=0; i<3; ++i) for(int j=0; j<N; ++j) if(j>>i&1) arr[j]-=arr[j^(1<<i)]; for(int i=3; i<LG; ++i) for(int j=0; j<N; j+=8) if(j>>i&1) fsub(&arr[j],&arr[j^(1<<i)],&arr[j]); } void subset_conv(u32* arr1, u32* arr2, u32* res, int x=0, int y=0){ alignas(64) u32 f[LG+1][N],g[LG+1][N]; memset(f,0,sizeof f),memset(g,0,sizeof g),memset(res,0,sizeof res); for(int i=0; i<N; ++i){ int t=__builtin_popcount(i); if(t<x) assert(!arr1[t]); if(t<y) assert(!arr2[t]); f[t][i]=arr1[i],g[t][i]=arr2[i]; } for(int i=x; i<=LG; ++i) sos(f[i]); for(int i=y; i<=LG; ++i) sos(g[i]); for(int i=x+y; i<=LG; ++i){ alignas(64) u32 h[N]; memset(h,0,sizeof h); for(int j=x; j<=i-y; ++j) for(int _=0; _<N; _+=8) ma_u32(&f[j][_],&g[i-j][_],&h[_],&h[_]); sos_rev(h); for(int j=0; j<N; ++j) if(__builtin_popcount(j)==i) res[j]=h[j]; } } //i_am_noob //#define wiwihorz void balbitorz(){} int n,a[20]; vector<vector<int>> to(maxn); u32 arr[12][1<<20]; bool check(u32* arr){ bool res=0; for(int i=0; i<(1<<n); ++i) res|=arr[i]; return res; } void orzck(){ cin >> n; int cur=0; rep(n){ int x; cin >> x; if(x) a[cur++]=x; } n=cur; for(int s=0; s<(1<<n); ++s){ int x=__builtin_popcount(s); int tot=0; for(int i=0; i<n; ++i) if(s>>i&1) tot+=a[i]; if(!((tot+x)&1)) continue; int y=(x+1)/2; int s1=0; for(int i=0; i<n; ++i) if(s>>i&1){ if(y==0) break; s1|=1<<i,y--; } to[s^s1].pb(s1); } for(int s=1; s<(1<<n); ++s) if(!to[s].empty()){ //cout << "a " << s << endl; int x=__builtin_popcount(s); vector<array<int,3>> vec; for(int ss=s; ; ss=(ss-1)&s){ int tot=0; for(int i=0; i<n; ++i) if(s>>i&1){ if(ss>>i&1) tot+=a[i]; else tot-=a[i]; } vec.pb({tot,s,ss}); if(!ss) break; } for(auto s2: to[s]) for(int ss=s2; ; ss=(ss-1)&s2){ int tot=0; for(int i=0; i<n; ++i) if(s2>>i&1){ if(ss>>i&1) tot+=a[i]; else tot-=a[i]; } vec.pb({tot,s2,ss}); if(!ss) break; } sort(all(vec)); deque<pii> dq; for(auto [val,s2,ss]: vec){ if(s2==s){ dq.pb({val,ss}); if(dq.size()>3) dq.pop_front(); } else{ for(auto [i,j]: dq) if(val-i<=x*2&&(j!=0||ss!=s2)&&(j!=s||ss!=0)) arr[1][s|s2]=1; } } reverse(all(vec)); dq.clear(); for(auto [val,s2,ss]: vec){ if(s2==s){ dq.pb({val,ss}); if(dq.size()>3) dq.pop_front(); } else{ for(auto [i,j]: dq) if(i-val<=x*2&&(j!=0||ss!=s2)&&(j!=s||ss!=0)) arr[1][s|s2]=1; } } } //for(int s=0; s<(1<<n); ++s) cout << s << ' ' << arr[1][s] << endl; if(!check(arr[1])){ cout << n << "\n"; return; } for(int i=1; i<8; i<<=1){ subset_conv(arr[i],arr[i],arr[i*2],i*2,i*2); if(!check(arr[i*2])){ int cur=i; for(int j=i/2; j; j>>=1){ subset_conv(arr[cur],arr[j],arr[cur+j],cur*2,j*2); if(check(arr[cur+j])) cur+=j; } cout << n-cur << "\n"; return; } if(i==4){ int cur=8; for(int j=2; j; j>>=1){ subset_conv(arr[cur],arr[j],arr[cur+j],cur*2,j*2); if(check(arr[cur+j])) cur+=j; } cout << n-cur << "\n"; return; } } } signed main(){ ios_base::sync_with_stdio(0),cin.tie(0); // #ifdef i_am_noob // freopen("input1.txt","r",stdin); // freopen("output1.txt","w",stdout); // freopen("output2.txt","w",stderr); // #endif cout << fixed << setprecision(15); ld start=clock(); balbitorz(); int t; #ifdef wiwihorz cin >> t; #else t=1; #endif while(t--) orzck(); bug((clock()-start)/CLOCKS_PER_SEC); return 0; }
cpp
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
#include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> #define endl '\n' #define int long long #define all(a) a.begin(),a.end() #define pb push_back #define mod 1000000007 #define inf 1e18 #define ppb pop_back #define ff first #define ss second /// order_of_key return number of elements less than x -> os.order_of_key(x) /// cout << "oth element : " << *os.find_by_order(0) << endl; so it returns value of index int lcm(int x,int y) { return (x * 1LL * y) / __gcd(x,y); } // Graph on 2D Grid /*----------------------Graph Moves----------------*/ //const int dx[]={+1,-1,+0,+0}; //const int dy[]={+0,+0,+1,-1}; //const int dx[]={+0,+0,+1,-1,-1,+1,-1,+1}; // Kings Move //const int dy[]={-1,+1,+0,+0,+1,+1,-1,-1}; // Kings Move //const int dx[]={-2, -2, -1, -1, 1, 1, 2, 2}; // Knights Move //const int dy[]={-1, 1, -2, 2, -2, 2, -1, 1}; // Knights Move /*------------------------------------------------*/ #define debug(x); cerr << #x <<" "; _print(x); cerr << endl; void _print(int t) {cerr << t;} void _print(string t) {cerr << t;} void _print(char t) {cerr << t;} void _print(double t) {cerr << t;} template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} int dp[200005],maxc[30]; void solve() { int n,i,j,ans=0; string s; cin >> n >> s; for(i=0; i<n; i++) { dp[i] = 1; } for(i=0; i<n; i++) { for(j=25; j>s[i]-'a'; j--) { dp[i] = max(dp[i] , maxc[j] + 1); } maxc[s[i]-'a'] = max(maxc[s[i]-'a'] , dp[i]); ans = max(maxc[s[i]-'a'] , ans); } cout << ans << endl; for(i=0; i<n; i++) { cout << dp[i] << " "; } cout << endl; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; while(t--) { solve(); } } /** Test Case : **/
cpp
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9 abacbecfd OutputCopyYES 001010101 InputCopy8 aaabbcbb OutputCopyYES 01011011 InputCopy7 abcdedc OutputCopyNO InputCopy5 abcde OutputCopyYES 00000
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
#include <iostream> using namespace std; int main() { int n; string s, res = ""; cin >> n >> s; char c = 'a', d = 'a'; for (int i = 0; i < n; i++) { if (s[i] >= c) { res += "0"; c = s[i]; } else if (s[i] >= d) { res += "1"; d = s[i]; } else { cout << "NO"; return 0; } } cout << "YES" << endl << res; }
cpp
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
#include<bits/stdc++.h> #define int long long using namespace std; struct node{ int x,y; }p[100]; int dist(int a,int b,int c,int d){ if(a<c) swap(a,c); if(b<d) swap(b,d); return a-c+b-d; } signed main(){ int x,y,a,b,c,d,sx,sy,t,m=1,cnt=0,ans=-1; scanf("%lld%lld%lld%lld%lld%lld%lld%lld%lld",&x,&y,&a,&c,&b,&d,&sx,&sy,&t); p[1].x=x,p[1].y=y; while(dist(sx,sy,p[m].x*a+b,p[m].y*c+d)<=t||(dist(sx,sy,p[m].x*a+b,p[m].y*c+d)>t&&p[m].x*a+b<sx&&p[m].y*c+d<sy)){ m++,p[m].x=p[m-1].x*a+b,p[m].y=p[m-1].y*c+d; } for(int i=1;i<=m;i++){ int lasx=sx,lasy=sy,tot=0,j;cnt=0; for(j=i;j>0&&cnt+dist(lasx,lasy,p[j].x,p[j].y)<=t;j--){ cnt+=dist(lasx,lasy,p[j].x,p[j].y); lasx=p[j].x,lasy=p[j].y,tot++; } if(j!=0){ans=max(ans,tot);continue;} lasx=p[1].x,lasy=p[1].y; for(j=i+1;j<=m&&cnt+dist(lasx,lasy,p[j].x,p[j].y)<=t;j++){ cnt+=dist(lasx,lasy,p[j].x,p[j].y); lasx=p[j].x,lasy=p[j].y,tot++; } ans=max(ans,tot); } printf("%lld\n",ans); return 0; }
cpp
1320
D
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5 11011 3 1 3 3 1 4 2 1 2 3 OutputCopyYes Yes No
[ "data structures", "hashing", "strings" ]
#include <bits/stdc++.h> using namespace std; #define int long long #define N 200001 int P = 7; int M1 = 1000000009, M2 = 1000000007; int Power(int x, int y, int M){ int res = 1; while (y){ if (y % 2){ res *= x; res %= M; } x *= x; x %= M; y >>= 1; } return res; } int ModInv(int a, int M){ return Power(a, M - 2, M); } class StringHash{ public: int M; string s; int n; vector<int> pref; vector<int> b; vector<int> nb; vector<int> st; StringHash(int n, string s, int M){ this->n = n; this->s = s; this->M = M; pref.assign(n, 0); b.assign(n, 0); nb.assign(n, 0); st.assign(n, 0); int pr = 1; int c = 0; for (int i = 0; i < n; i++){ st[i] = ModInv(pr, M); if (s[i] == '0'){ if (c % 2){ b[i] = 1; } pref[i] = (1 + b[i]) * pr; pr *= P; pr %= M; c = 0; } else c++; if (i) pref[i] += pref[i - 1]; pref[i] %= M; } for (int i = n - 2; i >= 0; i--){ if (s[i] != '0') b[i] = b[i + 1]; } nb[n - 1] = (s[n - 1] == '0' ? 0 : 1); for (int i = n - 2; i >= 0; i--){ nb[i] = (s[i] == '0' ? 0 : (nb[i + 1] ^ 1)); } // for (int i = 0; i < n; i++) cout << pref[i] << ' '; // cout << endl; // for (int i = 0; i < n; i++) cout << b[i] << ' '; // cout << endl; // for (int i = 0; i < n; i++) cout << nb[i] << ' '; // cout << endl; } int hashval(int i, int l){ int val = pref[i + l - 1] - (i == 0 ? 0 : pref[i - 1]); val %= M; val *= st[i]; val -= b[i] + 1; val += nb[i] + 1; val %= M; val += M; val %= M; return val; } }; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; string s; cin >> s; int c1[n]; c1[0] = (s[0] == '0'); for (int i = 1; i < n; i++){ c1[i] = c1[i - 1] + (s[i] == '0'); } StringHash H1(n, s, M1); StringHash H2(n, s, M2); int q; cin >> q; for (int i = 0; i < q; i++){ int l1, l2, len; cin >> l1 >> l2 >> len; l1--; l2--; if (c1[l1 + len - 1] - (l1 == 0 ? 0 : c1[l1 - 1]) == 0){ cout << (c1[l2 + len - 1] - (l2 == 0 ? 0 : c1[l2 - 1]) == 0 ? "YES" : "NO") << endl; } else if (c1[l2 + len - 1] - (l2 == 0 ? 0 : c1[l2 - 1]) == 0){ cout << "NO" << endl; } else{ // cout << H1.hashval(l1, len) << ' ' << H1.hashval(l2, len) << ' ' << H2.hashval(l1, len) << ' ' << H2.hashval(l2, len) << endl; if (H1.hashval(l1, len) == H1.hashval(l2, len) && H2.hashval(l1, len) == H2.hashval(l2, len)){ cout << "YES" << endl; } else cout << "NO" << endl; } } }
cpp
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 5; int T, n, a[N]; int main () { scanf ("%d", &T); while (T --) { scanf ("%d", &n); for (int i = 1; i <= n; i ++) scanf ("%d", &a[i]); int l = 1, r = n; while (a[l + 1] >= l) l ++; while (a[r - 1] >= n - r + 1) r --; if (l >= r) puts ("Yes"); else puts ("No"); } return 0; }
cpp
1299
D
D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8 1 2 0 2 3 1 2 4 3 2 6 2 3 4 8 3 5 4 5 4 5 5 6 6 OutputCopy2 InputCopy7 9 1 2 0 1 3 1 2 3 9 2 4 3 2 5 4 4 5 7 3 6 6 3 7 7 6 7 8 OutputCopy1 InputCopy4 4 1 2 27 1 3 1 1 4 1 3 4 0 OutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.
[ "bitmasks", "combinatorics", "dfs and similar", "dp", "graphs", "graphs", "math", "trees" ]
#include<bits/stdc++.h> using namespace std; #define I inline int #define V inline void #define FOR(i,a,b) for(int i=a;i<=b;i++) #define ROF(i,a,b) for(int i=a;i>=b;i--) #define REP(u) for(int i=h[u],v;v=e[i].t,i;i=e[i].n) const int N=1e5+1,M=400,mod=1e9+7,bit[]={1,3,7,15,31}; V check(int&x){x-=mod,x+=x>>31&mod;} int n,m,tot,qwq,txt[N],dfn[N]; int h[N],fa[N],dep[N],dis[N],tag[N]; int to[M][M],dp[N][M],pre[N],id[1<<15]; struct edge{int t,n,w;}e[N<<1]; struct bas{ int a[5],flag; I ins(int x){ ROF(i,4,0)if(x>>i&1){ if(a[i])x^=a[i]; else return a[i]=x,1; } return flag=1,0; } I comp(){return a[0]|a[1]<<1|a[2]<<3|a[3]<<6|a[4]<<10;} V assign(int x){a[0]=x&1,a[1]=x>>1&3,a[2]=x>>3&7,a[3]=x>>6&15,a[4]=x>>10;} I hash(){ FOR(i,0,4)if(a[i]&&!(a[i]>>i&1))return -1; FOR(i,0,4)FOR(j,i+1,4)if(a[j]>>i&1)a[j]^=a[i]; return comp(); } }t[N][2],tmp; I merge(int x,int y){ static bas tx,ty;tx.assign(x),ty.assign(y); FOR(i,0,4)if(ty.a[i]&&!tx.ins(ty.a[i]))return 2; return tx.hash(); } V add_edge(int x,int y,int w){ if(y-1)e[++tot]=(edge){y,h[x],w},h[x]=tot; if(x-1)e[++tot]=(edge){x,h[y],w},h[y]=tot; } I find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);} V con(int x,int y){if(x-1&&y-1)fa[find(x)]=find(y);} V input(){ scanf("%d%d",&n,&m); FOR(i,1,n)fa[i]=i;int x,y,w; while(m--)scanf("%d%d%d",&x,&y,&w),con(x,y),add_edge(x,y,w); } queue<int>q; V bfs(){ for(q.push(1);!q.empty();q.pop()){ int u=q.front(),p=dfn[find(u)]; REP(u) if(!dep[v]) dep[v]=dep[u]+1,pre[v]=u,dis[v]=dis[u]^e[i].w,q.push(v); else if(u>v&&pre[u]!=v){ if(dep[u]==dep[v]&&dep[u]==1)tag[p]=dis[u]^dis[v]^e[i].w; else t[p][0].ins(dis[u]^dis[v]^e[i].w); } } } V init(){ FOR(i,2,n)if(!dfn[find(i)])dfn[find(i)]=++qwq; tot=0,memset(tag,-1,sizeof(tag)),bfs(),dp[0][1]=1; int p,x=0; FOR(i,0,(1<<15)-1){ tmp.assign(i),p=tmp.hash(); if(~p&&!id[p])txt[id[p]=++tot]=p; } FOR(i,1,qwq)if(~tag[i])t[i][1]=t[i][0],t[i][1].ins(tag[i]); FOR(i,1,tot)FOR(j,1,tot)to[i][j]=id[merge(txt[i],txt[j])]; } V work(){ int p,ans=0; FOR(i,1,qwq){ if(!t[i][0].flag){ p=id[t[i][0].hash()]; FOR(j,1,tot)check(dp[i][to[j][p]]+=(dp[i-1][j]<<!!~tag[i])%mod); } if(~tag[i]&&!t[i][1].flag){ p=id[t[i][1].hash()]; FOR(j,1,tot)check(dp[i][to[j][p]]+=dp[i-1][j]); } FOR(j,1,tot)check(dp[i][j]+=dp[i-1][j]); } FOR(i,1,tot)check(ans+=dp[qwq][i]); cout<<ans<<'\n'; } int main(){ input(); init(); work(); return 0; }
cpp
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1 OutputCopy1.000000000000 InputCopy2 OutputCopy1.500000000000 NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
[ "combinatorics", "greedy", "math" ]
#include <bits/stdc++.h> using namespace std; #define all(x) x.begin(),x.end() #define pb push_back #define ll long long #define repp(n) for(int i=0;i<n;i++) //typedef __int128 lll; const ll MOD=998244353; const ll mod = 1e9+7; #define ret(a) cout<<a<<"\n"; return #define rep(i,a,b) for(long long i = a; i < b; i++) double n; void solve(){ cin>>n; double ans = 0 ; while(n>0){ ans += (1/n); n--; } cout<<ans<<endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); // int t; // cin>>t; // while(t--) solve(); return 0; }
cpp
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6 1 10 19 9876 12345 1000000000 OutputCopy1 11 21 10973 13716 1111111111
[ "math" ]
#include <iostream> #include <vector> #include <algorithm> using namespace std; int operation(int); int main() { int t,s,value; cin>>t; vector<int> testcases; for (int i = 0; i <t; i++) { cin>>value; testcases.push_back(value); } for (int i = 0; i <t; i++) { cout<<operation(testcases[i])<<endl; } return 0; } int operation(int bal) { int credit,debit,quot=0; int finaldebit=0; while (bal>=10) { credit=0,debit=0; quot=bal/10; credit=quot; debit=quot*10; finaldebit+=debit; bal=bal+credit-debit; } finaldebit=finaldebit+bal; return finaldebit; }
cpp
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(0), ios::sync_with_stdio(0); int t, n; cin >> t; while (t--) { cin >> n; vector<int> a(2*n); for (int i = 0; i < 2*n; i++) cin >> a[i]; sort(a.begin(), a.end()); cout << (a[n] - a[n-1]) << '\n'; } }
cpp
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
#include <iostream> #include <vector> int n; std::vector<int> x, y; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cin >> n; if (n % 2 == 1) { std::cout << "NO\n"; return 0; } x.resize(n); y.resize(n); for (int i = 0; i < n; ++i) std::cin >> x[i] >> y[i]; int x0 = x[0] + x[n / 2]; int y0 = y[0] + y[n / 2]; for (int i = 0; i < n / 2; ++i) { if (x[i] + x[i + n / 2] != x0 || y[i] + y[i + n / 2] != y0) { std::cout << "NO\n"; return 0; } } std::cout << "YES\n"; return 0; }
cpp
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3 1 1 4 5 5 11 OutputCopyYES YES NO NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.
[ "binary search", "brute force", "math", "ternary search" ]
#include <bits/stdc++.h> using namespace std; using ll=long long; bool isPrime(ll n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (ll i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } 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; } int main() { // your code goes here ll test; cin>>test; while(test--) { ll n,d,A=0,B=0; cin>>n>>d; A=(n-1)*(n-1); B=(n-2)*(n-2); if((A-4*(d-n))>=0||(B-4*(d-n+1))>=0) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
cpp
1292
C
C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3 1 2 2 3 OutputCopy3 InputCopy5 1 2 1 3 1 4 3 5 OutputCopy10 NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.
[ "combinatorics", "dfs and similar", "dp", "greedy", "trees" ]
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(),(x).end() #define rep(i,n) for(int i=0;i<(n);i++) #define rep3(i,m,n) for(int i=(m);i<(n);i++) #define foreach(x,a) for(auto& (x) : (a) ) #define endl '\n' #define dump(x) cout << #x << " = " << (x) << endl; #define YES(n) cout << ((n) ? "YES" : "NO" ) << endl #define Yes(n) cout << ((n) ? "Yes" : "No" ) << endl #define POSSIBLE(n) cout << ((n) ? "POSSIBLE" : "IMPOSSIBLE" ) << endl #define Possible(n) cout << ((n) ? "Possible" : "Impossible" ) << endl #define pb(a) push_back(a) #define sz(x) ((int)(x).size()) #define in(a,us) (us).find(a)!=(us).end() template<typename S> using Vec = vector<S>; template<typename S, typename T> using P = pair<S,T>; template<typename S, typename T, typename U> using Tpl = tuple<S,T,U>; using ll = long long; using ld = long double; using Pii = P<int, int>; using Pll = P<ll,ll>; using Tiii = Tpl<int,int,int>; using Tll = Tpl<ll,ll,ll>; using Vi = Vec<int>; using VVi = Vec<Vi>; template<typename S, typename T> using umap = unordered_map<S,T>; template<typename S> using uset = unordered_set<S>; using Graph = VVi; int depth[3002][3002]; int par[3002][3002]; int childn[3002][3002]; ll DP[3002][3002]; void dfs(int v, int root, Graph &g){ childn[root][v] = 1; for(auto v1: g[v]){ if (v1!=par[root][v]){ depth[root][v1] = depth[root][v]+1; par[root][v1] = v; dfs(v1, root, g); childn[root][v] += childn[root][v1]; } } } int main(){ cin.tie(0)->sync_with_stdio(0); int n; cin >> n; Graph g(n,Vi()); rep(i,n-1){ int u,v; cin >> u >> v; u--;v--; g[u].push_back(v); g[v].push_back(u); } rep(i,n) { par[i][i] = -1; depth[i][i] = 0; dfs(i, i, g); } Vec<Vec<Pii>> p(n, Vec<Pii>()); rep(i,n) rep3(j,i+1,n){ p[depth[i][j]].push_back({i,j}); } rep(i,n) DP[i][i] = 0; ll ans = 0; rep(i,n){ for(auto [u,v]: p[i]){ DP[u][v] = max(DP[u][par[u][v]],DP[par[v][u]][v]) + childn[u][v]*childn[v][u]; DP[v][u] = DP[u][v]; ans = max(ans, DP[u][v]); } } cout << ans << endl; }
cpp
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5 1 2 2 3 3 4 4 5 5 1 3 1 2 2 1 4 1 3 2 1 4 1 3 3 4 2 3 3 9 5 2 3 3 9 OutputCopyYES YES NO YES NO NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
#include <bits/stdc++.h> using namespace std; #define int int64_t int n; const int LOG = 20; const int N = 1e5 + 10; vector<int> g[N]; int depth[N]; int LCA[N][LOG]; void dfs(int node, int parent) { depth[node] = depth[parent] + 1; LCA[node][0] = parent; for(int child : g[node]) { if(child == parent) { continue; } dfs(child, node); } } void build() { for(int j = 1; j < LOG; j++) { for(int i = 1; i <= n; i++) { LCA[i][j] = LCA[LCA[i][j - 1]][j - 1]; } } } int find(int a, int b) { if(depth[b] < depth[a]) { swap(a, b); } int diff = depth[b] - depth[a]; for(int j = 0; j < LOG; j++) { if((diff & (1 << j))) { b = LCA[b][j]; } } if(a == b) { return a; } for(int j = LOG - 1; j >= 0; j--) { if(LCA[a][j] != LCA[b][j]) { a = LCA[a][j]; b = LCA[b][j]; } } return LCA[a][0]; } int dist(int a, int b) { int lca = find(a, b); return depth[a] + depth[b] - 2 * depth[lca]; } int32_t main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n; for(int i = 0; i + 1 < n; i++) { int a, b; cin >> a >> b; g[a].push_back(b); g[b].push_back(a); } depth[0] = -1; dfs(1, 0); build(); int q; cin >> q; while(q--) { int x, y, a, b, k; cin >> x >> y >> a >> b >> k; int without = dist(a, b); if((without & 1) == (k & 1) && without <= k) { cout << "YES\n"; continue; } int with = dist(a, x) + dist(b, y) + 1; if((with & 1) == (k & 1) && with <= k) { cout << "YES\n"; continue; } with = dist(a, y) + dist(b, x) + 1; if((with & 1) == (k & 1) && with <= k) { cout << "YES\n"; continue; } cout << "NO\n"; } return 0; }
cpp