id,desc,data,time_limit,memory_limit,std,test,cate,difficulty 1,"Given a sequence of length $n$, there are $q$ queries to find the maximum value in specified intervals. Return the XOR sum of the answers to these $q$ queries. solution main function ```cpp class Solution { public: int solve(vector& num, vector > q) { } }; ``` Example 1: Input: num = [5,4,8,9,3,4,6] , q = [[0,3],[3,5]] Output: 0 Constraints: 1 <= n,q <= @data 1 <= s_i <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[200, 100, 64], [1600, 800, 64], [12800, 6400, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(vector& nums, vector>& queries) { int xorSum = 0; for (const auto& q : queries) { int l = q.first; int r = q.second; int maxVal = INT_MIN; for (int i = l; i <= r; ++i) { maxVal = max(maxVal, nums[i]); } xorSum ^= maxVal; } return xorSum; } int solve2(vector& nums, vector>& queries) { int n = nums.size(); int blockSize = sqrt(n); int numBlocks = (n + blockSize - 1) / blockSize; vector blockMax(numBlocks, INT_MIN); for (int i = 0; i < n; ++i) { int blockIndex = i / blockSize; blockMax[blockIndex] = max(blockMax[blockIndex], nums[i]); } auto query = [&](int l, int r) -> int { int maxVal = INT_MIN; while (l <= r && l % blockSize != 0) { maxVal = max(maxVal, nums[l]); ++l; } while (l + blockSize - 1 <= r) { int blockIndex = l / blockSize; maxVal = max(maxVal, blockMax[blockIndex]); l += blockSize; } while (l <= r) { maxVal = max(maxVal, nums[l]); ++l; } return maxVal; }; int xorSum = 0; for (const auto& q : queries) { int l = q.first; int r = q.second; xorSum ^= query(l, r); } return xorSum; } int solve3(vector& nums, vector>& queries) { int n = nums.size(); int log = log2(n) + 1; vector> sparse(n, vector(log)); for (int i = 0; i < n; ++i) { sparse[i][0] = nums[i]; } for (int j = 1; (1 << j) <= n; ++j) { for (int i = 0; i + (1 << j) - 1 < n; ++i) { sparse[i][j] = max(sparse[i][j - 1], sparse[i + (1 << (j - 1))][j - 1]); } } auto query = [&](int l, int r) -> int { int len = r - l + 1; int k = log2(len); return max(sparse[l][k], sparse[r - (1 << k) + 1][k]); }; int xorSum = 0; for (const auto& q : queries) { int l = q.first; int r = q.second; xorSum ^= query(l, r); } return xorSum; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector< int > s; vector< pair > q; for(int i=1,x;i<=n;i++) { scanf(""%d"",&x); s.push_back(x); } for(int i=1,x,y;i<=m;i++) { scanf(""%d"",&x); scanf(""%d"",&y); q.push_back({x,y}); } // solve Solution solution; auto result = solution.solve(s,q); // output cout << result << ""\n""; return 0; }",data_structures,medium 2,"Given a sequence of length n, there are q queries for the product of a subarray. Each query's answer is mod p. Return the XOR sum of the answers to the q queries. solution main function ```cpp class Solution { public: int solve(vector& num, vector > q,int p) { } }; ``` Example 1: Input: num = [5,4,8,9,3,4,6] , q = [[0,3],[3,5]], p = 10 Output: 8 Constraints: 1 <= n,q <= @data 1 <= s_i <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[281, 100, 64], [2250, 800, 64], [18000, 6400, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(vector& num, vector>& queries, int p) { #define int long long int xor_sum = 0; for (auto& query : queries) { int l = query.first, r = query.second; long long product = 1; for (int i = l; i <= r; ++i) { product = (product * num[i]) % p; } xor_sum ^= product; } return xor_sum; #undef int } int solve2(vector& num, vector>& queries, int p) { #define int long long int n = num.size(); int block_size = sqrt(n); vector block_product((n + block_size - 1) / block_size, 1); for (int i = 0; i < n; ++i) { block_product[i / block_size] = (block_product[i / block_size] * num[i]) % p; } int xor_sum = 0; for (auto& query : queries) { int l = query.first, r = query.second; long long product = 1; int start_block = l / block_size; int end_block = r / block_size; if (start_block == end_block) { for (int i = l; i <= r; ++i) { product = (product * num[i]) % p; } } else { for (int i = l; i < (start_block + 1) * block_size; ++i) { product = (product * num[i]) % p; } for (int i = start_block + 1; i < end_block; ++i) { product = (product * block_product[i]) % p; } for (int i = end_block * block_size; i <= r; ++i) { product = (product * num[i]) % p; } } xor_sum ^= product; } return xor_sum; #undef int } int solve3(vector& num, vector>& queries, int p) { #define int long long int n = num.size(); int log_n = log2(n) + 1; vector> st(n, vector(log_n)); for (int i = 0; i < n; ++i) { st[i][0] = num[i] % p; } for (int j = 1; (1 << j) <= n; ++j) { for (int i = 0; i + (1 << j) - 1 < n; ++i) { st[i][j] = (st[i][j - 1] * st[i + (1 << (j - 1))][j - 1]) % p; } } auto query_product = [&](int l, int r) { long long product = 1; for (int j = log_n - 1; j >= 0; --j) { if ((1 << j) <= r - l + 1) { product = (product * st[l][j]) % p; l += (1 << j); } } return product; }; int xor_sum = 0; for (auto& query : queries) { xor_sum ^= query_product(query.first, query.second); } return xor_sum; #undef int } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,p; cin>>n>>m>>p; vector< int > s; vector< pair > q; for(int i=1,x;i<=n;i++) { scanf(""%d"",&x); s.push_back(x); } for(int i=1,x,y;i<=m;i++) { scanf(""%d"",&x); scanf(""%d"",&y); q.push_back({x,y}); } // solve Solution solution; auto result = solution.solve(s,q,p); // output cout << result << ""\n""; return 0; }",data_structures,medium 3,"You are given a dictionary `dic` consisting of `n` strings (with characters numbered starting from 0), and then `m` strings `q`. Each string in `q` represents a query asking whether the string exists in the dictionary. If it does, return the corresponding string's index; otherwise, return 0. The final answer is the XOR sum of all the returned values. solution main function ```cpp class Solution { public: int solve(vector& dic, vector& q) { } }; ``` Example 1: Input: num = [""abc"",""ac"",""ab"",""cd""] , q = [""abc"",""cd"",""dc"",""ac""] Output: 2 Constraints: 1 <= n <= @data the length of string <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 500, 1000]",1000,"[[200, 100, 64], [1600, 800, 80], [12800, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(vector& dic, vector& q) { #define ull unsigned long long const ull bas=13331ull; int ans=0; unordered_map mp; for(int i=0;isecond); } return ans; } int solve2(vector& dic, vector& q) { #define ull unsigned long long int ans=0; for(auto str:q) { for(int i=0;i using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector< string > a,b; for(int i=1,x;i<=n;i++) { string str; cin>>str; a.push_back(str); } for(int i=1,x;i<=m;i++) { string str; cin>>str; b.push_back(str); } // solve Solution solution; auto result = solution.solve(a,b); // output cout << result << ""\n""; return 0; }",string,medium 4,"There are $n$ elements. The $i$-th element has three attributes: $a_i$, $b_i$, and $c_i$. Let $f(i)$ denote the number of $j$'s that satisfy $a_j \leq a_i$, $b_j \leq b_i$, $c_j \leq c_i$, and $j \neq i$. Returns the result of all $f(i)$ ' xor ' solution main function ```cpp class Solution { public: int solve(vector >& s) { } }; ``` Example 1: Input: num = [[3,3,3],[2,3,3],[2,3,1],[3,1,1],[3,1,2],[1,3,1],[1,1,2],[1,2,2],[1,3,2],[1,2,1]] Output: 8 Constraints: 1 <= s.length <= @data s[i].length == 3 Each element in s is $[a_i,b_i,c_i]$ 1 <= $a_i,b_i,c_i$ <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[200, 100, 64], [1600, 800, 80], [12800, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: struct Node { int a,b,c,t,sum; bool operator == (Node x) const { return a==x.a&&b==x.b&&c==x.c; } }; vector s,f; vector ans; struct BIT { int lim; vector tre; inline int lowbit(int x){return x&(-x);} inline void insert(int x,int val){for(int i=x;i<=lim;i+=lowbit(i))tre[i]+=val;} inline int query(int x){int sum=0;for(int i=x;i>0;i-=lowbit(i))sum+=tre[i];return sum;} }T; inline void CDQ(int l,int r) { if(l>=r) return ; int mid=(l+r)>>1; CDQ(l,mid); CDQ(mid+1,r); int i=l,j=mid+1,k=l; while(i<=mid&&j<=r) if(s[i].b<=s[j].b) T.insert(s[i].c,s[i].t),f[k++]=s[i++]; else s[j].sum+=T.query(s[j].c),f[k++]=s[j++]; while(i<=mid) T.insert(s[i].c,s[i].t),f[k++]=s[i++]; while(j<=r) s[j].sum+=T.query(s[j].c),f[k++]=s[j++]; for(i=l;i<=mid;i++) T.insert(s[i].c,-s[i].t); for(i=l;i<=r;i++) s[i]=f[i]; } int solve1(vector >& num) { sort(num.begin(),num.end()); int n=num.size(); int m=n; int cnt=0,out=0; T.lim = m; s.resize(n+1,{0,0,0,0,0}); f.resize(n+1,{0,0,0,0,0}); ans.resize(n+1,0); T.tre.resize(m+1,0); for(int i=1;i<=n;i++) { s[i].a=num[i-1][0]; s[i].b=num[i-1][1]; s[i].c=num[i-1][2]; s[i].t=1; s[i].sum=0; } for(int i=1;i<=n;i++) if(s[i]==s[i-1]) s[cnt].t++; else s[++cnt]=s[i]; CDQ(1,cnt); for(int i=1;i<=cnt;i++) ans[s[i].sum+s[i].t-1]+=s[i].t; for(int i=0;i >& s) { sort(s.begin(),s.end()); int n=s.size(),ans=0; for(int i=0;i=s[j][1]) if(s[i][2]>=s[j][2]) temp++; int j=i+1; while(j using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< vector > s; for(int i=1,x;i<=n;i++) { vector temp; for(int j=1;j<=3;j++) cin>>x,temp.push_back(x); s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }",data_structures,medium 5,"# Problem Statement Even after copying the paintings from famous artists for ten years, unfortunately, Eric is still unable to become a skillful impressionist painter. He wants to forget something, but the white bear phenomenon just keeps hanging over him. Eric still remembers $n$ pieces of impressions in the form of an integer array. He records them as $w_1, w_2, \ldots, w_n$. However, he has a poor memory of the impressions. For each $1 \leq i \leq n$, he can only remember that $l_i \leq w_i \leq r_i$. Eric believes that impression $i$ is unique if and only if there exists a possible array $w_1, w_2, \ldots, w_n$ such that $w_i \neq w_j$ holds for all $1 \leq j \leq n$ with $j \neq i$. Please help Eric determine whether impression $i$ is unique for every $1 \leq i \leq n$, **independently** for each $i$. Perhaps your judgment can help rewrite the final story. The main function of the solution is defined as: ```cpp class Solution { public: void solve(int &n, vector &l, vector &r, string &res) { // write your code here } }; ``` where: - return: store the answer in `res`, which is an initially empty output parameter. The answer string must contain $n$ characters. The $i$-th character should be '1' if impression $i$ is unique, and '0' otherwise. # Example 1: - Input: n = 2 l = [1, 1] r = [1, 1] - Output: 00 # Constraints: - $1 \leq n \leq @data$ - $1 \leq l[i] \leq r[i] \leq 2 * n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: void solve1(int &n, vector &l, vector &r, string &res) { vector cnt(2 * n); vector pre(2 * n + 1); for (int i = 0; i < n; i++) { l[i]--; if (l[i] + 1 == r[i]) { cnt[l[i]]++; } } for (int i = 0; i < 2 * n; i++) { pre[i + 1] = pre[i] + (cnt[i] == 0); } for (int i = 0; i < n; i++) { if (l[i] + 1 < r[i]) { res += (pre[l[i]] != pre[r[i]]) + '0'; } else { res += (cnt[l[i]] == 1) + '0'; } } } void solve2(int &n, vector &l, vector &r, string &res) { for (int i = 0; i < n; i++) { for (int j = l[i]; j <= r[i]; j++) { int flag = 0; for (int k = 0; k < n; k++) { if (k == i) continue; if (l[k] == r[k] && l[k] == j) { flag = 1; break; } } if (flag == 0) { res += '1'; break; } if (j == r[i]) res += '0'; } } } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector l(n), r(n); for (int i = 0; i < n; i++) { cin >> l[i] >> r[i]; } // solve Solution solution; string result; solution.solve(n, l, r, result); // output cout << result << ""\n""; return 0; }","binary,data_structures,greedy",hard 6,"# Problem Statement Robin's brother and mother are visiting, and Robin gets to choose the start day for each visitor. All days are numbered from $1$ to $n$. Visitors stay for $d$ continuous days, all of those $d$ days must be between day $1$ and $n$ inclusive. Robin has a total of $k$ risky 'jobs' planned. The $i$-th job takes place between days $l_i$ and $r_i$ inclusive, for $1 \le i \le k$. If a job takes place on any of the $d$ days, the visit overlaps with this job (the length of overlap is unimportant). Robin wants his brother's visit to overlap with the maximum number of **distinct jobs**, and his mother's the minimum. Find suitable start days for the visits of Robin's brother and mother. If there are multiple suitable days, choose the earliest one. The main function of the solution is defined as: ```cpp class Solution { public: pair solve(int &n, int &d, int &k, vector &l, vector &r) { // write your code here } }; ``` where: - return: pair of integers, the start days for Robin's brother and mother respectively. # Example 1: - Input: n = 2, d = 1, k = 1 l = [1], r = [2] - Output: (1, 1) # Constraints: - $1 \leq d, k \leq n \leq @data$ - $1 \leq l[i] \leq r[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: pair solve1(int &n, int &d, int &k, vector &l, vector &r) { vector L(n + 1), R(n + 1); for (int i = 0; i < k; i++) { int ll = l[i], rr = r[i]; ll--; L[ll]++; R[rr]++; } for (int i = 1; i <= n; i++) { R[i] += R[i - 1]; } for (int i = n - 1; i >= 0; i--) { L[i] += L[i + 1]; } int mx = -1; int imx = -1; int mn = n + 1; int imn = -1; for (int i = 0; i <= n - d; i++) { int v = R[i] + L[i + d]; if (v > mx) { mx = v; imx = i + 1; } if (v < mn) { mn = v; imn = i + 1; } } return {imn, imx}; } pair solve2(int &n, int &d, int &k, vector &l, vector &r) { int max = -1; int min = k + 1; int maxl = -1; int minl = -1; for (int i = 1; i + d - 1 <= n; i++) { int count = 0; for (int j = 0; j < k; j++) { if (!(r[j] < i || l[j] > i + d - 1)) { count++; } } if (count > max) { max = count; maxl = i; } if (count < min) { min = count; minl = i; } } return {maxl, minl}; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, d, k; cin >> n >> d >> k; vector l(k), r(k); for (int i = 0; i < k; i++) { cin >> l[i] >> r[i]; } // solve Solution solution; auto result = solution.solve(n, d, k, l, r); // output cout << result.first << "" "" << result.second << ""\n""; return 0; }",data_structures,hard 7,"# Problem Statement Polycarp was given an array $a$ of $n$ integers. He really likes triples of numbers, so for each $j$ ($1 \le j \le n - 2$) he wrote down a triple of elements $[a_j, a_{j + 1}, a_{j + 2}]$. Polycarp considers a pair of triples $b$ and $c$ beautiful if they differ in exactly one position, that is, one of the following conditions is satisfied: - $b_1 \ne c_1$ and $b_2 = c_2$ and $b_3 = c_3$; - $b_1 = c_1$ and $b_2 \ne c_2$ and $b_3 = c_3$; - $b_1 = c_1$ and $b_2 = c_2$ and $b_3 \ne c_3$. Find the number of beautiful pairs of triples among the written triples $[a_j, a_{j + 1}, a_{j + 2}]$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the number of beautiful pairs of triples among the pairs of the form [aj,aj+1,aj+2]. # Example 1: - Input: n = 5 a = [3, 2, 2, 2, 3] - Output: 2 # Constraints: - $3 \leq n \leq @data$ - $1 \leq a[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { long long ans = 0; map, int> mp[3]; map, int> mp2; for (int i = 0; i + 2 < n; i++) { for (int j = 0; j < 3; j++) { array v{(a[i + (j + 1) % 3]), (a[i + (j + 2) % 3])}; if (mp[j].find(v) != mp[j].end()) { ans += mp[j][v]; } } for (int j = 0; j < 3; j++) { array v{(a[i + (j + 1) % 3]), (a[i + (j + 2) % 3])}; mp[j][v] += 1; } if (mp2.find({a[i], a[i + 1], a[i + 2]}) != mp2.end()) { ans -= 3 * mp2[{a[i], a[i + 1], a[i + 2]}]; } mp2[{a[i], a[i + 1], a[i + 2]}] += 1; } return ans; } long long solve2(int &n, vector &a) { long long ans = 0; for (int i = 0; i + 2 < n; i++) { for (int j = 0; j + 2 < n; j++) { if (i == j) continue; if ((a[i] != a[j] && a[i+1]==a[j+1] && a[i+2]==a[j+2])||(a[i] == a[j] && a[i+1]!=a[j+1] && a[i+2]==a[j+2])||(a[i] == a[j] && a[i+1]==a[j+1] && a[i+2]!=a[j+2])) { ans++; } } } return ans/2; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",data_structures,hard 8,"# Problem Statement Maxim has an array $a$ of $n$ integers and an array $b$ of $m$ integers ($m \le n$). Maxim considers an array $c$ of length $m$ to be good if the elements of array $c$ can be rearranged in such a way that at least $k$ of them match the elements of array $b$. For example, if $b = [1, 2, 3, 4]$ and $k = 3$, then the arrays $[4, 1, 2, 3]$ and $[2, 3, 4, 5]$ are good (they can be reordered as follows: $[1, 2, 3, 4]$ and $[5, 2, 3, 4]$), while the arrays $[3, 4, 5, 6]$ and $[3, 4, 3, 4]$ are not good. Maxim wants to choose every subsegment of array $a$ of length $m$ as the elements of array $c$. Help Maxim count how many selected arrays will be good. In other words, find the number of positions $1 \le l \le n - m + 1$ such that the elements $a_l, a_{l+1}, \dots, a_{l + m - 1}$ form a good array. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &m, int &k, vector &a, vector &b) { // write your code here } }; ``` where: - return: the number of good arrays. # Example 1: - Input: n = 7, m = 4, k = 2 a = [4, 1, 2, 3, 4, 5, 6] b = [1, 2, 3, 4] - Output: 4 # Constraints: - $1 \leq k \leq m \leq n \leq @data$ - $1 \leq a[i], b[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &m, int &k, vector &a, vector &b) { map cnt; for (int i = 0; i < m; i++) { cnt[b[i]]++; } int ans = 0; int good = 0; for (int i = 0; i < m - 1; i++) { good += cnt[a[i]]-- > 0; } for (int i = 0; i <= n - m; i++) { good += cnt[a[i + m - 1]]-- > 0; ans += (good >= k); good -= ++cnt[a[i]] > 0; } return ans; } int solve2(int &n, int &m, int &k, vector &a, vector &b) { int ans = 0; sort(b.begin(), b.end()); for (int i = 0; i <= n - m; i++) { int good = 0; int pre = 0; int num = 0; for (int j = 0; j < m; j++) { if (pre != b[j]) { if (pre != 0) good += min(num, (int)count(a.begin() + i, a.begin() + i + m, pre)); num = 1; pre = b[j]; } } if (pre != 0) good += count(a.begin() + i, a.begin() + i + m, pre); if (good >= k) ans++; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m, k; cin >> n >> m >> k; vector a(n), b(m); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < m; i++) cin >> b[i]; // solve Solution solution; auto result = solution.solve(n, m, k, a, b); // output cout << result << ""\n""; return 0; }","data_structures,two_pointers",medium 9,"# Problem Statement A progressive square of size $n$ is an $n \times n$ matrix. Maxim chooses three integers $a_{1,1}$, $c$, and $d$ and constructs a progressive square according to the following rules: $$ a_{i+1,j} = a_{i,j} + c $$ $$ a_{i,j+1} = a_{i,j} + d $$ For example, if $n = 3$, $a_{1,1} = 1$, $c=2$, and $d=3$, then the progressive square looks as follows: $$ \begin{pmatrix} 1 & 4 & 7 \\ 3 & 6 & 9 \\ 5 & 8 & 11 \end{pmatrix} $$ Last month Maxim constructed a progressive square and remembered the values of $n$, $c$, and $d$. Recently, he found an array $b$ of $n^2$ integers in random order and wants to make sure that these elements are the elements of **that specific** square. It can be shown that for any values of $n$, $a_{1,1}$, $c$, and $d$, there exists exactly one progressive square that satisfies all the rules. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, int &c, int &d, vector &a) { // write your code here } }; ``` where: - return ""YES"" if a progressive square for the given n, c, and d can be constructed from the array elements a, otherwise return ""NO"". # Example 1: - Input: n = 3, c = 2, d = 3 b = [3, 9, 6, 5, 7, 1, 10, 4, 8] - Output: NO # Constraints: - $1 \leq n * n \leq @data$ - $1 \leq c, d \leq 10^6$ - $1 \leq b[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, int &c, int &d, vector &a) { sort(a.begin(), a.end()); vector b(n * n); for (int i = 0; i < n * n; i++) { b[i] = a[0] + i / n * c + i % n * d; } sort(b.begin(), b.end()); if (a == b) { return ""YES""; } else { return ""NO""; } } string solve2(int &n, int &c, int &d, vector &a) { sort(a.begin(), a.end()); int x = a[0]; for (int i = 0; i < n * n; i++) { int tar = x + i / n * c + i % n * d; for (int j = 0; j < n * n; j++) { if (a[j] == tar) { a[j] = -1; break; } if (j == n * n - 1) { return ""NO""; } } } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, c, d; cin >> n >> c >> d; vector a(n * n); for (int i = 0; i < n * n; i++) { cin >> a[i]; } // solve Solution solution; auto result = solution.solve(n, c, d, a); // output cout << result << ""\n""; return 0; }","sort,data_structures",medium 10,"# Problem Statement Iulia has $n$ glasses arranged in a line. The $i$-th glass has $a_i$ units of juice in it. Iulia drinks only from odd-numbered glasses, while her date drinks only from even-numbered glasses. To impress her date, Iulia wants to find a contiguous subarray of these glasses such that both Iulia and her date will have the same amount of juice in total if only the glasses in this subarray are considered. Please help her to do that. More formally, find out if there exists two indices $l$, $r$ such that $1 \leq l \leq r \leq n$, and $a_l + a_{l + 2} + a_{l + 4} + \dots + a_{r} = a_{l + 1} + a_{l + 3} + \dots + a_{r-1}$ if $l$ and $r$ have the same parity and $a_l + a_{l + 2} + a_{l + 4} + \dots + a_{r - 1} = a_{l + 1} + a_{l + 3} + \dots + a_{r}$ otherwise. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, vector &a) { // write your code here } }; ``` where: - return ""YES"" if there exists a subarray satisfying the condition, and ""NO"" otherwise. # Example 1: - Input: n = 3 a = [1, 3, 2] - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { set s = {0}; long long sum = 0; for (int i = 0; i < n; i++) { sum += i % 2 ? a[i] : -a[i]; s.insert(sum); } return s.size() == n + 1 ? ""NO"" : ""YES""; } string solve2(int &n, vector &a) { for (int i = 0; i < n; i++) { long long sum = 0; for (int j = i; j < n; j++) { sum += j % 2 ? a[j] : -a[j]; if (sum == 0) return ""YES""; } } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","data_structures,math",medium 11,"# Problem Statement In the summer, Vika likes to visit her country house. There is everything for relaxation: comfortable swings, bicycles, and a river. There is a wooden bridge over the river, consisting of $n$ planks. It is quite old and unattractive, so Vika decided to paint it. And in the shed, they just found cans of paint of $k$ colors. After painting each plank in one of $k$ colors, Vika was about to go swinging to take a break from work. However, she realized that the house was on the other side of the river, and the paint had not yet completely dried, so she could not walk on the bridge yet. In order not to spoil the appearance of the bridge, Vika decided that she would still walk on it, but only stepping on planks of the same color. Otherwise, a small layer of paint on her sole will spoil the plank of another color. Vika also has a little paint left, but it will only be enough to repaint **one** plank of the bridge. Now Vika is standing on the ground in front of the first plank. To walk across the bridge, she will choose some planks of the same color (after repainting), which have numbers $1 \le i_1 < i_2 < \ldots < i_m \le n$ (planks are numbered from $1$ from left to right). Then Vika will have to cross $i_1 - 1, i_2 - i_1 - 1, i_3 - i_2 - 1, \ldots, i_m - i_{m-1} - 1, n - i_m$ planks as a result of each of $m + 1$ steps. Since Vika is afraid of falling, she does not want to take too long steps. Help her and tell her the minimum possible maximum number of planks she will have to cross **in one step**, if she can repaint one (**or zero**) plank a different color while crossing the bridge. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &k, vector &c) { // write your code here } }; ``` where: - return: the minimum possible maximum number of planks that Vika will have to step over in one step. # Example 1: - Input: n = 5, k = 2 a = [1, 1, 2, 1, 1] - Output: 0 # Constraints: - $1 \leq k \leq n \leq @data$ - $1 \leq c[i] \leq k$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 160, 64], [6400, 1280, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &k, vector &c) { vector lst(k, -1); vector> f(k); for (int i = 0; i < n; i++) { c[i]--; f[c[i]].push_back(i - 1 - lst[c[i]]); lst[c[i]] = i; } int ans = n; for (int i = 0; i < k; i++) { f[i].push_back(n - 1 - lst[i]); sort(f[i].begin(), f[i].end(), greater()); int res = f[i][0] / 2; if (f[i].size() > 1) { res = max(res, f[i][1]); } ans = min(ans, res); } return ans; } int solve2(int &n, int &k, vector &c) { int ans = n; for (int i = 1; i <= k; i++) { int pre = -1; int mx1 = 0, mx2 = 0; for (int j = 0; j < n; j++) { if (c[j] == i) { int x = j - pre; if (x > mx1) { mx2 = mx1; mx1 = x; } else if (x > mx2) { mx2 = x; } pre = j; } } int x = n - pre; if (x > mx1) { mx2 = mx1; mx1 = x; } else if (x > mx2) { mx2 = x; } ans = min(ans, max(mx2 - 1, (mx1 - 1) / 2)); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, k, a); // output cout << result << ""\n""; return 0; }","binary,data_structures,greedy,sort",hard 12,"# Problem Statement There is a deck of $n$ cards, each of which is characterized by its power. There are two types of cards: - a hero card, the power of such a card is always equal to $0$; - a bonus card, the power of such a card is always positive. You can do the following with the deck: - take a card from the top of the deck; - if this card is a bonus card, you can put it **on top** of your bonus deck or discard; - if this card is a hero card, then the power of **the top** card from your bonus deck is added to his power (if it is not empty), after that the hero is added to your army, and the used bonus discards. Your task is to use such actions to gather an army with the maximum possible total power. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &s) { // write your code here } }; ``` where: - return: the maximum possible total power of the army that can be achieved. # Example 1: - Input: n = 5 s = [3, 3, 3, 0, 0] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $0 \leq s[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &s) { priority_queue q; long long ans = 0; for (int i = 0; i < n; i++) { if (s[i] == 0) { if (!q.empty()) { ans += q.top(); q.pop(); } } else { q.push(s[i]); } } return ans; } long long solve2(int &n, vector &s) { long long ans = 0; for (int i = 0; i < n; i++) { if (s[i] == 0) { int max = 0; int maxIndex = -1; for (int j = 0; j < i; j++) { if (s[j] > max) { max = s[j]; maxIndex = j; } } if (maxIndex != -1) { ans += max; s[maxIndex] = 0; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","data_structures,greedy",medium 13,"# Problem Statement To destroy humanity, The Monster Association sent $n$ monsters to Earth's surface. The $i$-th monster has health $h_i$ and power $p_i$. With his last resort attack, True Spiral Incineration Cannon, Genos can deal $k$ damage to all monsters alive. In other words, Genos can reduce the health of all monsters by $k$ (if $k > 0$) with a single attack. However, after every attack Genos makes, the monsters advance. With their combined efforts, they reduce Genos' attack damage by the power of the $^\dagger$weakest monster $^\ddagger$alive. In other words, the minimum $p_i$ among all currently living monsters is subtracted from the value of $k$ after each attack. $^\dagger$The Weakest monster is the one with the least power. $^\ddagger$A monster is alive if its health is strictly greater than $0$. Will Genos be successful in killing all the monsters? The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, int &k, vector &h, vector &p) { // write your code here } }; ``` where: - return: YES if Genos could kill all monsters and NO otherwise. # Example 1: - Input: n = 6, k = 7 h = [18, 5, 13, 9, 10, 1] p = [2, 7, 2, 1, 2, 6] - Output: YES # Constraints: - $1 \leq n, k \leq @data$ - $1 \leq h[i], p[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, int &k, vector &h, vector &p) { priority_queue, vector>, greater>> q; for (int i = 0; i < n; i++) q.push({p[i], h[i]}); int cnt = k; while (!q.empty()) { auto [x, y] = q.top(); q.pop(); if (cnt >= y) continue; q.push({x, y}); k -= x; if (k <= 0) { return ""NO""; } cnt += k; } return ""YES""; } string solve2(int &n, int &k, vector &h, vector &p) { int cnt = k; while (1) { int mn = 1e9; int pos = -1; for (int i = 0; i < n; i++) { if (p[i] == 0) continue; if (p[i] < mn) { mn = p[i]; pos = i; } } if (pos == -1) break; p[pos] = 0; if (cnt >= h[pos]) continue; k -= mn; if (k <= 0) { return ""NO""; } cnt += k; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector h(n), p(n); for (int i = 0; i < n; i++) { cin >> h[i]; } for (int i = 0; i < n; i++) { cin >> p[i]; } // solve Solution solution; auto result = solution.solve(n, k, h, p); // output cout << result << ""\n""; return 0; }","binary,data_structures,math,sort",medium 14,"A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i. Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [6,0,8,2,1,5] Output: 4 Example 2: Input: nums = [9,8,1,0,1,9,4,0,4,1] Output: 7 Constraints: 2 <= nums.length <= @data 0 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int n = nums.size(); stack indicesStack; for (int i = 0; i < n; i++) { if (indicesStack.empty() || nums[indicesStack.top()] > nums[i]) { indicesStack.push(i); } } int maxWidth = 0; for (int j = n - 1; j >= 0; j--) { while (!indicesStack.empty() && nums[indicesStack.top()] <= nums[j]) { maxWidth = max(maxWidth, j - indicesStack.top()); indicesStack.pop(); } } return maxWidth; } int solve2(vector& nums) { int n = nums.size(); int maxWidth = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (nums[i] <= nums[j]) { maxWidth = max(maxWidth, j - i); } } } return maxWidth; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout << result << ""\n""; return 0; }",two_pointers,medium 15,"There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti. Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved. After each square is dropped, you must record the height of the current tallest stack of squares. Return an integer array ans where ans[i] represents the height described above after dropping the ith square. solution main function ```cpp class Solution { public: vector solve(vector>& positions) { } }; ``` Example 1: Input: positions = [[1,2],[2,3],[6,1]] Output: [2,5,5] Example 2: Input: positions = [[100,100],[200,100]] Output: [100,100] Constraints: 1 <= positions.length <= @data 1 <= lefti <= 10^8 1 <= sideLengthi <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1000, 100, 64], [8000, 800, 100], [64000, 6400, 800]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; struct SegmentTree { SegmentTree(int n) : n(n) { size = 1; while (size < n) { size <<= 1; } tree.resize(2 * size); lazy.resize(2 * size); } void add_range(int l, int r, int h) { l += size; r += size; tree[l] = max(tree[l], h); tree[r] = max(tree[r], h); if (l != r) { if (!(l & 1)) { lazy[l + 1] = max(lazy[l - 1], h); } if (r & 1) { lazy[r - 1] = max(lazy[r - 1], h); } } l >>= 1; r >>= 1; while (l != r) { tree[l] = max(tree[2 * l], tree[2 * l + 1]); tree[r] = max(tree[2 * r], tree[2 * r + 1]); if (l / 2 != r / 2) { if (!(l & 1)) { lazy[l + 1] = max(lazy[l + 1], h); } if (r & 1) { lazy[r - 1] = max(lazy[r - 1], h); } } l >>= 1; r >>= 1; } while (l > 0) { tree[l] = max(tree[2 * l], tree[2 * l + 1]); l >>= 1; } } int max_range(int l, int r) { l += size; r += size; int max_val = max(tree[l], tree[r]); while (l / 2 != r / 2) { if (!(l & 1)) { max_val = max(tree[l + 1], max_val); max_val = max(lazy[l + 1], max_val); } if (r & 1) { max_val = max(tree[r - 1], max_val); max_val = max(lazy[r - 1], max_val); } max_val = max(max_val, lazy[l]); max_val = max(max_val, lazy[r]); l >>= 1; r >>= 1; } max_val = max(max_val, lazy[r]); while (l / 2 > 0) { max_val = max(lazy[l], max_val); l >>= 1; } return max_val; } int global_max() { return max_range(0, n - 1); } int size; int n; vector tree; vector lazy; }; class Solution { public: vector solve1(vector>& positions) { vector qans(positions.size()); for (int i = 0; i < positions.size(); i++) { int left = positions[i][0]; int size = positions[i][1]; int right = left + size; qans[i] += size; for (int j = i + 1; j < positions.size(); j++) { int left2 = positions[j][0]; int size2 = positions[j][1]; int right2 = left2 + size2; if (left2 < right && left < right2) { qans[j] = max(qans[j], qans[i]); } } } vector ans; int cur = -1; for (int x: qans) { cur = max(cur, x); ans.push_back(cur); } return ans; } vector solve2(vector>& positions) { vector points; for (const auto& rect : positions) { points.push_back(rect[0]); points.push_back(rect[0] + rect[1] - 1); } sort(begin(points), end(points)); auto new_end = unique(begin(points), end(points)); points.resize(distance(begin(points), new_end)); SegmentTree st(points.size()); vector results; int max_height = 0; for (const auto& rect : positions) { int x_1 = rect[0]; int x_2 = rect[0] + rect[1] - 1; int l = distance(begin(points), lower_bound(begin(points), end(points), x_1)); int r = distance(begin(points), lower_bound(begin(points), end(points), x_2)); int cur_height = st.max_range(l, r); int new_height = rect[1] + cur_height; max_height = max(new_height, max_height); st.add_range(l, r, new_height); results.push_back(max_height); } return results; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< vector > s; for(int i=1,x,y;i<=n;i++) { scanf(""%d"",&x); scanf(""%d"",&y); vector temp; temp.push_back(x); temp.push_back(y); s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output for(auto it:result) printf(""%d "",it); // cout << result << ""\n""; return 0; }",data_structures,hard 16,"There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n). Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). solution main function ```cpp class Solution { public: int solve(vector& rating) { } }; ``` Example 1: Input: rating = [2,5,3,4,1] Output: 3 Example 2: Input: rating = [2,1,3] Output: 0 Constraints: n == rating.length 3 <= n <= @data 1 <= rating[i] <= 10^5 All the integers in rating are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",3000,"[[2000, 200, 64], [16000, 1600, 160], [128000, 12800, 1280]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector ordered; vector tree; void update(int index, int val) { for (int i=index+1; i 0; i &= i-1) { res += tree[i]; } return res; } int solve1(vector& rating) { int n = rating.size(); tree.resize(n+1); ordered = rating; sort(ordered.begin(), ordered.end()); auto get_idx = [&](int rate) { return lower_bound(ordered.begin(), ordered.end(), rate) - ordered.begin(); }; vector lo(n), hi(n); for (int i=0; i& rating) { int n = rating.size(); int ans = 0; for (int j = 1; j < n - 1; ++j) { int iless = 0, imore = 0; int kless = 0, kmore = 0; for (int i = 0; i < j; ++i) { if (rating[i] < rating[j]) { ++iless; } else if (rating[i] > rating[j]) { ++imore; } } for (int k = j + 1; k < n; ++k) { if (rating[k] < rating[j]) { ++kless; } else if (rating[k] > rating[j]) { ++kmore; } } ans += iless * kmore + imore * kless; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector rat; for(int i=1;i<=n;i++) { int x; cin>>x; rat.push_back(x); } // solve Solution solution; auto result = solution.solve(rat); // output cout< using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { int n = s.size(); string t = ""$#""; for (const char &c: s) { t += c; t += '#'; } n = t.size(); t += '!'; auto f = vector (n); int iMax = 0, rMax = 0, ans = 0; for (int i = 1; i < n; ++i) { f[i] = (i <= rMax) ? min(rMax - i + 1, f[2 * iMax - i]) : 1; while (t[i + f[i]] == t[i - f[i]]) ++f[i]; if (i + f[i] - 1 > rMax) { iMax = i; rMax = i + f[i] - 1; } ans += (f[i] / 2); } return ans; } int solve2(string s) { int n = s.size(), ans = 0; for (int i = 0; i < 2 * n - 1; ++i) { int l = i / 2, r = i / 2 + i % 2; while (l >= 0 && r < n && s[l] == s[r]) { --l; ++r; ++ans; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string str; cin>>str; // solve Solution solution; auto result = solution.solve(str); // output cout<>& matrix, int k) { } }; ``` Example 1: Input: matrix = [[5,2],[1,6]], k = 1 Output: 7 Example 2: Input: matrix = [[5,2],[1,6]], k = 2 Output: 5 Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= @data 0 <= matrix[i][j] <= 10^6 1 <= k <= m * n Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[200, 125, 64], [1600, 1000, 500], [12800, 8000, 4000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& matrix, int k) { int m = matrix.size(), n = matrix[0].size(); vector results; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if(i-1>=0) matrix[i][j] ^= matrix[i - 1][j]; if(j-1>=0) matrix[i][j] ^= matrix[i][j - 1]; if(i-1>=0&&j-1>=0) matrix[i][j] ^= matrix[i - 1][j - 1]; results.push_back(matrix[i][j]); } } nth_element(results.begin(), results.begin() + k - 1, results.end(), greater()); return results[k - 1]; } int solve2(vector>& matrix, int k) { int n = matrix.size(), m = matrix[0].size(); priority_queue, greater> pq; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] ^= (i - 1 > -1 ? matrix[i - 1][j] : 0) ^ (j - 1 > -1 ? matrix[i][j - 1] : 0) ^ (i - 1 > -1 && j - 1 > -1 ? matrix[i - 1][j - 1] : 0); if (pq.size() < k) pq.push(matrix[i][j]); else { if (pq.top() < matrix[i][j]) { pq.pop(); pq.push(matrix[i][j]); } } } } return pq.top(); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,k;cin>>n>>m>>k; vector > num; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } num.push_back(temp); } // solve Solution solution; auto result = solution.solve(num,k); // output cout<& arr) { } }; ``` Example 1: Input: arr = [2,3,1,6,7] Output: 4 Example 2: Input: arr = [2,3,1,6,7] Output: 4 Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= 10^8 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& arr) { int ans = 0; int n = arr.size(); for (int i = 0; i < n - 1; ++i) { int temp = arr[i]; for (int j = i + 1; j < n; ++j) { temp ^= arr[j]; if (temp == 0) ans += j - i; } } return ans; } int solve2(vector &arr) { int n = arr.size(); unordered_map cnt, total; int ans = 0, s = 0; for (int k = 0; k < n; ++k) { int val = arr[k]; if (cnt.count(s ^ val)) { ans += cnt[s ^ val] * k - total[s ^ val]; } ++cnt[s]; total[s] += k; s ^= val; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector arr; for(int i=1;i<=n;i++) { int x; cin>>x; arr.push_back(x); } // solve Solution solution; auto result = solution.solve(arr); // output cout< i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all. Return an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount. solution main function ```cpp class Solution { public: vector solve(vector& prices) { // write your code here } }; ``` Example 1: Input: prices = [8,4,6,2,3] Output: [4,2,4,2,3] Example 2: Input: prices = [1,2,3,4,5] Output: [1,2,3,4,5] Constraints: 1 <= prices.length <= @data 1 <= prices[i] <= 10^3 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector& prices) { int n = prices.size(); vector ans(n); stack st; for (int i = n - 1; i >= 0; i--) { while (!st.empty() && st.top() > prices[i]) { st.pop(); } ans[i] = st.empty() ? prices[i] : prices[i] - st.top(); st.emplace(prices[i]); } return ans; } vector solve2(vector& prices) { int n = prices.size(); vector ans; for (int i = 0; i < n; ++i) { int discount = 0; for (int j = i + 1; j < n; ++j) { if(prices[j] <= prices[i]){ discount = prices[j]; break; } } ans.emplace_back(prices[i] - discount); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector price; for(int i=1;i<=n;i++) { int x; cin>>x; price.push_back(x); } // solve Solution solution; auto result = solution.solve(price); // output for(auto it:result) cout<& nums1, vector& nums2) { } }; ``` Example 1: Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Example 2: Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] Output: 5 Constraints: 1 <= nums1.length, nums2.length <= @data 0 <= nums1[i], nums2[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: const int mod = 1000000009; const int base = 113; long long qPow(long long x, long long n) { long long ret = 1; while (n) { if (n & 1) { ret = ret * x % mod; } x = x * x % mod; n >>= 1; } return ret; } bool check(vector& A, vector& B, int len) { long long hashA = 0; for (int i = 0; i < len; i++) { hashA = (hashA * base + A[i]) % mod; } unordered_set bucketA; bucketA.insert(hashA); long long mult = qPow(base, len - 1); for (int i = len; i < A.size(); i++) { hashA = ((hashA - A[i - len] * mult % mod + mod) % mod * base + A[i]) % mod; bucketA.insert(hashA); } long long hashB = 0; for (int i = 0; i < len; i++) { hashB = (hashB * base + B[i]) % mod; } if (bucketA.count(hashB)) { return true; } for (int i = len; i < B.size(); i++) { hashB = ((hashB - B[i - len] * mult % mod + mod) % mod * base + B[i]) % mod; if (bucketA.count(hashB)) { return true; } } return false; } int solve1(vector& A, vector& B) { int left = 1, right = min(A.size(), B.size()) + 1; while (left < right) { int mid = (left + right) >> 1; if (check(A, B, mid)) { left = mid + 1; } else { right = mid; } } return left - 1; } int maxLength(vector& A, vector& B, int addA, int addB, int len) { int ret = 0, k = 0; for (int i = 0; i < len; i++) { if (A[addA + i] == B[addB + i]) { k++; } else { k = 0; } ret = max(ret, k); } return ret; } int solve2(vector& A, vector& B) { int n = A.size(), m = B.size(); int ret = 0; for (int i = 0; i < n; i++) { int len = min(m, n - i); int maxlen = maxLength(A, B, i, 0, len); ret = max(ret, maxlen); } for (int i = 0; i < m; i++) { int len = min(n, m - i); int maxlen = maxLength(A, B, 0, i, len); ret = max(ret, maxlen); } return ret; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector num1,num2; for(int i=1;i<=n;i++) { int x; cin>>x; num1.push_back(x); } for(int i=1;i<=m;i++) { int x; cin>>x; num2.push_back(x); } // solve Solution solution; auto result = solution.solve(num1,num2); // output cout< using namespace std; #include using namespace std; class Solution { static constexpr int mod = 1e9 + 7; public: int solve1(int n) { vector> moves = { {4, 6}, {6, 8}, {7, 9}, {4, 8}, {3, 9, 0}, {}, {1, 7, 0}, {2, 6}, {1, 3}, {2, 4} }; vector> d(2, vector(10, 0)); fill(d[1].begin(), d[1].end(), 1); for (int i = 2; i <= n; i++) { int x = i & 1; for (int j = 0; j < 10; j++) { d[x][j] = 0; for (int k : moves[j]) { d[x][j] = (d[x][j] + d[x ^ 1][k]) % mod; } } } int res = 0; for (auto x : d[n % 2]) { res = (res + x) % mod; } return res; } vector> mul(const vector> <h, const vector> &rth) { vector> res(lth.size(), vector(rth[0].size(), 0)); for (int k = 0; k < lth[0].size(); k++) { for (int i = 0; i < lth.size(); i++) { for (int j = 0; j < rth[0].size(); j++) { res[i][j] = (res[i][j] + 1ll * lth[i][k] * rth[k][j] % mod) % mod; } } } return res; } int solve2(int n) { vector> base = { {0, 0, 0, 0, 1, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 0, 1}, {0, 0, 0, 0, 1, 0, 0, 0, 1, 0}, {1, 0, 0, 1, 0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 0, 0, 1, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 1, 0, 0, 0, 0, 0} }; vector> res = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} }; vector> base2 = vector>(10, vector(10, 0)); for (int i = 0; i < 10; i++) { base2[i][i] = 1; } n--; while (n > 0) { if (n & 1) { base2 = mul(base2, base); } base = mul(base, base); n >>= 1; } res = mul(res, base2); int ret = 0; for (auto x : res[0]) { ret = (ret + x) % mod; } return ret; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout<& nums) { } }; ``` Example 1: Input: nums = [4,9,6,10] Output: 1 Example 2: Input: nums = [6,8,11,12] Output: 1 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= @data*10 nums.length == n Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve1(vector& nums) { int maxElement = *max_element(nums.begin(), nums.end()); vector sieve(maxElement + 1, 1); sieve[1] = 0; for (int i = 2; i <= sqrt(maxElement + 1); i++) { if (sieve[i] == 1) { for (int j = i * i; j <= maxElement; j += i) { sieve[j] = 0; } } } int currValue = 1; int i = 0; while (i < nums.size()) { int difference = nums[i] - currValue; if (difference < 0) { return 0; } if (sieve[difference] == 1 or difference == 0) { i++; currValue++; } else { currValue++; } } return 1; } bool checkPrime(int x) { for (int i = 2; i <= sqrt(x); i++) { if (x % i == 0) { return 0; } } return 1; } bool solve2(vector& nums) { for (int i = 0; i < nums.size(); i++) { int bound; if (i == 0) { bound = nums[0]; } else { bound = nums[i] - nums[i - 1]; } if (bound <= 0) { return 0; } int largestPrime = 0; for (int j = bound - 1; j >= 2; j--) { if (checkPrime(j)) { largestPrime = j; break; } } nums[i] = nums[i] - largestPrime; } return 1; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector num; cin>>n; for(int i=1,x;i<=n;i++) { cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout<& skill) { } }; ``` Example 1: Input: skill = [3,2,5,1,3,4] Output: 22 Example 2: Input: skill = [3,4] Output: 12 Constraints: 2 <= skill.length <= @data skill.length is even. 1 <= skill[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 10000, 100000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: long long solve1(vector& skill) { int n = skill.size(); int totalSkill = 0; vector skillFrequency(2001, 0); for (int playerSkill : skill) { totalSkill += playerSkill; skillFrequency[playerSkill]++; } if (totalSkill % (n / 2) != 0) { return -1; } int targetTeamSkill = totalSkill / (n / 2); long long totalChemistry = 0; for (int playerSkill : skill) { int partnerSkill = targetTeamSkill - playerSkill; if (skillFrequency[partnerSkill] == 0) { return -1; } totalChemistry += (long long)playerSkill * (long long)partnerSkill; skillFrequency[partnerSkill]--; } return totalChemistry / 2; } long long solve2(vector& skill) { sort(skill.begin(), skill.end()); int total = skill.front() + skill.back(); long long chemistry = 0; for (int i = 0, j = skill.size() - 1; i < j; ++i, --j) { if (skill[i] + skill[j] != total) return -1; chemistry += (long long)skill[i] * skill[j]; } return chemistry; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector num; cin>>n; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout<& nums) { } }; ``` Example 1: Input: nums = [1,2,3] Output: 4 Example 2: Input: nums = [1,3,3] Output: 4 Constraints: 1 <= nums.length <= @data -10^6 <= nums[i] <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: long long solve1(vector& nums) { int n = nums.size(); long long answer = 0; stack stk; for (int right = 0; right <= n; ++right) { while (!stk.empty() && (right == n || nums[stk.top()] >= nums[right])) { int mid = stk.top(); stk.pop(); int left = stk.empty() ? -1 : stk.top(); answer -= (long long)nums[mid] * (right - mid) * (mid - left); } stk.push(right); } stk.pop(); for (int right = 0; right <= n; ++right) { while (!stk.empty() && (right == n || nums[stk.top()] <= nums[right])) { int mid = stk.top(); stk.pop(); int left = stk.empty() ? -1 : stk.top(); answer += (long long)nums[mid] * (right - mid) * (mid - left); } stk.push(right); } return answer; } long long solve2(vector& nums) { int n = int(nums.size()); long long answer = 0; for (int left = 0; left < n; ++left) { int minVal = nums[left], maxVal = nums[left]; for (int right = left; right < n; ++right) { maxVal = max(maxVal, nums[right]); minVal = min(minVal, nums[right]); answer += maxVal - minVal; } } return answer; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< int > a; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } // solve Solution solution; auto result = solution.solve(a); // output cout << result << ""\n""; return 0; }",math,medium 26,"# Problem Statement Given an array with $n$ intergers $a_1, a_2, \dots, a_n$, and $m$ operations, the $i$-th operation is * $1, p, b$: Given $p$ and $b$, update $a_p = b$. * $2, l, r$: Given $l$ and $r$, return the sum of values in interval $[l, r]$. The solution's main function is: ```cpp class Solution { public: long long solve(int &n, vector &a, int &m, vector> &ops) { // write your code here } }; ``` where: - `op` is an array of 3 integers, $op[0]$ is the operation type, $op[1]$ and $op[2]$ are the parameters of the operation. - return the xor value of all operation 2 answers, please return the result in a `long long` type. # Example 1 - Input: n = 5 a = [1, 2, 3, 4, 5] m = 3 ops = [[2, 1, 3], [1, 2, 6], [2, 1, 3]] - Output: 12 # Constraints: - $1 \leq n, m \leq @data$ - $1 \leq a_i, b \leq 10^6$ - $1 \leq p, l, r \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[5000, 50000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a, int &m, vector> &ops) { vector b(n + 1); auto add = [&](int i, int x) { for (; i <= n; i += i & -i) b[i] += x; }; auto ask = [&](int i) { long long res = 0; for (; i > 0; i -= i & -i) res += b[i]; return res; }; for (int i = 0; i < n; i++) add(i + 1, a[i]); long long ans = 0; for (auto &[op, l, r] : ops) { if (op == 1) { add(l, -a[l - 1]); a[l - 1] = r; add(l, r); } else ans = ans ^ (ask(r) - ask(l - 1)); } return ans; } long long solve2(int &n, vector &a, int &m, vector> &ops) { long long ans = 0; for (auto &[op, l, r] : ops) { if (op == 1) a[l - 1] = r; else { long long sum = 0; for (int i = l - 1; i < r; i++) sum += a[i]; ans = ans ^ sum; } } return ans; } long long solve3(int &n, vector &a, int &m, vector> &ops) { int blockSize = static_cast(sqrt(n)) + 1; int blockCount = (n + blockSize - 1) / blockSize; vector blockSum(blockCount, 0); for (int i = 0; i < n; ++i) blockSum[i / blockSize] += a[i]; long long result = 0; for (const auto &op : ops) { int type = op[0]; if (type == 1) { int p = op[1] - 1; int b = op[2]; int blockIndex = p / blockSize; blockSum[blockIndex] += b - a[p]; a[p] = b; } else if (type == 2) { int l = op[1] - 1; int r = op[2] - 1; long long sum = 0; int startBlock = l / blockSize; int endBlock = r / blockSize; if (startBlock == endBlock) for (int i = l; i <= r; ++i) sum += a[i]; else { for (int i = l; i < (startBlock + 1) * blockSize; ++i) sum += a[i]; for (int i = startBlock + 1; i < endBlock; ++i) sum += blockSum[i]; for (int i = endBlock * blockSize; i <= r; ++i) sum += a[i]; } result ^= sum; } } return result; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; int m; cin >> m; vector> ops(m); for (int i = 0; i < m; i++) cin >> ops[i][0] >> ops[i][1] >> ops[i][2]; // solve Solution solution; auto result = solution.solve(n, a, m, ops); // output cout << result << ""\n""; return 0; }",data_structures,medium 27,"You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s. solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""aacaba"" Output: 2 Example 2: Input: s = ""abcd"" Output: 1 Constraints: 1 <= s.length <= @data s consists of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { ios::sync_with_stdio(0); cin.tie(0); int ls[26] = {0}, rs[26] = {0}, res = 0, lu=0, ru=0; for(char &c: s){ rs[c-'a']++; ru += (rs[c-'a']==1); } for(char &c: s){ rs[c-'a']--; ls[c-'a']++; ru -= (rs[c-'a']==0); lu += (ls[c-'a']==1); res += (ru==lu); } return res; } int solve2(string s) { int n = (int)s.size(); int res = 0; for (int i = 1; i < n; ++i) { unsigned int lm = 0, rm = 0; int lu = 0, ru = 0; for (int j = 0; j < i; ++j) { unsigned int b = 1u << (s[j] - 'a'); if ((lm & b) == 0u) { lm |= b; ++lu; } } for (int j = i; j < n; ++j) { unsigned int b = 1u << (s[j] - 'a'); if ((rm & b) == 0u) { rm |= b; ++ru; } } if (lu == ru) ++res; } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: static int solve1(string& s, int k) { const int n=s.size(); int freq[3]={0}; for(char c: s) freq[c-'a']++; if (any_of(freq, freq+3, [k](int f){ return f= k && lb >= k && lc >= k) { if (L < ans) ans = L; if (ans == 0) break; } int ra = 0, rb = 0, rc = 0; int maxR = n - L; for (int R = 1; R <= maxR; ++R) { char c = s[n - R]; if (c == 'a') ++ra; else if (c == 'b') ++rb; else ++rc; if (la + ra >= k && lb + rb >= k && lc + rc >= k) { int t = L + R; if (t < ans) ans = t; break; } } if (L < n) { char c = s[L]; if (c == 'a') ++la; else if (c == 'b') ++lb; else ++lc; } } return ans; } }; auto init = []() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 'c'; }(); #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int k; string s; cin>>s>>k; // solve Solution solution; auto result = solution.solve(s,k); // output cout << result << ""\n""; return 0; }",string,hard 29,"On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed. solution main function ```cpp class Solution { public: int solve(vector>& stones) { // write your code here } }; ``` Example 1: Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] Output: 5 Example 2: Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]] Output: 3 Constraints: 1 <= stones.length <= @data 0 <= xi, yi <= 10^4 No two stones are at the same coordinate point. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[2000, 200, 64], [16000, 1600, 160], [128000, 12800, 1280]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: void dfs(int i, vector>& stones, vector& visited) { visited[i] = true; for (int j = 0; j < stones.size(); ++j) { if (!visited[j] && (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1])) { dfs(j, stones, visited); } } } int solve1(vector>& stones) { int size = stones.size(); vector visited(size, false); int count = 0; for (int i = 0; i < size; i++) { if (!visited[i]) { dfs(i, stones, visited); count++; } } return size - count; } int solve2(vector>& stones) { int n = (int)stones.size(); int components = 0; for (int i = 0; i < n; ++i) { if (stones[i][0] >= 0) { components++; stones[i][0] = -(stones[i][0] + 1); stones[i][1] = -(stones[i][1] + 1); bool changed; do { changed = false; for (int j = 0; j < n; ++j) { if (stones[j][0] >= 0) { bool connect = false; for (int k = 0; k < n; ++k) { if (stones[k][0] < 0) { int rx = -stones[k][0] - 1; int ry = -stones[k][1] - 1; if (rx == stones[j][0] || ry == stones[j][1]) { connect = true; break; } } } if (connect) { stones[j][0] = -(stones[j][0] + 1); stones[j][1] = -(stones[j][1] + 1); changed = true; } } } } while (changed); } } long long res = (long long)n - (long long)components; if (res < INT_MIN) return INT_MIN; if (res > INT_MAX) return INT_MAX; return (int)res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector > stones; for(int i=1;i<=n;i++) { int x,y; cin>>x>>y; vector temp; temp.push_back(x); temp.push_back(y); stones.push_back(temp); } // solve Solution solution; auto result = solution.solve(stones); // output cout< using namespace std; #include using namespace std; class Solution { public: bool solve1(string str1, string str2) { int str2Index = 0; int lengthStr1 = str1.size(), lengthStr2 = str2.size(); for (int str1Index = 0; str1Index < lengthStr1 && str2Index < lengthStr2; ++str1Index) { if (str1[str1Index] == str2[str2Index] || (str1[str1Index] + 1 == str2[str2Index]) || (str1[str1Index] - 25 == str2[str2Index])) { str2Index++; } } return str2Index == lengthStr2; } bool solve2(string str1, string str2) { int n = (int)str1.size(), m = (int)str2.size(); int i = 0, j = 0; while (i < n && j < m) { char need = str2[j]; char prevc = (need == 'a' ? 'z' : char(need - 1)); if (str1[i] == need || str1[i] == prevc) ++j; ++i; } return j == m; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string a,b; cin>>a>>b; // solve Solution solution; int result = solution.solve(a,b); // output cout<& nums, int k) { } }; ``` Example 1: Input: nums = [1,1,2,1,1], k = 3 Output: 2 Example 2: Input: nums = [2,4,6], k = 1 Output: 0 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 10^5 1 <= k <= nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(vector& nums, int k) { return atMost(nums, k) - atMost(nums, k - 1); } int solve2(vector& nums, int k) { long long res = 0; int n = (int)nums.size(); for (int i = 0; i < n; ++i) { int odd = 0; for (int j = i; j < n; ++j) { if (nums[j] & 1) { ++odd; if (odd > k) break; } if (odd == k) ++res; } } return (int)res; } private: int atMost(vector& nums, int k) { int windowSize = 0, subarrays = 0, start = 0; for (int end = 0; end < nums.size(); end++) { windowSize += nums[end] % 2; while (windowSize > k) { windowSize -= nums[start] % 2; start++; } subarrays += end - start + 1; } return subarrays; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; vector num; cin>>n>>k; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num,k); // output cout< using namespace std; class Solution { public: int solve1(int &m, int &a, int &b, int &c) { int x = m; int y = m; int ans = 0; int take = min(x, a); x -= take; ans += take; take = min(y, b); y -= take; ans += take; take = min(x + y, c); ans += take; return ans; } int solve2(int &m, int &a, int &b, int &c) { int maxA = a < m ? a : m; int maxB = b < m ? b : m; long long best = 0; for (int takeA = 0; takeA <= maxA; ++takeA) { int remRow1 = m - takeA; for (int takeB = 0; takeB <= maxB; ++takeB) { int remRow2 = m - takeB; long long seated = (long long)takeA + (long long)takeB; int remSeats = remRow1 + remRow2; int takeC = c < remSeats ? c : remSeats; seated += (long long)takeC; if (seated > best) best = seated; } } if (best > INT_MAX) return INT_MAX; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int m, a, b, c; cin >> m >> a >> b >> c; // solve Solution solution; auto result = solution.solve(m, a, b, c); // output cout << result << ""\n""; return 0; }",math,easy 33,"You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. solution main function ```cpp class Solution { public: int solve(vector>& matrix) { } }; ``` Example 1: Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] Output: 4 Example 2: Input: matrix = [[1,0,1,0,1]] Output: 3 Constraints: m == matrix.length n == matrix[i].length 1 <= m * n <= @data matrix[i][j] is either 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& matrix) { int m = matrix.size(), n = matrix[0].size(); int ans = 0; for(int j = 0; j < n; j++) for(int i = 1; i < m; i++) if(matrix[i][j] == 1) matrix[i][j] += matrix[i-1][j]; for(int i = 0; i < m; i++) { sort(matrix[i].begin(), matrix[i].end()); reverse(matrix[i].begin(), matrix[i].end()); for(int j = 0; j < n; j++) ans = max(ans, matrix[i][j]*(j+1)); } return ans; } int solve2(vector>& matrix) { int m = (int)matrix.size(); int n = (int)matrix[0].size(); for(int j = 0; j < n; ++j) for(int i = 1; i < m; ++i) matrix[i][j] = (matrix[i][j] == 0 ? 0 : matrix[i-1][j] + 1); long long ans = 0; for(int i = 0; i < m; ++i) { int maxH = 0; for(int j = 0; j < n; ++j) if(matrix[i][j] > maxH) maxH = matrix[i][j]; for(int h = 1; h <= maxH; ++h) { int cnt = 0; for(int j = 0; j < n; ++j) if(matrix[i][j] >= h) ++cnt; long long area = 1LL * h * cnt; if(area > ans) ans = area; } } if(ans > INT_MAX) return INT_MAX; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > s; for(int i=1;i<=n;i++) { vector temp; for(int j=1,x;j<=m;j++) { cin>>x; temp.push_back(x); } s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output cout<>& matrix) { } }; ``` Example 1: Input: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] Output: 15 Example 2: Input: matrix = [ [1,0,1], [1,1,0], [1,1,0] ] Output: 7 Constraints: 1 <= matrix.length <= @data 1 <= matrix[0].length <= @data 0 <= matrix[i][j] <= 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& matrix) { int row = matrix.size(), col = matrix[0].size(), result = 0, prev = 0; vector dp(col + 1, 0); for (int i = 1; i <= row; i++) { for (int j = 1; j <= col; j++) { if (matrix[i - 1][j - 1] == 1) { int temp = dp[j]; dp[j] = 1 + min(prev, min(dp[j - 1], dp[j])); prev = temp; result += dp[j]; } else { dp[j] = 0; } } } return result; } int solve2(vector>& matrix) { int n = matrix.size(); if (n == 0) return 0; int m = matrix[0].size(); long long result = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (matrix[i][j] != 1) continue; result++; int maxSize = min(n - i, m - j); for (int s = 2; s <= maxSize; ++s) { int ii = i + s - 1; int jj = j + s - 1; bool ok = true; for (int c = j; c <= jj; ++c) { if (matrix[ii][c] == 0) { ok = false; break; } } if (ok) { for (int r = i; r < ii; ++r) { if (matrix[r][jj] == 0) { ok = false; break; } } } if (!ok) break; result++; } } } return (int)result; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > mat; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } mat.push_back(temp); } // solve Solution solution; auto result = solution.solve(mat); // output cout< solve(int &n, int &k, int &s, int &q, vector> &edges, vector> &colors, vector> &queries) { // write your code here } }; ``` where: - `n`: number of nodes in the tree - `k`: number of distinct colors - `s`: total number of (node, color) assignments - `q`: number of queries - `edges`: `n-1` edges (u, v), 1-based, describing the tree - `colors`: `s` pairs (v, x), meaning color `x` is in `C_v` (all pairs are distinct) - `queries`: `q` pairs (u, v), each a path query - return: a vector of `q` integers, the answers in input order, printed space-separated # Example 1: - Input: - n = 3, k = 5, s = 5, q = 4 - edges = [(1,3), (2,1)] - colors = [(1,1), (1,2), (1,3), (1,4), (1,5)] - queries = [(1,3), (2,3), (1,2), (1,1)] - Output: - [0, 0, 0, 5] # Constraints: - $1 \leq n, k, q \leq @data$ - $1 \leq s \leq \min(n \cdot k, @data)$ - Edges form a tree - All `s` pairs in `colors` are pairwise distinct - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1000, 500, 250], [8000, 4000, 2000], [64000, 32000, 16000]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &n, int &k, int &s, int &q, vector> &edges, vector> &colors, vector> &queries) { vector> g(n); for (auto &e : edges) { int u = e.first - 1; int v = e.second - 1; g[u].push_back(v); g[v].push_back(u); } vector>> f(n); f.reserve(n); for (auto &px : colors) { int v = px.first - 1; int x = px.second - 1; f[v].emplace_back(x, v); } vector tin(n), tout(n); int T = 0; vector par(n, -1); vector idx(n, 0); vector st; st.reserve(n); vector mark(k, -1); st.push_back(0); par[0] = -1; while (!st.empty()) { int v = st.back(); if (idx[v] == 0) { tin[v] = ++T; for (auto &pc : f[v]) mark[pc.first] = pc.second; } if (idx[v] < (int)g[v].size()) { int u = g[v][idx[v]++]; if (u == par[v]) continue; par[u] = v; for (auto &pc : f[u]) { int c = pc.first; if (mark[c] != -1) pc.second = mark[c]; } st.push_back(u); continue; } for (auto &pc : f[v]) mark[pc.first] = -1; tout[v] = ++T; st.pop_back(); } auto isAnc = [&](int x, int y) -> bool { return tin[x] <= tin[y] && tout[y] <= tout[x]; }; vector>> qs(n); qs.reserve(n); for (int i = 0; i < q; i++) { int u = queries[i].first - 1; int v = queries[i].second - 1; if (f[u].size() > f[v].size()) swap(u, v); qs[v].emplace_back(u, i); } vector ans(q, 0); vector colMark(k, -1); vector> memo(n, make_pair(-1, -1)); for (int v = 0; v < n; v++) { for (auto &pc : f[v]) colMark[pc.first] = pc.second; for (auto &qq : qs[v]) { int u = qq.first; int qi = qq.second; if (memo[u].first == v) { ans[qi] = memo[u].second; continue; } int cnt = 0; for (auto &pc : f[u]) { int c = pc.first; int verU = pc.second; int verV = colMark[c]; if (verV != -1) { if (isAnc(verU, v) && isAnc(verV, u)) cnt++; } } ans[qi] = cnt; memo[u] = {v, cnt}; } for (auto &pc : f[v]) colMark[pc.first] = -1; } return ans; } vector solve2(int &n, int &k, int &s, int &q, vector> &edges, vector> &colors, vector> &queries) { vector> g(n); for (auto &e : edges) { int u = e.first - 1; int v = e.second - 1; g[u].push_back(v); g[v].push_back(u); } auto hasColor = [&](int v, int c) -> bool { for (auto &px : colors) { if (px.first - 1 == v && px.second - 1 == c) return true; } return false; }; vector ans; ans.reserve(q); for (int i = 0; i < q; i++) { int u = queries[i].first - 1; int v = queries[i].second - 1; int cnt = 0; for (int c = 0; c < k; c++) { if (!hasColor(u, c)) continue; if (!hasColor(v, c)) continue; vector vis(n, 0); queue qu; vis[u] = 1; qu.push(u); bool ok = false; while (!qu.empty()) { int cur = qu.front(); qu.pop(); if (cur == v) { ok = true; break; } for (int nx : g[cur]) { if (vis[nx]) continue; if (!hasColor(nx, c)) continue; vis[nx] = 1; qu.push(nx); } } if (ok) cnt++; } ans.push_back(cnt); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k, s, q; cin >> n >> k >> s >> q; vector> edges; edges.reserve(n - 1); for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; edges.emplace_back(u, v); } vector> colors; colors.reserve(s); for (int i = 0; i < s; i++) { int v, x; cin >> v >> x; colors.emplace_back(v, x); } vector> queries; queries.reserve(q); for (int i = 0; i < q; i++) { int u, v; cin >> u >> v; queries.emplace_back(u, v); } // solve Solution solution; auto result = solution.solve(n, k, s, q, edges, colors, queries); // output for (int i = 0; i < (int)result.size(); i++) cout << result[i] << "" \n""[i + 1 == (int)result.size()]; return 0; }","graph,data_structures",hard 36,"There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. solution main function ```cpp class Solution { public: int solve(vector& row) { } }; ``` Example 1: Input: row = [0,2,1,3] Output: 1 Example 2: Input: row = [3,2,0,1] Output: 0 Constraints: 2n == row.length 2 <= n <= @data n is even. 0 <= row[i] < 2n Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 20, 30]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class DSU {public: vectorparent; DSU(int n) { parent.resize(n); for(int i=0;i& row) { int n=row.size()/2; DSU obj(n); for(int i=0;i& row) { int n = (int)row.size(); int ans = 0; for(int i=0;i using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector row; for(int i=1;i<=n;i++) { int x; cin>>x; row.push_back(x); } // solve Solution solution; auto result = solution.solve(row); // output // for(auto it:result) cout< using namespace std; class Solution { public: static long long modPow(long long a, long long e, long long mod) { long long r = 1 % mod; a %= mod; while (e > 0) { if (e & 1) r = (__int128)r * a % mod; a = (__int128)a * a % mod; e >>= 1; } return r; } static void sievePrimes(int limit, vector &primes) { vector isComp(limit + 1, 0); primes.clear(); for (int i = 2; i <= limit; ++i) { if (!isComp[i]) primes.push_back(i); for (int p : primes) { long long v = 1LL * p * i; if (v > limit) break; isComp[(int)v] = 1; if (i % p == 0) break; } } } static void factorSmallInt(int n, const vector &primes, unordered_map &out) { for (int p : primes) { if (1LL * p * p > n) break; if (n % p == 0) { int c = 0; while (n % p == 0) n /= p, ++c; out[p] += c; } } if (n > 1) out[n] += 1; } int solve(int &x, int &y, int &z) { const int MOD = 998244353; static vector primes; static bool inited = false; if (!inited) { sievePrimes(1000, primes); inited = true; } unordered_map fm; factorSmallInt(x, primes, fm); factorSmallInt(y, primes, fm); factorSmallInt(z, primes, fm); unordered_map fphim; for (auto &kv : fm) { int p = kv.first; int t = p - 1; if (t > 1) { unordered_map tmp; factorSmallInt(t, primes, tmp); for (auto &kv2 : tmp) fphim[kv2.first] += kv2.second; } } long long prod = 1; for (auto &kv : fphim) { int q = kv.first; int beta = kv.second; if (fm.find(q) != fm.end()) continue; long long qk = modPow(q, beta, MOD); long long term = (1 + ( (qk + MOD - 1) % MOD ) * (long long)modPow(q, MOD - 2, MOD)) % MOD; prod = (prod * term) % MOD; } long long mmod = ( (1LL * x % MOD) * (1LL * y % MOD) ) % MOD; mmod = (mmod * (1LL * z % MOD)) % MOD; long long ans = prod * modPow(mmod, MOD - 2, MOD) % MOD; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int x, y, z; cin >> x >> y >> z; // solve Solution solution; auto result = solution.solve(x, y, z); // output cout << result << ""\n""; return 0; }",math,hard 38,"Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get modulo 998244353. If n = 1, the answer is considered 0 because it cannot be split into at least two positive integers. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 1 Output: 0 Example 2: Input: n = 2 Output: 1 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 1000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: const long long mod=998244353; int power(long long x,long long y) { long long temp=1; while(y) { if(y&1) temp=temp*x%mod; x=x*x%mod; y>>=1; } return temp; } int solve1(int n) { if (n <= 3) { return n - 1; } int quotient = n / 3; int remainder = n % 3; if (remainder == 0) return power(3, quotient); else if (remainder == 1) return power(3, quotient - 1) * 4ll%mod; else return power(3, quotient) * 2ll%mod; } int solve2(int n) { if (n <= 3) return n - 1; long double best_log = -1e100L; long long best_prod = 0; for (int m = 2; m <= n; ++m) { int a = n / m; int r = n % m; long double val = (long double)(m - r) * logl((long double)a) + (long double)r * logl((long double)(a + 1)); long long p1 = (m - r) ? power(a, m - r) : 1; long long p2 = r ? power(a + 1, r) : 1; long long prod = (long long)((__int128)p1 * p2 % mod); if (val > best_log) { best_log = val; best_prod = prod; } } return (int)best_prod; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< &num) { // write your code here } }; ``` Pass in parameters: 1 integer, n. An array with num containing n positive integers. Return parameters: An integer representing the answer to the quiz question Example 1: Input: n=4,num=[1, 2, 3, 4] Output: 2 Constraints: 3≤n≤@data, 1≤num[i] ≤10000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 20, 100]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n, vector &num) { num.insert(num.begin(), 0); int m = 0; sort(num.begin() + 1, num.begin() + n + 1); for (int i = 3; i <= n; i++) { for (int j = 1; j < i - 1; j++) { for (int k = j + 1; k < i; k++) { if (num[j] + num[k] == num[i]) { m++; goto skip; } } } skip:; } return m; } int solve2(int n, vector &num) { sort(num.begin(), num.end()); int m = 0; for (int i = 2; i < n; i++) { int l = 0, r = i - 1; while (l < r) { long long s = (long long)num[l] + (long long)num[r]; if (s == num[i]) { m++; break; } else if (s < num[i]) { l++; } else { r--; } } } return m; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1,x;i<=n;i++) { cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(n,num); // output cout << result << ""\n""; return 0; }",greedy,medium 40,"There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: Start at the 1st friend. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. The last friend you counted leaves the circle and loses the game. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. Else, the last friend in the circle wins the game. Given the number of friends, n, and an integer k, return the winner of the game. solution main function ```cpp class Solution { public: int solve(int n, int k) { } }; ``` Example 1: Input: n = 5, k = 2 Output: 3 Example 2: Input: n = 6, k = 5 Output: 1 Constraints: 1 <= k <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n, int k) { int ans = 0; for (int i = 1; i <= n; ++i) { ans = (ans + k) % i; } return ans + 1; } int solve2(int n, int k) { long long ans = 1; for (int i = 2; i <= n; ++i) { ans = (ans + k - 1) % i + 1; } return (int)ans; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; // solve Solution solution; auto result = solution.solve(n,k); // output cout< solve(vector& names, vector& heights) { } }; ``` Example 1: Input: names = [""Mary"",""John"",""Emma""], heights = [180,165,170] Output: [""Mary"",""Emma"",""John""] Example 2: Input: names = [""Alice"",""Bob"",""Bob""], heights = [155,185,150] Output: [""Bob"",""Alice"",""Bob""] Constraints: n == names.length == heights.length 1 <= n <= @data 1 <= names[i].length <= 20 1 <= heights[i] <= 10^5 names[i] consists of lower and upper case English letters. All the values of heights are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 200, 100], [6400, 1600, 800]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: std::vector solve1(std::vector &names, std::vector &heights) { std::vector indexes(heights.size()); std::iota(indexes.begin(), indexes.end(), 0); std::sort(indexes.begin(), indexes.end(), [&heights](int i, int j) { return heights[i] > heights[j]; }); std::vector res(names.size()); for (size_t i = 0; i < names.size(); i++) res[i] = std::move(names[indexes[i]]); return res; } std::vector solve2(std::vector &names, std::vector &heights) { size_t n = names.size(); for (size_t i = 0; i < n; ++i) { size_t pos = i; int mx = heights[i]; for (size_t j = i + 1; j < n; ++j) { int h = heights[j]; if (h > mx) { mx = h; pos = j; } } if (pos != i) { std::swap(heights[i], heights[pos]); std::swap(names[i], names[pos]); } } return names; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; vector h; for(int i=1;i<=n;i++) { string x;cin>>x; s.push_back(x); } for(int i=1;i<=n;i++) { int x;cin>>x; h.push_back(x); } // solve Solution solution; auto result = solution.solve(s,h); // output // cout << result << ""\n""; for(auto it:result) cout<> &edges) { // write your code here } }; ``` where: - `n` is the number of vertices - `edges` is the array of edges (u, v) - Return the minimum number of zelda-operations # Example 1: - Input: n = 4 edges = [(1, 2), (1, 3), (3, 4)] - Output: 1 # Constraints: - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 400, 80], [6400, 3200, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector> &edges) { vector deg(n); for (auto [x, y] : edges) deg[x - 1]++, deg[y - 1]++; int ans = (std::count(deg.begin(), deg.end(), 1) + 1) / 2; return ans; } int solve2(int &n, vector> &edges) { long long leaves = 0; for (int v = 1; v <= n; ++v) { int c = 0; for (size_t i = 0; i < edges.size(); ++i) { if (edges[i].first == v || edges[i].second == v) { ++c; if (c > 1) break; } } if (c == 1) ++leaves; } return int((leaves + 1) / 2); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector> edges(n - 1); for (int i = 0; i < n - 1; i++) cin >> edges[i].first >> edges[i].second; // solve Solution solution; auto result = solution.solve(n, edges); // output cout << result << ""\n""; return 0; }","tree,greedy",medium 43,"# Problem Statement You are given a list of $n$ integers $a_1, a_2, \dots, a_n$. You need to pick $8$ elements from the list and use them as coordinates of four points. These four points should be corners of a rectangle which has its sides parallel to the coordinate axes. Your task is to pick coordinates in such a way that the resulting rectangle has the maximum possible area. The rectangle can be degenerate, i. e. its area can be $0$. Each integer can be used as many times as it occurs in the list (or less). The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return : the maximum area of the rectangle, or $-1$ if it is impossible to form a rectangle. # Example 1: - Input: n = 8 a = [0, 0, -1, 2, 2, 1, 1, 3] - Output: -1 # Constraints: - $8 \leq n \leq @data$ - $-10^4 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { bool firstOccur(const vector &a, int idx) { for (int i = 0; i < idx; ++i) if (a[i] == a[idx]) return false; return true; } public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int min1 = INT_MAX, min2 = INT_MAX, max1 = INT_MIN, max2 = INT_MIN; for (int i = 0, pre = 1E9; i < n; i++) { if (a[i] != pre) { pre = a[i]; continue; } pre = 1E9; if (a[i] < min1) { min2 = min1; min1 = a[i]; } else if (a[i] < min2) { min2 = a[i]; } else if (a[i] > max1) { max2 = max1; max1 = a[i]; } else if (a[i] > max2) { max2 = a[i]; } } if (min1 == INT_MAX || min2 == INT_MAX || max1 == INT_MIN || max2 == INT_MIN) return -1; return max((max1 - min1) * (max2 - min2), (max2 - min1) * (max1 - min2)); } int solve2(int &n, vector &a) { long long best = -1; for (int i = 0; i < n; ++i) { if (!firstOccur(a, i)) continue; for (int j = i; j < n; ++j) { if (!firstOccur(a, j)) continue; long long dx = llabs((long long)a[j] - (long long)a[i]); for (int k = 0; k < n; ++k) { if (!firstOccur(a, k)) continue; for (int l = k; l < n; ++l) { if (!firstOccur(a, l)) continue; int need1 = 2 * (1 + (a[j] == a[i]) + (a[k] == a[i]) + (a[l] == a[i])); int need2 = 2 * (1 + (a[i] == a[j]) + (a[k] == a[j]) + (a[l] == a[j])); int need3 = 2 * (1 + (a[i] == a[k]) + (a[j] == a[k]) + (a[l] == a[k])); int need4 = 2 * (1 + (a[i] == a[l]) + (a[j] == a[l]) + (a[k] == a[l])); int c1 = 0, c2 = 0, c3 = 0, c4 = 0; for (int t = 0; t < n; ++t) { int x = a[t]; if (x == a[i] && c1 < need1) ++c1; if (x == a[j] && c2 < need2) ++c2; if (x == a[k] && c3 < need3) ++c3; if (x == a[l] && c4 < need4) ++c4; if (c1 == need1 && c2 == need2 && c3 == need3 && c4 == need4) break; } if (c1 == need1 && c2 == need2 && c3 == need3 && c4 == need4) { long long dy = llabs((long long)a[l] - (long long)a[k]); long long area = dx * dy; if (area > best) best = area; } } } } } if (best < 0) return -1; if (best > INT_MAX) return (int)best; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","sort,greedy",hard 44,"Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false. solution main function ```cpp class Solution { public: bool solve(string s, int k) { } }; ``` Example 1: Input: s = ""00110110"", k = 2 Output: 1 Example 2: Input: s = ""0110"", k = 1 Output: 1 Constraints: 1 <= s.length <= @data s[i] is either '0' or '1'. 1 <= k <= 20 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[200, 64, 64], [1600, 500, 275], [12800, 4000, 2200]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve1(string s, int k) { int n = s.size(); if(k > n) { return false; } int cur = 0; vector vis(1 << k, false); for(int i = 0; i < k; ++i) { cur = (cur << 1) + (s[i] == '1'); } vis[cur] = true; for(int i = k; i < n; ++i) { cur = (cur << 1) + (s[i] == '1'); cur &= ~(1 << k); vis[cur] = true; } for(bool v : vis) { if(!v) { return false; } } return true; } bool solve2(string s, int k) { int n = (int)s.size(); if (k > n) return false; int total = 1 << k; if (n - k + 1 < total) return false; int mask = total - 1; for (int target = 0; target < total; ++target) { int cur = 0; for (int i = 0; i < k; ++i) { cur = (cur << 1) + (s[i] == '1'); } bool found = (cur == target); for (int i = k; !found && i < n; ++i) { cur = ((cur << 1) & mask) + (s[i] == '1'); if (cur == target) found = true; } if (!found) return false; } return true; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; string str; cin>>str>>n; // solve Solution solution; int result = solution.solve(str,n); // output cout<& arr) { } }; ``` Example 1: Input: arr = [4,3,2,1,0] Output: 1 Example 2: Input: arr = [1,0,2,3,4] Output: 4 Constraints: n == arr.length 1 <= n <= @data 0 <= arr[i] < n All the elements of arr are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& arr) { int n = arr.size(); int chunks = 0, maxElement = 0; for (int i = 0; i < n; i++) { maxElement = max(maxElement, arr[i]); if (maxElement == i) { chunks++; } } return chunks; } int solve2(vector& arr) { int n = arr.size(); long long pref = 0, target = 0; int chunks = 0; for (int i = 0; i < n; ++i) { pref += arr[i]; target += i; if (pref == target) ++chunks; } return chunks; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector num; cin>>n; for(int i=1,x;i<=n;i++) { cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout<& nums) { } }; ``` Example 1: Input: nums = [1,15,6,3] Output: 9 Example 2: Input: nums = [1,2,3,4] Output: 0 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 2000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int elementSum = 0; int digitSum = 0; for(int i=0;i0){ int lastDigit = n%10; digitSum += lastDigit; n=n/10; } } int absoluteDifference = abs (elementSum - digitSum); return absoluteDifference; } int solve2(vector& nums) { long long elementSum = 0; long long digitSum = 0; for (int x : nums) { elementSum += x; int t = x; while (t > 0) { digitSum += t % 10; t /= 10; } } long long diff = elementSum - digitSum; if (diff < 0) diff = -diff; return (int)diff; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n;cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return the the number of unique procedures that result in c=k, modulo 998244353. # Example 1: - Input: n = 4 a = [2, -5, 3, -3] - Output: 12 # Constraints: - $2 \leq n \leq @data$ - $-10^9 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve(int &n, vector &a) { const int mod = 998244353; long long cnt1 = 1, cnt2 = 1; long long c1 = 0, c2 = 0; for (int i = 0; i < n; i++) { long long pre1 = c1, pre2 = c2; c1 = max({pre1 + a[i], abs(pre2 + a[i])}); c2 = pre2 + a[i]; if (pre1 + a[i] == abs(pre2 + a[i])) { if (pre1 == pre2) cnt1 = cnt1 * 2 % mod, cnt2 = cnt2 * 2 % mod; else cnt1 = (cnt1 * 2 + cnt2) % mod; } else if (c1 == pre1 + a[i]) { cnt1 = cnt1 * 2 % mod; if (c2 >= 0) cnt2 = cnt2 * 2 % mod; } else cnt1 = cnt2; } return cnt1; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",dp,hard 48,"There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n, indicating that you must do the following routine for n minutes: At the first minute, color any arbitrary unit cell blue. Every minute thereafter, color blue every uncolored cell that touches a blue cell Return the number of colored cells at the end of n minutes. solution main function ```cpp class Solution { public: long long solve(int n) { } }; ``` Example 1: Input: n = 1 Output: 1 Example 2: Input: n = 2 Output: 5 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: long long solve1(int n) { return static_cast(n) * n + static_cast(n - 1) * (n - 1); } long long solve2(int n) { long long ans = 0; if (n <= 0) return 0; ans = 1; for (int t = 2; t <= n; ++t) { ans += 4LL * (t - 1); } return ans; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< using namespace std; class Solution { public: int solve1(int &n, string &s) { int ans = 0; for (int i = 0; i < n; i++) { if (i + 3 <= n && s.substr(i, 3) == ""pie"") ans++; if (i + 3 <= n && s.substr(i, 3) == ""map"") ans++; if (i + 5 <= n && s.substr(i, 5) == ""mapie"") ans--; } return ans; } int solve2(int &n, string &s) { int ans = 0; for (int i = 0; i < n; i++) { if (i + 2 < n) { char a = s[i], b = s[i + 1], c = s[i + 2]; if (a == 'p' && b == 'i' && c == 'e') ans++; if (a == 'm' && b == 'a' && c == 'p') { ans++; if (i + 4 < n && s[i + 3] == 'i' && s[i + 4] == 'e') ans--; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","math,dp,greedy,string",easy 50,"# Problem Statement Vika and her friends went shopping in a mall, which can be represented as a rectangular grid of rooms with sides of length $n$ and $m$. Each room has coordinates $(a, b)$, where $1 \le a \le n, 1 \le b \le m$. Thus we call a hall with coordinates $(c, d)$ a neighbouring for it if $|a - c| + |b - d| = 1$. Tired of empty fashion talks, Vika decided to sneak away unnoticed. But since she hasn't had a chance to visit one of the shops yet, she doesn't want to leave the mall. After a while, her friends noticed Vika's disappearance and started looking for her. Currently, Vika is in a room with coordinates $(x, y)$, and her $k$ friends are in rooms with coordinates $(x_1, y_1)$, $(x_2, y_2)$, ... $, (x_k, y_k)$, respectively. The coordinates can coincide. Note that all the girls **must** move to the neighbouring rooms. Every minute, first Vika moves to one of the adjacent to the side rooms of her choice, and then each friend (**seeing Vika's choice**) also chooses one of the adjacent rooms to move to. If **at the end of the minute** (that is, after all the girls have moved on to the neighbouring rooms) at least one friend is in the same room as Vika, she is caught and all the other friends are called. Tell us, can Vika run away from her annoying friends forever, or will she have to continue listening to empty fashion talks after some time? The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, int &m, int &k, int &x, int &y, vector> &a) { // write your code here } }; ``` where: - `n` and `m` are the size of the mall, `k` is the number of friends - `x` and `y` are Vika's initial position - `a` is the initial position of the friends - return ""YES"" if Vika can run away from her friends forever, otherwise return ""NO"" # Example 1: - Input: n = 2, m = 2, k = 2 x = 1, y = 1 a = [(1, 1), (1, 2)] - Output: NO # Constraints: - $1 \leq n, m, k \leq @data$ - $1 \leq x, x_i \leq n$ - $1 \leq y, y_i \leq m$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int n, int m, int k, int x, int y, vector> &a) { bool caught = false; for (int i = 0; i < k; i++) { int X = a[i].first, Y = a[i].second; if ((x + y + X + Y) % 2 == 0) caught = true; } return caught ? ""NO"" : ""YES""; } string solve2(int n, int m, int k, int x, int y, vector> &a) { int pv = ((x ^ y) & 1); for (int i = 0; i < k; ++i) { int X = a[i].first, Y = a[i].second; if (((X ^ Y) & 1) == pv) return ""NO""; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m, k; cin >> n >> m >> k; int x, y; cin >> x >> y; vector> a(k); for (auto &[X, Y] : a) cin >> X >> Y; // solve Solution solution; auto result = solution.solve(n, m, k, x, y, a); // output cout << result << ""\n""; return 0; }","graph,math",medium 51,"You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer. solution main function ```cpp class Solution { public: int solve(vector& target) { } }; ``` Example 1: Input: target = [1,2,3,2,1] Output: 3 Example 2: Input: target = [3,1,1,2] Output: 4 Constraints: 1 <= target.length <= @data 1 <= target[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& target) { int noOfOperations = target[0]; for(int i = 1; i < target. size(); i++) { if(target[i] > target[i-1]) noOfOperations += (target[i]-target[i-1]); } return noOfOperations; } int solve2(vector& target) { long long res = 0; int prev = 0; for (size_t i = 0; i < target.size(); ++i) { int diff = target[i] - prev; if (diff > 0) res += diff; prev = target[i]; } if (res > INT_MAX) return INT_MAX; if (res < INT_MIN) return INT_MIN; return (int)res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< >&r) { // write your code here } }; ``` Pass in parameters: 1 integer n. A two-dimensional vector array $n-1$row is a semi-matrix $r(i,j)$($1\le i using namespace std; class Solution { public: int solve(int n, vector >&r) { int f[n+1]; for(int i=0;i<=n;i++) f[i]=0; for (int i=1;i<=n;i++) for (int j=i+1;j<=n;j++) { if (f[j]==0||f[j]>f[i]+r[i-1][j-i-1]) f[j]=f[i]+r[i-1][j-i-1]; } return f[n]; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin >> n; vector > r; for(int i=1;i temp; for(int j=1;j<=n-i;j++) { int x; cin>>x; temp.push_back(x); } r.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,r); // output cout << result << ""\n""; return 0; }","dp,graph",medium 53,"# Problem Statement You are given an array consisting of $n$ integers $a_1$, $a_2$, ..., $a_n$. Initially $a_x = 1$, all other elements are equal to $0$. You have to perform $m$ operations. During the $i$-th operation, you choose two indices $c$ and $d$ such that $l_i \le c, d \le r_i$, and swap $a_c$ and $a_d$. Calculate the number of indices $k$ such that it is possible to choose the operations so that $a_k = 1$ in the end. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &x, int &m, vector &l, vector &r) { // write your code here } }; ``` where: - return: the number of indices k such that it is possible to choose the operations so that ak=1 in the end. # Example 1: - Input: n = 6, x = 4, m = 3 l = [1,2,5] r = [6,3,5] - Output: 6 # Constraints: - $1 \leq m \leq @data$ - $1 \leq x \leq n \leq 10^9$ - $1 \leq l[i] \leq r[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &x, int &m, vector &l, vector &r) { int cl, cr; cl = x; cr = x; for (int i = 0; i < m; i++) { if (max(l[i], cl) <= min(r[i], cr)) { cl = min(l[i], cl); cr = max(r[i], cr); } } return cr - cl + 1; } int solve2(int &n, int &x, int &m, vector &l, vector &r) { long long L = x, R = x; int start = -1; for (int i = 0; i < m; i++) { if ((long long)l[i] <= L && (long long)r[i] >= R) { L = l[i]; R = r[i]; start = i; break; } } if (start == -1) return 1; for (int i = start + 1; i < m; i++) { long long ml = max(l[i], L); long long mr = min(r[i], R); if (ml <= mr) { if ((long long)l[i] < L) L = l[i]; if ((long long)r[i] > R) R = r[i]; } } long long ans = R - L + 1; if (ans < 0) ans = 0; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n,x,m; cin >> n >> x >> m; vector l(m),r(m); for (int i = 0; i < m; i++) cin >> l[i] >> r[i]; // solve Solution solution; auto result = solution.solve(n, x, m, l, r); // output cout << result << ""\n""; return 0; }","math,two_pointers",hard 54,"# Problem Statement: YunQian is standing on an infinite plane with the Cartesian coordinate system on it. In one move, she can move to the diagonally adjacent point on the top right or the adjacent point on the left. That is, if she is standing on point $(x,y)$, she can either move to point $(x+1,y+1)$ or point $(x-1,y)$. YunQian initially stands at point $(a,b)$ and wants to move to point $(c,d)$. Find the minimum number of moves she needs to make or declare that it is impossible. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &a, int &b, int &c, int &d) { // write your code here } }; ``` Where: - `a, b, c, d`: integers representing the coordinates of Yunqian's initial position and target position. - return value: the minimum number of moves Yunqian needs to make to reach the target position. If it is impossible to reach the target position, return -1. # Example 1: - Input: a = -1, b = 0, c = -1, d = 2 - Output: 4 # Constraints: - $-@data \leq a, b, c, d \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &a, int &b, int &c, int &d) { a -= b; c -= d; if (a < c || b > d) return -1; return (a - c) + (d - b); } int solve2(int &a, int &b, int &c, int &d) { long long A = a, B = b, C = c, D = d; if (D < B) return -1; long long u = D - B; long long v = A + u - C; if (v < 0) return -1; long long m = u + v; if (m > INT_MAX) return -1; return (int)m; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int a, b, c, d; cin >> a >> b >> c >> d; // solve Solution solution; auto result = solution.solve(a, b, c, d); // output cout << result << ""\n""; return 0; }","graph,greedy,math",hard 55,"# Problem Statement You have $5$ different types of coins, each with a value equal to one of the first $5$ triangular numbers: $1$, $3$, $6$, $10$, and $15$. These coin types are available in abundance. Your goal is to find the minimum number of these coins required such that their total value sums up to exactly $n$. We can show that the answer always exists. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n) { // write your code here } }; ``` where: - return: the minimum number of coins required. # Example 1: - Input: n = 2 - Output: 2 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 1000000, 100000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n) { array a = {1, 3, 6, 10, 15}; int cnt = 0; if (n >= 30) { int num = n / 15; n = n % 15 + 15 * 2; cnt = num - 2; } vector dp(n + 1, INT_MAX); dp[0] = 0; for (int j = 1; j <= n; j++) for (int i = 0; i < 5; i++) { if (j - a[i] >= 0) dp[j] = min(dp[j], dp[j - a[i]] + 1); } return dp[n] + cnt; } int solve2(int &n) { if (n <= 0) return 0; int best = INT_MAX; int max15 = n / 15; for (int a = 0; a <= max15; ++a) { int rem1 = n - 15 * a; int bmax = rem1 / 10; for (int kb = 0; kb < 3; ++kb) { int b = bmax - kb; if (b < 0) continue; int t = rem1 - 10 * b; int c6 = t / 6; int r6 = t - c6 * 6; int c3 = r6 / 3; int c1 = r6 - c3 * 3; int total = a + b + c6 + c3 + c1; if (total < best) best = total; } } return best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }","dp,math",hard 56,"# Problem Statement You are given an undirected unweighted tree $T$ with $n$ vertices. Define a complete undirected weighted graph $G$ with the same vertex set, where the weight between $u$ and $v$ in $G$ equals the distance between them in the tree $T$. For every subset $S$ of vertices, consider the minimum spanning tree (MST) of the subgraph of $G$ induced by $S$. Compute the sum of MST weights over all subsets $S$, modulo $10^9+7$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector> &edges) { // write your code here } }; ``` where: - `n`: the number of vertices in the tree - `edges`: `n-1` edges `(u, v)` (1-based), forming a tree - return: the sum of MST weights over all subsets, modulo $10^9+7$ # Example 1: - Input: ``` n = 3 edges = [(1,2),(2,3)] ``` - Output: ``` 6 ``` # Constraints: - $1 \le n \le @data$ - Tree input: exactly $n-1$ edges, $1 \le u,v \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 1000, 5000]",2000,"[[100, 64, 64], [800, 400, 160], [6400, 3200, 1280]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, vector> &edges) { const int MOD = 1000000007; vector> g(n + 1); for (auto &e : edges) { int u = e.first, v = e.second; g[u].push_back(v); g[v].push_back(u); } vector order; order.reserve(n); vector pos(n + 1, 0); { queue q; vector vis(n + 1, 0); vis[1] = 1; q.push(1); while (!q.empty()) { int u = q.front(); q.pop(); order.push_back(u); pos[u] = (int)order.size(); for (int v : g[u]) { if (!vis[v]) { vis[v] = 1; q.push(v); } } } } vector pw2(n + 1); pw2[0] = 1; for (int i = 1; i <= n; i++) { pw2[i] = (pw2[i - 1] << 1); if (pw2[i] >= MOD) pw2[i] -= MOD; } long long ans = 0; vector cnt(n + 1, 0); auto dfs = [&](auto &&self, int u, int fa, int lim, int depth) -> void { if (depth > 0) cnt[depth]++; for (int v : g[u]) { if (v == fa) continue; if (pos[v] > lim) continue; self(self, v, u, lim, depth + 1); } }; for (int lim = 1; lim <= n; lim++) { fill(cnt.begin(), cnt.end(), 0); int root = order[lim - 1]; dfs(dfs, root, 0, lim, 0); long long cur = 0; for (int j = 1; j <= n; j++) { cnt[j] += cnt[j - 1]; int exp = lim - cnt[j - 1] - 1; int add = pw2[exp]; add -= 1; if (add < 0) add += MOD; cur += add; if (cur >= MOD) cur -= MOD; } ans = (ans + cur * pw2[n - lim]) % MOD; } if (ans < 0) ans += MOD; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector> edges; edges.reserve(max(0, n - 1)); for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; edges.push_back({u, v}); } // solve Solution solution; auto result = solution.solve(n, edges); // output cout << result << ""\n""; return 0; }","graph,tree,combinatorics",hard 57,"You are given two strings s1 and s2 of equal length consisting of letters ""x"" and ""y"" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j]. Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so. solution main function ```cpp class Solution { public: int solve(string s1, string s2) { } }; ``` Example 1: Input: s1 = ""xx"", s2 = ""yy"" Output: 1 Example 2: Input: s1 = ""xy"", s2 = ""yx"" Output: 2 Constraints: 1 <= s1.length, s2.length <= @data s1.length == s2.length s1, s2 only contain 'x' or 'y' Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(string s1, string s2) { int xy = 0, yx = 0; for (int i = 0; i < s1.size(); ++i) { if (s1[i] == 'x' && s2[i] == 'y') xy++; if (s1[i] == 'y' && s2[i] == 'x') yx++; } if ((xy + yx) % 2 != 0) return -1; return xy / 2 + yx / 2 + (xy % 2) * 2; } int solve2(string s1, string s2) { int n = (int)s1.size(); int pending_xy = 0, pending_yx = 0; int ans = 0; for (int i = 0; i < n; ++i) { char a = s1[i], b = s2[i]; if (a == b) continue; if (a == 'x') { if (pending_xy) { --pending_xy; ++ans; } else { ++pending_xy; } } else { if (pending_yx) { --pending_yx; ++ans; } else { ++pending_yx; } } } int rem = pending_xy + pending_yx; if (rem & 1) return -1; if (pending_xy == 1 && pending_yx == 1) ans += 2; return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string a,b; cin>>a>>b; // solve Solution solution; auto result = solution.solve(a,b); // output // for(auto it:result) cout< using namespace std; class Solution { public: int solve(string s, int k) { int currentNumber = 0; for (char ch : s) { int position = ch - 'a' + 1; while (position > 0) { currentNumber += position % 10; position /= 10; } } for (int i = 1; i < k; ++i) { int digitSum = 0; while (currentNumber > 0) { digitSum += currentNumber % 10; currentNumber /= 10; } currentNumber = digitSum; if (currentNumber < 10) { break; } } return currentNumber; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int k; string s; cin>>k>>s; // solve Solution solution; auto result = solution.solve(s,k); // output cout<& nums1, vector& nums2) { } }; ``` Example 1: Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5] Output: 3 Example 2: Input: nums1 = [1,3,7,1,7], nums2 = [1,9,2,5,1] Output: 2 Constraints: 1 <= nums1.length == nums2.length <= @data 1 <= nums1[i], nums2[i] <= 2000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(vector& nums1, vector& nums2) { int n1 = nums1.size(); int n2 = nums2.size(); vector dp(n2 + 1), dpPrev(n2 + 1); for (int i = 1; i <= n1; i++) { for (int j = 1; j <= n2; j++) { if (nums1[i - 1] == nums2[j - 1]) { dp[j] = 1 + dpPrev[j - 1]; } else { dp[j] = max(dp[j - 1], dpPrev[j]); } } dpPrev = dp; } return dp[n2]; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< int > a,b; for(int i=1,x;i<=n;i++) { cin>>x; a.push_back(x); } for(int i=1,x;i<=n;i++) { cin>>x; b.push_back(x); } // solve Solution solution; int result = solution.solve(a,b); // output cout << result << ""\n""; return 0; }",dp,medium 60,"# Problem Statement You are given an array $a$ of size $n$. You will do the following process to calculate your penalty: 1. Split array $a$ into two (possibly empty) subsequences$^\dagger$ $s$ and $t$ such that every element of $a$ is either in $s$ or $t^\ddagger$. 2. For an array $b$ of size $m$, define the penalty $p(b)$ of an array $b$ as the number of indices $i$ between $1$ and $m - 1$ where $b_i < b_{i + 1}$. 3. The total penalty you will receive is $p(s) + p(t)$. If you perform the above process optimally, find the minimum possible penalty you will receive. $^\dagger$ A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements. $^\ddagger$ Some valid ways to split array $a=[3,1,4,1,5]$ into $(s,t)$ are $([3,4,1,5],[1])$, $([1,1],[3,4,5])$ and $([\,],[3,1,4,1,5])$ while some invalid ways to split $a$ are $([3,4,5],[1])$, $([3,1,4,1],[1,5])$ and $([1,3,4],[5,1])$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return a single integer representing the minimum possible penalty you will receive. # Example 1: - Input: n = 5 a = [1, 2, 3, 4, 5] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int ans = 0; for (int i = 0, x = n, y = n, ai; i < n; i += 1) { ai = a[i]; if (ai > x and ai > y) { ans += 1; (x < y ? x : y) = ai; } else if (ai <= x and ai <= y) { (x < y ? x : y) = ai; } else if (ai <= x) { x = ai; } else { y = ai; } } return ans; } int solve2(int &n, vector &a) { int ans = 0; int s_top = n, t_top = n; for (int i = 0; i < n; ++i) { int v = a[i]; int c = (v > s_top) + (v > t_top); if (c == 2) { ++ans; if (s_top < t_top) s_top = v; else t_top = v; } else if (c == 0) { if (s_top < t_top) s_top = v; else t_top = v; } else { if (v <= s_top) s_top = v; else t_top = v; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",dp,hard 61,"You are given a 0-indexed integer array nums of length n. nums contains a valid split at index i if the following are true: The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements. There is at least one element to the right of i. That is, 0 <= i < n - 1. Return the number of valid splits in nums. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [10,4,-8,7] Output: 2 Example 2: Input: nums = [2,3,1,0] Output: 2 Constraints: 2 <= nums.length <= @data -10^5 <= nums[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { long long leftSum = 0, rightSum = 0; for (int num : nums) { rightSum += num; } int count = 0; for (int i = 0; i < nums.size() - 1; i++) { leftSum += nums[i]; rightSum -= nums[i]; if (leftSum >= rightSum) { count++; } } return count; } int solve2(vector& nums) { int n = (int)nums.size(); int count = 0; for (int i = 0; i < n - 1; ++i) { long long leftSum = 0; for (int j = 0; j <= i; ++j) leftSum += (long long)nums[j]; long long rightSum = 0; for (int j = i + 1; j < n; ++j) rightSum += (long long)nums[j]; if (leftSum >= rightSum) ++count; } return count; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }",math,easy 62,"# Problem Statement Monocarp is playing a computer game on a grid with $2$ rows and $n$ columns. The strings $s1$ and $s2$ describe the two rows of the grid. A character `0` means the cell is safe, and a character `1` means the cell contains a trap. Determine whether the level is passable. For this task, the level is passable if every column has at least one safe cell. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, string &s1, string &s2) { // write your code here } }; ``` where: - `n` is the number of columns. - `s1` is the first row of the grid. - `s2` is the second row of the grid. - return: `""YES""` if the level is passable, and `""NO""` otherwise. # Example 1 - Input: n = 6 s1 = ""010101"" s2 = ""101010"" - Output: YES # Constraints - $3 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve(int &n, string &s1, string &s2) { for (int i = 0; i < n; i++) if (s1[i] == '1' && s2[i] == '1') return ""NO""; return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s1, s2; cin >> s1 >> s2; // solve Solution solution; auto result = solution.solve(n, s1, s2); // output cout << result << ""\n""; return 0; }","search,dp,greedy",medium 63,"# Problem Statement We call a polynomial $f(x) = a_0 + a_1 x + a_2 x^2 + \dots + a_n x^n$ valid of degree $n$ if and only if each $a_i$ is a non-negative integer for $0 \le i \le n$, and $a_n \ne 0$. For a valid polynomial $f(x)$, define its twin polynomial $g(x) = \sum_{i=0}^{n} i \cdot x^{a_i}.$ For example, if $f(x)=1+2x+2x^3$, then $g(x)=0\cdot x^{1} + 1\cdot x^{2} + 2\cdot x^{0} + 3\cdot x^{2} = 2 + 4x^2.$ We call $f(x)$ cool if and only if $f(x) = g(x)$. You are given an incomplete valid polynomial of degree $n$: the array $(a_0,\dots,a_n)$, where some positions are determined (known) and others are $-1$ (unknown). It is guaranteed that $a_0$ and $a_n$ are $-1$ in the input. Count the number of cool valid polynomials consistent with the given information. Since the answer can be large, output it modulo $10^9+7$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: degree of the polynomial. - `a`: an array of length `n+1`, where `a[i] = -1` means unknown, otherwise `0 ≤ a[i] ≤ n`. - return: the number of cool valid polynomials modulo $10^9+7$. # Example: - Input: - n = 2 - a = [-1, -1, -1] - Output: - 3 # Constraints: - $1 \le n \le @data$ - $a_i \in \{-1\} \cup [0, n]$ - $a_0 = a_n = -1$ in the input - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { const int MOD = 1000000007; if ((int)a.size() != n + 1) return 0; for (int i = 0; i <= n; ++i) { if (a[i] != -1 && (a[i] < 0 || a[i] > n)) return 0; } for (int i = 1; i <= n; ++i) { if (a[i] == -1) continue; if (a[i] == 0 || a[i] == i) continue; int j = a[i]; if (a[j] == -1) { a[j] = i; } else if (a[j] != i) { return 0; } } if (a[n] == 0) return 0; int m = 0; for (int i = 1; i <= n; ++i) if (a[i] == -1) ++m; auto computeF = [&](int t) -> pair { if (t == 0) return {1, 0}; long long f0 = 1; long long f1 = 2; if (t == 1) return {(int)f1, (int)f0}; long long prev2 = f0, prev1 = f1, cur = 0; for (int i = 2; i <= t; ++i) { cur = (2 * prev1 + (long long)(i - 1) * prev2) % MOD; prev2 = prev1; prev1 = cur; } return {(int)cur, (int)prev2}; }; auto [Fm, Fm_1] = computeF(m); int ans = 0; if (a[n] == -1) { ans = Fm - Fm_1; if (ans < 0) ans += MOD; } else { ans = Fm; } return ans % MOD; } int solve2(int &n, vector &a) { const int MOD = 1000000007; if ((int)a.size() != n + 1) return 0; for (int i = 0; i <= n; ++i) { if (a[i] != -1 && (a[i] < 0 || a[i] > n)) return 0; } for (int i = 1; i <= n; ++i) { if (a[i] == -1) continue; int j = a[i]; if (j == 0 || j == i) continue; if (j < 0 || j > n) return 0; if (a[j] == -1) { a[j] = i; } else if (a[j] != i) { return 0; } } if (a[n] == 0) return 0; int m = 0; for (int i = 1; i <= n; ++i) if (a[i] == -1) ++m; auto modpow = [&](long long base, long long exp) -> long long { long long res = 1 % MOD; base %= MOD; while (exp > 0) { if (exp & 1) res = (res * base) % MOD; base = (base * base) % MOD; exp >>= 1; } return res; }; auto inv = [&](long long x) -> long long { return modpow(x, MOD - 2); }; auto computeF = [&](int t) -> int { if (t < 0) return 0; long long res = 0; long long comb = 1; long long pow2 = modpow(2, t); long long inv4 = inv(4); long long odd = 1; int r = 0; int maxk = t / 2; for (int k = 0; k <= maxk; ++k) { long long term = comb; term = (term * odd) % MOD; term = (term * pow2) % MOD; res += term; if (res >= MOD) res -= MOD; if (k == maxk) break; long long inv_r1 = inv(r + 1); comb = (comb * (t - r)) % MOD; comb = (comb * inv_r1) % MOD; long long inv_r2 = inv(r + 2); comb = (comb * (t - (r + 1))) % MOD; comb = (comb * inv_r2) % MOD; r += 2; odd = (odd * (2LL * k + 1)) % MOD; pow2 = (pow2 * inv4) % MOD; } return (int)(res % MOD); }; int Fm = computeF(m); int ans; if (a[n] == -1) { int Fm1 = computeF(m - 1); ans = Fm - Fm1; if (ans < 0) ans += MOD; } else { ans = Fm; } return ans % MOD; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n + 1); for (int i = 0; i <= n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,math",hard 64,"# Problem Statement There are two screens which can display sequences of uppercase Latin letters. Initially, both screens display nothing. In one second, you can do one of the following two actions: - choose a screen and an uppercase Latin letter, and append that letter to **the end** of the sequence displayed on that screen; - choose a screen and copy the sequence from it to the other screen, **overwriting the sequence that was displayed on the other screen**. You have to calculate the minimum number of seconds you have to spend so that the first screen displays the sequence $s$, and the second screen displays the sequence $t$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(string &s, string &t) { // write your code here } }; ``` where: - return: the minimum possible number of seconds you have to spend so that the first screen displays the sequence s, and the second screen displays the sequence t. # Example 1: - Input: s = ""GARAGE"" t = ""GARAGEFORSALE"" - Output: 14 # Constraints: - $1 \leq s.length, t.length \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(string &s, string &t) { int i = 0; while (i < s.size() && i < t.size() && s[i] == t[i]) i++; int ans = s.size() + t.size() - max(0, i - 1); return ans; } int solve2(string &s, string &t) { long long n = (long long)s.size(); long long m = (long long)t.size(); long long l = 0; while (l < n && l < m && s[(size_t)l] == t[(size_t)l]) ++l; long long ans = min(n + m, n + m + 1 - l); if (ans > INT_MAX) return INT_MAX; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string s, t; cin >> s >> t; // solve Solution solution; auto result = solution.solve(s, t); // output cout << result << ""\n""; return 0; }","string,greedy,two_pointers",hard 65,"Xiao Ming's flower shop has just opened. In order to attract customers, he wants to put a row of flowers in front of the shop, with a total of $m$ pots. By investigating customers' preferences, Xiao Ming made a list of customers' favorite $n$ flowers. In order to display more flowers at the door, it is stipulated that the $i$-th type of flower cannot exceed $a_i$ pots, and the same type of flowers must be placed together, and the different types must be arranged in increasing order of their labels. Try programming to figure out how many different flower arrangements there are. Since the answer can be very large, return it modulo 1000007. Function Signature ```cpp class Solution { public: int solve(int n, int m, vector &a) { // write your code here } }; ``` Example 1: Input: n=2, m=4, a=[3, 2] Output: 2 Constraints: 0 < n, m <= @data 0 <= a[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 50, 100]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n, int m, vector &a) { const int mod = 1000007; a.insert(a.begin(), 0); vector f(m + 1, 0), sum(m + 1, 0); f[0] = 1; for (int i = 0; i <= m; i++) sum[i] = 1; for (int i = 1; i <= n; i++) { for (int j = m; j >= 1; j--) { int t = j - min(a[i], j) - 1; if (t < 0) f[j] = (f[j] + sum[j - 1]) % mod; else f[j] = (f[j] + sum[j - 1] - sum[t] + mod) % mod; } for (int j = 1; j <= m; j++) sum[j] = (sum[j - 1] + f[j]) % mod; } return f[m]; } int solve2(int n, int m, vector &a) { const int mod = 1000007; if (n <= 0) return (m == 0) ? 1 : 0; long long totalCap = 0; for (int i = 0; i < n; ++i) totalCap += (a[i] < 0 ? 0 : a[i]); if (m > totalCap) return 0; const int BASE = 1 << 10; for (int i = 0; i < n; ++i) { int cap = a[i]; if (cap < 0) cap = 0; a[i] = (cap << 10); } long long ans = 0; long long s = 0; if (s == m) ans = (ans + 1) % mod; while (true) { int k = 0; while (k < n) { int cap = a[k] >> 10; int cnt = a[k] & (BASE - 1); if (cnt < cap) { cnt++; a[k] = (cap << 10) | cnt; s += 1; break; } else { s -= cnt; cnt = 0; a[k] = (cap << 10) | cnt; ++k; } } if (k == n) break; if (s == m) { ans++; if (ans >= mod) ans -= mod; } } return (int)(ans % mod); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; vector a; cin>>n>>m; for(int i=1,x;i<=n;i++) { cin>>x; a.push_back(x); } // solve Solution solution; auto result = solution.solve(n,m,a); // output cout << result << ""\n""; return 0; }",dp,hard 66,"# Problem Statement This is a counting problem on binary strings. For a binary string r, define f(r) as the result of repeatedly and simultaneously deleting all substrings ""10"" from r, until no ""10"" remains. For example, f(100110001) = 001 since: 10_0110_001 → 010_01 → 001. A binary string s is called almost-palindrome if and only if f(s) = f(rev(s)), where rev(s) is the reverse of s. Given an integer n, compute the number of distinct almost-palindrome binary strings of length n, modulo 998244353. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n) { // write your code here } }; ``` where: - `n`: the length of the binary string - return: the number of almost-palindrome binary strings of length `n` modulo 998244353 # Example 1: - Input: n = 3 - Output: 4 # Constraints: - $1 \leq n \leq @data$ - Modulo: 998244353 - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 400, 200], [6400, 3200, 1600]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n) { const int mod = 998244353; auto add = [&](int x, int y) -> int { x += y; return x < mod ? x : x - mod; }; auto sub = [&](int x, int y) -> int { x -= y; return x < 0 ? x + mod : x; }; auto cadd = [&](int &x, int y) { x += y; if (x >= mod) x -= mod; }; auto csub = [&](int &x, int y) { x -= y; if (x < 0) x += mod; }; if (n == 0) return 1; vector inv(n + 1, 0), a(n + 1, 0), s(n + 1, 0); inv[1] = 1; for (int i = 2; i <= n; i++) inv[i] = (int)((long long)(mod - mod / i) * inv[mod % i] % mod); a[0] = 1; s[0] = 1; for (int i = 1; i <= n; i++) { a[i] = (int)((long long)a[i - 1] * inv[i] % mod * (n - i + 1) % mod); s[i] = add(s[i - 1], a[i]); } auto ask = [&](int l, int r) -> int { l = max(l, 0); r = min(r, n); if (l > r) return 0; return l ? sub(s[r], s[l - 1]) : s[r]; }; auto calc = [&](int k, int t) -> int { int sum = 0; for (int p = 0; ((n + k) >> 1) - p * (k + 2 - t) >= 0; p++) { cadd(sum, ask(((n - k) >> 1) - p * (k + 2 - t), ((n + k) >> 1) - t - p * (k + 2 - t))); } for (int p = 0; ((n - k) >> 1) - 1 - p * (k + 2 - t) >= 0; p++) { csub(sum, (int)((long long)(k + 1 - t) * a[((n - k) >> 1) - 1 - p * (k + 2 - t)] % mod)); } for (int p = 1; ((n - k) >> 1) + p * (k + 2 - t) <= n; p++) { cadd(sum, ask(((n - k) >> 1) + p * (k + 2 - t), ((n + k) >> 1) - t + p * (k + 2 - t))); } for (int p = 0; ((n + k) >> 1) + 1 - t + p * (k + 2 - t) <= n; p++) { csub(sum, (int)((long long)(k + 1 - t) * a[((n + k) >> 1) + 1 - t + p * (k + 2 - t)] % mod)); } return sum; }; int ans = 0; for (int i = 1, x = 0, y = 0; i <= n; i++) { if ((n + i) & 1) continue; cadd(ans, x); x = calc(i, 0); cadd(ans, x); y = calc(i, 1); csub(ans, add(y, y)); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }",math,hard 67,"# Problem Statement You are given a row of $n$ towers with heights $a_1, a_2, \dots, a_n$. When looking from the left, you see all towers that are strictly higher than all previous ones. When looking from the right, you see all towers that are strictly higher than all following ones. For a height sequence $h$, let $L(h)$ be the set of heights visible from the left, and $R(h)$ the set of heights visible from the right. Count the number of subsequences $a'$ of $a$ such that: - $L(a') = L(a)$, and - $R(a') = R(a)$. Return the answer modulo $998244353$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: length of the sequence, - `a`: the array of heights, - return: the number of valid subsequences modulo $998244353$. ## Example - Input: ``` n = 9 a = [3, 5, 5, 7, 4, 6, 7, 2, 4] ``` - Output: ``` 51 ``` ## Constraints - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[100, 1000, 5000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, vector &a) { const int MOD = 998244353; if (n == 0) return 0; int m = *max_element(a.begin(), a.end()); vector L; int cur = INT_MIN; for (int i = 0; i < n; i++) { if (a[i] > cur) { L.push_back(a[i]); cur = a[i]; } } int K = (int)L.size(); vector dpL(n, 0); vector c(K + 1, 0), inc(K + 1, 0); c[0] = 1; for (int i = 0; i < n; i++) { fill(inc.begin(), inc.end(), 0); for (int j = K; j >= 1; --j) { if (a[i] == L[j - 1]) { inc[j] = (inc[j] + c[j - 1]) % MOD; } } for (int j = 1; j <= K; ++j) { if (a[i] <= L[j - 1]) { c[j] = int((2LL * c[j]) % MOD); } } for (int j = 1; j <= K; ++j) { c[j] += inc[j]; if (c[j] >= MOD) c[j] -= MOD; } if (a[i] == m) { dpL[i] = c[K - 1]; } } vector R; cur = INT_MIN; for (int i = n - 1; i >= 0; --i) { if (a[i] > cur) { R.push_back(a[i]); cur = a[i]; } } int KR = (int)R.size(); vector dpR(n, 0); vector cR(KR + 1, 0), incR(KR + 1, 0); cR[0] = 1; for (int i = n - 1; i >= 0; --i) { fill(incR.begin(), incR.end(), 0); for (int j = KR; j >= 1; --j) { if (a[i] == R[j - 1]) { incR[j] = (incR[j] + cR[j - 1]) % MOD; } } for (int j = 1; j <= KR; ++j) { if (a[i] <= R[j - 1]) { cR[j] = int((2LL * cR[j]) % MOD); } } for (int j = 1; j <= KR; ++j) { cR[j] += incR[j]; if (cR[j] >= MOD) cR[j] -= MOD; } if (a[i] == m) { dpR[i] = cR[KR - 1]; } } vector p2(n + 1, 1); for (int i = 1; i <= n; i++) p2[i] = int((2LL * p2[i - 1]) % MOD); vector pos; for (int i = 0; i < n; i++) if (a[i] == m) pos.push_back(i); long long ans = 0; int s = (int)pos.size(); for (int u = 0; u < s; ++u) { int i = pos[u]; for (int v = u; v < s; ++v) { int j = pos[v]; int between = j > i ? (j - i - 1) : 0; long long ways = 1LL * dpL[i] * dpR[j] % MOD; ans = (ans + ways * p2[between]) % MOD; } } return int(ans); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,data_structures",hard 68,"# Problem Statement The next lecture in a high school requires two topics to be discussed. The $i$-th topic is interesting by $a_i$ units for the teacher and by $b_i$ units for the students. The pair of topics $i$ and $j$ ($i < j$) is called **good** if $a_i + a_j > b_i + b_j$ (i.e. it is more interesting for the teacher). Your task is to find the number of **good** pairs of topics. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a, vector &b) { // write your code here } }; ``` where: - return: the number of **good** pairs of topics. # Example 1: - Input: n = 5 a = [4, 8, 2, 6, 2] b = [4, 5, 4, 1, 3] - Output: 7 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i], b[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a, vector &b) { for (int i = 0; i < n; i++) a[i] -= b[i]; sort(a.begin(), a.end()); long long ans = 0; for (int i = 0, j = n; i < n; i++) { while (j > 0 && a[i] + a[j - 1] > 0) j--; ans += n - max(i + 1, j); } return ans; } long long solve2(int &n, vector &a, vector &b) { long long ans = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { long long ta = (long long)a[i] + (long long)a[j]; long long tb = (long long)b[i] + (long long)b[j]; if (ta > tb) ans++; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; // solve Solution solution; auto result = solution.solve(n, a, b); // output cout << result << ""\n""; return 0; }","two_pointers,sort",easy 69,"# Problem Statement Initially, array $a$ contains just the number $1$. You can perform several operations in order to change the array. In an operation, you can select some subsequence$^{\dagger}$ of $a$ and add into $a$ an element equal to the sum of all elements of the subsequence. You are given a final array $c$. Check if $c$ can be obtained from the initial array $a$ by performing some number (possibly 0) of operations on the initial array. $^{\dagger}$ A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly zero, but not all) elements. In other words, select $k$ ($1 \leq k \leq |a|$) distinct indices $i_1, i_2, \dots, i_k$ and insert anywhere into $a$ a new element with the value equal to $a_{i_1} + a_{i_2} + \dots + a_{i_k}$. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, vector &c) { // write your code here } }; ``` where: - return: ""YES"" if such a sequence of operations exists, and ""NO"" otherwise. # Example 1: - Input: n = 1 c = [1] - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq c[i] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &c) { sort(c.begin(), c.end()); long long s = 0; for (int i = 0; i < n; i++) { if (s + (i == 0) < c[i]) return ""NO""; s += c[i]; } return ""YES""; } string solve2(int &n, vector &c) { for (int i = 0; i < n; ++i) { int minIdx = i; for (int j = i + 1; j < n; ++j) if (c[j] < c[minIdx]) minIdx = j; if (minIdx != i) { int tmp = c[i]; c[i] = c[minIdx]; c[minIdx] = tmp; } } long long s = 0; for (int i = 0; i < n; i++) { long long add = (i == 0 ? 1 : 0); if (s + add < c[i]) return ""NO""; s += c[i]; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","sort,two_pointers",medium 70,"Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order. A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. solution main function ```cpp class Solution { public: vector solve(vector>& matrix) { } }; ``` Example 1: Input: matrix = [[3,7,8],[9,11,13],[15,16,17]] Output: [15] Example 2: Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]] Output: [12] Constraints: m == matrix.length n == matrix[i].length 1 <= n, m <= @data 1 <= matrix[i][j] <= 10^5. All elements in the matrix are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 500]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector>& matrix) { int N = matrix.size(), M = matrix[0].size(); int rMinMax = INT_MIN; for (int i = 0; i < N; i++) { int rMin = INT_MAX; for (int j = 0; j < M; j++) { rMin = min(rMin, matrix[i][j]); } rMinMax = max(rMinMax, rMin); } int cMaxMin = INT_MAX; for (int i = 0; i < M; i++) { int cMax = INT_MIN; for (int j = 0; j < N; j++) { cMax = max(cMax, matrix[j][i]); } cMaxMin = min(cMaxMin, cMax); } if (rMinMax == cMaxMin) { return {rMinMax}; } return {}; } vector solve2(vector>& matrix) { int n = matrix.size(); int m = matrix[0].size(); vector res; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { int v = matrix[i][j]; bool rowMin = true; for (int k = 0; k < m; ++k) { if (matrix[i][k] < v) { rowMin = false; break; } } if (!rowMin) continue; bool colMax = true; for (int k = 0; k < n; ++k) { if (matrix[k][j] > v) { colMax = false; break; } } if (colMax) res.push_back(v); } } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input vector > s; int n,m; cin>>n>>m; for(int i=1;i<=n;i++) { vector temp; for(int j=1,x;j<=m;j++) { scanf(""%d"",&x); temp.push_back(x); } s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output sort(result.begin(),result.end()); for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return YES if there are at least two ways to partition a, and NO otherwise. # Example 1: - Input: n = 4 a = [2, 3, 5, 7] - Output: YES # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { for (int i = 1; i < n; i++) { int x = a[i - 1]; int y = a[i]; if (x > y) { swap(x, y); } if (2 * x > y) { return ""YES""; } } return ""NO""; } string solve2(int &n, vector &a) { for (int l = 0; l < n; l++) { int cur_min = a[l]; int cur_max = a[l]; for (int r = l + 1; r < n; r++) { int v = a[r]; if (v < cur_min) cur_min = v; if (v > cur_max) cur_max = v; if ((long long)cur_min * 2 > (long long)cur_max) return ""YES""; } } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,greedy,math",hard 72,"Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. solution main function ```cpp class Solution { public: vector solve(vector& arr1, vector& arr2) { } }; ``` Example 1: Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19] Example 2: Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] Output: [22,28,8,6,17,44] Constraints: 1 <= arr1.length, arr2.length <= @data 0 <= arr1[i], arr2[i] <= @data All the elements of arr2 are distinct. Each arr2[i] is in arr1. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve(vector& arr1, vector& arr2) { int maxElement = *max_element(arr1.begin(), arr1.end()); vector count(maxElement + 1); for (int element : arr1) { count[element]++; } vector result; for (int element : arr2) { while (count[element] > 0) { result.push_back(element); count[element]--; } } for (int num = 0; num <= maxElement; num++) { while (count[num] > 0) { result.push_back(num); count[num]--; } } return result; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector a,b; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } for(int i=1;i<=m;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output // cout << result << ""\n""; for(auto it:result) cout< solve(vector& arr, int k) { } }; ``` Example 1: Input: arr = [1,2,3,5], k = 3 Output: [2,5] Example 2: Input: arr = [1,7], k = 1 Output: [1,7] Constraints: 2 <= arr.length <= @data 1 <= arr[i] <= 2*10^6 arr[0] == 1 arr[i] is a prime number for i > 0. All the numbers of arr are unique and sorted in strictly increasing order. 1 <= k <= arr.length * (arr.length - 1) / 2 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 1000, 50000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve(vector& arr, int k) { int n = arr.size(); double left = 0.0, right = 1.0; while (true) { double mid = (left + right) / 2; int i = -1, count = 0; int x = 0, y = 1; for (int j = 1; j < n; ++j) { while ((double)arr[i + 1] / arr[j] < mid) { ++i; if ((long long)arr[i] * y > (long long)arr[j] * x) { x = arr[i]; y = arr[j]; } } count += i + 1; } if (count == k) { return {x, y}; } if (count < k) { left = mid; } else { right = mid; } } } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n, k; cin >> n >> k; vector num; for (int i = 1; i <= n; i++) { int x; cin >> x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num, k); // output for (size_t i = 0; i < result.size(); i++) { if (i) cout << ' '; cout << result[i]; } return 0; } ",two_pointers,hard 74,"# Problem Statement The girl named Masha was walking in the forest and found a complete binary tree of height $n$ and a permutation $p$ of length $m=2^n$. A complete binary tree of height $n$ is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is $n$. The picture below shows the complete binary tree for $n=2$. A permutation is an array consisting of $n$ different integers from $1$ to $n$. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not ($2$ occurs twice), and $[1,3,4]$ is also not a permutation ($n=3$, but there is $4$ in the array). Let's enumerate $m$ leaves of this tree from left to right. The leaf with the number $i$ contains the value $p_i$ ($1 \le i \le m$). Masha considers a tree beautiful if the values in its leaves are ordered from left to right in increasing order. In one operation, Masha can choose any non-leaf vertex of the tree and swap its left and right sons (along with their subtrees). Help Masha understand if she can make a tree beautiful in a certain number of operations. If she can, then output the minimum number of operations to make the tree beautiful. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &m, vector &p) { // write your code here } }; ``` where: - return the minimum possible number of operations for which Masha will be able to make the tree beautiful, or -1 if this is not possible. # Example 1: - Input: m = 8 p = [6, 5, 7, 8, 4, 3, 1, 2] - Output: 4 # Constraints: - $1 \leq m \leq @data$ - $m$ is a power of $2$ - $1 \leq p[i] \leq m$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 131072]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int ans = 0; for (int len = 2; len <= n; len *= 2) { for (int i = 0; i < n; i += len) { if (a[i] > a[i + len / 2]) { ans++; for (int j = 0; j < len / 2; j++) swap(a[i + j], a[i + len / 2 + j]); } } } for (int i = 0; i < n; i++) { if (a[i] != i + 1) ans = -1; } return ans; } int solve2(int &n, vector &a) { int ans = 0; for (int len = 2; len <= n; len <<= 1) { int half = len >> 1; for (int i = 0; i < n; i += len) { int minL = INT_MAX, maxL = INT_MIN; for (int j = i; j < i + half; ++j) { int v = a[j]; if (v < minL) minL = v; if (v > maxL) maxL = v; } int minR = INT_MAX, maxR = INT_MIN; for (int j = i + half; j < i + len; ++j) { int v = a[j]; if (v < minR) minR = v; if (v > maxR) maxR = v; } if (maxL < minR) { continue; } else if (maxR < minL) { ++ans; for (int j = 0; j < half; ++j) { int t = a[i + j]; a[i + j] = a[i + half + j]; a[i + half + j] = t; } } else { return -1; } } } for (int i = 0; i < n; ++i) { if (a[i] != i + 1) return -1; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int m; cin >> m; vector p(m); for (int i = 0; i < m; i++) cin >> p[i]; // solve Solution solution; auto result = solution.solve(m, p); // output cout << result << ""\n""; return 0; }","search,graph,tree,sort",hard 75,"You are given an integer array nums of size n where n is a multiple of 3 and a positive integer k. In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum. Rick stated that magnetic force between two different balls at positions x and y is |x - y|. Given the integer array position and the integer m. Return the required force. solution main function ```cpp class Solution { public: int solve(vector& position, int m) { } }; ``` Example 1: Input: position = [1,2,3,4,7], m = 3 Output: 3 Example 2: Input: position = [5,4,3,2,1,1000000000], m = 2 Output: 999999999 Constraints: n == position.length 2 <= n <= @data 1 <= position[i] <= 10^9 All integers in position are distinct. 2 <= m <= position.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[2000, 1000, 100], [16000, 8000, 800], [128000, 64000, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool canPlaceBalls(int x, vector &position, int m) { int prevBallPos = position[0]; int ballsPlaced = 1; for (int i = 1; i < position.size() && ballsPlaced < m; ++i) { int currPos = position[i]; if (currPos - prevBallPos >= x) { ballsPlaced += 1; prevBallPos = currPos; } } return ballsPlaced == m; } int solve(vector &position, int m) { int answer = 0; int n = position.size(); sort(position.begin(), position.end()); int low = 1; int high = ceil(position[n - 1] / (m - 1.0)); while (low <= high) { int mid = low + (high - low) / 2; if (canPlaceBalls(mid, position, m)) { answer = mid; low = mid + 1; } else { high = mid - 1; } } return answer; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector num; for(int i=1;i<=n;i++) { int x;scanf(""%d"",&x); num.push_back(x); } // solve Solution solution; auto result = solution.solve(num,m); // output cout << result << ""\n""; // for(auto it:result) cout< &a, string &s) { // write your code here } }; ``` where: - `a`: contains $n-1$ integers, $a_i$ is the parent of the vertex with the number $i$ for all $i = 2, \dots, n$. - `s`: 'B' or 'W' denoting the color of each vertex. - return: the number of balanced subtrees. # Example 1: - Input: n = 7 a = [1, 1, 2, 3, 3, 5] s = ""WBBWWBW"" - Output: 2 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] < i$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 160, 80], [6400, 1280, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a, string &s) { vector b(n); for (int i = 0; i < n - 1; i++) a[i]--; for (int i = 0; i < n; i++) { b[i] = (s[i] == 'W' ? 1 : -1); } for (int i = n - 2; i >= 0; i--) { b[a[i]] += b[i + 1]; } return count(b.begin(), b.end(), 0); } int solve2(int &n, vector &a, string &s) { int ans = 0; for (int u = 1; u <= n; ++u) { int sum = 0; for (int v = 1; v <= n; ++v) { int x = v; while (x != u && x != 1) { x = a[x - 2]; } if (x == u) { sum += (s[v - 1] == 'W' ? 1 : -1); } } if (sum == 0) ++ans; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n - 1); for (int i = 0; i < n - 1; i++) { cin >> a[i]; } string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, a, s); // output cout << result << ""\n""; return 0; }","search,dp,graph,tree",hard 77,"You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [3,2,4,6] Output: 7 Example 2: Input: nums = [1,2,3,9,2] Output: 11 Constraints: 1 <= nums.length <= @data 0 <= nums[i] <= 10^8 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int res=0; int n=nums.size(); for(int i=0;i& nums) { int res = 0; int n = (int)nums.size(); for (int b = 0; b < 31; ++b) { int mask = 1 << b; for (int i = 0; i < n; ++i) { if (nums[i] & mask) { res |= mask; break; } } } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< solve(int &n, vector &a, int &q, vector &b) { // write your code here } }; ``` where: - `n`: the size of the array - `a`: the array of non-negative integers - `q`: number of scenarios - `b`: for each scenario, the max number of allowed operations - return: an array of size `q`, the answer for each scenario # Example 1: - Input: ``` n = 2, q = 2 a = [1, 3] b = [0, 3] ``` - Output: ``` 2 3 ``` # Constraints: - $1 \leq n \leq @data$ - $0 \leq a[i] \leq 10^9$ - $1 \leq q \leq @data$ - $0 \leq b_i \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 400, 200], [6400, 3200, 1600]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &n, vector &a, int &q, vector &b) { const int MAX_BIT = 31; int ora = 0; for (int i = 0; i < n; i++) ora |= a[i]; int base = __builtin_popcount((unsigned)ora); vector costs; costs.reserve(MAX_BIT + 1); costs.push_back(0); vector ta(a.begin(), a.end()); long long cost = 0; int x = ora; for (int i = 0; i <= 30; i++) { if (~x >> i & 1) { x |= 1 << i; for (int j = i; j >= 0; j--) { int nv = 0; for (int k = 0; k < n; k++) nv |= (int)ta[k]; if ((nv >> j) & 1) continue; int mask = (1 << j) - 1; int t = -1; for (int k = 0; k < n; k++) { if (t == -1 || ((int)ta[k] & mask) > ((int)ta[t] & mask)) t = k; } long long delta = (1LL << j) - ((long long)ta[t] & mask); cost += delta; ta[t] += delta; } costs.push_back(cost); } } vector ans(q); for (int i = 0; i < q; i++) { long long bi = b[i]; int t = int(upper_bound(costs.begin(), costs.end(), bi) - costs.begin()) - 1; if (t < 0) t = 0; ans[i] = base + t; } return ans; } vector solve2(int &n, vector &a, int &q, vector &b) { const int MAX_BIT = 31; int ora = 0; for (int i = 0; i < n; i++) ora |= a[i]; int base = __builtin_popcount((unsigned)ora); vector costs; costs.reserve(MAX_BIT + 1); costs.push_back(0); vector ta(n); for (int i = 0; i < n; i++) ta[i] = a[i]; long long cost = 0; for (int j = 0; j <= 30; j++) { int nv = 0; for (int k = 0; k < n; k++) nv |= (int)ta[k]; if ((nv >> j) & 1) continue; long long mask = (1LL << j) - 1; int t = 0; for (int k = 1; k < n; k++) { if ((ta[k] & mask) > (ta[t] & mask)) t = k; } long long delta = (1LL << j) - (ta[t] & mask); cost += delta; ta[t] += delta; costs.push_back(cost); } vector ans(q); for (int i = 0; i < q; i++) { long long bi = b[i]; int t = int(upper_bound(costs.begin(), costs.end(), bi) - costs.begin()) - 1; if (t < 0) t = 0; ans[i] = base + t; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, q; cin >> n >> q; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector b(q); for (int i = 0; i < q; i++) cin >> b[i]; // solve Solution solution; auto result = solution.solve(n, a, q, b); // output for (int i = 0; i < (int)result.size(); i++) cout << result[i] << ""\n""; return 0; }","greedy,math",hard 79,"# Problem Statement There is an initially empty sheet with `n` rows and `m` columns. You perform painting operations, each time choosing either any row or any column and painting all its cells in a color. In the first operation, cells are painted with color `1`. For operation `i > 1`, you may choose color `c_{i-1}` or `c_{i-1} + 1`, where `c_{i-1}` is the color chosen at operation `i-1`. We call the final coloring beautiful if: - every cell is colored; - for each color from `1` to `k`, there is at least one cell of that color, and no other colors are used. For a beautiful coloring, define its value as the minimum number of operations to obtain it. For each `i` from `min(n, m)` to `n + m - 1`, compute the number of beautiful colorings with value `i`, modulo `998244353`. The main function of the solution is defined as: ```cpp class Solution { public: vector solve(int &n, int &m, int &k) { // write your code here } }; ``` where: - `n`: number of rows - `m`: number of columns - `k`: number of colors used (exactly colors `1..k`) - return: an array `ans` of length `n + m`, where for each `i` in `[min(n,m), n+m-1]`, `ans[i]` equals the number of beautiful colorings with value `i` modulo `998244353` (positions outside the range may be `0`). Example: Input: n = 2, m = 2, k = 2 Output: 4 4 Explanation: The answers for values 2 and 3 are both 4. # Constraints: - $2 \le n, m \le @data$ - $1 \le k \le n + m - 1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 1000, 2000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 128]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: static const int MOD = 998244353; static int add_mod(int a, int b) { int s = a + b; if (s >= MOD) s -= MOD; if (s < 0) s += MOD; return s; } static int mul_mod(long long a, long long b) { return int((a * b) % MOD); } static int pow_mod(int a, long long e) { long long r = 1, x = a; while (e) { if (e & 1) r = (r * x) % MOD; x = (x * x) % MOD; e >>= 1; } return int(r); } static int inv_mod(int a) { return pow_mod(a, MOD - 2); } static int C(int n, int r) { if (r < 0 || r > n) return 0; int k = min(r, n - r); long long res = 1; for (int i = 1; i <= k; i++) { res = (res * (n - k + i)) % MOD; res = (res * inv_mod(i)) % MOD; } return int(res); } static int f_t(int t, int colors) { if (colors < 0) return 0; if (t < colors) return 0; int s = 0; int comb = 1; for (int j = 0; j <= colors; j++) { int base = colors - j; int pw = pow_mod(base, t); int term = mul_mod(comb, pw); if (j & 1) term = (MOD - term) % MOD; s = add_mod(s, term); if (j < colors) { int num = colors - j; int den = j + 1; comb = mul_mod(comb, num); comb = mul_mod(comb, inv_mod(den)); } } return s; } vector solve1(int &n, int &m, int &k) { const int NM = n + m; vector fact(NM + 1), ifact(NM + 1); fact[0] = 1; for (int i = 1; i <= NM; i++) fact[i] = mul_mod(fact[i - 1], i); ifact[NM] = pow_mod(fact[NM], MOD - 2); for (int i = NM; i >= 1; i--) ifact[i - 1] = mul_mod(ifact[i], i); auto C = [&](int nn, int rr) -> int { if (rr < 0 || rr > nn) return 0; return mul_mod(fact[nn], mul_mod(ifact[rr], ifact[nn - rr])); }; vector f(NM, 0); int colors = k - 1; if (colors >= 0) { for (int j = 0; j <= colors; j++) { int base = colors - j; int coeff = C(colors, j); if (j & 1) coeff = (MOD - coeff) % MOD; int p = 1; for (int t = 0; t < NM; t++) { if (t >= colors) { f[t] = add_mod(f[t], mul_mod(coeff, p)); } p = mul_mod(p, base); } } } vector ans(NM, 0); for (int a = 0; a <= n - 1; a++) { int cn = C(n, a); for (int b = 0; b <= m - 1; b++) { int cm = C(m, b); int t = a + b; int idx = t + min(n - a, m - b); int waysAssign = f[t]; if (waysAssign == 0) continue; ans[idx] = add_mod(ans[idx], mul_mod(waysAssign, mul_mod(cn, cm))); } } return ans; } vector solve2(int &n, int &m, int &k) { const int NM = n + m; vector ans(NM, 0); int colors = k - 1; for (int a = 0; a <= n - 1; a++) { int cn = C(n, a); for (int b = 0; b <= m - 1; b++) { int cm = C(m, b); int t = a + b; int idx = t + min(n - a, m - b); int waysAssign = f_t(t, colors); if (waysAssign == 0) continue; ans[idx] = add_mod(ans[idx], mul_mod(waysAssign, mul_mod(cn, cm))); } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m, k; cin >> n >> m >> k; // solve Solution solution; auto result = solution.solve(n, m, k); // output int L = min(n, m); for (int i = L; i <= n + m - 1; i++) cout << result[i] << "" \n""[i == n + m - 1]; return 0; }","math,dp",hard 80,"Given a list of 24-hour clock points in the format ""HH:MM"", return the minimum minute difference between any two points in the list. solution main function ```cpp class Solution { public: int solve(vector& timePoints) { } }; ``` Example 1: Input: timePoints = [""23:59"",""00:00""] Output: 1 Example 2: Input: timePoints = [""00:00"",""23:59"",""00:00""] Output: 0 Constraints: 2 <= timePoints.length <= @data timePoints[i] is in the format ""HH:MM"" Time limit: @time_limit ms Memory limit: @memory_limit KB","[20, 100, 100000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& timePoints) { vector minutes(24 * 60, false); for (string time : timePoints) { int h = stoi(time.substr(0, 2)); int m = stoi(time.substr(3)); int min = h * 60 + m; if (minutes[min]) return 0; minutes[min] = true; } int prevIndex = INT_MAX; int firstIndex = INT_MAX; int lastIndex = INT_MAX; int ans = INT_MAX; for (int i = 0; i < 24 * 60; i++) { if (minutes[i]) { if (prevIndex != INT_MAX) { ans = min(ans, i - prevIndex); } prevIndex = i; if (firstIndex == INT_MAX) { firstIndex = i; } lastIndex = i; } } return min(ans, 24 * 60 - lastIndex + firstIndex); } int solve2(vector& timePoints) { int n = (int)timePoints.size(); if (n > 1440) return 0; int ans = INT_MAX; for (int i = 0; i < n; ++i) { const string& a = timePoints[i]; int h1 = (a[0]-'0')*10 + (a[1]-'0'); int m1 = (a[3]-'0')*10 + (a[4]-'0'); int t1 = h1*60 + m1; for (int j = i + 1; j < n; ++j) { const string& b = timePoints[j]; int h2 = (b[0]-'0')*10 + (b[1]-'0'); int m2 = (b[3]-'0')*10 + (b[4]-'0'); int t2 = h2*60 + m2; int diff = t1 - t2; if (diff < 0) diff = -diff; int wrap = 1440 - diff; int cur = diff < wrap ? diff : wrap; if (cur < ans) ans = cur; if (ans == 0) return 0; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< string > a; for(int i=1;i<=n;i++) { string x; cin>>x; a.push_back(x); } // solve Solution solution; int result = solution.solve(a); // output cout << result << ""\n""; return 0; }","math,sort,string",easy 81,"# Problem Statement You are at a marketplace with two traders, each represented by a permutation over the same set of $n$ items. Let those permutations be $p$ and $s$. If you hold item $i$, you may trade it for item $j$ if either $p_i > p_j$ (using the first trader) or $s_i > s_j$ (using the second trader). We say item $i$ is at least as valuable as item $j$ if starting with item $i$ you can perform some (possibly zero) trades and obtain item $j$. At any time, you have exactly one item. Assume traders have infinite supply of each item. There will be $q$ updates; each update swaps two positions in one of the permutations. After every update, output the number of ordered pairs $(i,j)$ ($1 \le i,j \le n$) such that item $i$ is at least as valuable as item $j$. The main function of the solution is defined as: ```cpp class Solution { public: vector solve(int &n, int &q, vector &p, vector &s, vector> &ops) { // write your code here } }; ``` where: - `n`: number of items - `q`: number of updates - `p`, `s`: permutations of `[1..n]` - `ops`: `q` updates `(tp, i, j)` where `tp=1` swaps `p[i], p[j]` and `tp=2` swaps `s[i], s[j]` - return: an array of length `q`, the k-th value is the answer after the first k updates # Example - Input: - n = 3, q = 3 - p = [1, 2, 3] - s = [3, 2, 1] - ops = [(2, 1, 3), (2, 1, 3), (1, 1, 2)] - Output: - [6, 9, 9] # Constraints: - $2 \le n \le @data$ - $1 \le q \le @data$ - `p`, `s` are permutations of `[1..n]` - each update has `i \ne j` - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",2000,"[[1000, 500, 250], [8000, 4000, 2000], [64000, 32000, 16000]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { struct Tag { int add = 0; void apply(const Tag &t) { add += t.add; } }; struct Info { int min = INT_MAX; int l = -1; int r = -1; long long ans = 0; void apply(const Tag &t) { min += t.add; } friend Info operator+(const Info &L, const Info &R) { if (L.min < R.min) { return L; } if (L.min > R.min) { return R; } Info x; x.min = L.min; x.l = L.l; x.r = R.r; x.ans = L.ans + R.ans + 1LL * (R.l - L.r) * (R.l - L.r - 1) / 2; return x; } }; template struct LazySegmentTree { int n; std::vector info; std::vector tag; LazySegmentTree() : n(0) {} LazySegmentTree(int n_, InfoT v_ = InfoT()) { init(n_, v_); } template LazySegmentTree(std::vector init_) { init(init_); } void init(int n_, InfoT v_ = InfoT()) { init(std::vector(n_, v_)); } template void init(std::vector init_) { n = init_.size(); info.assign(4 << std::__lg(max(1, n)), InfoT()); tag.assign(4 << std::__lg(max(1, n)), TagT()); std::function build = [&](int p, int l, int r) { if (r - l == 1) { info[p] = init_[l]; return; } int m = (l + r) / 2; build(2 * p, l, m); build(2 * p + 1, m, r); pull(p); }; build(1, 0, n); } void pull(int p) { info[p] = info[2 * p] + info[2 * p + 1]; } void apply(int p, const TagT &v) { info[p].apply(v); tag[p].apply(v); } void push(int p) { apply(2 * p, tag[p]); apply(2 * p + 1, tag[p]); tag[p] = TagT(); } void modify(int p, int l, int r, int x, const InfoT &v) { if (r - l == 1) { info[p] = v; return; } int m = (l + r) / 2; push(p); if (x < m) { modify(2 * p, l, m, x, v); } else { modify(2 * p + 1, m, r, x, v); } pull(p); } void modify(int p, const InfoT &v) { modify(1, 0, n, p, v); } InfoT rangeQuery(int p, int l, int r, int x, int y) { if (l >= y || r <= x) { return InfoT(); } if (l >= x && r <= y) { return info[p]; } int m = (l + r) / 2; push(p); return rangeQuery(2 * p, l, m, x, y) + rangeQuery(2 * p + 1, m, r, x, y); } InfoT rangeQuery(int l, int r) { return rangeQuery(1, 0, n, l, r); } void rangeApply(int p, int l, int r, int x, int y, const TagT &v) { if (l >= y || r <= x) { return; } if (l >= x && r <= y) { apply(p, v); return; } int m = (l + r) / 2; push(p); rangeApply(2 * p, l, m, x, y, v); rangeApply(2 * p + 1, m, r, x, y, v); pull(p); } void rangeApply(int l, int r, const TagT &v) { return rangeApply(1, 0, n, l, r, v); } }; public: vector solve1(int &n, int &q, vector &p, vector &s, vector> &ops) { for (int i = 0; i < n; i++) { p[i]--; s[i]--; } std::vector ip(n), is(n); for (int i = 0; i < n; i++) { ip[p[i]] = i; is[s[i]] = i; } LazySegmentTree seg; std::vector init(n + 1); for (int i = 0; i <= n; i++) init[i] = Info{0, i, i, 0}; seg.init(init); std::vector vis(n, 0); auto add = [&](int x, int t = 1) { vis[x] = (t == 1); if (s[x]) { int y = is[s[x] - 1]; if (vis[y] && p[x] < p[y]) { seg.rangeApply(p[x] + 1, p[y] + 1, {t}); } } if (s[x] + 1 < n) { int y = is[s[x] + 1]; if (vis[y] && p[y] < p[x]) { seg.rangeApply(p[y] + 1, p[x] + 1, {t}); } } }; for (int i = 0; i < n; i++) { add(i); } vector out; out.reserve(q); for (int i = 0; i < q; i++) { int t, x, y; t = ops[i][0]; x = ops[i][1] - 1; y = ops[i][2] - 1; add(x, -1); add(y, -1); if (t == 1) { std::swap(p[x], p[y]); std::swap(ip[p[x]], ip[p[y]]); } else { std::swap(s[x], s[y]); std::swap(is[s[x]], is[s[y]]); } add(x, 1); add(y, 1); out.push_back(1LL * n * (n + 1) / 2 + seg.rangeQuery(0, n + 1).ans); } return out; } vector solve2(int &n, int &q, vector &p, vector &s, vector> &ops) { vector out; out.reserve(q); for (int tcase = 0; tcase < q; tcase++) { int tp = ops[tcase][0]; int x = ops[tcase][1] - 1; int y = ops[tcase][2] - 1; if (tp == 1) { int tmp = p[x]; p[x] = p[y]; p[y] = tmp; } else { int tmp = s[x]; s[x] = s[y]; s[y] = tmp; } long long total = 0; for (int i = 0; i < n; i++) { int Pmax = p[i]; int Smax = s[i]; int cnt = 0; if (p[i] <= n) { p[i] += n; cnt++; } bool changed = true; while (changed) { changed = false; for (int v = 0; v < n; v++) { if (p[v] <= n) { if (p[v] < Pmax || s[v] < Smax) { int opv = p[v]; int osv = s[v]; p[v] = opv + n; if (opv > Pmax) Pmax = opv; if (osv > Smax) Smax = osv; cnt++; changed = true; } } } } total += cnt; for (int v = 0; v < n; v++) { if (p[v] > n) p[v] -= n; } } out.push_back(total); } return out; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, q; cin >> n >> q; vector p(n), s(n); for (int i = 0; i < n; i++) cin >> p[i]; for (int i = 0; i < n; i++) cin >> s[i]; vector> ops(q); for (int i = 0; i < q; i++) { int tp, x, y; cin >> tp >> x >> y; ops[i] = {tp, x, y}; } // solve Solution solution; auto result = solution.solve(n, q, p, s, ops); // output for (size_t i = 0; i < result.size(); i++) cout << result[i] << ""\n""; return 0; }","data_structures,graph",hard 82,"You are given an integer array nums and an integer k. Select exactly k elements from nums such that their sum is as large as possible. Return the selected values as an integer array of length k. The returned order does not matter; the runner compares the selected values after sorting them. solution main function ```cpp class Solution { public: vector solve(vector& nums, int k) { } }; ``` Example 1: Input: nums = [2,1,3,3], k = 2 Output: [3,3] Example 2: Input: nums = [-1,-2,3,4], k = 3 Output: [-1,3,4] Constraints: 1 <= nums.length <= @data -10^5 <= nums[i] <= 10^5 1 <= k <= nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector& nums, int k) { int n = nums.size(), i = 0, t = k; vector ans; while(t>0){ ans.push_back(nums[i]); i++; t--; } for(int j=i;j solve2(vector& nums, int k) { int n = (int)nums.size(); vector ans; ans.reserve(k); for (int t = 0; t < k; ++t) { int idx = -1; int mx = numeric_limits::min(); for (int i = 0; i < n; ++i) { if (nums[i] > mx) { mx = nums[i]; idx = i; } } if (idx >= 0) { ans.push_back(nums[idx]); nums[idx] = numeric_limits::min(); } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k;cin>>n>>k; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,k); // output sort(result.begin(),result.end()); for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int steps, int arrLen) { int MOD = 1e9 + 7; arrLen = min(arrLen, steps); vector dp(arrLen, 0); vector prevDp(arrLen, 0); prevDp[0] = 1; for (int remain = 1; remain <= steps; remain++) { fill(dp.begin(),dp.end(),0); for (int curr = arrLen - 1; curr >= 0; curr--) { int ans = prevDp[curr]; if (curr > 0) { ans = (ans + prevDp[curr - 1]) % MOD; } if (curr < arrLen - 1) { ans = (ans + prevDp[curr + 1]) % MOD; } dp[curr] = ans; } prevDp = dp; } return dp[0]; } int solve2(int steps, int arrLen) { const int MOD = 1000000007; if (steps <= 0) return 1; if (arrLen <= 0) return 0; arrLen = min(arrLen, steps); unsigned __int128 t = 0; long long ans = 0; while (true) { unsigned __int128 r = t; int pos = 0; bool ok = true; bool isLast = true; for (int i = 0; i < steps; ++i) { unsigned int move = (unsigned int)(r % 3); r /= 3; if (move != 2) isLast = false; if (move == 0) { } else if (move == 1) { if (pos == 0) { ok = false; break; } --pos; } else { if (pos == arrLen - 1) { ok = false; break; } ++pos; } } if (ok && pos == 0) { ans += 1; if (ans >= MOD) ans -= MOD; } if (isLast) break; ++t; } return (int)(ans % MOD); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; // solve Solution solution; auto result = solution.solve(n,m); // output cout << result << ""\n""; return 0; }",dp,medium 84,"Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique. Return the result in ascending order. solution main function ```cpp class Solution { public: vector solve(vector& nums1, vector& nums2) { } }; ``` Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Constraints: 1 <= nums1.length, nums2.length <= @data 0 <= nums1[i], nums2[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve(vector& nums1, vector& nums2) { vector result; int n = nums1.size(); int m = nums2.size(); sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (nums1[i] == nums2[j]) { if (find(result.begin(), result.end(), nums1[i]) == result.end()) { result.push_back(nums1[i]); } break; } } } return result; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector a,b; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } for(int i=1;i<=m;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output // cout << result << ""\n""; for(auto it:result) cout<& words) { } }; ``` Example 1: Input: words = [""a"",""aba"",""ababa"",""aa""] Output: 4 Example 2: Input: words = [""pa"",""papa"",""ma"",""mama""] Output: 2 Constraints: 1 <= words.length <= @data 1 <= words[i].length <= @data words[i] consists only of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 50, 100]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& words) { int n = words.size(); int count = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { string& str1 = words[i]; string& str2 = words[j]; if (str1.size() > str2.size()) continue; if (str2.find(str1) == 0 && str2.rfind(str1) == str2.size() - str1.size()) { ++count; } } } return count; } int solve2(vector& words) { long long count = 0; int n = (int)words.size(); for (int i = 0; i < n; ++i) { const string& str1 = words[i]; size_t l1 = str1.size(); for (int j = i + 1; j < n; ++j) { const string& str2 = words[j]; size_t l2 = str2.size(); if (l1 > l2) continue; bool isPrefix = true; for (size_t k = 0; k < l1; ++k) { if (str1[k] != str2[k]) { isPrefix = false; break; } } if (!isPrefix) continue; bool isSuffix = true; size_t start = l2 - l1; for (size_t k = 0; k < l1; ++k) { if (str1[k] != str2[start + k]) { isSuffix = false; break; } } if (isSuffix) ++count; } } return (int)count; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector str; cin>>n; for(int i=1;i<=n;i++) { string s; cin>>s; str.push_back(s); } // solve Solution solution; auto result = solution.solve(str); // output cout<& arr) { } }; ``` Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Example 2: Input: arr = [1,1] Output: 1 Constraints: 1 <= arr.length <= @data 0 <= arr[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& arr) { int n = arr.size(); vector candidates = {arr[n / 4], arr[n / 2], arr[3 * n / 4]}; int target = n / 4; for (int candidate : candidates) { int left = lower_bound(arr.begin(), arr.end(), candidate) - arr.begin(); int right = upper_bound(arr.begin(), arr.end(), candidate) - arr.begin() - 1; if (right - left + 1 > target) { return candidate; } } return -1; } int solve2(vector& arr) { long long n = (long long)arr.size(); if (n == 0) return -1; long long threshold = n / 4; long long count = 0; int prev = 0; bool hasPrev = false; for (long long i = 0; i < n; ++i) { int x = arr[i]; if (!hasPrev || x != prev) { prev = x; count = 1; hasPrev = true; } else { ++count; } if (count > threshold) { return x; } } return -1; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< int > a; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } // solve Solution solution; auto result = solution.solve(a); // output cout << result << ""\n""; return 0; }",math,easy 87,"# Problem Statement: Given an array $a$ of $n$ elements, return the minimum value that appears at least three times, or return -1 if there is no such value. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` Where: - return the minimum value that appears at least three times, or -1 if there is no such value. # Example 1: - Input: n = 5 a = [1, 2, 3, 2, 2] - Output: 2 # Constraints: - $0 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int cnt = 1; for (int i = 1; i < n; i++) { if(a[i]==a[i-1])cnt++; else cnt = 1; if(cnt==3)return a[i]; } return -1; } int solve2(int &n, vector &a) { if (n <= 0) return -1; for (int val = 1; val <= n; ++val) { int cnt = 0; for (int i = 0; i < n; ++i) { if (a[i] == val) { ++cnt; if (cnt == 3) return val; } } } return -1; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","sort,greedy",easy 88,"Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j]. If there is no way to make arr1 strictly increasing, return -1. solution main function ```cpp class Solution { public: int solve(vector& arr1, vector& arr2) { } }; ``` Example 1: Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] Output: 1 Example 2: Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] Output: 2 Constraints: 1 <= arr1.length, arr2.length <= @data 0 <= arr1[i], arr2[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 600]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& arr1, vector& arr2) { arr1.insert(arr1.begin(),-1); arr1.push_back(2e9); sort(arr2.begin(), arr2.end()); arr2.erase(unique(arr2.begin(), arr2.end()), arr2.end()); int n = arr1.size(); vector dp(n, 1e9); dp[0] = 0; int m = arr2.size(); for (int i = 1; i < n; i++) { if (arr1[i] > arr1[i - 1]) dp[i] = dp[i - 1]; for (int j = 0; j < i; j++) { int idx = lower_bound(arr2.begin(), arr2.end(), arr1[j] + 1) - arr2.begin(); int cnt = i - j - 1; if (idx + cnt <= m && idx + cnt > 0 && arr2[idx + cnt - 1] < arr1[i]&&arr1[i]>arr1[j]) { dp[i] = min(dp[j] + cnt, dp[i]); } } } if (dp[n - 1] == 1e9) return -1; else return dp[n - 1]; } int solve2(vector& arr1, vector& arr2) { int n = (int)arr1.size(); if (n <= 1) return 0; bool inc = true; for (int i = 1; i < n; ++i) if (!(arr1[i] > arr1[i-1])) { inc = false; break; } if (inc) return 0; sort(arr2.begin(), arr2.end()); int m = (int)arr2.size(); int w = 0; for (int i = 0; i < m; ++i) { if (i == 0 || arr2[i] != arr2[i-1]) arr2[w++] = arr2[i]; } m = w; arr2.resize(m); auto count_between = [&](long long low, long long high)->int { if (m == 0) return 0; if (high <= low + 1) return 0; int L = int(upper_bound(arr2.begin(), arr2.end(), low) - arr2.begin()); int R = int(lower_bound(arr2.begin(), arr2.end(), high) - arr2.begin()); int cnt = R - L; return cnt < 0 ? 0 : cnt; }; auto check_mask = [&](unsigned long long mask)->bool { long long prev = LLONG_MIN; int need = 0; for (int i = 0; i < n; ++i) { bool rep = ((mask >> i) & 1ULL) != 0ULL; if (rep) { ++need; } else { long long ai = (long long)arr1[i]; if (ai <= prev) return false; if (need > 0) { int cnt = count_between(prev, ai); if (cnt < need) return false; need = 0; } prev = ai; } } if (need > 0) { int cnt = count_between(prev, LLONG_MAX); if (cnt < need) return false; } return true; }; if (n > 62) { int kmax = min(n, 20); for (int k = 0; k <= kmax; ++k) { if (k == 0) { if (check_mask(0ULL)) return 0; continue; } unsigned long long comb = (k >= 64) ? ~0ULL : ((1ULL << k) - 1ULL); unsigned long long limit = (1ULL << min(62, n)); if (k > min(62, n)) continue; while (comb < limit) { if (check_mask(comb)) return k; unsigned long long x = comb & -comb; unsigned long long y = comb + x; comb = y + (((y ^ comb) / x) >> 2); } } unsigned long long mask = 0ULL; for (int i = 62; i < n; ++i) { long long prev = LLONG_MIN; int need = 0; bool ok = true; for (int j = 0; j < n; ++j) { bool rep = (j >= 62); if (rep) { ++need; } else { long long ai = (long long)arr1[j]; if (ai <= prev) { ok = false; break; } if (need > 0) { int cnt = count_between(prev, ai); if (cnt < need) { ok = false; break; } need = 0; } prev = ai; } } if (ok) { if (need > 0) { int cnt = count_between(prev, LLONG_MAX); if (cnt < need) ok = false; } } if (ok) return n - 62; break; } return -1; } for (int k = 0; k <= n; ++k) { if (k == 0) { if (check_mask(0ULL)) return 0; continue; } if (k >= 64) continue; unsigned long long comb = (1ULL << k) - 1ULL; unsigned long long limit = (n == 64) ? ULLONG_MAX : (1ULL << n); while (comb < limit) { if (check_mask(comb)) return k; unsigned long long x = comb & -comb; unsigned long long y = comb + x; unsigned long long next = y + (((y ^ comb) / x) >> 2); comb = next; } } return -1; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; vector a,b; cin>>n>>m; for(int i=1,x;i<=n;i++) { cin>>x; a.push_back(x); } for(int i=1,x;i<=m;i++) { cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output cout<& nums) { } }; ``` Example 1: Input: nums = [1000,100,10,2] Output: ""1000/(100/10/2)"" Example 2: Input: nums = [2,3,4] Output: ""2/(3/4)"" Constraints: 1 <= nums.length <= @data 2 <= nums[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[20, 100, 100000]",1000,"[[1000, 100, 64], [8000, 800, 100], [64000, 6400, 800]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: string solve1(vector& nums) { string str = to_string(nums[0]); if(nums.size() == 1) return str; if(nums.size() == 2) { str += ""/"" + to_string(nums[1]); return str; } str += ""/("" + to_string(nums[1]); for(int i=2; i& nums) { int n = (int)nums.size(); if (n == 0) return """"; if (n == 1) return to_string(nums[0]); if (n == 2) { string res = to_string(nums[0]); res.push_back('/'); res += to_string(nums[1]); return res; } string res = to_string(nums[0]); res += ""/(""; res += to_string(nums[1]); for (int i = 2; i < n; ++i) { res.push_back('/'); res += to_string(nums[i]); } res.push_back(')'); return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< int > a; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } // solve Solution solution; auto result = solution.solve(a); // output cout << result << ""\n""; return 0; }","math,sort,string",medium 90,"# Problem Statement Matryoshka is a wooden toy in the form of a painted doll, inside which you can put a similar doll of a smaller size. A set of nesting dolls contains one or more nesting dolls, their sizes are consecutive positive integers. Thus, a set of nesting dolls is described by two numbers: $s$ — the size of a smallest nesting doll in a set and $m$ — the number of dolls in a set. In other words, the set contains sizes of $s, s + 1, \dots, s + m - 1$ for some integer $s$ and $m$ ($s,m > 0$). You had one or more sets of nesting dolls. Recently, you found that someone mixed all your sets in one and recorded a sequence of doll sizes — integers $a_1, a_2, \dots, a_n$. You do not remember how many sets you had, so you want to find the **minimum** number of sets that you could initially have. For example, if a given sequence is $a=[2, 2, 3, 4, 3, 1]$. Initially, there could be $2$ sets: - the first set consisting of $4$ nesting dolls with sizes $[1, 2, 3, 4]$; - a second set consisting of $2$ nesting dolls with sizes $[2, 3]$. According to a given sequence of sizes of nesting dolls $a_1, a_2, \dots, a_n$, determine the minimum number of nesting dolls that can make this sequence. Each set is completely used, so all its nesting dolls are used. Each element of a given sequence must correspond to exactly one doll from some set. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the minimum possible number of matryoshkas sets. # Example 1: - Input: n = 6 a = [2, 2, 3, 4, 3, 1] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int ans = 0, L = 0, R = 0, last = 0, last_count = 0; while (L < n) { while (R < n && a[L] == a[R]) R++; if (a[L] != last + 1) ans += R - L; else ans += R - L - min(last_count, R - L); last = a[L]; last_count = R - L; L = R; } return ans; } int solve2(int &n, vector &a) { sort(a.begin(), a.end()); int ans = 0; int len = n; const int sentinel = numeric_limits::min(); while (len > 0) { ans++; long long expect = a[0]; for (int i = 0; i < len; ++i) { int v = a[i]; if ((long long)v == expect) { a[i] = sentinel; expect++; } else if ((long long)v > expect) { break; } } int write = 0; for (int i = 0; i < len; ++i) { if (a[i] != sentinel) a[write++] = a[i]; } len = write; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","sort,two_pointers",hard 91,"# Problem Statement Sasha found an array $a$ consisting of $n$ integers and asked you to paint elements. You have to paint each element of the array. You can use as many colors as you want, but each element should be painted into exactly one color, and for each color, there should be at least one element of that color. The cost of one color is the value of $\max(S) - \min(S)$, where $S$ is the sequence of elements of that color. The cost of the whole coloring is the **sum** of costs over all colors. For example, suppose you have an array $a = [\color{red}{1}, \color{red}{5}, \color{blue}{6}, \color{blue}{3}, \color{red}{4}]$, and you painted its elements into two colors as follows: elements on positions $1$, $2$ and $5$ have color $1$; elements on positions $3$ and $4$ have color $2$. Then: - the cost of the color $1$ is $\max([1, 5, 4]) - \min([1, 5, 4]) = 5 - 1 = 4$; - the cost of the color $2$ is $\max([6, 3]) - \min([6, 3]) = 6 - 3 = 3$; - the total cost of the coloring is $7$. For the given array $a$, you have to calculate the **maximum** possible cost of the coloring. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: return the maximum possible cost of the coloring # Example 1: - Input: n = 5 a = [1, 5, 6, 3, 4] - Output: 7 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int ans = 0; for (int i = 0; i < n - 1 - i; i++) ans += a[n - 1 - i] - a[i]; return ans; } int solve2(int &n, vector &a) { for (int i = 0; i < n; ++i) { int mi = i; for (int j = i + 1; j < n; ++j) { if (a[j] < a[mi]) mi = j; } if (mi != i) { int t = a[i]; a[i] = a[mi]; a[mi] = t; } } long long ans = 0; for (int i = 0; i < n - 1 - i; ++i) ans += (long long)a[n - 1 - i] - (long long)a[i]; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","two_pointers,greedy,sort",medium 92,"Given a positive integer n, return the punishment number of n. The punishment number of n is defined as the sum of the squares of all integers i such that: 1 <= i <= n The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 10 Output: 182 Example 2: Input: n = 37 Output: 1478 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { vector arr = {1, 9, 10, 36, 45, 55, 82, 91, 99, 100, 235, 297, 369, 370, 379, 414, 657, 675, 703, 756, 792, 909, 918, 945, 964, 990, 991, 999, 1000}; vector prefix = {0}; for(int i : arr) prefix.emplace_back(prefix.back() + i*i); int i = upper_bound(arr.begin(),arr.end(),n) - arr.begin(); return prefix[i]; } int solve2(int n) { long long ans = 0; for (int i = 1; i <= n; ++i) { long long sq = 1LL * i * i; long long p = 1; while (p <= sq / 10) p *= 10; int L = 0; for (long long t = p; t > 0; t /= 10) ++L; unsigned long long maskCount = (L > 1) ? (1ULL << (L - 1)) : 1ULL; bool ok = false; for (unsigned long long mask = 0; mask < maskCount && !ok; ++mask) { long long tmpS = sq, currP = p; long long sumSegments = 0, currNum = 0; for (int pos = 0; pos < L; ++pos) { int digit = int(tmpS / currP); tmpS %= currP; currP /= 10; currNum = currNum * 10 + digit; bool cut = (pos < L - 1) && (((mask >> (L - 2 - pos)) & 1ULL) != 0); if (cut) { sumSegments += currNum; currNum = 0; } } sumSegments += currNum; if (sumSegments == i) { ok = true; ans += sq; } } } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - If all passengers followed the recommendations, return ""YES"", otherwise return ""NO"" # Example 1: - Input: n = 5 a = [5, 4, 2, 1, 3] - Output: NO # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - All seat numbers are unique - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { int l = a[0], r = a[0]; bool ok = true; for (int i = 1; i < n; i++) { if (a[i] == l - 1) l--; else if (a[i] == r + 1) r++; else { ok = false; break; } } return ok ? ""YES"" : ""NO""; } string solve2(int &n, vector &a) { int left = a[0], right = a[0]; for (int i = 1; i < n; ++i) { int x = a[i]; if (x == left - 1) left = x; else if (x == right + 1) right = x; else return ""NO""; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",two_pointers,easy 94,"# Problem Statement You are given a sequence $a$ consisting of $n$ positive integers. You can perform the following operation any number of times. - Select an index $i$ ($1 \le i < n$), and subtract $\min(a_i,a_{i+1})$ from both $a_i$ and $a_{i+1}$. Determine if it is possible to make the sequence **non-decreasing** by using the operation any number of times. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, vector &a) { // write your code here } }; ``` where: - If it is possible to make the sequence non-decreasing, return ""YES"". Otherwise, return ""NO"". # Example 1: - Input: n = 5, a = [1, 2, 3, 4, 5] - Output: YES # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { for (int i = 1; i < n; i++) { if (a[i - 1] > a[i]) return ""NO""; a[i] -= a[i - 1]; } return ""YES""; } string solve2(int &n, vector &a) { long long prev = (long long)a[0]; for (int i = 1; i < n; i++) { if (prev > (long long)a[i]) return ""NO""; prev = (long long)a[i] - prev; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",greedy,medium 95,"Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [3,4,5,2] Output: 12 Example 2: Input: nums = [1,5,4,5] Output: 16 Constraints: 2 <= nums.length <= @data 1 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int n = nums.size(); sort(nums.begin(),nums.end()); int result = (nums[n-1] - 1) * (nums[n-2] - 1); return result; } int solve2(vector& nums) { int n = nums.size(); long long maxProd = LLONG_MIN; for (int i = 0; i < n; ++i) { long long a = (long long)nums[i] - 1; for (int j = i + 1; j < n; ++j) { long long b = (long long)nums[j] - 1; long long p = a * b; if (p > maxProd) maxProd = p; } } return (int)maxProd; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout << result << ""\n""; // for(auto it:result) cout< using namespace std; class Solution { public: int solve1(int &n, string &s) { int minans = 1000000000; for (int j = 0; j < 26; j++) { for (int t = 0; t < 26; t++) { int cans = 0; for (int i = 0; i < n / 2 * 2; i++) { if (i % 2 == 0 && s[i] - 'a' != j) cans++; if (i % 2 == 1 && s[i] - 'a' != t) cans++; } minans = min(minans, cans); if (n % 2 == 0) continue; for (int i = n - 2; i > -1; i--) { if (i % 2 == 0 && s[i] - 'a' != j) cans--; if (i % 2 == 1 && s[i] - 'a' != t) cans--; if (i % 2 == 0 && s[i + 1] - 'a' != j) cans++; if (i % 2 == 1 && s[i + 1] - 'a' != t) cans++; minans = min(minans, cans); } } } if (n % 2 == 0) return minans; else return minans + 1; } int solve2(int &n, string &s) { int minans = 1000000000; if (n % 2 == 0) { for (int j = 0; j < 26; j++) { for (int t = 0; t < 26; t++) { int cans = 0; for (int i = 0; i < n; i++) { int ch = s[i] - 'a'; if ((i & 1) == 0) { if (ch != j) cans++; } else { if (ch != t) cans++; } } if (cans < minans) minans = cans; } } return minans; } else { for (int j = 0; j < 26; j++) { for (int t = 0; t < 26; t++) { int cans = 0; for (int i = 0; i < n - 1; i++) { int ch = s[i] - 'a'; if ((i & 1) == 0) { if (ch != j) cans++; } else { if (ch != t) cans++; } } if (cans < minans) minans = cans; for (int i = n - 2; i >= 0; i--) { int ch_i = s[i] - 'a'; int ch_ip1 = s[i + 1] - 'a'; if ((i & 1) == 0) { if (ch_i != j) cans--; } else { if (ch_i != t) cans--; } if ((i & 1) == 0) { if (ch_ip1 != j) cans++; } else { if (ch_ip1 != t) cans++; } if (cans < minans) minans = cans; } } } return minans + 1; } } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","dp,greedy,data_structures,string",hard 97,"# Problem Statement After receiving yet another integer array $a_1, a_2, \ldots, a_n$ at her birthday party, Index decides to perform some operations on it. Formally, there are $m$ operations that she is going to perform in order. Each of them belongs to one of the two types: - $\texttt{1 l r}$. Given two integers $l$ and $r$, for all $1 \leq i \leq n$ such that $l \leq a_i \leq r$, set $a_i := a_i + 1$. - $\texttt{2 l r}$. Given two integers $l$ and $r$, for all $1 \leq i \leq n$ such that $l \leq a_i \leq r$, set $a_i := a_i - 1$. For example, if the initial array $a = [7, 1, 3, 4, 3]$, after performing the operation $\texttt{+} \space 2 \space 4$, the array $a = [7, 1, 4, 5, 4]$. Then, after performing the operation $\texttt{-} \space 1 \space 10$, the array $a = [6, 0, 3, 4, 3]$. Index is curious about the maximum value in the array $a$. Please help her find it after each of the $m$ operations. The main function of the solution is defined as: ```cpp class Solution { public: vector solve(int &n, int &m, vector &a, vector> &ops) { // write your code here } }; ``` where: - `ops` is the array of operations, each element is an array of length 3, representing an operation - return an array, where the elements are the maximum value after each operation # Example 1: - Input: n = 5, m = 5 a = [1, 2, 3, 2, 1] ops = [[1, 1, 3], [2, 2, 3], [1, 1, 2], [1, 2, 4], [2, 6, 8]] - Output: [4, 4, 4, 5, 5] # Constraints: - $1 \leq n, m \leq @data$ - $1 \leq a[i] \leq 10^9$ - $1 \leq l \leq r \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 160, 80], [6400, 1280, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &n, int &m, vector &a, vector> &ops) { vector res; int mx = *max_element(a.begin(), a.end()); for (auto &[op, l, r] : ops) { if (l <= mx && mx <= r) mx += op == 1 ? 1 : -1; res.push_back(mx); } return res; } vector solve2(int &n, int &m, vector &a, vector> &ops) { vector res; res.reserve(m); for (auto &[op, l, r] : ops) { long long curMax = LLONG_MIN; int delta = (op == 1 ? 1 : -1); for (int i = 0; i < n; ++i) { int ai = a[i]; if (l <= ai && ai <= r) { long long v = (long long)ai + delta; a[i] = (int)v; if (v > curMax) curMax = v; } else { if ((long long)ai > curMax) curMax = ai; } } res.push_back((int)curMax); } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector> ops(m); for (int i = 0; i < m; i++) cin >> ops[i][0] >> ops[i][1] >> ops[i][2]; // solve Solution solution; auto result = solution.solve(n, m, a, ops); // output for (auto &x : result) cout << x << "" ""; cout << ""\n""; return 0; }","greedy,data_structures",easy 98,"You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: It is the empty string, or It can be written as AB, where both A and B are balanced strings, or It can be written as [C], where C is a balanced string. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced. solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""][]["" Output: 1 Example 2: Input: s = ""[]"" Output: 0 Constraints: n == s.length 2 <= n <= @data n is even. s[i] is either '[' or ']'. The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve(string s) { int stackSize = 0; int n = s.size(); for (int i = 0; i < n; i++) { char ch = s[i]; if (ch == '[') stackSize++; else { if (stackSize > 0) stackSize--; } } return (stackSize + 1) / 2; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout< &a, vector &b) { // write your code here } }; ``` where: - `n`: number of trap patterns (turn periodicity) - `m`: target cell index to reach - `a`: array of size `n`, where `2 ≤ a[i] ≤ 10` - `b`: array of size `n`, where `0 ≤ b[i] < a[i]` - return: the minimum number of turns to reach cell `m`, or `-1` if impossible. # Example: - Input: ``` n = 2, m = 5 a = [2, 2] b = [0, 1] ``` - Output: ``` 5 ``` # Constraints: - $1 \leq n \leq 10$ - $1 \leq m \leq @data$ - $2 \leq a[i] \leq 10$ - $0 \leq b[i] < a[i]$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000000, 1000000000, 1000000000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, long long &m, vector &a, vector &b) { int l=1;for(int i=0;iv((size_t)cap+1,1e9),w(n,-1);v[0]=0;w[0]=0; int x=0,i=0,s,e,d; while(xn){ return -1; } } if(x==m){ return v[m]; }else{ return v[(m-s-1)%(e-s)+s+1]+d*((m-s-1)/(e-s)); } } long long solve2(int &n, long long &m, vector &a, vector &b) { long long x = 0; long long t = 0; int noProgress = 0; while (x < m) { int idx = (int)(t % n); long long nx = x + 1; if (nx % (long long)a[idx] != (long long)b[idx]) { x = nx; noProgress = 0; } else { noProgress++; if (noProgress >= n) return -1; } t++; } return t; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; long long m; cin >> n >> m; vector a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; // solve Solution solution; auto result = solution.solve(n, m, a, b); // output cout << result << ""\n""; return 0; }",dp,hard 100,"You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge. The graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i]. The edge score of a node i is defined as the sum of the labels of all the nodes that have an edge pointing to i. Return the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index. solution main function ```cpp class Solution { public: int solve(vector& edges) { } }; ``` Example 1: Input: edges = [1,0,0,0,0,7,7,5] Output: 7 Example 2: Input: edges = [2,0,0,2] Output: 0 Constraints: n == edges.length 2 <= n <= @data 0 <= edges[i] < n edges[i] != i Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& edges) { ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using ll=long long; vector score(edges.size(),0); ll maxi=0; int val=INT_MAX; for (int i=0;imaxi){ val=i; maxi=score[i]; } } return val; } int solve2(vector& edges) { ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); int n = (int)edges.size(); long long bestScore = -1; int bestIdx = 0; for (int i = 0; i < n; ++i) { long long s = 0; for (int j = 0; j < n; ++j) { if (edges[j] == i) s += j; } if (s > bestScore) { bestScore = s; bestIdx = i; } } return bestIdx; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< int > edge; for(int i=1,x,y,z;i<=n;i++) { scanf(""%d"",&x); edge.push_back(x); } // solve Solution solution; auto result = solution.solve(edge); // output // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return: # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: 3 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin() + 1, a.end()); for (int i = 1; i < n; i++) { if (a[i] > a[0]) { a[0] = (a[0] + a[i] + 1) / 2; } } return a[0]; } int solve2(int &n, vector &a) { long long x = a[0]; while (true) { long long mn = LLONG_MAX; int idx = -1; for (int i = 1; i < n; i++) { if ((long long)a[i] > x && (long long)a[i] < mn) { mn = a[i]; idx = i; } } if (idx == -1) break; long long t = (mn - x + 1) / 2; x += t; a[idx] -= (int)t; } return (int)x; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,sort",hard 102,"You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner. solution main function ```cpp class Solution { public: int solve(vector>& books, int shelfWidth) { } }; ``` Example 1: Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 Output: 6 Example 2: Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 Output: 4 Constraints: 1 <= books.length <= @data 1 <= thicknessi <= shelfWidth <= 100 1 <= heighti <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(std::vector> const& books, int const& shelfWidth) { std::vector table(books.size() + 1, INT_MAX); table[0] = 0; for (int i{1}; i <= (int)books.size(); ++i) { int total_width{}, mx_height{}; for (int j{i}; j >= 1; j--) { total_width += books[j - 1][0]; if (total_width > shelfWidth) break; mx_height = std::max(mx_height, books[j - 1][1]); table[i] = std::min(table[i], mx_height + table[j - 1]); } } return table[books.size()]; } int solve2(std::vector> const& books, int const& shelfWidth) { int n = (int)books.size(); if (n == 0) return 0; int m = n - 1; if (m == 0) { long long total = 0; int w = 0, h = 0; for (int i = 0; i < n; ++i) { int th = books[i][0]; int ht = books[i][1]; w += th; if (w > shelfWidth) return INT_MAX / 4; if (ht > h) h = ht; } total += h; return (int)total; } uint64_t limit_lo = (m >= 64) ? ~0ULL : (uint64_t)((1ULL << m) - 1); uint64_t limit_hi = (m <= 64) ? 0ULL : (uint64_t)((m - 64 >= 64) ? ~0ULL : ((1ULL << (m - 64)) - 1)); uint64_t cur_lo = 0ULL, cur_hi = 0ULL; long long best = LLONG_MAX; while (true) { long long total = 0; int curW = 0; int curH = 0; bool ok = true; for (int i = 0; i < n; ++i) { int th = books[i][0]; int ht = books[i][1]; curW += th; if (curW > shelfWidth) { ok = false; break; } if (ht > curH) curH = ht; if (i < n - 1) { bool split = false; if (i < 64) split = ((cur_lo >> i) & 1ULL); else split = ((cur_hi >> (i - 64)) & 1ULL); if (split) { total += curH; curW = 0; curH = 0; } } } if (ok) { total += curH; if (total < best) best = total; } if (cur_lo == limit_lo && cur_hi == limit_hi) break; cur_lo++; if (cur_lo == 0) cur_hi++; } return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,wid; vector > num; cin>>n>>wid; for(int i=1;i<=n;i++) { int x,y; cin>>x>>y; vector temp; temp.push_back(x); temp.push_back(y); num.push_back(temp); } // solve Solution solution; auto result = solution.solve(num,wid); // output cout<& arr) { } }; ``` Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Example 2: Input: arr = [5,4,3,2,1] Output: 4 Constraints: 1 <= arr.length <= @data 0 <= arr[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(vector& arr) { int right = arr.size() - 1; while (right > 0 && arr[right] >= arr[right - 1]) { right--; } int ans = right; int left = 0; while (left < right && (left == 0 || arr[left - 1] <= arr[left])) { while (right < arr.size() && arr[left] > arr[right]) { right++; } ans = min(ans, right - left - 1); left++; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout << result << ""\n""; return 0; }","two_pointers,binary",medium 104,"A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [0,1,0,1,1,0,0] Output: 1 Example 2: Input: nums = [0,1,1,1,0,0,1,1,0] Output: 2 Constraints: 1 <= nums.length <= @data nums[i] is either 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int minimumSwaps = INT_MAX; int totalOnes = accumulate(nums.begin(), nums.end(), 0); int onesCount = nums[0]; int end = 0; for (int start = 0; start < nums.size(); ++start) { if (start != 0) { onesCount -= nums[start - 1]; } while (end - start + 1 < totalOnes) { end++; onesCount += nums[end % nums.size()]; } minimumSwaps = min(minimumSwaps, totalOnes - onesCount); } return minimumSwaps; } int solve2(vector& nums) { int n = (int)nums.size(); int totalOnes = 0; for (int v : nums) totalOnes += (v != 0); if (totalOnes <= 1 || totalOnes == n) return 0; int ans = INT_MAX; for (int start = 0; start < n; ++start) { int zeros = 0; for (int j = 0; j < totalOnes; ++j) { int idx = start + j; if (idx >= n) idx -= n; if (nums[idx] == 0) ++zeros; } if (zeros < ans) ans = zeros; } if (ans == INT_MAX) return 0; return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout<>& grid) { // write your code here } }; ``` Example 1: Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]] Output: 2 Example 2: Input: grid = [[1,1]] Output: 2 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data grid[i][j] is either 0 or 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 30, 50]",1000,"[[400, 64, 64], [3200, 320, 125], [25600, 2560, 1000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int countIslands(vector>& grid, int n, int m) { int cnt = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 1) { ++cnt; grid[i][j] = 2; bool changed = true; while (changed) { changed = false; for (int x = 0; x < n; ++x) { for (int y = 0; y < m; ++y) { if (grid[x][y] == 1) { if ((x > 0 && grid[x - 1][y] == 2) || (x + 1 < n && grid[x + 1][y] == 2) || (y > 0 && grid[x][y - 1] == 2) || (y + 1 < m && grid[x][y + 1] == 2)) { grid[x][y] = 2; changed = true; } } } } } } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 2) grid[i][j] = 1; } } return cnt; } public: void dfs(int x, int y, vector>& grid, int n, int m) { grid[x][y] = 2; for (int i = 0; i < 4; ++i) { int tx = dx[i] + x; int ty = dy[i] + y; if (tx < 0 || tx >= n || ty < 0 || ty >= m || grid[tx][ty] != 1) { continue; } dfs(tx, ty, grid, n, m); } } int count(vector>& grid, int n, int m) { int cnt = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 1) { cnt++; dfs(i, j, grid, n, m); } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 2) { grid[i][j] = 1; } } } return cnt; } int solve1(vector>& grid) { int n = grid.size(), m = grid[0].size(); if (count(grid, n, m) != 1) { return 0; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j]) { grid[i][j] = 0; if (count(grid, n, m) != 1) { return 1; } grid[i][j] = 1; } } } return 2; } int solve2(vector>& grid) { int n = (int)grid.size(), m = (int)grid[0].size(); if (countIslands(grid, n, m) != 1) return 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 1) { grid[i][j] = 0; int c = countIslands(grid, n, m); if (c != 1) { grid[i][j] = 1; return 1; } grid[i][j] = 1; } } } return 2; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > g; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } g.push_back(temp); } // solve Solution solution; auto result = solution.solve(g); // output cout< 1$). - Each vertex that is connected to only one other vertex is connected by edges to $k$ more new vertices. This step should be done **at least once**. After some mathematical research, Rudolf realized that such snowflakes may not have any number of vertices. Help Rudolf check if a snowflake with $n$ vertices can exist. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n) { // write your code here } }; ``` where: - return ""YES"" if a snowflake with $n$ vertices can exist, otherwise return ""NO"". # Example 1: - Input: n = 15 - Output: ""YES"" # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n) { int ok = 0; for (int i = 2; i <= n && !ok; i++) { long long sum = 1 + i + 1LL * i * i, p = 1LL * i * i; if (sum > n) break; while (sum < n) sum += p *= i; if (sum == n) ok = 1; } return ok ? ""YES"" : ""NO""; } string solve2(int &n) { long long N = n; if (N < 7) return ""NO""; for (int t = 2;; t++) { __int128 sumMin = 1, termMin = 1; for (int i = 1; i <= t; i++) { termMin *= 2; sumMin += termMin; if (sumMin > N) break; } if (sumMin > N) break; long long lo = 2, hi = N; while (lo <= hi) { long long mid = lo + (hi - lo) / 2; __int128 s = 1, tm = 1; bool exceeded = false; for (int i = 1; i <= t; i++) { tm *= mid; s += tm; if (s > N) { exceeded = true; break; } } if (!exceeded && s == N) return ""YES""; if (!exceeded && s < N) lo = mid + 1; else hi = mid - 1; } } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }",math,medium 107,"# Problem Statement Alice got a permutation $a_1, a_2, \ldots, a_n$ of $[1,2,\ldots,n]$, and Bob got another permutation $b_1, b_2, \ldots, b_n$ of $[1,2,\ldots,n]$. They are going to play a game with these arrays. In each turn, the following events happen in order: - Alice chooses either the first or the last element of her array and removes it from the array; - Bob chooses either the first or the last element of his array and removes it from the array. The game continues for $n-1$ turns, after which both arrays will have exactly one remaining element: $x$ in the array $a$ and $y$ in the array $b$. If $x=y$, Bob wins; otherwise, Alice wins. Find which player will win if both players play optimally. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, vector &a, vector &b) { // write your code here } }; ``` where: - return Alice if Alice wins; otherwise, return Bob. # Example 1: - Input: n = 2 a = [1, 2] b = [1, 2] - Output: Bob # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i], b[i] \leq n$ - a[i] is distinct. - b[i] is distinct. - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve(int &n, vector &a, vector &b) { if (a == b) return ""Bob""; reverse(b.rbegin(), b.rend()); if (a == b) return ""Bob""; return ""Alice""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector b(n); for (int i = 0; i < n; i++) cin >> b[i]; // solve Solution solution; auto result = solution.solve(n, a, b); // output cout << result << ""\n""; return 0; }",game,hard 108,"# Problem Statement Slavic has an array of length $n$ consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array. What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to $s$ after performing all the operations? In case the sum $s$ can't be obtained after any amount of operations, you should output \-1. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &s, vector &a) { // write your code here } }; ``` where: - return: the minimum amount of operations required to have the total sum of the array equal to s, or -1 if obtaining an array with sum s isn't possible. # Example 1: - Input: n = 3, s = 1 a = [1, 0, 0] - Output: 0 # Constraints: - $1 \leq n, s \leq @data$ - $a[i] \in \{0, 1\}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &s, vector &a) { int ans = n + 1; int cur = 0; for (int i = 0, j = 0; i < n; i++) { while (j < n && cur + a[j] <= s) { cur += a[j]; j++; } if (cur == s) { ans = min(ans, n - (j - i)); } cur -= a[i]; } if (ans > n) { ans = -1; } return ans; } int solve2(int &n, int &s, vector &a) { int ans = (s == 0 ? n : n + 1); long long target = s; for (int i = 0; i < n; i++) { long long sum = 0; for (int j = i; j < n; j++) { sum += a[j]; if (sum == target) { int ops = n - (j - i + 1); if (ops < ans) { ans = ops; } } if (sum > target) { break; } } } if (ans > n) { ans = -1; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, s; cin >> n >> s; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, s, a); // output cout << result << ""\n""; return 0; }","two_pointers,binary",hard 109,"You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern of size m consisting of integers -1, 0, and 1. A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions hold for each element pattern[k]: nums[i + k + 1] > nums[i + k] if pattern[k] == 1. nums[i + k + 1] == nums[i + k] if pattern[k] == 0. nums[i + k + 1] < nums[i + k] if pattern[k] == -1. Return the count of subarrays in nums that match the pattern. solution main function ```cpp class Solution { public: int solve(vector& nums, vector& pattern) { } }; ``` Example 1: Input: nums = [1,2,3,4,5,6], pattern = [1,1] Output: 4 Example 2: Input: nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] Output: 2 Constraints: 2 <= n == nums.length <= @data 1 <= nums[i] <= 10^9 1 <= m == pattern.length < n -1 <= pattern[i] <= 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums, vector& pattern) { int n = nums.size(); int m = pattern.size(); int count = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (j - i + 1 == m + 1) { int l = i; int flag = 0; for (int k = 0; k < m; k++, l++) { if (pattern[k] == 1 && nums[l + 1] > nums[l]) { continue; } else if (pattern[k] == 0 && nums[l + 1] == nums[l]) { continue; } else if (pattern[k] == -1 && nums[l + 1] < nums[l]) { continue; } else { flag = 1; break; } } if (flag == 0) { count++; } } } } return count; } int solve2(vector& nums, vector& pattern) { int n = (int)nums.size(); int m = (int)pattern.size(); long long count = 0; for (int i = 0; i + m < n; ++i) { int ok = 1; for (int k = 0; k < m; ++k) { int a = nums[i + k]; int b = nums[i + k + 1]; int p = pattern[k]; if (p == 1) { if (!(b > a)) { ok = 0; break; } } else if (p == 0) { if (!(b == a)) { ok = 0; break; } } else { if (!(b < a)) { ok = 0; break; } } } if (ok) ++count; } return (int)count; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n; vector a,b; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } cin>>m; for(int i=1;i<=m;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output // for(auto it:result) cout< solve(vector& nums) { } }; ``` Example 1: Input: nums = [4,3,10,9,8] Output: [10,9] Example 2: Input: nums = [4,4,7,6,7] Output: [7,7,6] Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector& nums) { vector res; auto sub_sum = 0, half_sum = accumulate(begin(nums), end(nums), 0) / 2; priority_queue pq(begin(nums), end(nums)); while (sub_sum <= half_sum) { res.push_back(pq.top()); sub_sum += res.back(); pq.pop(); } return res; } vector solve2(vector& nums) { long long total = 0; for (int v : nums) total += v; long long sub = 0; int n = (int)nums.size(); int k = 0; for (int i = 0; i < n; ++i) { int maxIdx = i; for (int j = i + 1; j < n; ++j) { if (nums[j] > nums[maxIdx]) maxIdx = j; } if (maxIdx != i) swap(nums[i], nums[maxIdx]); sub += nums[i]; if (sub > total - sub) { k = i + 1; break; } } vector res; res.reserve(k); for (int i = 0; i < k; ++i) res.push_back(nums[i]); return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n;cin>>n; vector a; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } // solve Solution solution; auto result = solution.solve(a); // output for(auto it:result) cout< &p) { // write your code here } }; ``` where: - return: the number of lucky elements in the permutation. # Example 1: - Input: n = 3 p = [2, 1, 3] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $1 \leq p[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, vector &p) { for (int i = 0; i < n; i++) p[i]--; int minlose = n; int mn = n; int ans = 0; for (int i = 0; i < n; i++) { int win = 0; if (p[i] < mn) { mn = p[i]; win = 1; } else { win = (minlose < p[i]); } if (!win) { ans += 1; minlose = min(minlose, p[i]); } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,greedy",hard 112,"You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7. solution main function ```cpp class Solution { public: int solve(vector& nums, int n, int left, int right) { } }; ``` Example 1: Input: nums = [1,2,3,4], n = 4, left = 1, right = 5 Output: 13 Example 2: Input: nums = [1,2,3,4], n = 4, left = 3, right = 4 Output: 6 Constraints: n == nums.length 1 <= nums.length <= @data 1 <= nums[i] <= 100 1 <= left <= right <= n * (n + 1) / 2 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { int mod = 1e9 + 7; pair countAndSum(vector& nums, int n, int target) { int count = 0; long long currentSum = 0, totalSum = 0, windowSum = 0; for (int j = 0, i = 0; j < n; ++j) { currentSum += nums[j]; windowSum += nums[j] * (j - i + 1); while (currentSum > target) { windowSum -= currentSum; currentSum -= nums[i++]; } count += j - i + 1; totalSum += windowSum; } return {count, totalSum}; } long long sumOfFirstK(vector& nums, int n, int k) { int minSum = *min_element(nums.begin(), nums.end()); int maxSum = accumulate(nums.begin(), nums.end(), 0); int left = minSum, right = maxSum; while (left <= right) { int mid = left + (right - left) / 2; if (countAndSum(nums, n, mid).first >= k) right = mid - 1; else left = mid + 1; } auto [count, sum] = countAndSum(nums, n, left); return sum - left * (count - k); } static long long countLE(vector& nums, int n, long long target) { long long cnt = 0, sum = 0; int i = 0; for (int j = 0; j < n; ++j) { sum += nums[j]; while (i <= j && sum > target) { sum -= nums[i++]; } cnt += (j - i + 1); } return cnt; } public: int solve1(vector& nums, int n, int left, int right) { long result = (sumOfFirstK(nums, n, right) - sumOfFirstK(nums, n, left - 1)) % mod; return (result + mod) % mod; } int solve2(vector& nums, int n, int left, int right) { const int MOD = 1000000007; long long res = 0; long long maxSum = 0; int minSum = INT_MAX; for (int i = 0; i < n; ++i) { maxSum += nums[i]; if (nums[i] < minSum) minSum = nums[i]; } for (int k = left; k <= right; ++k) { long long lo = minSum, hi = maxSum, ans = maxSum; while (lo <= hi) { long long mid = lo + (hi - lo) / 2; long long cnt = countLE(nums, n, mid); if (cnt >= k) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } res += ans % MOD; if (res >= (1LL << 61)) res %= MOD; } return (int)(res % MOD); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,l,r; vector num; cin>>n>>l>>r; for(int i=1,x;i<=n;i++) { cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num,n,l,r); // output cout<& batteries) { } }; ``` Example 1: Input: n = 2, batteries = [3,3,3] Output: 4 Example 2: Input: n = 2, batteries = [1,1,1,1] Output: 2 Constraints: 1 <= n <= batteries.length <= @data 1 <= batteries[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool check(int n, vector& batteries, long long mid) { long long target = n * mid; long long sum = 0; for (int battery : batteries) { sum += min((long long)battery, mid); if (sum >= target) return true; } return false; } long long solve1(int n, vector& batteries) { long long low = 1; long long high = accumulate(batteries.begin(), batteries.end(), 0LL) / n; long long result = 0; while (low <= high) { long long mid = low + (high - low) / 2; if (check(n, batteries, mid)) { result = mid; low = mid + 1; } else { high = mid - 1; } } return result; } long long solve2(int n, vector& batteries) { long long total = 0; for (int x : batteries) total += x; long long high = total / n; long long ans = 0; long long step = 1; while (step <= high) step <<= 1; step >>= 1; while (step > 0) { long long t = ans + step; if (t <= high) { long long s = 0; for (int b : batteries) { s += min((long long)b, t); if (s >= (long long)n * t) break; } if (s >= (long long)n * t) ans = t; } step >>= 1; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector s; for(int i=1;i<=m;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(n,s); // output cout << result << ""\n""; return 0; }","greedy,sort,binary",medium 114,"# Problem Statement: Given an array $a=[a_1,a_2,\dots,a_n]$ of $n$ positive integers, you can do operations of two types on it: 1. Add $1$ to **every** element with an **odd** index. In other words change the array as follows: $a_1 := a_1 +1, a_3 := a_3 + 1, a_5 := a_5+1, \dots$. 2. Add $1$ to **every** element with an **even** index. In other words change the array as follows: $a_2 := a_2 +1, a_4 := a_4 + 1, a_6 := a_6+1, \dots$. Determine if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers. In other words, determine if you can make all elements of the array have the same parity after any number of operations. Note that you can do operations of both types any number of times (even none). Operations of different types can be performed a different number of times. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, vector &a) { // write your code here } }; ``` Where: - The return value is ""YES"" if it is possible to make all elements of the array have the same parity after any number of operations, and ""NO"" otherwise. # Example 1: - Input: n = 5 a = [1000, 1, 1000, 1, 1000] - Output: YES # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[64, 64, 64], [400, 64, 64], [3200, 320, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { for (int i = 2; i < n; i++) if (a[i] % 2 != a[i - 2] % 2) return ""NO""; return ""YES""; } string solve2(int &n, vector &a) { for (int ko = 0; ko < 2; ++ko) { for (int ke = 0; ke < 2; ++ke) { int firstParity = (a[0] + ko) & 1; bool ok = true; for (int i = 1; i < n; ++i) { int togg = (i % 2 == 0) ? ko : ke; if (((a[i] + togg) & 1) != firstParity) { ok = false; break; } } if (ok) return ""YES""; } } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,math",medium 115,"You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti]. You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other. Return the minimum number of groups you need to make. Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect. solution main function ```cpp class Solution { public: int solve(vector>& intervals) { } }; ``` Example 1: Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]] Output: 3 Example 2: Input: intervals = [[1,3],[5,6],[8,10],[11,13]] Output: 1 Constraints: 1 <= intervals.length <= @data intervals[i].length == 2 1 <= lefti <= righti <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 160, 80], [6400, 1280, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: struct cmp { bool operator()(const pair& a, const pair& b) { if (a.first == b.first) return a.second > b.second; return a.first > b.first; } }; struct cmp2 { bool operator()(const int& a, const int& b) { return a > b; } }; int solve1(vector>& intervals) { int n = intervals.size(); sort(intervals.begin(), intervals.end()); priority_queue, greater> group; for(int i=0;i cur = make_pair(intervals[i][0],intervals[i][1]); if(group.empty()) group.push(cur.second); else{ int tail = group.top(); if (tail < cur.first) { tail = cur.second; group.pop(); group.push(tail); } else group.push(cur.second); } } return group.size(); } int solve2(vector>& intervals) { int n = (int)intervals.size(); int ans = 0; for (int i = 0; i < n; ++i) { int x = intervals[i][0]; int cnt = 0; for (int j = 0; j < n; ++j) { if (intervals[j][0] <= x && intervals[j][1] >= x) { ++cnt; } } if (cnt > ans) ans = cnt; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector > num; cin>>n; for(int i=1,x,y;i<=n;i++) { cin>>x>>y; vector temp; temp.push_back(x); temp.push_back(y); num.push_back(temp); } // solve Solution solution; auto result = solution.solve(num); // output cout< using namespace std; #include using namespace std; class Solution { public: int prime(int n) { if (n == 1) { return 0; } for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { return 0; } } return 1; } int solve1(int n) { int count = 0; for (int i = 1; i <= n; ++i) { if (prime(i) == 1) { count++; } } long long int perm = 1; for (int i = 1; i <= count; ++i) { perm = (perm * i) % 1000000007; } for (int i = 1; i <= n - count; ++i) { perm = (perm * i) % 1000000007; } return perm; } int solve2(int n) { const int MOD = 1000000007; int primes = 0; for (int x = 2; x <= n; ++x) { bool isPrime = true; for (int d = 2; d < x; ++d) { if (x % d == 0) { isPrime = false; break; } } if (isPrime) ++primes; } long long ans = 1; for (int i = 2; i <= primes; ++i) { ans = (ans * i) % MOD; } for (int i = 2; i <= n - primes; ++i) { ans = (ans * i) % MOD; } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output // for(auto it:result) cout<& nums) { } }; ``` Example 1: Input: nums = [1,2,3,3] Output: 3 Example 2: Input: nums = [2,1,2,5,3,2] Output: 2 Constraints: 2 <= n <= @data nums.length == 2 * n 0 <= nums[i] <= 10^4 nums contains n + 1 unique elements and one of them is repeated exactly n times. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve(vector& nums) { for (int i = 0; i + 2 < nums.size(); ++i) if (nums[i] == nums[i + 1] || nums[i] == nums[i + 2]) return nums[i]; return nums.back(); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector str; cin>>n; for(int i=1;i<=2*n;i++) { int s; cin>>s; str.push_back(s); } // solve Solution solution; auto result = solution.solve(str); // output cout<& values) { } }; ``` Example 1: Input: values = [8,1,5,2,6] Output: 11 Example 2: Input: values = [1,2] Output: 2 Constraints: 2 <= values.length <= @data 1 <= values[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& values) { int n = values.size(); int maxLeftScore = values[0]; int maxScore = 0; for (int i = 1; i < n; i++) { int currentRightScore = values[i] - i; maxScore = max(maxScore, maxLeftScore + currentRightScore); int currentLeftScore = values[i] + i; maxLeftScore = max(maxLeftScore, currentLeftScore); } return maxScore; } int solve2(vector& values) { int n = (int)values.size(); long long best = LLONG_MIN; for (int i = 0; i < n; ++i) { long long li = (long long)values[i] + i; for (int j = i + 1; j < n; ++j) { long long s = li + (long long)values[j] - j; if (s > best) best = s; } } if (best == LLONG_MIN) return 0; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< int > a; for(int i=1,x;i<=n;i++) { cin>>x; a.push_back(x); } // solve Solution solution; int result = solution.solve(a); // output cout << result << ""\n""; return 0; }",greedy,easy 119,"Given an array of integers arr and an integer d. In one step you can jump from index i to index: i + x where: i + x < arr.length and 0 < x <= d. i - x where: i - x >= 0 and 0 < x <= d. In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time. solution main function ```cpp class Solution { public: int solve(vector& arr, int d) { } }; ``` Example 1: Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2 Output: 4 Example 2: Input: arr = [3,3,3,3,3], d = 3 Output: 1 Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= 10^5 1 <= d <= arr.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& arr, int d) { arr.push_back(INT_MAX); uint32_t sz = arr.size(); vector score(sz, 0); stack st; vector duplicates; int best = 0; for(uint32_t i = 0; i < sz; i++) { duplicates.resize(0); while(!st.empty() && (arr[i] > arr[st.top()] || i - st.top() > d)) { uint32_t j = st.top(); st.pop(); if(!st.empty()) { if(arr[st.top()] > arr[j]) { score[st.top()] = max(score[st.top()], 1 + score[j]); while(duplicates.size() > 0) { if(duplicates.back() - st.top() <= d) { score[st.top()] = max(score[st.top()], 1 + score[duplicates.back()]); } duplicates.pop_back(); } } else { duplicates.push_back(j); } } if(i - j <= d) { score[i] = max(score[i], score[j] + 1); } } st.push(i); } score.pop_back(); arr.pop_back(); return *max_element(score.begin(), score.end()) + 1; } int solve2(vector& arr, int d) { const int BASE = 1 << 30; int n = (int)arr.size(); if(n == 0) return 0; int answer = 1; while(true) { int v = INT_MAX; int cnt = 0; for(int i = 0; i < n; ++i) { int a = arr[i]; if(a > 0 && a < BASE) { ++cnt; if(a < v) v = a; } } if(cnt == 0) break; for(int i = 0; i < n; ++i) { if(arr[i] == v) { int currV = v; int bestJump = 0; for(int x = 1; x <= d; ++x) { int j = i - x; if(j < 0) break; int aj = arr[j]; if(aj >= 0 && aj >= currV) break; if(aj < currV) { int dpj = (aj >= 0) ? 0 : (-aj - 1); if(dpj + 1 > bestJump) bestJump = dpj + 1; } } for(int x = 1; x <= d; ++x) { int j = i + x; if(j >= n) break; int aj = arr[j]; if(aj >= 0 && aj >= currV) break; if(aj < currV) { int dpj = (aj >= 0) ? 0 : (-aj - 1); if(dpj + 1 > bestJump) bestJump = dpj + 1; } } if(bestJump + 1 > answer) answer = bestJump + 1; arr[i] = BASE + bestJump; } } for(int i = 0; i < n; ++i) { if(arr[i] >= BASE) { arr[i] = -(arr[i] - BASE + 1); } } } return answer; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,d; cin>>n>>d; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,d); // output // for(auto it:result) cout<& nums) { } }; ``` Example 1: Input: nums = [1,3,2,4] Output: 1 Example 2: Input: nums = [100,1,10] Output: 9 Constraints: 2 <= nums.length <= @data 1 <= nums[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int ans = 1e9; sort(nums.begin(), nums.end()); for(int i = 1; i < nums.size(); i++){ ans = min(ans, nums[i] - nums[i - 1]); } return ans; } int solve2(vector& nums) { long long best = LLONG_MAX; int n = (int)nums.size(); for (int i = 0; i < n; ++i) { long long ai = nums[i]; for (int j = i + 1; j < n; ++j) { long long diff = ai - (long long)nums[j]; if (diff < 0) diff = -diff; if (diff < best) best = diff; } } return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout<& tickets, int k) { } }; ``` Example 1: Input: tickets = [2,3,2], k = 2 Output: 6 Example 2: Input: tickets = [5,1,1,1], k = 0 Output: 8 Constraints: n == tickets.length 1 <= n <= @data 1 <= tickets[i] <= 100 0 <= k < n Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 10000, 100000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& tickets, int k) { int time = 0; for (int i = 0; i < tickets.size(); i++) { if (i <= k) { time += min(tickets[k], tickets[i]); } else { time += min(tickets[k] - 1, tickets[i]); } } return time; } int solve2(vector& tickets, int k) { long long time = 0; int n = (int)tickets.size(); int i = 0; while (k >= 0 && k < n && tickets[k] > 0) { if (tickets[i] > 0) { tickets[i]--; time++; if (i == k && tickets[k] == 0) break; } i++; if (i == n) i = 0; } if (time > INT_MAX) return INT_MAX; return (int)time; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; vector num; cin>>n>>k; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num,k); // output cout< &a) { // write your code here } }; ``` where: - return: the maximum score that you can get. # Example 1: - Input: n = 1 a = [69] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int mx = *max_element(a.begin(), a.end()); int mn = *min_element(a.begin(), a.end()); return (mx - mn) * (n - 1); } int solve2(int &n, vector &a) { if (n <= 1) return 0; int mn = a[0], mx = a[0]; int iMin = 0; for (int i = 1; i < n; ++i) { if (a[i] < mn) { mn = a[i]; iMin = i; } if (a[i] > mx) { mx = a[i]; } } if (mn == mx) return 0; if (iMin != 0) swap(a[0], a[iMin]); int posMax = -1; for (int i = 1; i < n; ++i) { if (a[i] == mx) { posMax = i; break; } } if (posMax == -1) { for (int i = 0; i < n; ++i) { if (a[i] == mx) { posMax = i; break; } } } if (posMax != 1) swap(a[1], a[posMax]); long long sum = 0; int curMin = INT_MAX, curMax = INT_MIN; for (int i = 0; i < n; ++i) { if (a[i] < curMin) curMin = a[i]; if (a[i] > curMax) curMax = a[i]; sum += (long long)curMax - (long long)curMin; } return (int)sum; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",sort,easy 123,"# Problem Statement Given a rooted tree T with n vertices (rooted at 1) and an integer array a of length n, count the number of permutations p of [1..n] that satisfy: For every vertex u (1 ≤ u ≤ n), there are exactly a_u ancestors v of u in T such that p_v < p_u. Output the answer modulo 998244353. It is guaranteed that the input is chosen so that at least one valid permutation exists. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &fa, vector &a) { // write your code here } }; ``` where: - n: number of vertices in the tree (root is 1) - fa: array of length n-1, where fa[i-2] is the parent of vertex i for i=2..n - a: array of length n, a[u-1] is a_u - return: the number of valid permutations modulo 998244353 # Example 1: - Input: ``` n = 5 fa = [1, 2, 3, 4] a = [0, 1, 2, 3, 4] ``` - Output: ``` 1 ``` # Constraints: - $2 \leq n \leq @data$ - $0 \leq a_i < n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 5000]",1000,"[[100, 64, 64], [800, 200, 64], [6400, 1600, 320]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &fa, vector &a) { const int MOD = 998244353; auto addmod = [&](long long x, long long y) -> int { return int((x + y) % MOD); }; vector A(n + 1, 0); for (int i = 1; i <= n; i++) A[i] = a[i - 1]; vector> g(n + 1); for (int i = 2; i <= n; i++) { int p = fa[i - 2]; g[p].push_back(i); } vector fac(n + 1), ifac(n + 1); auto modpow = [&](long long a, long long e) { long long r = 1; while (e) { if (e & 1) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return r; }; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = int(1LL * fac[i - 1] * i % MOD); ifac[0] = 1; ifac[n] = int(modpow(fac[n], MOD - 2)); for (int i = n - 1; i >= 1; i--) ifac[i] = int(1LL * ifac[i + 1] * (i + 1) % MOD); auto C = [&](int N, int K) -> int { if (K < 0 || K > N) return 0; return int(1LL * fac[N] * ifac[K] % MOD * ifac[N - K] % MOD); }; long long ans = 1; vector dep(n + 1, 0); function(int)> dfs = [&](int u) -> vector { vector cnt(dep[u] + 2, 0); for (int v : g[u]) { dep[v] = dep[u] + 1; vector cv = dfs(v); if ((int)cnt.size() < (int)cv.size()) cnt.resize(cv.size(), 0); for (int i = 0; i < (int)cv.size(); i++) { ans = ans * C(cnt[i] + cv[i], cnt[i]) % MOD; cnt[i] += cv[i]; } } int au = A[u]; if (au > dep[u]) return vector{-1}; vector nextCnt; nextCnt.reserve(max(0, (int)cnt.size() - 1)); for (int i = 0; i < au; i++) nextCnt.push_back(cnt[i]); int valA = (au < (int)cnt.size() ? cnt[au] : 0); int valA1 = (au + 1 < (int)cnt.size() ? cnt[au + 1] : 0); nextCnt.push_back(valA + valA1 + 1); for (int i = au + 2; i < (int)cnt.size(); i++) nextCnt.push_back(cnt[i]); return nextCnt; }; vector res = dfs(1); if (!res.empty() && res[0] == -1) return 0; if ((int)res.size() != 1) return 0; return int(ans % MOD); } int solve2(int &n, vector &fa, vector &a) { const int MOD = 998244353; const int MASK = 0x40000000; auto depthOf = [&](int u) -> int { int d = 0; while (u != 1) { u = fa[u - 2]; d++; } return d; }; for (int u = 1; u <= n; u++) { int au = a[u - 1]; int du = depthOf(u); if (au > du) return 0; } auto countPlacedAncestors = [&](int u) -> int { int c = 0; while (u != 1) { u = fa[u - 2]; if (a[u - 1] & MASK) c++; } return c; }; long long ans = 0; function dfs = [&](int placed) { if (placed == n) { ans++; if (ans >= MOD) ans -= MOD; return; } for (int u = 1; u <= n; u++) { if ((a[u - 1] & MASK) == 0) { int need = a[u - 1]; int have = countPlacedAncestors(u); if (have == need) { a[u - 1] ^= MASK; dfs(placed + 1); a[u - 1] ^= MASK; } } } }; dfs(0); return int(ans % MOD); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector fa(n - 1); for (int i = 0; i < n - 1; i++) cin >> fa[i]; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, fa, a); // output cout << result << ""\n""; return 0; }","dp,graph,math",hard 124,"# Problem Statement Given an array $a$ consisting of $n$ elements, find the maximum possible sum the array can have after performing the following operation **any number of times**: - Choose $2$ **adjacent** elements and flip both of their signs. In other words choose an index $i$ such that $1 \leq i \leq n - 1$ and assign $a_i = -a_i$ and $a_{i+1} = -a_{i+1}$. Note that the answer may be large, so use a 64-bit integer type. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` Where: - `n` is the length of the array. - `a` is an array of length $n$. - The function should return a 64-bit integer representing the maximum sum of the array after performing the above operation any number of times. # Example 1 - Input: n = 3 a = [-1, -1, -1] - Output: 1 # Constraints - $2 \leq n \leq @data$ - $-10^9 \leq a_i \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { long long sum = 0; int neg = 0; for (int i = 0; i < n; i++) { if (a[i] < 0) { neg++; a[i] = -a[i]; } sum += a[i]; } if (neg % 2 == 1) { int mn = *min_element(a.begin(), a.end()); sum -= 2 * mn; } return sum; } long long solve2(int &n, vector &a) { if (n <= 1) { long long s = 0; for (int i = 0; i < n; ++i) s += a[i]; return s; } if (n - 1 <= 60) { unsigned long long limit = 1ULL << (n - 1); long long best = LLONG_MIN; for (unsigned long long mask = 0; mask < limit; ++mask) { long long s = 0; int prev = 0; for (int i = 0; i < n; ++i) { int xi = (i < n - 1) ? int((mask >> i) & 1ULL) : 0; int pi = prev ^ xi; s += pi ? -(long long)a[i] : (long long)a[i]; prev = xi; } if (s > best) best = s; } return best; } long long sum = 0; long long mn = LLONG_MAX; int neg = 0; for (int i = 0; i < n; i++) { long long v = a[i]; if (v < 0) { neg++; v = -v; } sum += v; if (v < mn) mn = v; } if (neg % 2 == 1) sum -= 2 * mn; return sum; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,greedy,sort",medium 125,"You are given a string s. You can perform the following process on s any number of times: Choose an index i in the string such that there is at least one character to the left of index i that is equal to s[i], and at least one character to the right that is also equal to s[i]. Delete the closest character to the left of index i that is equal to s[i]. Delete the closest character to the right of index i that is equal to s[i]. Return the minimum length of the final string s that you can achieve. solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""abaacbcbb"" Output: 5 Example 2: Input: s = ""aa"" Output: 2 Constraints: 1 <= s.length <= @data s consists only of lowercase English letters Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { vector charFrequency(26, 0); int totalLength = 0; for (char currentChar : s) { charFrequency[currentChar - 'a']++; } for (int frequency : charFrequency) { if (frequency == 0) continue; if (frequency % 2 == 0) { totalLength += 2; } else { totalLength += 1; } } return totalLength; } int solve2(string s) { while (true) { bool changed = false; for (int i = 0; i < (int)s.size(); ++i) { char c = s[i]; int L = i - 1; while (L >= 0 && s[L] != c) --L; if (L < 0) continue; int R = i + 1; while (R < (int)s.size() && s[R] != c) ++R; if (R >= (int)s.size()) continue; s.erase(R, 1); s.erase(L, 1); changed = true; break; } if (!changed) break; } return (int)s.size(); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string str; cin>>str; // solve Solution solution; auto result = solution.solve(str); // output cout << result << ""\n""; // for(auto it:result) cout< &a) { // write your code here } }; ``` Where: - `n` is an integer representing the size of the array. - `a` is a vector of integers, representing the given array. - The function should return an integer, representing the minimum number of operations required to make the product divisible by $2^n$, or $-1$ if it is not possible. # Example 1: - Input: n = 2 a = [3, 2] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a_i \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int cur = 0; for (int i = 0; i < n; i++) { int x = a[i]; cur += __builtin_ctz(x); } int cnt[20]{}; for (int i = 1; i <= n; i++) cnt[__builtin_ctz(i)]++; int ans = 0; for (int i = 19; i >= 0; i--) { while (cur < n && cnt[i]) { cur += i; cnt[i]--; ans++; } } if (cur < n) ans = -1; return ans; } int solve2(int &n, vector &a) { long long cur = 0; for (int i = 0; i < n; i++) cur += __builtin_ctz(a[i]); if (cur >= n) return 0; int ans = 0; for (int k = 30; k >= 1 && cur < n; --k) { for (int idx = n; idx >= 1 && cur < n; --idx) { if (__builtin_ctz(idx) == k) { cur += k; ans++; } } } if (cur < n) return -1; return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","math,greedy,sort",medium 127,"In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root ""help"" is followed by the word ""ful"", we can form a derivative ""helpful"". Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length. Return the sentence after the replacement. solution main function ```cpp class Solution { public: string solve(vector& dictionary, string sentence) { // write your code here } }; ``` Example 1: Input: dictionary = [""cat"",""bat"",""rat""], sentence = ""the cattle was rattled by the battery"" Output: ""the cat was rat by the bat"" Example 2: Input: dictionary = [""a"",""b"",""c""], sentence = ""aadsfasf absbs bbab cadsfafs"" Output: ""a a b c"" Constraints: 1 <= dictionary.length <= @data 1 <= dictionary[i].length <= 100 dictionary[i] consists of only lower-case letters. 1 <= sentence.length <= 10^6 sentence consists of only lower-case letters and spaces. The number of words in sentence is in the range [1, 1000] The length of each word in sentence is in the range [1, 1000] Every two consecutive words in sentence will be separated by exactly one space. sentence does not have leading or trailing spaces. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[3200, 1600, 800], [25600, 12800, 6400], [204800, 102400, 51200]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: struct Trie { unordered_map children; }; string solve1(vector& dictionary, string sentence) { Trie *trie = new Trie(); for (auto &word : dictionary) { Trie *cur = trie; for (char &c: word) { if (!cur->children.count(c)) { cur->children[c] = new Trie(); } cur = cur->children[c]; } cur->children['#'] = new Trie(); } vector words = split(sentence, ' '); for (auto &word : words) { word = findRoot(word, trie); } string ans; for (int i = 0; i < words.size() - 1; i++) { ans.append(words[i]); ans.append("" ""); } ans.append(words.back()); return ans; } vector split(string &str, char ch) { int pos = 0; int start = 0; vector ret; while (pos < str.size()) { while (pos < str.size() && str[pos] == ch) { pos++; } start = pos; while (pos < str.size() && str[pos] != ch) { pos++; } if (start < str.size()) { ret.emplace_back(str.substr(start, pos - start)); } } return ret; } string findRoot(string &word, Trie *trie) { string root; Trie *cur = trie; for (char &c : word) { if (cur->children.count('#')) { return root; } if (!cur->children.count(c)) { return word; } root.push_back(c); cur = cur->children[c]; } return root; } string solve2(vector& dictionary, string sentence) { string ans; ans.reserve(sentence.size()); size_t pos = 0; size_t n = sentence.size(); while (pos < n) { size_t start = pos; while (pos < n && sentence[pos] != ' ') pos++; size_t end = pos; size_t bestLen = SIZE_MAX; int bestIdx = -1; size_t wordLen = end - start; for (size_t i = 0; i < dictionary.size(); ++i) { const string& root = dictionary[i]; size_t rl = root.size(); if (rl > wordLen) continue; size_t k = 0; while (k < rl && sentence[start + k] == root[k]) ++k; if (k == rl) { if (rl < bestLen) { bestLen = rl; bestIdx = (int)i; } } } if (bestIdx != -1) { ans.append(dictionary[bestIdx]); } else { ans.append(sentence, start, wordLen); } if (pos < n) { ans.push_back(' '); pos++; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector words; string text; for(int i=1;i<=n;i++) { string s; cin>>s; words.push_back(s); } for(int i=1;i<=m;i++) { string s; cin>>s; text+=s; if(i!=m) text+="" ""; } // solve Solution solution; auto result = solution.solve(words,text); // output cout<& nums1, vector& nums2) { } }; ``` Example 1: Input: nums1 = [1,2,3], nums2 = [2,4] Output: 2 Example 2: Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5] Output: 2 Constraints: 1 <= nums1.length, nums2.length <= @data 1 <= nums1[i], nums2[j] <= 10^9 Both nums1 and nums2 are sorted in non-decreasing order. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve(vector& nums1, vector& nums2) { if (nums1.size() > nums2.size()) { return solve(nums2, nums1); } for (int num : nums1) { if (binarySearch(num, nums2)) { return num; } } return -1; } private: bool binarySearch(int target, vector& nums) { int left = 0; int right = nums.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] > target) { right = mid - 1; } else if (nums[mid] < target) { left = mid + 1; } else { return true; } } return false; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; vector a,b; cin>>n>>m; for(int i=1,x;i<=n;i++) { cin>>x; a.push_back(x); } for(int i=1,x;i<=m;i++) { cin>>x; b.push_back(x); } sort(a.begin(),a.end()); sort(b.begin(),b.end()); // solve Solution solution; auto result = solution.solve(a,b); // output cout< &a) { // write your code here } }; ``` where: - return ""YES"" if there is a sequence of operations that results in the only remaining element of the list being equal to $k$, otherwise return ""NO"". # Example 1: - Input: n = 4, k = 5 a = [4, 2, 2, 7] - Output: YES # Constraints: - $2 \leq n \leq @data$ - $1 \leq k \leq 10^9$ - $-10^9 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, int &k, vector &a) { sort(a.begin(), a.end()); bool ok = false; for (int i = 0; i < n; i++) { int x = a[i] + k; auto it = lower_bound(a.begin(), a.end(), x); if (it != a.end() && (*it) == x) { ok = true; break; } } return (ok ? ""YES"" : ""NO""); } string solve2(int &n, int &k, vector &a) { long long kk = (long long)k; for (int i = 0; i < n; i++) { int ai = a[i]; for (int j = 0; j < n; j++) { if (j == i) continue; long long diff = (long long)a[j] - (long long)ai; if (diff == kk) { return ""YES""; } } } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, k, a); // output cout << result << ""\n""; return 0; }","data_structures,greedy,math,two_pointers",hard 130,"# Problem Statement There is a row of $n$ towers with heights $a_1, a_2, \dots, a_n$. If you look at this row from the left, you see all towers that are strictly higher than all the towers before them. Similarly, if you look from the right, you see all towers that are strictly higher than all towers after them. Let $L(a)$ be the set of heights you see from the left, and $R(a)$ be the set of heights you see from the right, when the sequence of heights is $a$. You are to count the number of subsequences $a'$ of $a$ such that $L(a)=L(a')$ and $R(a)=R(a')$. Since the answer can be large, output it modulo $998244353$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: length of the array - `a`: array of tower heights - return: the number of valid subsequences modulo 998244353 # Example: - Input: ``` n = 9 a = [3, 5, 5, 7, 4, 6, 7, 2, 4] ``` - Output: ``` 51 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 200, 80], [6400, 1600, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, vector &a) { vector leftMax; { int last = 0; for (int i = 0; i < n; ++i) { if (a[i] > last) { leftMax.push_back(a[i]); last = a[i]; } } } vector rightMax; { int last = 0; for (int i = n - 1; i >= 0; --i) { if (a[i] > last) { rightMax.push_back(a[i]); last = a[i]; } } } struct SegmentTree { int size; vector val, tag; void init(int n) { size = n; val.assign(4 * max(1, n), 0); tag.assign(4 * max(1, n), 1); } void pushdown(int p) { int cur = tag[p]; if (cur != 1) { tag[p << 1] = 1ll * tag[p << 1] * cur % 998244353; tag[p << 1 | 1] = 1ll * tag[p << 1 | 1] * cur % 998244353; val[p << 1] = 1ll * val[p << 1] * cur % 998244353; val[p << 1 | 1] = 1ll * val[p << 1 | 1] * cur % 998244353; tag[p] = 1; } } void pushup(int p) { val[p] = (val[p << 1] + val[p << 1 | 1]) % 998244353; } void rangeMul(int L, int R, int p, int l, int r, int mul) { if (L > R) return; if (L <= l && r <= R) { val[p] = 1ll * val[p] * mul % 998244353; tag[p] = 1ll * tag[p] * mul % 998244353; return; } pushdown(p); int mid = (l + r) >> 1; if (L <= mid) rangeMul(L, R, p << 1, l, mid, mul); if (R > mid) rangeMul(L, R, p << 1 | 1, mid + 1, r, mul); pushup(p); } void pointAdd(int idx, int v, int p, int l, int r) { if (l == r) { val[p] += v; if (val[p] >= 998244353) val[p] -= 998244353; return; } pushdown(p); int mid = (l + r) >> 1; if (idx <= mid) pointAdd(idx, v, p << 1, l, mid); else pointAdd(idx, v, p << 1 | 1, mid + 1, r); pushup(p); } int pointQuery(int idx, int p, int l, int r) { if (l == r) return val[p]; pushdown(p); int mid = (l + r) >> 1; if (idx <= mid) return pointQuery(idx, p << 1, l, mid); else return pointQuery(idx, p << 1 | 1, mid + 1, r); } }; vector dpL(n, 0); { int m = (int)leftMax.size(); SegmentTree seg; seg.init(m); for (int i = 0; i < n; ++i) { int pos = int(lower_bound(leftMax.begin(), leftMax.end(), a[i]) - leftMax.begin()); if (pos < m && leftMax[pos] == a[i]) { int val = (pos == 0) ? 1 : seg.pointQuery(pos - 1, 1, 0, m - 1); dpL[i] = val; if (pos <= m - 1) seg.rangeMul(pos, m - 1, 1, 0, m - 1, 2); if (m > 0) seg.pointAdd(pos, dpL[i], 1, 0, m - 1); } else { if (pos <= m - 1) seg.rangeMul(pos, m - 1, 1, 0, m - 1, 2); } } } vector dpR(n, 0); { int m = (int)rightMax.size(); SegmentTree seg; seg.init(m); for (int i = n - 1; i >= 0; --i) { int pos = int(lower_bound(rightMax.begin(), rightMax.end(), a[i]) - rightMax.begin()); if (pos < m && rightMax[pos] == a[i]) { int val = (pos == 0) ? 1 : seg.pointQuery(pos - 1, 1, 0, m - 1); dpR[i] = val; if (pos <= m - 1) seg.rangeMul(pos, m - 1, 1, 0, m - 1, 2); if (m > 0) seg.pointAdd(pos, dpR[i], 1, 0, m - 1); } else { if (pos <= m - 1) seg.rangeMul(pos, m - 1, 1, 0, m - 1, 2); } } } vector pow2(n + 1, 1), invpow2(n + 1, 1); for (int i = 1; i <= n; ++i) pow2[i] = (pow2[i - 1] << 1) % 998244353; int inv2 = (998244353 + 1) / 2; for (int i = 1; i <= n; ++i) invpow2[i] = 1ll * invpow2[i - 1] * inv2 % 998244353; int mx = 0; for (int x : a) mx = max(mx, x); vector> pack; int sum = 0; for (int i = 0; i < n; ++i) { if (a[i] == mx) { int Lp = 1ll * dpL[i] * invpow2[i] % 998244353; int Rp = 1ll * dpR[i] * pow2[i] % 998244353; pack.push_back({Lp, Rp}); sum += Rp; if (sum >= 998244353) sum -= 998244353; } } int ans = 0; for (auto &e : pack) { int Lv = e[0], Rv = e[1]; ans = (ans + 1ll * Lv * Rv) % 998244353; sum -= Rv; if (sum < 0) sum += 998244353; ans = (ans + 1ll * Lv * sum % 998244353 * inv2) % 998244353; } if (ans < 0) ans += 998244353; return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","data_structures,dp",hard 131,"There is a row of $N$coins on the table, and each coin is heads up. Now to flip all the coins tails up, the rule is that you can flip any $N- $1 coin at a time (heads up are flipped tails up and vice versa). Find the shortest sequence of operations (turning each flip of $N-1 coin into one operation). solution main function ```cpp class Solution { public: pair< int,vector > solve(int n) { // write your code here } }; ``` Pass in parameters: An even natural number $n$. Return parameters: An integer represents the minimum number of operations required. A vector array that stores the state of the coins on the table after each operation (a row containing $N$integers $0$or $1$, representing the state of each coin, $0$representing heads up and $1$representing tails up). The output of redundant Spaces is not allowed. In cases where there are multiple operation options, only the lexicographic order of the operation needs to output a minimum of one. The lexicographic order of operations means that for each position in an operation, $1$means flip and $0$means no flip. But what you need to output is the state after each operation, $0$means heads up, $1$means tails up. Example 1: Input: n=4 Output: (4,[""0111"", ""1100"", ""0001"", ""1111""]) Constraints: 0 using namespace std; #include using namespace std; class Solution { public: pair< int,vector > solve1(int n) { vector ans; for (int i=1;i<=n;i++){ string s; for (int j=1;j<=i;j++) s.push_back(48|~i&1); for (int j=i+1;j<=n;j++) s.push_back(48|i&1); ans.push_back(s); } return {n,ans}; } pair> solve2(int n) { vector ans; ans.reserve(n); for (int t = 1; t <= n; ++t) { char first = (t & 1) ? '0' : '1'; char second = (t & 1) ? '1' : '0'; string s; s.reserve(n); for (int j = 1; j <= n; ++j) s.push_back(j <= t ? first : second); ans.push_back(move(s)); } return {n, ans}; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< &w) { // write your code here } }; ``` Pass in parameters: The two integers are $n and m$, respectively, indicating the number of people receiving water and the number of taps. 1 array, $n$integers $w_1,w_2,\ldots,w_n$, separated by a space between each two integers, $w_i$indicates the amount of water received by the student with $i$ Return parameters: An integer representing the total time required to connect the water. Example 1: Input: n=5,m=3,w=[4, 4, 1, 2, 1] Output: 4 Example 2: Input: n=8,m=4,w=[23, 71, 87, 32, 70, 93, 80, 76] Output: 163 Constraints: 0 using namespace std; class Solution { public: int solve1(int n, int m, vector &w) { w.insert(w.begin(), 0); int t = m + 1; int ans = 0; while (t <= n + m) { for (int i = 1; i <= m; i++) { w[i]--; if (w[i] == 0) { if (t <= n) w[i] = w[t]; t++; } } ans++; } return ans; } int solve2(int n, int m, vector &w) { if (n <= 0 || m <= 0) return 0; if (m > n) m = n; long long ans = 0; int t = m; while (true) { bool done = (t >= n); for (int i = 0; i < m; ++i) { if (w[i] > 0) w[i]--; if (w[i] == 0) { if (t < n) { w[i] = w[t]; ++t; done = false; } } if (w[i] > 0) done = false; } ans++; if (done) break; } if (ans > INT_MAX) return INT_MAX; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m;cin>>n>>m; vector w; for(int i=1,x;i<=n;i++) { cin>>x; w.push_back(x); } // solve Solution solution; auto result = solution.solve(n,m,w); // output cout << result << ""\n""; return 0; }",greedy,medium 133,"Xuan Xuan and Kai Kai are playing a game called ""Dragon Tiger Fight"", the game board is a line segment, there are $n$barracks on the line segment (numbered $1 \sim n$from left to right), and the adjacent numbered barracks are separated by $1$cm, that is, the board is a line segment with a length of $n-1$cm. There are $c_i$engineers in the $i$barracks. Xuan Xuan is on the left, representing ""dragon""; Kai Kai is on the right, representing ""Tiger"". They use barracks $m$as a demarcation line, the sappers on the left belong to the Dragon force, the sappers on the right belong to the tiger force, and the sappers in barracks $m$are very tangled, they don't belong to either side. The momentum of a barracks is: the number of engineers in the barracks $\times $the distance between the barracks and the $m$barracks; The power of a party participating in the game is defined as the sum of the momentum of all the barracks belonging to that party. During the game, at some point, a total of $s_1$engineers suddenly appeared in the $p_1$barracks. As a friend of Xuan Xuan and Kai Kai, you know that if the gap between the two sides is too great, Xuan Xuan and Kai Kai are not willing to continue to play. In order for the game to continue, you need to select a barracks $p_2$and send all your $s_2$engineers to the barracks $p_2$, making the momentum gap between the two sides as small as possible. Note: The sengineer you hold in the barracks has the same power as the other Sengineers in that barracks (if you fall in the $m$barracks, you don't belong to any power). solution main function ```cpp class Solution { public: long long solve(long long n, long long m, long long p1, long long s1, long long s2, vector &c) { // write your code here } }; ``` Pass in parameters: 5 integers: $n,m,p_1,s_1,s_2$. 1 array, c contains $n$positive integers, the first positive integer represents the number of engineers in the barracks numbered $i$at the beginning of $c_i$. Return parameters: An integer $p_2$indicates the barracks number you selected. If multiple numbers are optimal, the smallest number is used. Example 1: Input: n=6,m=4,p1=6,s1=5,s2=2,c=[2, 3, 2, 3, 2, 3] Output: 2 Example 2: Input: n = 6, m = 5, p = 4, s1 = 1, s2 = 1, c = [1, 1, 1, 1, 1, 16] Output: 1 Constraints: 1 using namespace std; #include using namespace std; class Solution { public: long long solve1(long long n, long long m, long long p1, long long s1, long long s2, vector &c) { c.insert(c.begin(), 0); long long gap = 0; double where; long long ans; c[p1] += s1; for (long long i = 1; i <= n; i++) gap += (m - i) * c[i]; double dgap = gap; where = m + dgap / s2; if (where >= n) ans = n; else if (where <= 1) ans = 1; else { long long iwhere = where; if (iwhere == where) ans = iwhere; else { long long ans1 = abs(gap + (m - iwhere) * s2); long long ans2 = abs(gap + (m - iwhere - 1) * s2); ans = ans1 <= ans2 ? iwhere : iwhere + 1; } } return ans; } long long solve2(long long n, long long m, long long p1, long long s1, long long s2, vector &c) { c[p1 - 1] += s1; long long gap = 0; for (long long i = 1; i <= n; ++i) gap += (m - i) * c[i - 1]; long long bestPos = 1; long long bestVal = llabs(gap + (m - 1) * s2); for (long long p2 = 2; p2 <= n; ++p2) { long long cur = llabs(gap + (m - p2) * s2); if (cur < bestVal) { bestVal = cur; bestPos = p2; } } return bestPos; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input long long n,m,p1,s1,s2; cin>>n; vector c; for(long long i=1,x;i<=n;i++) { cin>>x; c.push_back(x); } cin>>m>>p1>>s1>>s2; // solve Solution solution; auto result = solution.solve(n,m,p1,s1,s2,c); // output cout << result << ""\n""; return 0; }",greedy,hard 134,"Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties. Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins. solution main function ```cpp class Solution { public: bool solve(vector& piles) { } }; ``` Example 1: Input: piles = [5,3,4,5] Output: 1 Example 2: Input: piles = [3,7,2,3] Output: 1 Constraints: 2 <= piles.length <= @data piles.length is even. 1 <= piles[i] <= 500 sum(piles[i]) is odd. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve1(vector& piles) { return true; } bool solve2(vector& piles) { long long evenSum = 0, oddSum = 0; for (size_t i = 0; i < piles.size(); ++i) { if ((i & 1) == 0) evenSum += piles[i]; else oddSum += piles[i]; } long long alice = evenSum >= oddSum ? evenSum : oddSum; long long bob = evenSum + oddSum - alice; return alice > bob; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector num; cin>>n; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; int result = solution.solve(num); // output cout< solve(int &n, vector &a) { // write your code here } }; ``` Where: - `n` is an integer representing the size of the array. - `a` is a vector of integers, representing the given non-decreasing array. - The function should return a vector of integers, where the k-th element represents the cost of the subsequence $[a_1, a_2, \ldots, a_k]$. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: [1, 1, 2] # Constraints: - $1 \leq n \leq @data$ - $1 \leq a_i \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 160, 80], [6400, 1280, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve(int &n, vector &a) { vector ans; for (int i = 0, k = 0; i < n; i++) { while (k <= i && a[i - k] >= k + 1) k += 1; ans.push_back(k); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output for (auto x : result) cout << x << "" ""; cout << ""\n""; return 0; }","two_pointers,binary,math",hard 136,"In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. solution main function ```cpp class Solution { public: vector solve(int label) { } }; ``` Example 1: Input: label = 14 Output: [1,3,4,14] Example 2: Input: label = 26 Output: [1,2,6,10,26] Constraints: 1 <= label <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(int label) { vectorans; ans.push_back(label); int level = log2(label); if(label==1) return ans; while(level>0) { int parent = label/2; int start = pow(2,level-1); int end = 2*start-1; int complement = start+end-parent; ans.push_back(complement); label = complement; level--; } reverse(ans.begin(),ans.end()); return ans; } vector solve2(int label) { int n = 0; int t = label; while (t > 0) { t >>= 1; n++; } vector ans(n); int i = n - 1; while (true) { ans[i] = label; if (label == 1) break; int level = i + 1; long long start = 1LL << (level - 1); long long end = (start << 1) - 1; long long sum = start + end; label = (int)((sum - label) / 2); i--; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output for(auto it:result) cout<> solve(int rows, int cols, int rCenter, int cCenter) { } }; ``` Example 1: Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0 Output: [[0,0],[0,1]] Example 2: Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1 Output: [[0,1],[0,0],[1,1],[1,0]] Constraints: 1 <= rows, cols <= @data 0 <= rCenter < rows 0 <= cCenter < cols Time limit: @time_limit ms Memory limit: @memory_limit KB","[20, 50, 100]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector> solve(int rows, int cols, int rCenter, int cCenter) { vector> res; vector>> v; for(int i=0;i using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int a,c,b,d; cin>>a>>b>>c>>d; // solve Solution solution; auto result = solution.solve(a,b,c,d); // output // for(auto it:result) cout< using namespace std; class Solution { public: string solve(int &n, string &s, string &t) { for (int i = 0; i < n; i++) { if (s[i] == '0' && t[i] == '1') return ""NO""; if (s[i] == '1') return ""YES""; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s, t; cin >> s >> t; // solve Solution solution; auto result = solution.solve(n, s, t); // output cout << result << ""\n""; return 0; }","bit_manipulation,constructive_algorithms",hard 139,"Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses. solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""(1)+((2))+(((3)))"" Output: 3 Example 2: Input: s = ""()(())((()()))"" Output: 3 Constraints: 1 <= s.length <= @data s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'. It is guaranteed that parentheses expression s is a VPS. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { int ans = 0; int openBrackets = 0; for (char c : s) { if (c == '(') { openBrackets++; } else if (c == ')') { openBrackets--; } ans = max(ans, openBrackets); } return ans; } int solve2(string s) { int n = (int)s.size(); int ans = 0; for (int i = 0; i < n; ++i) { int depth = 0; int bestPrefix = 0; for (int j = 0; j <= i; ++j) { char c = s[j]; if (c == '(') { depth++; if (depth > bestPrefix) bestPrefix = depth; } else if (c == ')') { depth--; } } if (bestPrefix > ans) ans = bestPrefix; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout< &p) { // write your code here } }; ``` where: - the return value is the minimum number of operations needed to make the permutation simple # Example 1: - Input: n = 5 p = [1, 2, 3, 4, 5] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq p[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 256]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &p) { int ans = 0; vector vis(n); for (int i = 0; i < n; i++) { p[i]--; } for (int i = 0; i < n; i++) { if (vis[i]) continue; int j = i; int len = 0; while (!vis[j]) { vis[j] = true; j = p[j]; len++; } ans += (len - 1) / 2; } return ans; } int solve2(int &n, vector &p) { int ans = 0; for (int i = 0; i < n; i++) { p[i]--; } for (int i = 0; i < n; i++) { if (p[i] < 0) continue; int j = i; int len = 0; while (p[j] >= 0) { int t = p[j]; p[j] = -p[j] - 1; j = t; len++; } ans += (len - 1) / 2; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","data_structures,graph,greedy,search",hard 141,"# Problem Statement Timur initially had a binary string$^{\dagger}$ $s$ (possibly of length $0$). He performed the following operation several (possibly zero) times: - Add $\texttt{0}$ to one end of the string and $\texttt{1}$ to the other end of the string. For example, starting from the string $\texttt{1011}$, you can obtain either $\color{red}{\texttt{0}}\texttt{1011}\color{red}{\texttt{1}}$ or $\color{red}{\texttt{1}}\texttt{1011}\color{red}{\texttt{0}}$. You are given Timur's final string. What is the length of the **shortest** possible string he could have started with? $^{\dagger}$ A binary string is a string (possibly the empty string) whose characters are either $\texttt{0}$ or $\texttt{1}$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, string &s) { // write your code here } }; ``` where: - return a single nonnegative integer — the shortest possible length of Timur's original string. Note that Timur's original string could have been empty, in which case you should return 0 . # Example 1: - Input: n = 3 s = ""100"" - Output: 1 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, string &s) { int i = 0, j = n; while (i + 2 <= j && s[i] != s[j - 1]) i++, j--; return j - i; } int solve2(int &n, string &s) { int l = 0, r = n - 1; int len = n; while (l < r && s[l] != s[r]) { ++l; --r; len -= 2; } return len; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }",two_pointers,medium 142,"# Problem Statement Alice and Bob are playing a game. There is a list of $n$ booleans, each of which is either true or false, given as a binary string $^{\text{∗}}$ of length $n$ (where $\texttt{1}$ represents true, and $\texttt{0}$ represents false). Initially, there are no operators between the booleans. Alice and Bob will take alternate turns placing and or or between the booleans, with Alice going first. Thus, the game will consist of $n-1$ turns since there are $n$ booleans. Alice aims for the final statement to evaluate to true, while Bob aims for it to evaluate to false. Given the list of boolean values, determine whether Alice will win if both players play optimally. To evaluate the final expression, repeatedly perform the following steps until the statement consists of a single true or false: - If the statement contains an and operator, choose any one and replace the subexpression surrounding it with its evaluation. - Otherwise, the statement contains an or operator. Choose any one and replace the subexpression surrounding the or with its evaluation. For example, the expression true or false and false is evaluated as true or (false and false) $=$ true or false $=$ true. It can be shown that the result of any compound statement is unique. $^{\text{∗}}$A binary string is a string that only consists of characters $\texttt{0}$ and $\texttt{1}$ The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, string &s) { // write your code here } }; ``` where: - return ""YES"" (without quotes) if Alice wins, and ""NO"" (without quotes) otherwise. # Example 1: - Input: n = 2, s = ""11"" - Output: YES # Constraints: - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 128]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, string &s) { s = '1' + s + '1'; if (s.find(""11"") != -1) return ""YES""; else return ""NO""; } string solve2(int &n, string &s) { if (n <= 0) return ""NO""; if (s.front() == '1' || s.back() == '1') return ""YES""; for (int i = 0; i + 1 < n; ++i) { if (s[i] == '1' && s[i + 1] == '1') return ""YES""; } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }",game,medium 143,"Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that: nums[a] + nums[b] + nums[c] == nums[d], and a < b < c < d solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [1,2,3,6] Output: 1 Example 2: Input: nums = [3,3,6,4,5] Output: 0 Constraints: 4 <= nums.length <= @data 1 <= nums[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB","[30, 40, 50]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int cnt=0; int n=nums.size(); for(int i=0;i& nums) { int cnt = 0; int n = (int)nums.size(); for (int d = 3; d < n; ++d) { for (int a = 0; a <= d - 3; ++a) { long long sa = nums[a]; for (int b = a + 1; b <= d - 2; ++b) { long long sab = sa + nums[b]; for (int c = b + 1; c <= d - 1; ++c) { if (sab + nums[c] == nums[d]) { ++cnt; } } } } } return cnt; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout<& words) { } }; ``` Example 1: Input: words = [""abc"",""car"",""ada"",""racecar"",""cool""] Output: ""ada"" Example 2: Input: words = [""notapalindrome"",""racecar""] Output: ""racecar"" Constraints: 1 <= words.length <= @data 1 <= words[i].length <= @data words[i] consists only of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool isPalindrome(string& s) { int start = 0; int end = s.size() - 1; while (start <= end) { if (s[start] != s[end]) { return false; } start++; end--; } return true; } string solve1(vector& words) { for (string s : words) { if (isPalindrome(s)) { return s; } } return """"; } string solve2(vector& words) { for (size_t i = 0; i < words.size(); ++i) { string& s = words[i]; int l = 0, r = (int)s.size() - 1; bool ok = true; while (l < r) { if (s[l] != s[r]) { ok = false; break; } ++l; --r; } if (ok) return s; } return """"; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector s; cin>>n; for(int i=1;i<=n;i++) { string t; cin>>t; s.push_back(t); } // solve Solution solution; auto result = solution.solve(s); // output cout<& nums1, vector& nums2) { } }; ``` Example 1: Input: nums1 = [2,1,3], nums2 = [10,2,5,0] Output: 13 Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 0 Constraints: 1 <= nums1.length, nums2.length <= @data 0 <= nums1[i], nums2[j] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums1, vector& nums2) { int xor1 = 0; int xor2 = 0; int len1 = nums1.size(); int len2 = nums2.size(); if (len2 % 2 != 0) { for (int num : nums1) { xor1 ^= num; } } if (len1 % 2 != 0) { for (int num : nums2) { xor2 ^= num; } } return xor1 ^ xor2; } int solve2(vector& nums1, vector& nums2) { int ans = 0; size_t n = nums1.size(); size_t m = nums2.size(); for (size_t i = 0; i < n; ++i) { int a = nums1[i]; for (size_t j = 0; j < m; ++j) { ans ^= (a ^ nums2[j]); } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; vector a,b; cin>>n>>m; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } for(int i=1;i<=m;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output cout<& nums) { } }; ``` Example 1: Input: nums = [2,3,-1,8,4] Output: 3 Example 2: Input: nums = [1,-1,4] Output: 2 Constraints: 1 <= nums.length <= @data -1000 <= nums[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int len = nums.size(); if (len == 1) return 0; if (len == 0) return -1; int leftsum = 0; int totalsum = accumulate(nums.begin(),nums.end(),0); for (int i = 0; i< len; i++){ int rightsum = totalsum - leftsum - nums[i]; if (rightsum == leftsum) return i; leftsum += nums[i]; } return -1; } int solve2(vector& nums) { int n = (int)nums.size(); if (n == 0) return -1; if (n == 1) return 0; for (int i = 0; i < n; ++i) { long long left = 0; for (int j = 0; j < i; ++j) left += nums[j]; long long right = 0; for (int k = i + 1; k < n; ++k) right += nums[k]; if (left == right) return i; } return -1; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n;cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< solve(vector& arr) { } }; ``` Example 1: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] Example 2: Input: arr = [400] Output: [-1] Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector& arr) { int n = arr.size(); int mx = -1; int p; for(int i = n-1; i>=0; i--){ p = arr[i]; arr[i] = mx; if(p>mx){ mx = p; } } return arr; } vector solve2(vector& arr) { int n = arr.size(); for(int i = 0; i < n; ++i){ int mx = -1; for(int j = i + 1; j < n; ++j){ if(arr[j] > mx) mx = arr[j]; } arr[i] = mx; } return arr; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int numBottles, int numExchange) { int b = numBottles, e= numExchange; return b + (((-2*e) + 3 + sqrt(4*e*e + 8*b - 12*e + 1)) / 2); } int solve2(int numBottles, int numExchange) { long long full = numBottles; long long empty = 0; long long need = numExchange; long long total = 0; while (true) { if (full > 0) { total += full; empty += full; full = 0; } if (empty >= need) { empty -= need; need++; full = 1; } else { break; } } return (int)total; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,d; cin>>n>>d; // solve Solution solution; auto result = solution.solve(n,d); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { int score = 0; for (int i = 0; i < s.size() - 1; ++i) { score += abs(s[i] - s[i + 1]); } return score; } int solve2(string s) { if (s.size() < 2) return 0; long long sum = 0; char prev = s[0]; for (size_t i = 1; i < s.size(); ++i) { int d = int(s[i]) - int(prev); if (d < 0) d = -d; sum += d; prev = s[i]; } return static_cast(sum); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }",string,easy 150,"# Problem Statement A club plans to hold a party and will invite some of its $n$ members. The $n$ members are identified by the numbers $1, 2, \dots, n$. If member $i$ is not invited, the party will gain an unhappiness value of $a_i$. There are $m$ pairs of friends among the $n$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited. However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number. What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even? The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &m, vector &a, vector> &p) { // write your code here } }; ``` where: - `p` represents that p.first and p.second are friends. - return the minimum unhappiness value. # Example 1: - Input: n = 3, m = 1 a = [2, 1, 3] p = [(1, 3)] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $0 \leq m \leq \frac{n(n-1)}{2}$ - $0 \leq a[i] \leq 10^4$ - $1 \leq p[i].first, p[i].second \leq n$ - $p[i].first \neq p[i].second$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 245, 80], [6400, 1960, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &m, vector &a, vector> &p) { int ans = 1E9; if (m % 2 == 0) return 0; vector deg(n); for (int i = 0; i < m; i++) { p[i].first--; p[i].second--; deg[p[i].first]++; deg[p[i].second]++; ans = min(ans, a[p[i].first] + a[p[i].second]); } for (int i = 0; i < n; i++) { if (deg[i] % 2) ans = min(ans, a[i]); } return ans; } int solve2(int &n, int &m, vector &a, vector> &p) { if (m % 2 == 0) return 0; int ans = 1000000000; for (int i = 0; i < m; i++) { int u = p[i].first - 1; int v = p[i].second - 1; int s = a[u] + a[v]; if (s < ans) ans = s; } for (int i = 1; i <= n; i++) { int parity = 0; for (int j = 0; j < m; j++) { int u = p[j].first; int v = p[j].second; if (u == i || v == i) parity ^= 1; } if (parity) { int ai = a[i - 1]; if (ai < ans) ans = ai; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector> p(m); for (int i = 0; i < m; i++) cin >> p[i].first >> p[i].second; // solve Solution solution; auto result = solution.solve(n, m, a, p); // output cout << result << ""\n""; return 0; }",graph,hard 151,"Give an integer N and K transformation rules. Rules: - Change one digit to another. - The right part of the rule cannot be zero. Find out how many different integers can be produced by any number of transformations (0 or more). Only the number of outputs is required. solution main function ```cpp class Solution { public: string solve(string N, int K, vector > &rules) { // write your code here } }; ``` Example 1: Input: N = 234, K = 2, rules = [ [2, 5], [3, 6] ] Output: 4 Constraints: 0 using namespace std; #include using namespace std; class Solution { public: bool tag[10][10]={}; int d[10]={}; int p[1000]={}; string solve(string a, int n, vector > &rules) { string ans; int x,y; for(int i=0;i=0;i--) ans.push_back(p[i]+'0'); return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string N; int K; cin >> N >> K; vector > rules; for (int i = 0; i < K; i++) { int x,y; cin >>x>>y; rules.push_back({x,y}); } // solve Solution solution; auto result = solution.solve(N,K,rules); // output cout << result ; return 0; }",graph,hard 152,"Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: In the beginning, you have the permutation P=[1,2,3,...,m]. For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i]. Return an array containing the result for the given queries. solution main function ```cpp class Solution { public: vector solve(vector& queries, int m) { } }; ``` Example 1: Input: queries = [3,1,2,1], m = 5 Output: [2,1,2,1] Example 2: Input: queries = [4,1,2,2], m = 4 Output: [3,1,2,0] Constraints: 1 <= m <= @data 1 <= queries.length <= m 1 <= queries[i] <= m Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int querySum(vector& BIT, int x) { int sum = 0; for (; x > 0; x -= (x & -x)) { sum += BIT[x]; } return sum; } void update(vector& BIT, int x, const int val) { for (; x < BIT.size(); x += (x & -x)) { BIT[x] += val; } } vector solve1(vector& queries, int m) { if (m == 1) { return {0}; } int n = queries.size(); vector ans, tree(m + n + 1, 0), hash(m + 1); for (int i = 1; i <= m; i++) { hash[i] = n + i; update(tree, n + i, 1); } for (auto q : queries) { ans.push_back(querySum(tree, hash[q] - 1)); update(tree, hash[q], -1); update(tree, n, 1); hash[q] = n--; } return ans; } vector solve2(vector& queries, int m) { int n = (int)queries.size(); vector res; res.reserve(n); for (int i = 0; i < n; ++i) { int q = queries[i]; int last = -1; for (int j = i - 1; j >= 0; --j) { if (queries[j] == q) { last = j; break; } } if (last >= 0) { int cnt = 0; for (int s = i - 1; s > last; --s) { int x = queries[s]; bool seenLater = false; for (int u = s + 1; u <= i - 1; ++u) { if (queries[u] == x) { seenLater = true; break; } } if (!seenLater) ++cnt; } res.push_back(cnt); } else { int distinctTotal = 0; int lessCount = 0; for (int s = 0; s <= i - 1; ++s) { int x = queries[s]; bool seenLater = false; for (int u = s + 1; u <= i - 1; ++u) { if (queries[u] == x) { seenLater = true; break; } } if (!seenLater) { ++distinctTotal; if (x < q) ++lessCount; } } long long pos = (long long)distinctTotal + (long long)q - 1 - (long long)lessCount; res.push_back((int)pos); } } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,m); // output for(auto it:result) cout<>& customers) { } }; ``` Example 1: Input: customers = [[1,2],[2,5],[4,3]] Output: 5.0000 Example 2: Input: customers = [[5,2],[5,4],[10,3],[20,1]] Output: 3.2500 Constraints: 1 <= customers.length <= @data 1 <= arrivali, timei <= 10^4 arrivali <= arrivali+1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: double solve1(vector>& customers) { int nextIdleTime = 0; long long netWaitTime = 0; for (int i = 0; i < customers.size(); i++) { nextIdleTime = max(customers[i][0], nextIdleTime) + customers[i][1]; netWaitTime += nextIdleTime - customers[i][0]; } double averageWaitTime = static_cast(netWaitTime) / customers.size(); return averageWaitTime; } double solve2(vector>& customers) { long long currentTime = 0; long long totalWait = 0; for (size_t i = 0; i < customers.size(); ++i) { long long arrival = customers[i][0]; long long duration = customers[i][1]; if (currentTime < arrival) currentTime = arrival; currentTime += duration; totalWait += currentTime - arrival; } return static_cast(totalWait) / customers.size(); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector > s; for(int i=1;i<=n;i++) { vector temp; int x,y; cin>>x>>y; temp.push_back(x); temp.push_back(y); s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output printf(""%.4lf"",result); // cout << result << ""\n""; // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { long long mod=1e9+7; long long twoC=6; int threeC=6; for(int i=2;i<=n;i++) { long long oldTwo=twoC; long long oldThree=threeC; twoC=(3ll*oldTwo+2ll*oldThree)%mod; threeC=(2ll*oldTwo+2ll*oldThree)%mod; } return (twoC+threeC)%mod; } int solve2(int n) { const long long mod = 1000000007LL; long long two = 6, three = 6; if (n == 1) return (int)((two + three) % mod); long long a = 3, b = 2, c = 2, d = 2; long long e = n - 1; long long v1 = two, v2 = three; while (e > 0) { if (e & 1) { long long nv1 = (a * v1 + b * v2) % mod; long long nv2 = (c * v1 + d * v2) % mod; v1 = nv1; v2 = nv2; } long long na = (a * a + b * c) % mod; long long nb = (a * b + b * d) % mod; long long nc = (c * a + d * c) % mod; long long nd = (c * b + d * d) % mod; a = na; b = nb; c = nc; d = nd; e >>= 1; } return (int)((v1 + v2) % mod); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output // for(auto it:result) cout<& grades) { } }; ``` Example 1: Input: grades = [10,6,12,7,3,5] Output: 3 Example 2: Input: grades = [8,8] Output: 1 Constraints: 1 <= grades.length <= @data 1 <= grades[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& A) { return (int)(sqrt(A.size() * 2 + 0.25) - 0.5); } int solve2(vector& A) { long long n = (long long)A.size(); long long k = 0, need = 1; while (n >= need) { n -= need; ++k; ++need; } return (int)k; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector nums; for(int i=1;i<=n;i++) { int x; cin>>x; nums.push_back(x); } // solve Solution solution; auto result = solution.solve(nums); // output // for(auto it:result) cout< using namespace std; class Solution { public: long long solve1(string &s) { int type = 0, cnt = 0; long long ans = 0; for (int i = 0, j = 0; i < (int)s.size(); i += 1) { while (j < (int)s.size()) { if (s[j] == '?') j += 1; else if (cnt == 0 or type == (s[j] - '0') ^ (j % 2)) { cnt += 1; type = (s[j] - '0') ^ (j % 2); j += 1; } else break; } ans += j - i; if (s[i] != '?') cnt -= 1; } return ans; } long long solve2(string &s) { long long ans = 0; int n = (int)s.size(); for (int l = 0; l < n; ++l) { bool ok0 = true, ok1 = true; for (int r = l; r < n; ++r) { char c = s[r]; if (c != '?') { int parity = (r - l) & 1; char exp0 = parity ? '1' : '0'; char exp1 = parity ? '0' : '1'; if (c != exp0) ok0 = false; if (c != exp1) ok1 = false; } if (ok0 || ok1) ans += 1; else break; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string s; cin >> s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }","search,string,dp,two_pointers",hard 157,"Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. solution main function ```cpp class Solution { public: vector> solve(int n) { } }; ``` Example 1: Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]] Example 2: Input: n = 1 Output: [[1]] Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",1000,"[[2000, 1000, 100], [16000, 8000, 800], [128000, 64000, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int floorMod(int x, int y) { return ((x % y) + y) % y; } vector> solve1(int n) { vector> result(n, vector(n)); int cnt = 1; int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int d = 0; int row = 0; int col = 0; while (cnt <= n * n) { result[row][col] = cnt++; int r = floorMod(row + dir[d][0], n); int c = floorMod(col + dir[d][1], n); if (result[r][c] != 0) d = (d + 1) % 4; row += dir[d][0]; col += dir[d][1]; } return result; } vector> solve2(int n) { vector> result(n, vector(n)); long long total = 1LL * n * n; int top = 0, bottom = n - 1, left = 0, right = n - 1; long long val = 1; while (val <= total) { for (int j = left; j <= right && val <= total; ++j) { result[top][j] = (int)val++; } ++top; for (int i = top; i <= bottom && val <= total; ++i) { result[i][right] = (int)val++; } --right; if (top <= bottom) { for (int j = right; j >= left && val <= total; --j) { result[bottom][j] = (int)val++; } --bottom; } if (left <= right) { for (int i = bottom; i >= top && val <= total; --i) { result[i][left] = (int)val++; } ++left; } } return result; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output // cout << result << ""\n""; // for(auto it:result) cout<& nums) { } }; ``` Example 1: Input: nums = [5,6,2,7,4] Output: 34 Example 2: Input: nums = [4,2,5,9,7,4,8] Output: 64 Constraints: 2 <= nums.length <= @data 1 <= nums[i] <= 10^3 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int biggest = 0; int secondBiggest = 0; int smallest = INT_MAX; int secondSmallest = INT_MAX; for (int num : nums) { if (num > biggest) { secondBiggest = biggest; biggest = num; } else { secondBiggest = max(secondBiggest, num); } if (num < smallest) { secondSmallest = smallest; smallest = num; } else { secondSmallest = min(secondSmallest, num); } } return biggest * secondBiggest - smallest * secondSmallest; } int solve2(vector& nums) { int n = (int)nums.size(); long long best = LLONG_MIN; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { long long p1 = 1LL * nums[i] * nums[j]; for (int k = 0; k < n; ++k) { if (k == i || k == j) continue; for (int l = k + 1; l < n; ++l) { if (l == i || l == j) continue; long long p2 = 1LL * nums[k] * nums[l]; long long diff = p1 - p2; if (diff > best) best = diff; } } } } if (best == LLONG_MIN) return 0; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector num; cin>>n; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout<>& rectangles) { } }; ``` Example 1: Input: rectangles = [[5,8],[3,9],[5,12],[16,5]] Output: 3 Example 2: Input: rectangles = [[2,3],[3,7],[4,3],[3,7]] Output: 3 Constraints: 1 <= rectangles.length <= @data rectangles[i].length == 2 1 <= li, wi <= 10^9 li != wi Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& v){ int maxSqr=0,ans=0; for(int i=0;imaxSqr){ maxSqr=temp; ans=1; } } return ans; } int solve2(vector>& v){ int n = (int)v.size(); int maxSqr = 0; for(int i = 0; i < n; ++i){ int a = v[i][0], b = v[i][1]; int m = a < b ? a : b; if(m > maxSqr) maxSqr = m; } int ans = 0; for(int i = 0; i < n; ++i){ int a = v[i][0], b = v[i][1]; int m = a < b ? a : b; if(m == maxSqr) ++ans; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n;cin>>n; vector > s; for(int i=1,x;i<=n;i++) { vector temp; cin>>x; temp.push_back(x); cin>>x; temp.push_back(x); s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< &w) { // write your code here } }; ``` where: - return: the maximum number of candies Alice and Bob can eat in total while satisfying the condition. # Example 1: - Input: n = 3 w = [10,20,10] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq w[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &w) { int ans = 0; for (int i = 0, j = n - 1, L = 0, R = 0; i <= j;) { L += w[i++]; while (R < L and j >= i) R += w[j--]; if (L == R) ans = max(ans, i + n - j - 1); } return ans; } int solve2(int &n, vector &w) { int ans = 0; long long left_sum = 0; for (int k = 1; k <= n; ++k) { left_sum += (long long)w[k - 1]; long long right_sum = 0; int max_m = n - k; int idx = n - 1; for (int m = 1; m <= max_m; ++m) { right_sum += (long long)w[idx--]; if (right_sum == left_sum) { ans = max(ans, k + m); break; } if (right_sum > left_sum) { break; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector w(n); for (int i = 0; i < n; i++) cin >> w[i]; // solve Solution solution; auto result = solution.solve(n, w); // output cout << result << ""\n""; return 0; }","two_pointers,binary,greedy",medium 161,"A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies. solution main function ```cpp class Solution { public: int solve(vector& cost) { } }; ``` Example 1: Input: cost = [1,2,3] Output: 5 Example 2: Input: cost = [6,5,7,9,2,2] Output: 23 Constraints: 1 <= cost.length <= @data 1 <= cost[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& cost) { sort(cost.begin(),cost.end(),greater()); int sum=0; int count=0; for(int i=0;i& cost) { long long total = 0; int n = (int)cost.size(); while (true) { int i1 = -1; for (int i = 0; i < n; ++i) { if (cost[i] > 0 && (i1 == -1 || cost[i] > cost[i1])) i1 = i; } if (i1 == -1) break; int c1 = cost[i1]; cost[i1] = 0; int i2 = -1; for (int i = 0; i < n; ++i) { if (cost[i] > 0 && (i2 == -1 || cost[i] > cost[i2])) i2 = i; } if (i2 == -1) { total += c1; break; } int c2 = cost[i2]; cost[i2] = 0; total += c1 + c2; int lim = c1 < c2 ? c1 : c2; int i3 = -1; for (int i = 0; i < n; ++i) { int v = cost[i]; if (v > 0 && v <= lim && (i3 == -1 || v > cost[i3])) i3 = i; } if (i3 != -1) cost[i3] = 0; } return (int)total; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n;cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< using namespace std; class Solution { public: int solve1(int &n, string &s) { int i, j, ans; vector vis(26); ans = 0; for (i = 0; i < n; i++) { if (vis[s[i] - 'a']) continue; vis[s[i] - 'a'] = 1; ans += n - i; } return ans; } int solve2(int &n, string &s) { long long ans = 0; int cnt = 0; bool seen[26] = {0}; for (int i = 0; i < n; ++i) { int idx = s[i] - 'a'; if (!seen[idx]) { seen[idx] = true; ++cnt; } ans += cnt; } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","string,dp,data_structures",hard 163,"Given two arrays of integers nums and index. Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. solution main function ```cpp class Solution { public: vector solve(vector& nums, vector& index) { } }; ``` Example 1: Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Example 2: Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] Constraints: 1 <= nums.length, index.length <= @data nums.length == index.length 0 <= nums[i] <= 100 0 <= index[i] <= i Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector& nums, vector& arr) { int n= arr.size(); vectortar; tar.push_back(nums[0]); for(int i = 1; i < n; i++) { tar.insert(tar.begin() + arr[i], nums[i]); } return tar; } vector solve2(vector& nums, vector& arr) { int n = (int)arr.size(); vector tar(n); int len = 0; for (int i = 0; i < n; ++i) { int pos = arr[i]; for (int j = len - 1; j >= pos; --j) { tar[j + 1] = tar[j]; } tar[pos] = nums[i]; ++len; } return tar; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n;cin>>n; vector a,b; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } for(int i=1;i<=n;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return: the maximum sum of the maximum by size alternating subsequence, please use `long long` type for the return value # Example 1: - Input: n = 5 a = [1, 2, 3, -1, -2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $-10^9 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { pair neg, pos; for (int i = 0; i < n; ++i) { if (a[i] < 0) neg = max(neg, make_pair(pos.first + 1, pos.second + a[i])); else pos = max(pos, make_pair(neg.first + 1, neg.second + a[i])); } return max(neg, pos).second; } long long solve2(int &n, vector &a) { long long sum = 0; int i = 0; while (i < n) { int best = a[i]; int s = a[i] > 0 ? 1 : -1; ++i; while (i < n && ((a[i] > 0 ? 1 : -1) == s)) { if (a[i] > best) best = a[i]; ++i; } sum += (long long)best; } return sum; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,greedy,two_pointers",hard 165,"# Problem Statement Let's call a number a binary decimal if it is a positive integer and all digits in its decimal notation are either $0$ or $1$. For example, $1\,010\,111$ is a binary decimal, while $10\,201$ and $787\,788$ are not. Given a number $n$, you are asked whether or not it is possible to represent $n$ as a product of some (not necessarily distinct) binary decimals. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n) { // write your code here } }; ``` where: - return ""YES"" if n can be represented as a product of binary decimals, and ""NO"" otherwise. # Example 1: - Input: n = 121 - Output: YES # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 100000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve(int &n) { vector a = {10, 11, 100, 101, 110, 111, 1001, 1011, 1101, 1111, 10001, 10011, 10111, 10101, 11101, 11011, 11111, 11001}; sort(a.rbegin(), a.rend()); for (auto i : a) { while (n % i == 0) { n /= i; } } return n == 1 ? ""YES"" : ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }","dp,math",hard 166,"# Problem Statement When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book. Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &t, vector &a) { // write your code here } }; ``` where: - return: the maximum number of books Valera can read. # Example 1: - Input: n = 4, t = 5, a = [3, 1, 2, 1] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq t \leq 10^9$ - $1 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &t, vector &a) { int i = 0, j = 0, k = 0, mx = 0, sum = 0; while (i < n) { if (sum + a[i] <= t) { k++; sum += a[i]; } else { i--; k--; sum -= a[j++]; } i++; if (mx < k) mx = k; } return mx; } int solve2(int &n, int &t, vector &a) { int mx = 0; long long T = t; for (int i = 0; i < n; i++) { long long sum = 0; int cnt = 0; for (int j = i; j < n; j++) { long long v = a[j]; if (sum + v <= T) { sum += v; cnt++; } else { break; } } if (mx < cnt) mx = cnt; } return mx; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, t; cin >> n >> t; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, t, a); // output cout << result << ""\n""; return 0; }","search,two_pointers",medium 167,"You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions: 0 <= i < j < k < nums.length nums[i], nums[j], and nums[k] are pairwise distinct. In other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k]. Return the number of triplets that meet the conditions. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [4,4,2,4,3] Output: 3 Example 2: Input: nums = [1,1,1,1,1] Output: 0 Constraints: 3 <= nums.length <= @data 1 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { unordered_map freq; for (int i : nums){ freq[i]++; } int left = 0; int right = nums.size(); int res = 0; for (auto i : freq){ int value = i.second; int mid = value; right -= value; res += left * value * right; left += value; } return res; } int solve2(vector& nums) { int n = (int)nums.size(); long long res = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (nums[i] == nums[j]) continue; for (int k = j + 1; k < n; ++k) { if (nums[i] != nums[k] && nums[j] != nums[k]) { ++res; } } } } return (int)res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { int score = 0; for (int i = 0; i < s.size() - 1; ++i) { score += abs(s[i] - s[i + 1]); } return score; } int solve2(string s) { long long score = 0; if (s.size() <= 1) return 0; char prev = s[0]; for (size_t i = 1; i < s.size(); ++i) { int diff = int(prev) - int(s[i]); if (diff < 0) diff = -diff; score += diff; prev = s[i]; } if (score > INT_MAX) return INT_MAX; if (score < INT_MIN) return INT_MIN; return (int)score; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: string solve1(string s, int k) { string ans=""""; int cou=0; for(int i=0;i using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; string s; cin>>n>>s; // solve Solution solution; auto result = solution.solve(s,n); // output // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - `n`: the length of the array - `a`: the array of integers - return: the minimum possible sum, or `-1` if it can be decreased indefinitely # Example: - Input: ``` n = 2 a = [2, 1] ``` - Output: ``` 2 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { sort(a.begin(), a.end()); if (n == 1) return a[0]; if (n == 2) { long long s = (long long)a[0] + a[1]; return s - (s % 2); } long long sum = 0; for (int x : a) sum += x; long long ans = sum; int maxv = a.back(); unsigned long long l = 1; for (int i = 2; i < n; i++) { unsigned long long g = std::gcd(l, (unsigned long long)i); __int128 tmp = (__int128)(l / g) * i; if (tmp > (unsigned long long)maxv) { l = 0; break; } l = (unsigned long long)tmp; } for (int i = 1; i < n; i++) { if (i < 2) continue; unsigned long long lhs = l ? (a[i] % l) : (unsigned long long)a[i]; unsigned long long rhs = l ? (a[i - 1] % l) : (unsigned long long)a[i - 1]; if (lhs != rhs) return -1; } long long pref = a[0]; int lastRem = -1; for (int i = 1; i < n; i++) { pref += a[i]; int r = (int)(pref % (i + 1)); if (r >= 2) return -1; if (lastRem == -1) lastRem = r; else if (lastRem != r) return -1; ans = min(ans, sum - r); } return ans; } long long solve2(int &n, vector &a) { if (n == 1) return (long long)a[0]; long long sum = 0; for (int i = 0; i < n; ++i) sum += (long long)a[i]; if (n == 2) return sum - (sum & 1LL); sort(a.begin(), a.end()); int maxv = a.back(); unsigned long long L = 1; for (int k = 2; k < n; ++k) { unsigned long long g = std::gcd(L, (unsigned long long)k); __int128 t = (__int128)(L / g) * k; if ((unsigned long long)t > (unsigned long long)maxv) { L = 0; break; } L = (unsigned long long)t; } if (L) { unsigned long long r0 = (unsigned long long)(a[0] % L); for (int i = 1; i < n; ++i) { if ((unsigned long long)(a[i] % L) != r0) return -1; } } else { int v0 = a[0]; for (int i = 1; i < n; ++i) { if (a[i] != v0) return -1; } } long long best = sum; long long pref = a[0]; int last = -1; for (int i = 1; i < n; ++i) { pref += a[i]; int r = (int)(pref % (i + 1)); if (r >= 2) return -1; if (last == -1) last = r; else if (last != r) return -1; long long cand = sum - r; if (cand < best) best = cand; } return best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","math,sort",hard 171,"# Problem Statement For a permutation $p_1,p_2,\dots,p_n$ of length $n$, the coloring sequence $s$ is produced by the following process: - Initially, there are $n$ white cells indexed $1 \dots n$. At second $0$, all scores are $0$. - At second $i$ ($1 \le i \le n$): - If $i>1$, find the nearest black cell to cell $p_i$ among already colored cells, and increase the score of that black cell by $1$. In case of multiple nearest black cells, choose the one with the lowest index. - Color cell $p_i$ black. After all cells are colored black, let $s_i$ be the score of cell $i$; the vector $s$ is the coloring sequence. You are given an incomplete coloring sequence $s$, where some $s_i$ are fixed and others are unknown (denoted as $-1$). Count the number of permutations $p$ that can produce a coloring sequence consistent with the given $s$. Print the answer modulo $998244353$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &s) { // write your code here } }; ``` where: - `n`: number of cells - `s`: length-`n` array, with `-1` for unknown entries, otherwise `0..n-1` - return: number of valid permutations modulo `998244353` # Example 1: - Input: ``` n = 3 s = [-1, -1, 1] ``` - Output: ``` 2 ``` # Constraints: - $2 \le n \le @data$ - $-1 \le s_i \le n-1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[20, 60, 100]",1000,"[[100, 64, 64], [800, 400, 160], [6400, 3200, 1280]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &s) { const int MOD = 998244353; vector a(n + 2, -1); for (int i = 1; i <= n; i++) a[i] = s[i - 1]; int fu = 0; for (int i = 1; i <= n; i++) fu += max(0, a[i]); if (fu >= n) return 0; auto mod_pow = [&](long long x, long long e) -> long long { long long r = 1; while (e) { if (e & 1) r = r * x % MOD; x = x * x % MOD; e >>= 1; } return r; }; vector fac(n + 1), ifac(n + 1); fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = 1LL * fac[i - 1] * i % MOD; ifac[n] = (int)mod_pow(fac[n], MOD - 2); for (int i = n; i >= 1; i--) ifac[i - 1] = 1LL * ifac[i] * i % MOD; auto Cnk = [&](int N, int K) -> int { if (K < 0 || K > N) return 0; return (int)(1LL * fac[N] * ifac[K] % MOD * ifac[N - K] % MOD); }; unordered_map dp; dp.max_load_factor(0.7f); function dfs = [&](int l, int r, int pl, int pr) -> int { if (l > r) return (pl <= 1 && pr <= 1) ? 1 : 0; if ((pl - 1) + (pr - 1) > r - l + 1) return 0; int st = 101 * (101 * (101 * pl + pr) + r) + l; auto it = dp.find(st); if (it != dp.end()) return it->second; int ans = 0; for (int k = l; k <= r; k++) { int p0 = (l > 1 && (r == n || k - l <= r - k)); int p1 = (r < n && (l == 1 || k - l > r - k)); int chooseWays = Cnk(r - l, k - l); if (pl == 1 && p0) continue; if (pr == 1 && p1) continue; if (a[k] == -1) { long long leftWays = dfs(l, k - 1, max(0, pl - p0), 0); long long rightWays = dfs(k + 1, r, 0, max(0, pr - p1)); ans = (ans + 1LL * chooseWays % MOD * leftWays % MOD * rightWays) % MOD; } else { for (int o = 0; o <= a[k]; o++) { long long leftWays = dfs(l, k - 1, max(0, pl - p0), o + 1); long long rightWays = dfs(k + 1, r, a[k] - o + 1, max(0, pr - p1)); ans = (ans + 1LL * chooseWays % MOD * leftWays % MOD * rightWays) % MOD; } } } dp[st] = ans; return ans; }; return dfs(1, n, 1, 1); } int solve2(int &n, vector &s) { const int MOD = 998244353; for (int i = 0; i < n; i++) if (s[i] < -1 || s[i] > n - 1) return 0; long long fu = 0; for (int i = 0; i < n; i++) fu += (s[i] >= 0 ? s[i] : 0); if (fu >= n) return 0; vector p(n); for (int i = 0; i < n; i++) p[i] = i + 1; long long ans = 0; do { vector score(n, 0); for (int t = 1; t <= n; t++) { int u = p[t - 1]; if (t > 1) { int nearestVal = -1; int nearestDist = INT_MAX; for (int j = 0; j <= t - 2; j++) { int v = p[j]; int dist = v > u ? v - u : u - v; if (dist < nearestDist || (dist == nearestDist && v < nearestVal)) { nearestDist = dist; nearestVal = v; } } score[nearestVal - 1]++; } } bool ok = true; for (int i = 0; i < n; i++) { if (s[i] != -1 && score[i] != s[i]) { ok = false; break; } } if (ok) ans++; if (ans >= MOD) ans %= MOD; } while (next_permutation(p.begin(), p.end())); return (int)(ans % MOD); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector s(n); for (int i = 0; i < n; i++) cin >> s[i]; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","dp,math",hard 172,"There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coins. You will pick the next pile with the maximum number of coins. Your friend Bob will pick the last pile. Repeat until there are no more piles of coins. Given an array of integers piles where piles[i] is the number of coins in the ith pile. Return the maximum number of coins that you can have. solution main function ```cpp class Solution { public: int solve(vector& piles) { } }; ``` Example 1: Input: piles = [2,4,1,2,7,8] Output: 9 Example 2: Input: piles = [2,4,5] Output: 4 Constraints: 3 <= piles.length <= @data piles.length % 3 == 0 1 <= piles[i] <= 10^4 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& piles) { int myCoins = 0; sort(piles.begin(), piles.end()); int l = 0, r = piles.size()-1; while(l < r){ l += 1; myCoins += piles[r-1]; r -= 2; } return myCoins; } int solve2(vector& piles) { long long myCoins = 0; int n = (int)piles.size(); int rounds = n / 3; for (int k = 0; k < rounds; ++k) { int idxMax1 = -1, idxMax2 = -1, idxMin = -1; int max1 = INT_MIN, max2 = INT_MIN, minv = INT_MAX; for (int i = 0; i < n; ++i) { int v = piles[i]; if (v >= 0 && v > max1) { max1 = v; idxMax1 = i; } } if (idxMax1 >= 0) piles[idxMax1] = -1; for (int i = 0; i < n; ++i) { int v = piles[i]; if (v >= 0 && v > max2) { max2 = v; idxMax2 = i; } } if (idxMax2 >= 0) { myCoins += piles[idxMax2]; piles[idxMax2] = -1; } for (int i = 0; i < n; ++i) { int v = piles[i]; if (v >= 0 && v < minv) { minv = v; idxMin = i; } } if (idxMin >= 0) piles[idxMin] = -1; } return (int)myCoins; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< int > num; for(int i=1,x;i<=n;i++) { cin>>x; num.push_back(x); } // solve Solution solution; int result = solution.solve(num); // output cout << result << ""\n""; return 0; }","math,greedy",hard 173,"# Problem Statement Vanya really likes math. One day when he was solving another math problem, he came up with an interesting tree. This tree is built as follows. Initially, the tree has only one vertex with the number $1$ — the root of the tree. Then, Vanya adds two children to it, assigning them consecutive numbers — $2$ and $3$, respectively. After that, he will add children to the vertices in increasing order of their numbers, starting from $2$, assigning their children the minimum unused indices. As a result, Vanya will have an infinite tree with the root in the vertex $1$, where each vertex will have exactly two children, and the vertex numbers will be arranged sequentially by layers. Vanya wondered what the sum of the vertex numbers on the path from the vertex with number $1$ to the vertex with number $n$ in such a tree is equal to. Since Vanya doesn't like counting, he asked you to help him find this sum. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(long long &n) { // write your code here } }; ``` where: - return: the sum of the vertex numbers on the path from the vertex with number $1$ to the vertex with number $n$. # Example 1: - Input: n = 3 - Output: 4 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000000, 1000000000000, 10000000000000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(long long &n) { long long ans = 0; while (n) { ans += n; n /= 2; } return ans; } long long solve2(long long &n) { long long ans = 0; long long m = n; while (m > 0) { ans += m; m >>= 1; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input long long n; cin >> n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }","math,tree,bit_manipulation",easy 174,"You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY). The cost of going from a position (x1, y1) to any other position in the space (x2, y2) is |x2 - x1| + |y2 - y1|. There are also some special roads. You are given a 2D array specialRoads where specialRoads[i] = [x1i, y1i, x2i, y2i, costi] indicates that the ith special road goes in one direction from (x1i, y1i) to (x2i, y2i) with a cost equal to costi. You can use each special road any number of times. Return the minimum cost required to go from (startX, startY) to (targetX, targetY). solution main function ```cpp class Solution { public: int solve(vector& start, vector& target, vector>& specialRoads) { } }; ``` Example 1: Input: start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]] Output: 5 Example 2: Input: start = [3,2], target = [5,7], specialRoads = [[5,7,3,2,1],[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]] Output: 7 Constraints: start.length == target.length == 2 1 <= startX <= targetX <= 10^5 1 <= startY <= targetY <= 10^5 1 <= specialRoads.length <= @data specialRoads[i].length == 5 startX <= x1i, x2i <= targetX startY <= y1i, y2i <= targetY 1 <= costi <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[20, 50, 100]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; template using min_pq = priority_queue, greater>; class Solution { public: int solve1(vector& start, vector& target, vector>& specialRoads) { const int INF = 1e9+10; int n = specialRoads.size(); vector d(n, INF); min_pq> pq; for (int i = 0; i < n; i++) { d[i] = abs(start[0] - specialRoads[i][0]) + abs(start[1] - specialRoads[i][1]) + specialRoads[i][4]; pq.push({d[i], i}); } int ans = abs(start[0] - target[0]) + abs(start[1] - target[1]); while (pq.size()) { auto [d_c, c] = pq.top(); pq.pop(); if (d_c != d[c]) continue; ans = min(ans, d_c + abs(target[0] - specialRoads[c][2]) + abs(target[1] - specialRoads[c][3])); for (int nxt = 0; nxt < n; nxt++) { int w = abs(specialRoads[c][2] - specialRoads[nxt][0]) + abs(specialRoads[c][3] - specialRoads[nxt][1]) + specialRoads[nxt][4]; if (d_c + w < d[nxt]) { d[nxt] = d_c + w; pq.push({d[nxt], nxt}); } } } return ans; } int solve2(vector& start, vector& target, vector>& specialRoads) { using ll = long long; int n = (int)specialRoads.size(); ll ans = llabs((ll)start[0] - (ll)target[0]) + llabs((ll)start[1] - (ll)target[1]); int processed = 0; const ll INF = (ll)4e18; while (processed < n) { ll best = INF; int idx = -1; for (int v = 0; v < n; ++v) { int cf = specialRoads[v][4]; if (cf < 0) continue; ll costv = (ll)cf; ll t = llabs((ll)start[0] - (ll)specialRoads[v][0]) + llabs((ll)start[1] - (ll)specialRoads[v][1]) + costv; for (int u = 0; u < n; ++u) { int ucf = specialRoads[u][4]; if (ucf >= 0) continue; ll du = -((ll)ucf) - 1; ll w = llabs((ll)specialRoads[u][2] - (ll)specialRoads[v][0]) + llabs((ll)specialRoads[u][3] - (ll)specialRoads[v][1]) + costv; ll cand = du + w; if (cand < t) t = cand; } if (t < best) { best = t; idx = v; } } if (idx == -1) break; specialRoads[idx][4] = -(int)(best + 1); ++processed; ll toTarget = best + llabs((ll)target[0] - (ll)specialRoads[idx][2]) + llabs((ll)target[1] - (ll)specialRoads[idx][3]); if (toTarget < ans) ans = toTarget; } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int x,y,x2,y2,n; cin>>x>>y>>x2>>y2>>n; vector > edge; vector start; start.push_back(x); start.push_back(y); vector targe; targe.push_back(x2); targe.push_back(y2); for(int i=1,x,y,z;i<=n;i++) { vector temp; scanf(""%d"",&x); scanf(""%d"",&y); scanf(""%d"",&z); temp.push_back(x); temp.push_back(y); temp.push_back(z); scanf(""%d"",&x); scanf(""%d"",&y); temp.push_back(x); temp.push_back(y); edge.push_back(temp); } // solve Solution solution; auto result = solution.solve(start,targe,edge); // output // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return YES if it is possible to paint the given sequence satisfying the above requirements, and NO otherwise. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: NO # Constraints: - $3 \leq n \leq @data$ - $0 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { sort(a.begin(), a.end()); long long i = 1, j = 0, sumi = a[0], sumj = 0, flag = 0; while (i + j <= n) { sumi += a[++i - 1]; sumj += a[n - (++j)]; if (sumj > sumi && i + j <= n) { flag = 1; break; } } if (flag) return ""YES""; else return ""NO""; } string solve2(int &n, vector &a) { sort(a.begin(), a.end()); long long sumBlue = a[0], sumRed = 0; int kmax = (n - 1) / 2; for (int k = 1; k <= kmax; ++k) { sumBlue += (long long)a[k]; sumRed += (long long)a[n - k]; if (sumRed > sumBlue) return ""YES""; } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,sort,two_pointers",hard 176,"# Problem Statement You have an array of integers $a$ of length $n$. You can apply the following operation to the given array: - Swap two elements $a_i$ and $a_j$ such that $i \neq j$, $a_i$ and $a_j$ are either **both** even or **both** odd. Determine whether it is possible to sort the array in non-decreasing order by performing the operation any number of times (possibly zero). For example, let $a$ = $[7, 10, 1, 3, 2]$. Then we can perform $3$ operations to sort the array: 1. Swap $a_3 = 1$ and $a_1 = 7$, since $1$ and $7$ are odd. We get $a$ = $[1, 10, 7, 3, 2]$; 2. Swap $a_2 = 10$ and $a_5 = 2$, since $10$ and $2$ are even. We get $a$ = $[1, 2, 7, 3, 10]$; 3. Swap $a_4 = 3$ and $a_3 = 7$, since $3$ and $7$ are odd. We get $a$ = $[1, 2, 3, 7, 10]$. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, vector &a) { // write your code here } }; ``` where: - Return value: Returns ""YES"" or ""NO"", indicating whether the array can be sorted in non-decreasing order. # Example 1: - Input: n = 5 a = [6, 6, 4, 1, 6] - Output: ""NO"" # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 400, 80], [6400, 3200, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { auto b = a; sort(b.begin(), b.end()); for (int i = 0; i < n; i++) { if ((a[i] - b[i]) % 2) return ""NO""; } return ""YES""; } string solve2(int &n, vector &a) { for (int i = 0; i < n; ++i) { if ((a[i] & 1) == 0) { int minIdx = i; int minVal = a[i]; for (int j = i + 1; j < n; ++j) { if ((a[j] & 1) == 0 && a[j] < minVal) { minVal = a[j]; minIdx = j; } } if (minIdx != i) { int tmp = a[i]; a[i] = a[minIdx]; a[minIdx] = tmp; } } } for (int i = 0; i < n; ++i) { if ((a[i] & 1) != 0) { int minIdx = i; int minVal = a[i]; for (int j = i + 1; j < n; ++j) { if ((a[j] & 1) != 0 && a[j] < minVal) { minVal = a[j]; minIdx = j; } } if (minIdx != i) { int tmp = a[i]; a[i] = a[minIdx]; a[minIdx] = tmp; } } } for (int i = 1; i < n; ++i) { if (a[i - 1] > a[i]) return ""NO""; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,two_pointers,sort",easy 177,"# Problem Statement There are $n$ families travelling to Pénjamo to witness Mexico's largest-ever ""walking a chicken on a leash"" marathon. The $i$-th family has $a_i$ family members. All families will travel using a single bus consisting of $r$ rows with $2$ seats each. A person is considered happy if: - Another family member is seated in the same row as them, or - They are sitting alone in their row (with an empty seat next to them). Determine the maximum number of happy people in an optimal seating arrangement. Note that **everyone** must be seated in the bus. It is guaranteed that all family members will fit on the bus. Formally, it is guaranteed that $\displaystyle\sum_{i=1}^{n}a_i \le 2r$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &r, vector &a) { // write your code here } }; ``` where: - return:the maximum number of happy people in an optimal seating arrangement. # Example 1: - Input: n = 3, r = 3, a = [2, 3, 1] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq r \leq 10^3$ - $1 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &r, vector &a) { int s = 0; int odd = 0; for (int i = 0; i < n; i++) { s += a[i]; odd += a[i] % 2; } int ans = s - max(0, (s + odd) / 2 - r) * 2; return ans; } int solve2(int &n, int &r, vector &a) { long long s = 0; long long pairs = 0; long long singles = 0; for (int i = 0; i < n; ++i) { s += a[i]; pairs += a[i] / 2; singles += a[i] % 2; } long long rows_needed = pairs + singles; long long ans = s; if (rows_needed > r) { long long merges = rows_needed - r; ans -= merges * 2; } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, r; cin >> n >> r; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, r, a); // output cout << result << ""\n""; return 0; }",math,easy 178,"Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. The answer is modulo 998244353. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 1 Output: 5 Example 2: Input: n = 2 Output: 15 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: const long long mod=998244353; const long long inv_24=291154603; int solve1(long long n) { return (n + 1ll) * (n + 2ll)%mod * (n + 3ll)%mod * (n + 4ll)%mod * inv_24%mod; } int solve2(long long n) { long long a = 1, b = 1, c = 1, d = 1, e = 1; for (long long i = 2; i <= n; ++i) { b = (b + a) % mod; c = (c + b) % mod; d = (d + c) % mod; e = (e + d) % mod; } long long ans = (a + b + c + d + e) % mod; return (int)ans; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< solve(int &n, int &q, string &s, vector> &queries) { // write your code here } }; ``` where: - `n`: length of the string `s` - `q`: number of queries - `s`: the string - `queries`: array of pairs `(l, r)` (1-indexed) - return: an array `ans` of size `q`, where `ans[i]` is the humor value for query `i` # Example - Input: ``` 12 6 aaaabbbbaaaa 1 12 2 7 3 10 4 7 5 9 4 5 ``` - Output: ``` 4 2 3 2 3 0 ``` # Constraints - $1 \le n, q \le @data$ - `s` only contains lowercase Latin letters - $1 \le l \le r \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1000, 500, 200], [8000, 4000, 1600], [64000, 32000, 12800]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &n, int &q, string &s, vector> &queries) { const int A = 26; const int K = 4; int maxNodes = n + 2; vector head(maxNodes, -1); vector to, nxt; vector ec; vector ff(maxNodes, 0); vector ff_(maxNodes, 0); vector len_(maxNodes, 0); vector childHead(maxNodes, -1), childTo, childNxt; vector ta(maxNodes, 0), tb(maxNodes, 0); vector uu(n + 1, 0); int node_cnt = 0; auto new_node = [&](int l) -> int { len_[node_cnt] = l; return node_cnt++; }; auto add_edge = [&](int u, int c, int v) { int id = (int) to.size(); to.push_back(v); nxt.push_back(head[u]); ec.push_back((unsigned char) c); head[u] = id; }; auto add_child = [&](int p, int v) { int id = (int) childTo.size(); childTo.push_back(v); childNxt.push_back(childHead[p]); childHead[p] = id; }; auto go = [&](int u, int c) -> int { for (int e = head[u]; e != -1; e = nxt[e]) if (ec[e] == c) return to[e]; return 0; }; int timer_ = 0; function dfs = [&](int u) { ta[u] = timer_++; for (int e = childHead[u]; e != -1; e = childNxt[e]) dfs(childTo[e]); tb[u] = timer_; }; auto build_eertree = [&]() { new_node(0); new_node(-1); ff[0] = ff_[0] = 1; add_child(1, 0); int last = 0; auto get_link = [&](int u, int i) -> int { while (i - 1 - len_[u] < 0 || s[i - 1 - len_[u]] != s[i]) u = ff[u]; return u; }; for (int i = 0; i < n; i++) { int c = s[i] - 'a'; int u = get_link(last, i); int v = go(u, c); if (!v) { int v_idx = new_node(len_[u] + 2); int f_node = go(get_link(ff[u], i), c); ff[v_idx] = f_node; ff_[v_idx] = ff[v_idx] == 0 || len_[v_idx] - len_[f_node] != len_[f_node] - len_[ff[f_node]] ? f_node : ff_[f_node]; add_edge(u, c, v_idx); add_child(f_node, v_idx); v = v_idx; } uu[i + 1] = last = v; } dfs(1); }; struct Fenwick { int n; vector ft; explicit Fenwick(int n) : n(n), ft(n, 0) {} void update(int i, int x) { while (i < n) { ft[i] = max(ft[i], x); i |= i + 1; } } int query(int i) { int x = -1; while (i >= 0) { x = max(x, ft[i]); i &= i + 1; i--; } return x; } }; struct SegmentTree { int n_; vector st1, st2; explicit SegmentTree(int n) { n_ = 1; while (n_ < n + 2) n_ <<= 1; st1.assign(n_ * 2, -1); st2.assign(n_ * 2, -1); } void st1_update(int i, int x) { i += n_; st1[i] = max(st1[i], x); while (i > 1) { i >>= 1; st1[i] = max(st1[i << 1], st1[i << 1 | 1]); } } int st1_query(int l, int r) { int x = -1; for (l += n_, r += n_; l <= r; l >>= 1, r >>= 1) { if (l & 1) x = max(x, st1[l++]); if (!(r & 1)) x = max(x, st1[r--]); } return x; } void st2_update(int l, int r, int x) { for (l += n_, r += n_; l <= r; l >>= 1, r >>= 1) { if (l & 1) st2[l] = max(st2[l], x), l++; if (!(r & 1)) st2[r] = max(st2[r], x), r--; } } int st2_query(int i) { int x = -1; for (i += n_; i > 0; i >>= 1) x = max(x, st2[i]); return x; } }; build_eertree(); vector> eh(n); vector leftOf(q), ans(q); for (int h = 0; h < q; h++) { int l = queries[h].first - 1; int r = queries[h].second - 1; leftOf[h] = l; if (r >= 0 && r < n) eh[r].push_back(h); } Fenwick fen(n); SegmentTree seg(n); for (int j = 0; j < n; j++) { int u = uu[j + 1]; if (u) { int i = seg.st1_query(ta[u], tb[u] - 1); if (i != -1) fen.update(n - 1 - (i - len_[u] + 1), len_[u]); } int v = u; while (v) { fen.update(n - 1 - (j - len_[v] + 1), len_[ff[v]]); int w = ff_[v], d = len_[v] - len_[ff[v]]; if (w) { int i = seg.st1_query(ta[w], tb[w] - 1); if (i != -1) fen.update(n - 1 - (i - len_[w] + 1), len_[w]); } for (int k = 1; k <= K && len_[w] + d * k <= len_[v]; k++) { int i = j - len_[w] - d * k + 1; fen.update(n - 1 - i, len_[w] + d * (k - 1)); } if (len_[v] - len_[w] >= d * K) { int i = j - len_[w] - d * K + 1; seg.st2_update(j - len_[v] + 2, i, j); } v = w; } u = uu[j + 1]; seg.st1_update(ta[u], j); for (int h : eh[j]) { int i = leftOf[h]; int x = fen.query(n - 1 - i); int j_ = seg.st2_query(i); if (j_ != -1 && j_ >= i) { u = uu[j_ + 1]; while (j_ - len_[ff_[u]] + 1 < i) u = ff_[u]; int d = len_[u] - len_[ff[u]]; int i_ = j_ - len_[u] + 1; i_ += (i - i_ + d - 1) / d * d; x = max(x, j_ - i_ + 1 - d); if (i_ > i) x = max(x, j_ - i_ - (d - i_ + i) * 2 + 1); } ans[h] = x; } } return ans; } vector solve2(int &n, int &q, string &s, vector> &queries) { auto is_pal = [&](int start, int len) -> bool { int i = start, j = start + len - 1; while (i < j) { if (s[i] != s[j]) return false; ++i; --j; } return true; }; auto equal_sub = [&](int i, int j, int len) -> bool { for (int k = 0; k < len; ++k) { if (s[i + k] != s[j + k]) return false; } return true; }; vector ans(q); for (int qi = 0; qi < q; ++qi) { int l = queries[qi].first - 1; int r = queries[qi].second - 1; int m = r - l + 1; int best = 0; if (m >= 2) { for (int L = m; L >= 1; --L) { int limit = m - L; bool found = false; for (int i = 0; i <= limit && !found; ++i) { int start = l + i; if (!is_pal(start, L)) continue; for (int j = i + 1; j <= limit; ++j) { if (equal_sub(l + i, l + j, L)) { best = L; found = true; break; } } } if (found) break; } } ans[qi] = best; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, q; cin >> n >> q; string s; cin >> s; vector> queries(q); for (int i = 0; i < q; i++) { int l, r; cin >> l >> r; queries[i] = {l, r}; } // solve Solution solution; auto result = solution.solve(n, q, s, queries); // output for (int x : result) cout << x << ""\n""; return 0; }","string,data_structures",hard 180,"# Problem Statement Luca is in front of a row of $n$ trees. The $i$-th tree has $a_i$ fruit and height $h_i$. He wants to choose a contiguous subarray of the array $[h_l, h_{l+1}, \dots, h_r]$ such that for each $i$ ($l \leq i < r$), **$h_i$ is divisible$^{\dagger}$ by $h_{i+1}$**. He will collect all the fruit from each of the trees in the subarray (that is, he will collect $a_l + a_{l+1} + \dots + a_r$ fruits). However, if he collects more than $k$ fruits in total, he will get caught. What is the maximum length of a subarray Luca can choose so he doesn't get caught? $^{\dagger}$ $x$ is divisible by $y$ if the ratio $\frac{x}{y}$ is an integer. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &k, vector &a, vector &h) { // write your code here } }; ``` where: - `n` is the number of trees, `k` is the maximum number of fruits - `a` is the array of fruit numbers, `h` is the array of tree heights - Return the maximum length # Example 1: - Input: n = 5, k = 12 a = [3, 2, 4, 1, 8] h = [4, 4, 2, 4, 1] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i], h[i] \leq 10^3$ - $1 \leq k \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &k, vector &a, vector &h) { int sum = 0; for (int i = 1; i < n; i++) { a[i] += a[i - 1]; } int ans = 0; for (int i = 0, j = 0; i < n; i++) { if (i && h[i - 1] % h[i] != 0) j = i; while (a[i] - (j == 0 ? 0 : a[j - 1]) > k) j++; ans = max(ans, i - j + 1); } return ans; } int solve2(int &n, int &k, vector &a, vector &h) { int ans = 0; for (int l = 0; l < n; l++) { long long s = 0; for (int r = l; r < n; r++) { if (r > l && h[r - 1] % h[r] != 0) break; s += (long long)a[r]; if (s <= (long long)k) { int len = r - l + 1; if (len > ans) ans = len; } else { break; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector a(n), h(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> h[i]; // solve Solution solution; auto result = solution.solve(n, k, a, h); // output cout << result << ""\n""; return 0; }","two_pointers,binary,math,dp",medium 181,"You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed. solution main function ```cpp class Solution { public: int solve(vector& arr) { // write your code here } }; ``` Example 1: Input: arr = [3,3,3,3,5,5,5,2,2,7] Output: 2 Example 2: Input: arr = [7,7,7,7,7,7] Output: 1 Constraints: 1 <= arr.length <= @data arr.length is even. 1 <= arr[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& arr) { sort(arr.begin(),arr.end()); vector arr_freq; arr_freq.push_back(1); int cir_freq = 0; for(int i=0;i=0;i--){ if(res_size>arr.size()/2){ res++; res_size -= arr_freq[i]; } else{ break; } } return res; } int solve2(vector& arr) { int n = (int)arr.size(); int target = n / 2; int removed = 0; int res = 0; while (removed < target) { int best_val = 0; int best_cnt = 0; for (int i = 0; i < n; ++i) { int v = arr[i]; if (v == 0) continue; int cnt = 0; for (int j = 0; j < n; ++j) { if (arr[j] == v) ++cnt; } if (cnt > best_cnt) { best_cnt = cnt; best_val = v; } } removed += best_cnt; ++res; for (int k = 0; k < n; ++k) { if (arr[k] == best_val) arr[k] = 0; } } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector arr; for(int i=1;i<=n;i++) { int x; cin>>x; arr.push_back(x); } // solve Solution solution; auto result = solution.solve(arr); // output cout< solve(vector& encoded) { } }; ``` Example 1: Input: encoded = [3,1] Output: [1,2,3] Example 2: Input: encoded = [6,5,4,6] Output: [2,4,1,5,3] Constraints: 3 <= n < @data n is odd. encoded.length == n - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve(vector& encoded) { int x=0; for(int i=1;i<=encoded.size()+1;i++){ x^=i; } for(int i=1;ians(encoded.size()+1); ans[0]=x; for(int i=1;i<=encoded.size();i++){ ans[i]=ans[i-1]^encoded[i-1]; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output for(auto it:result) cout< \mathrm{mex}(b)$. Here, $\mathrm{mex}(b)$ denotes the minimum excluded (MEX) of the integers in $b$. You are given an array $a$ consisting of $n$ non-negative integers. For its subarray $[a_l, a_{l+1}, \dots, a_r]$, denote the weight of the subarray as $w(l, r)$. For every $1 \le i \le n$, find the maximum weight over all subarrays of $a$ ending at index $i$, i.e., compute $\max_{1 \le l \le i} w(l, i)$ for each $i$. The main function of the solution is defined as: ```cpp class Solution { public: vector solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: the length of array `a` - `a`: an array of non-negative integers with `0 <= a[i] <= n` - return: an array of length `n`, where the i-th value is the maximum weight over all subarrays of `a` ending at index `i` (1-indexed in the statement, 0-indexed in implementation). # Example: - Input: `n = 5` `a = [2, 0, 3, 0, 1]` - Output: `[1, 1, 2, 2, 1]` # Constraints: - $1 \le n \le @data$ - $0 \le a[i] \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",1000,"[[250, 150, 75], [2000, 1200, 600], [16000, 9600, 4800]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &n, vector &a) { struct SegTree { int N; vector maxv, tag; SegTree(int n = 0) { init(n); } void init(int n) { N = n; maxv.assign(N * 4 + 4, 0); tag.assign(N * 4 + 4, 0); } void apply(int p, int v) { maxv[p] += v; tag[p] += v; } void push(int p) { if (tag[p]) { apply(p << 1, tag[p]); apply(p << 1 | 1, tag[p]); tag[p] = 0; } } void pull(int p) { maxv[p] = max(maxv[p << 1], maxv[p << 1 | 1]); } void add(int p, int l, int r, int ql, int qr, int v) { if (ql > qr) return; if (ql <= l && r <= qr) { apply(p, v); return; } push(p); int m = (l + r) >> 1; if (ql <= m) add(p << 1, l, m, ql, qr, v); if (qr > m) add(p << 1 | 1, m + 1, r, ql, qr, v); pull(p); } void add(int l, int r, int v) { add(1, 0, N, l, r, v); } void pointSet(int p, int l, int r, int pos, int v) { if (l == r) { maxv[p] = v; return; } push(p); int m = (l + r) >> 1; if (pos <= m) pointSet(p << 1, l, m, pos, v); else pointSet(p << 1 | 1, m + 1, r, pos, v); pull(p); } void pointSet(int pos, int v) { pointSet(1, 0, N, pos, v); } int queryMax() const { return maxv[1]; } }; SegTree st(n); vector res(n, 0); for (int i = 0; i < n; i++) { int x = a[i]; if (x > 0) st.add(0, x - 1, 1); st.pointSet(x, 0); res[i] = st.queryMax(); } return res; } vector solve2(int &n, vector &a) { vector res(n, 0); for (int i = 0; i < n; i++) { int best = 0; for (int l = 0; l <= i; l++) { int mex = 0; while (true) { bool found = false; for (int j = l; j <= i; j++) { if (a[j] == mex) { found = true; break; } } if (!found) break; ++mex; if (mex > n + 1) break; } int cnt = 0; for (int j = l; j <= i; j++) { if (a[j] > mex) ++cnt; } if (cnt > best) best = cnt; } res[i] = best; } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output for (int i = 0; i < (int)result.size(); i++) cout << result[i] << "" \n""[i + 1 == (int)result.size()]; return 0; }",data_structures,hard 184,"# Problem Statement You are given a binary array$^{\dagger}$ of length $n$. You are allowed to perform one operation on it **at most once**. In an operation, you can choose any element and flip it: turn a $0$ into a $1$ or vice-versa. What is the maximum number of inversions$^{\ddagger}$ the array can have after performing **at most one** operation? $^\dagger$ A binary array is an array that contains only zeroes and ones. $^\ddagger$ The number of inversions in an array is the number of pairs of indices $i,j$ such that $i a_j$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` Where: - `n` is an integer representing the length of the array. - `a` is a binary array of length $n$. - The function should return a 64-bit integer, representing the maximum number of inversions in the array after performing at most one operation. # Example 1: - Input: n = 4 a = [1, 0, 1, 0] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a_i \leq 1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { long long ans = 0; int c0 = 0, c1 = 0; int x0 = -1, x1 = -1; for (int i = 0; i < n; i++) { if (a[i] == 0) { c0++; ans += c1; if (x0 == -1) x0 = i; } else { c1++; x1 = i; } } long long res = ans; if (x0 != -1) ans = max(ans, res + c0 - 1 - x0); if (x1 != -1) ans = max(ans, res + c1 - 1 - (n - 1 - x1)); return ans; } long long solve2(int &n, vector &a) { long long baseInv = 0; long long ones_so_far = 0; int totalZeros = 0; for (int i = 0; i < n; ++i) { if (a[i] == 0) { baseInv += ones_so_far; ++totalZeros; } else { ++ones_so_far; } } long long ans = baseInv; int zeros_left = 0; int ones_left = 0; for (int i = 0; i < n; ++i) { int zeros_right = totalZeros - zeros_left - (a[i] == 0 ? 1 : 0); long long delta; if (a[i] == 0) { delta = (long long)zeros_right - (long long)ones_left; } else { delta = (long long)ones_left - (long long)zeros_right; } ans = max(ans, baseInv + delta); if (a[i] == 0) ++zeros_left; else ++ones_left; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","data_structures,greedy,math",hard 185,"Given two positive integers n and k, the binary string Sn is formed as follows: S1 = ""0"" Si = Si - 1 + ""1"" + reverse(invert(Si - 1)) for i > 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). For example, the first four strings in the above sequence are: S1 = ""0"" S2 = ""011"" S3 = ""0111001"" S4 = ""011100110110001"" Return the kth bit in Sn. It is guaranteed that k is valid for the given n. solution main function ```cpp class Solution { public: char solve(int n, int k) { } }; ``` Example 1: Input: n = 3, k = 1 Output: ""0"" Example 2: Input: n = 4, k = 11 Output: ""1"" Constraints: 1 <= n <= @data 1 <= k <= 2^n - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 15, 20]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: char solve1(int n, int k) { int positionInSection = k & -k; bool isInInvertedPart = ((k / positionInSection) >> 1 & 1) == 1; bool originalBitIsOne = (k & 1) == 0; if (isInInvertedPart) { return originalBitIsOne ? '0' : '1'; } else { return originalBitIsOne ? '1' : '0'; } } char solve2(int n, int k) { long long kk = k; long long mid = 1LL << (n - 1); bool flip = false; while (true) { if (kk == mid) { char c = (mid == 1 ? '0' : '1'); if (flip) c = (c == '0' ? '1' : '0'); return c; } else if (kk < mid) { mid >>= 1; } else { kk = mid - (kk - mid); flip = !flip; mid >>= 1; } } } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; // solve Solution solution; auto result = solution.solve(n,k); // output cout< &a) { // write your code here } }; ``` where: - return: the minimum possible number of customers needed to sell all the cars. # Example 1: - Input: n = 3, x = 2, a = [3, 1, 2] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq x \leq 10$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &x, vector &a) { long long sum = 0; int mx = 0; for (int i = 0; i < n; i++) { sum += a[i]; mx = max(mx, a[i]); } long long ans = max((sum + x - 1) / x, mx); return ans; } long long solve2(int &n, int &x, vector &a) { long long sum = 0; long long mx = 0; for (int i = 0; i < n; i++) { sum += (long long)a[i]; if ((long long)a[i] > mx) mx = a[i]; } long long lo = 0; long long hi = max(mx, (sum + (long long)x - 1) / (long long)x); while (lo < hi) { long long mid = (lo + hi) >> 1; if (mid >= mx && (long long)x * mid >= sum) hi = mid; else lo = mid + 1; } return lo; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, x; cin >> n >> x; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, x, a); // output cout << result << ""\n""; return 0; }","search,math",hard 187,"# Problem Statement You are given a string $s$ of length $n > 1$, consisting of digits from $0$ to $9$. You must insert exactly $n - 2$ symbols $+$ (addition) or $\times$ (multiplication) into this string to form a valid arithmetic expression. In this problem, the symbols cannot be placed before the first or after the last character of the string $s$, and two symbols cannot be written consecutively. Also, note that the order of the digits in the string cannot be changed. Let's consider $s = 987009$: - From this string, the following arithmetic expressions can be obtained: $9 \times 8 + 70 \times 0 + 9 = 81$, $98 \times 7 \times 0 + 0 \times 9 = 0$, $9 + 8 + 7 + 0 + 09 = 9 + 8 + 7 + 0 + 9 = 33$. Note that the number $09$ is considered valid and is simply transformed into $9$. - From this string, the following arithmetic expressions cannot be obtained: $+9 \times 8 \times 70 + 09$ (symbols should only be placed between digits), $98 \times 70 + 0 + 9$ (since there are $6$ digits, there must be exactly $4$ symbols). The result of the arithmetic expression is calculated according to the rules of mathematics — first all multiplication operations are performed, then addition. You need to find the minimum result that can be obtained by inserting exactly $n - 2$ addition or multiplication symbols into the given string $s$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, string &s) { // write your code here } }; ``` where: - return the minimum result of the arithmetic expression that can be obtained by inserting exactly n−2 addition or multiplication symbols into the given string. # Example 1: - Input: n = 2 s = ""10"" - Output: 10 # Constraints: - $2 \leq n \leq @data$ - $s[i] \in [0, 9]$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, string &s) { int cnt[2] = {}; int sum = 0; for (auto c : s) { sum += c - '0'; if (c <= '1') { cnt[c - '0']++; } } sum -= s[0] - '0'; if (s[0] <= '1') { cnt[s[0] - '0']--; } int ans = 1E9; for (int i = 0; i <= n - 2; i++) { sum -= s[i + 1] - '0'; if (s[i + 1] <= '1') { cnt[s[i + 1] - '0']--; } int v = std::stoi(s.substr(i, 2)); sum += v; if (v <= 1) { cnt[v]++; } int res; if (cnt[0] > 0) { res = 0; } else { res = std::max(1, sum - cnt[1]); } ans = std::min(ans, res); sum -= v; if (v <= 1) { cnt[v]--; } sum += s[i] - '0'; if (s[i] <= '1') { cnt[s[i] - '0']++; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }",dp,hard 188,"The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step: If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue. Otherwise, they will leave it and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat. solution main function ```cpp class Solution { public: int solve(vector& students, vector& sandwiches) { } }; ``` Example 1: Input: students = [1,1,0,0], sandwiches = [0,1,0,1] Output: 0 Example 2: Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] Output: 3 Constraints: 1 <= students.length, sandwiches.length <= @data students.length == sandwiches.length sandwiches[i] is 0 or 1. students[i] is 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& students, vector& sandwiches) { int circleStudentCount = 0; int squareStudentCount = 0; for (int student : students) { if (student == 0) { circleStudentCount++; } else { squareStudentCount++; } } for (int sandwich : sandwiches) { if (sandwich == 0 && circleStudentCount == 0) { return squareStudentCount; } if (sandwich == 1 && squareStudentCount == 0) { return circleStudentCount; } if (sandwich == 0) { circleStudentCount--; } else { squareStudentCount--; } } return 0; } int solve2(vector& students, vector& sandwiches) { int n = (int)students.size(); int m = (int)sandwiches.size(); int remaining = n; int sIdx = 0; int head = 0; int rotations = 0; if (n == 0 || m == 0) return n; while (remaining > 0 && sIdx < m) { while (remaining > 0 && students[head] == -1) { head++; if (head == n) head = 0; } if (remaining == 0) break; if (students[head] == sandwiches[sIdx]) { students[head] = -1; remaining--; sIdx++; rotations = 0; head++; if (head == n) head = 0; } else { head++; if (head == n) head = 0; rotations++; if (rotations >= remaining) break; } } return remaining; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input vector a,b; int n; cin>>n; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } for(int i=1;i<=n;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output cout<>& edges) { } }; ``` Example 1: Input: n = 5, edges = [[2,3],[2,4],[2,5],[3,4],[4,5]] Output: 1 Constraints: 2 <= n <= @data edges.size <=5*@data edges[i].size ==2 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int n, vector>& edges) { int m=edges.size(),ans=0; vector cnt; cnt.resize(n+10,0); for(auto it:edges) for(auto i:it) cnt[i]++; for(int i=1;i<=n;i++) if(cnt[i]&1) ans++; if(ans==0) return ans; return ans/2; } int solve2(int n, vector>& edges) { int m = (int)edges.size(); int ans = 0; for(int v = 1; v <= n; ++v) { int cnt = 0; for(int i = 0; i < m; ++i) { int a = edges[i][0]; int b = edges[i][1]; if(a == v) cnt++; if(b == v) cnt++; } if(cnt & 1) ans++; } if(ans == 0) return ans; return ans / 2; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector< vector > edge; for(int i=1,x,y;i<=m;i++) { scanf(""%d%d"",&x,&y); vector temp; temp.push_back(x); temp.push_back(y); edge.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,edge); // output cout << result << ""\n""; return 0; }",graph,easy 190,"# Problem Statement: You had $n$ positive integers $a_1, a_2, \dots, a_n$ arranged in a circle. For each pair of neighboring numbers ($a_1$ and $a_2$, $a_2$ and $a_3$, ..., $a_{n - 1}$ and $a_n$, and $a_n$ and $a_1$), you wrote down: are the numbers in the pair equal or not. Unfortunately, you've lost a piece of paper with the array $a$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $a$ which is consistent with information you have about equality or non-equality of corresponding pairs? The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, string &s) { // write your code here } }; ``` Where: - `n` is an integer representing the number of elements in the array. - `s` is a string consisting of the characters 'N' and 'E', where: - 'E' indicates the two adjacent numbers are equal. - 'N' indicates the two adjacent numbers are not equal. - The return value is ""YES"" if there exists an array $a$ consistent with the information you have, otherwise, it is ""NO"". # Example 1: - Input: n = 3 s = ""EEE"" - Output: YES # Constraints: - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve(int &n, string &s) { int cnt = 0; for (auto x : s) if (x == 'N') cnt++; if (cnt == 1) return ""NO""; else return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","greedy,data_structures",medium 191,"# Problem Statement You are given an $n \times m$ grid $a$ of non-negative integers. The value $a_{i,j}$ represents the depth of water at the $i$-th row and $j$-th column. A lake is a set of cells such that: - each cell in the set has $a_{i,j} > 0$, and - there exists a path between any pair of cells in the lake by going up, down, left, or right a number of times and without stepping on a cell with $a_{i,j} = 0$. The volume of a lake is the sum of depths of all the cells in the lake. Find the largest volume of a lake in the grid. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &m, vector> &a) { // write your code here } }; ``` where: - return value is the largest volume of a lake # Example 1: - Input: n = 3, m = 3 a = [ [1, 2, 0], [3, 4, 0], [0, 0, 5] ] - Output: 10 # Constraints: - $1 \leq n * m \leq @data$ - $0 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[225, 200, 150], [1800, 1600, 1200], [14400, 12800, 9600]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &m, vector> &a) { int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; int ans = 0; vector> vis(n, vector(m, false)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!vis[i][j] && a[i][j] > 0) { int res = 0; queue> q; q.push({i, j}); vis[i][j] = true; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); res += a[x][y]; for (int k = 0; k < 4; k++) { int nx = x + dx[k]; int ny = y + dy[k]; if (0 <= nx && nx < n && 0 <= ny && ny < m && a[nx][ny] > 0 && !vis[nx][ny]) { q.push({nx, ny}); vis[nx][ny] = true; } } } ans = max(ans, res); } } } return ans; } int solve2(int &n, int &m, vector> &a) { long long ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] > 0) { long long sum = a[i][j]; a[i][j] = -a[i][j]; bool changed = true; while (changed) { changed = false; for (int x = 0; x < n; x++) { for (int y = 0; y < m; y++) { if (a[x][y] > 0) { if ((x > 0 && a[x - 1][y] < 0) || (x + 1 < n && a[x + 1][y] < 0) || (y > 0 && a[x][y - 1] < 0) || (y + 1 < m && a[x][y + 1] < 0)) { sum += a[x][y]; a[x][y] = -a[x][y]; changed = true; } } } } } if (sum > ans) ans = sum; } } } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; vector> a(n, vector(m)); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> a[i][j]; // solve Solution solution; auto result = solution.solve(n, m, a); // output cout << result << ""\n""; return 0; }","graph,search,data_structures",easy 192,"# Problem Statement You are given a string $s$, consisting of lowercase Latin letters and/or question marks. A tandem repeat is a string of an even length such that its first half is equal to its second half. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Your goal is to replace each question mark with some lowercase Latin letter in such a way that the length of the longest substring that is a tandem repeat is maximum possible. The main function of the solution is defined as: ```cpp class Solution { public: int solve(string &s) { // write your code here } }; ``` where: - the return value is the length of the longest substring that is a tandem repeat # Example 1: - Input: s = ""?????"" - Output: 4 # Constraints: - $1 \leq s.length \leq @data$ - s consists of lowercase Latin letters or question marks - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 5000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(string &s) { int n = int(s.size()); int ans = 0; for (int len = n / 2; len >= 1; len--) { int t = 0; for (int i = 0; i + len < n; i++) { if (s[i] == s[i + len] || s[i] == '?' || s[i + len] == '?') { t += 1; if (t == len) { ans = max(ans, len); break; } } else t = 0; } } return ans * 2; } int solve2(string &s) { int n = int(s.size()); for (int L = (n / 2) * 2; L >= 2; L -= 2) { int half = L / 2; for (int i = 0; i + L <= n; i++) { int k = 0; while (k < half) { char a = s[i + k]; char b = s[i + k + half]; if (!(a == b || a == '?' || b == '?')) break; k++; } if (k == half) return L; } } return 0; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string s; cin >> s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }","dp,two_pointers,string",medium 193,"# Problem Statement You are given a number in binary representation consisting of exactly $n$ bits, possibly, with leading zeroes. For example, for $n = 5$ the number $6$ will be given as $00110$, and for $n = 4$ the number $9$ will be given as $1001$. Let's fix some integer $i$ such that $1 \le i \le n$. In one operation you can swap any two adjacent bits in the binary representation. Your goal is to find the smallest number of operations you are required to perform to make the number divisible by $2^i$, or say that it is impossible. Please note that for each $1 \le i \le n$ you are solving the problem independently. The main function of the solution is defined as: ```cpp class Solution { public: vector solve(int &n, string &s) { // write your code here } }; ``` where: - `n` is the number of bits in the binary representation - `s` is the binary representation of the number - Return an array, where the $i$-th element of the array represents the smallest number of operations required to make the number divisible by $2^i$, and the answer is large, use a $64$-bit integer type. # Example 1: - Input: n = 2 s = ""01"" - Output: [1, -1] # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 400, 256], [6400, 3200, 2048]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve(int &n, string &s) { long long ans = 0; vector res; int l = n, r = n; for (int i = 1; i <= n; i++) { if (ans != -1) { if (l > n - i && s[n - i] == '0') l -= 1; else { while (l > 0 && s[l - 1] == '1') l -= 1; if (l == 0) ans = -1; else ans += r - l; l -= 1; } r -= 1; } res.push_back(ans); } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output for (auto x : result) cout << x << "" ""; cout << ""\n""; return 0; }","two_pointers,binary,greedy,math",hard 194,"# Problem Statement We call a sequence `b1, b2, …, bk` good if there exists a coloring of each index `i` in red or blue such that for every pair of indices `i < j` with `bi > bj`, the colors assigned to `i` and `j` are different. Given a sequence `a1, a2, …, an`, compute the number of good subsequences of the sequence, including the empty subsequence. Since the answer can be very large, output it modulo `1e9+7`. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: length of the sequence - `a`: the sequence values, `1 <= a[i] <= n` - return: the number of good subsequences modulo `1e9+7` # Example 1: - Input: ``` n = 4 a = [4, 2, 3, 1] ``` - Output: ``` 13 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[200, 1000, 2000]",1000,"[[2048, 1500, 1000], [16384, 12000, 8000], [131072, 96000, 64000]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { private: using ll = long long; static const int mod = 1000000007; static int mul(int x,int y) { return (ll)(x%mod)*(y%mod)%mod; } static int add(int x,int y) { return (x+y)%mod; } static int sub(int x,int y) { return ((x-y)%mod+mod)%mod; } struct BIT { int n; vectort; BIT(const int &_n=0){init(_n);} void init(int _n){n=_n+2;t.assign(n,0);} void add(int i,int v) { for(i++;i=Solution::mod)t[i]-=Solution::mod; } } int ask(int i) { if(i<0)return 0; int res=0; for(i++;i>0;i-=i&-i) { res+=t[i]; if(res>=Solution::mod)res-=Solution::mod; } return res; } int range(int l,int r) { if(l>r)return 0; int res=ask(r)-ask(l-1); if(res<0)res+=Solution::mod; return res; } }; public: int solve(int &n, vector &a) { const int MOD = 1000000007; vector b(n + 5); vector a_perm(n + 5); vector> bit_lin(n + 5, vector(n + 5, 0)); vector> bit_col(n + 5, vector(n + 5, 0)); for (int i = 1; i <= n; i++) b[i] = a[i - 1]; for (int i = 1; i <= n; i++) { int v = 1; for (int j = 1; j < i; j++) if (b[j] <= b[i]) v++; for (int j = i + 1; j <= n; j++) if (b[j] < b[i]) v++; a_perm[i] = v; } for (int i = 0; i <= n + 1; i++) for (int j = 0; j <= n + 1; j++) bit_lin[i][j] = bit_col[i][j] = 0; auto addSelf = [&](int &x, int y) { x += y; if (x >= MOD) x -= MOD; }; auto update_lin = [&](int lin, int pos, int val) { pos++; for (int i = pos; i <= n + 1; i += (i & -i)) addSelf(bit_lin[lin][i], val); }; auto update_col = [&](int col, int pos, int val) { pos++; for (int i = pos; i <= n + 1; i += (i & -i)) addSelf(bit_col[col][i], val); }; auto query_lin = [&](int lin, int pos) { pos++; int rr = 0; for (int i = pos; i > 0; i -= (i & -i)) addSelf(rr, bit_lin[lin][i]); return rr; }; auto query_col = [&](int col, int pos) { pos++; int rr = 0; for (int i = pos; i > 0; i -= (i & -i)) addSelf(rr, bit_col[col][i]); return rr; }; update_lin(0, 0, 1); update_col(0, 0, 1); for (int i = 1; i <= n; i++) { int x = a_perm[i]; vector>> buffs; for (int j = x + 1; j <= n; j++) { int buff = query_lin(j, x - 1); if (buff) buffs.push_back({buff, {j, x}}); } for (int q = 0; q < x; q++) { int buff = query_col(q, x - 1); if (buff) buffs.push_back({buff, {x, q}}); } for (auto &it : buffs) { int val = it.first; int lin = it.second.first; int col = it.second.second; update_lin(lin, col, val); update_col(col, lin, val); } } int ans = 0; for (int lin = 0; lin <= n; lin++) addSelf(ans, query_lin(lin, n)); return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,data_structures",hard 195,"Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i. Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest. Reduce nums[i] to nextLargest. Return the number of operations to make all elements in nums equal. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [5,1,3] Output: 3 Example 2: Input: nums = [1,1,1] Output: 0 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(vector& nums) { sort(nums.begin(), nums.end(), greater()); int operations = 0; for (int i = 1; i < nums.size(); ++i) { if (nums[i] != nums[i - 1]) { operations += i; } } return operations; } int solve2(vector& nums) { long long ops = 0; long long cum = 0; long long upper = LLONG_MAX; bool first = true; while (true) { long long cur = LLONG_MIN; int cnt = 0; for (int x : nums) { long long xv = x; if (xv < upper) { if (xv > cur) { cur = xv; cnt = 1; } else if (xv == cur) { ++cnt; } } } if (cnt == 0) break; if (!first) ops += cum; first = false; cum += cnt; upper = cur; } return (int)ops; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { const int sum = (n * (n + 1) / 2); const int pivot = sqrt(sum); return pivot * pivot == sum ? pivot : -1; } int solve2(int n) { long long total = 1LL * n * (n + 1) / 2; for (int x = 1; x <= n; ++x) { long long left = 1LL * x * (x + 1) / 2; long long right = total - 1LL * (x - 1) * x / 2; if (left == right) return x; } return -1; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { int ans = n; ans ^= ans >> 16; ans ^= ans >> 8; ans ^= ans >> 4; ans ^= ans >> 2; ans ^= ans >> 1; return ans; } int solve2(int n) { int res = 0; while (n) { res ^= n; n >>= 1; } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; // for(auto it:result) cout< using namespace std; class Solution { public: string solve1(string &a, string &b) { int n = a.size(); for (int i = 0; i < n - 1; i++) if (a[i] == '0' && b[i] == '0' && a[i + 1] == '1' && b[i + 1] == '1') return ""YES""; return ""NO""; } string solve2(string &a, string &b) { int n = (int)a.size(); for (int i = 0; i + 1 < n; ++i) { if (a[i] == '0' && a[i + 1] == '1' && b[i] == '0' && b[i + 1] == '1') return ""YES""; } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string a, b; cin >> a >> b; // solve Solution solution; auto result = solution.solve(a, b); // output cout << result << ""\n""; return 0; }","greedy,dp",hard 199,"# Problem Statement You are given an array of positive integers `a` of length `n` and a positive integer `k`. You will play the following game: - At the start of the game, choose an odd integer `x` (`1 ≤ x ≤ n`). - Then do the following at most `k` times (possibly zero times): - Select a subsequence of `a` of length `x`, then replace every value in the subsequence with the median of that subsequence. Note that the integer `x` you choose cannot change between operations. Determine the maximum possible value of the sum of `a` after playing the game. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, int &k, vector &a) { // write your code here } }; ``` where: - `n`: the length of the array - `k`: the maximum number of operations - `a`: the array of positive integers - return: the maximum achievable sum of the array after the game # Example 1: - Input: `n = 5` `k = 1` `a = [1, 1, 5, 5, 5]` - Output: `25` # Constraints: - $1 \leq n \leq @data$ - $1 \leq k \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 200, 120], [6400, 1600, 960]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &k, vector &a) { sort(a.begin(), a.end()); vector pre(n + 1, 0); for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + a[i]; auto sum = [&](int l, int r) -> long long { if (l > r) return 0LL; return pre[r + 1] - pre[l]; }; long long base = pre[n]; long long ans = base; for (int i = 0; i < n; i++) { int hi = min(i, n - 1 - i); if (hi <= 0) continue; auto calc = [&](int y) -> long long { int lcnt = min(i, y * k); int rcnt = min(n - 1 - i, y); return 1LL * a[i] * (lcnt + rcnt) - sum(0, lcnt - 1) - sum(i + 1, i + rcnt); }; int lo = 1, hiY = hi; while (lo < hiY) { int mid = (lo + hiY) / 2; if (calc(mid) < calc(mid + 1)) lo = mid + 1; else hiY = mid; } ans = max(ans, base + calc(lo)); } return ans; } long long solve2(int &n, int &k, vector &a) { sort(a.begin(), a.end()); long long base = 0; for (int i = 0; i < n; i++) base += a[i]; long long ans = base; for (int i = 0; i < n; i++) { int hi = min(i, n - 1 - i); if (hi <= 0) continue; long long leftSum = 0; int lcntPrev = 0; long long rightSum = 0; int rcnt = 0; for (int y = 1; y <= hi; y++) { int new_lcnt = i; long long inc_k = 1LL * y * k; if (inc_k < new_lcnt) new_lcnt = (int)inc_k; while (lcntPrev < new_lcnt) { leftSum += a[lcntPrev]; lcntPrev++; } if (rcnt < y) { rightSum += a[i + rcnt + 1]; rcnt++; } long long improvement = 1LL * a[i] * (lcntPrev + rcnt) - (leftSum + rightSum); long long total = base + improvement; if (total > ans) ans = total; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, k, a); // output cout << result << ""\n""; return 0; }","sort,binary",hard 200,"You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once. You are given an array processorTime representing the time each processor becomes available and an array tasks representing how long each task takes to complete. Return the minimum time needed to complete all tasks. solution main function ```cpp class Solution { public: int solve(vector& processorTime, vector& tasks) { } }; ``` Example 1: Input: processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5] Output: 16 Example 2: Input: processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3] Output: 23 Constraints: 1 <= n == processorTime.length <= @data 0 <= processorTime[i] <= 10^9 1 <= tasks[i] <= 10^9 tasks.length == 4 * n Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& t, vector& v) { int n=v.size(); sort(t.begin(),t.end()); sort(v.begin(),v.end()); int j=n-1; int m=t.size(); int ans=0; for(int i=0;i& t, vector& v) { int m = (int)t.size(); int n = (int)v.size(); for (int i = 0; i < m; ++i) { int mi = i; for (int j = i + 1; j < m; ++j) { if (t[j] < t[mi]) mi = j; } if (mi != i) { int tmp = t[i]; t[i] = t[mi]; t[mi] = tmp; } } for (int i = 0; i < n; ++i) { int mi = i; for (int j = i + 1; j < n; ++j) { if (v[j] < v[mi]) mi = j; } if (mi != i) { int tmp = v[i]; v[i] = v[mi]; v[mi] = tmp; } } long long ans = 0; int j = n - 1; for (int i = 0; i < m; ++i) { for (int c = 0; c < 4; ++c) { long long cur = (long long)t[i] + (long long)v[j]; if (cur > ans) ans = cur; --j; } } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector a,b; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } for(int i=1;i<=4*n;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output // for(auto it:result) cout< solve(int &ac, int &dr, int &n, vector &a, vector &d, int &m, vector> &ops) { // write your code here } }; ``` where: - `ac, dr`: movie parameters, - `n`: number of users, - `a, d`: arrays of length n with user thresholds, - `m`: number of updates, - `ops[j] = {k, na, nd}`: update user k (1-indexed) to (na, nd), - return: an array of length m, answers after each update. # Example Input: ``` 20 25 4 1 22 1 30 1 22 50 30 5 3 1 25 2 23 22 4 10 27 1 21 21 3 20 26 ``` Output: ``` 3 2 4 4 0 ``` # Constraints - $1 \le ac,dr \le 10^6$ - $1 \le n \le @data$ - $1 \le a_i,d_i \le 10^6$ - $1 \le m \le @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[200, 100, 64], [1600, 800, 400], [12800, 6400, 3200]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &ac, int &dr, int &n, vector &a, vector &d, int &m, vector> &ops) { struct SegTree { int N; int P; vector add, mn; SegTree() : N(0) {} explicit SegTree(int n) { init(n); } void init(int n) { N = n; P = 1; while (P < N) P <<= 1; add.assign(2 * P, 0); mn.assign(2 * P, 0); build(1, 0, P); } void build(int p, int l, int r) { if (l + 1 == r) { mn[p] = (l < N) ? -l : INT_MAX / 4; return; } int m = (l + r) >> 1; build(p << 1, l, m); build(p << 1 | 1, m, r); mn[p] = std::min(mn[p << 1], mn[p << 1 | 1]); } inline void apply(int p, int v) { add[p] += v; mn[p] += v; } inline void push(int p) { if (add[p] != 0) { apply(p << 1, add[p]); apply(p << 1 | 1, add[p]); add[p] = 0; } } void range_add(int p, int l, int r, int L, int R, int v) { if (L >= R) return; if (L <= l && r <= R) { apply(p, v); return; } push(p); int m = (l + r) >> 1; if (L < m) range_add(p << 1, l, m, L, R, v); if (R > m) range_add(p << 1 | 1, m, r, L, R, v); mn[p] = std::min(mn[p << 1], mn[p << 1 | 1]); } void range_add(int L, int R, int v) { if (L < 0) L = 0; if (R > N) R = N; if (L >= R) return; range_add(1, 0, P, L, R, v); } int first_negative(int p, int l, int r) { if (l + 1 == r) return l; push(p); int m = (l + r) >> 1; if (mn[p << 1] < 0) return first_negative(p << 1, l, m); return first_negative(p << 1 | 1, m, r); } int first_negative() { return first_negative(1, 0, P); } }; auto calcP = [&](int ai, int di) -> int { long long x = (long long)max(ai - ac, 0); long long y = (long long)max(di - dr, 0); long long s = x + y; if (s > n) s = n; return (int)s; }; SegTree st(n + 2); for (int i = 0; i < n; i++) { int p = calcP(a[i], d[i]); st.range_add(p + 1, n + 2, 1); } vector ans; ans.reserve(m); for (int j = 0; j < m; j++) { int k = ops[j][0] - 1; int na = ops[j][1]; int nd = ops[j][2]; int oldp = calcP(a[k], d[k]); st.range_add(oldp + 1, n + 2, -1); a[k] = na; d[k] = nd; int newp = calcP(a[k], d[k]); st.range_add(newp + 1, n + 2, 1); int firstNeg = st.first_negative(); ans.push_back(firstNeg - 1); } return ans; } vector solve2(int &ac, int &dr, int &n, vector &a, vector &d, int &m, vector> &ops) { vector ans; ans.reserve(m); for (int j = 0; j < m; j++) { int k = ops[j][0] - 1; int na = ops[j][1]; int nd = ops[j][2]; a[k] = na; d[k] = nd; int p = 0; while (true) { int cnt = 0; for (int i = 0; i < n; i++) { int x = a[i] - ac; if (x < 0) x = 0; int y = d[i] - dr; if (y < 0) y = 0; long long s = (long long)x + (long long)y; if (s <= p) cnt++; } if (cnt == p) break; p = cnt; } ans.push_back(p); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int ac, dr; cin >> ac >> dr; int n; cin >> n; vector a(n), d(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> d[i]; int m; cin >> m; vector> ops(m); for (int i = 0; i < m; i++) { int k, na, nd; cin >> k >> na >> nd; ops[i] = {k, na, nd}; } // solve Solution solution; auto res = solution.solve(ac, dr, n, a, d, m, ops); // output for (int i = 0; i < (int)res.size(); i++) { cout << res[i] << ""\n""; } return 0; } ",data_structures,hard 202,"You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6. Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0. solution main function ```cpp class Solution { public: int solve(vector& rods) { } }; ``` Example 1: Input: rods = [1,2,3,6] Output: 6 Example 2: Input: rods = [1,2,3,4,5,6] Output: 10 Constraints: 1 <= rods.length <= @data 1 <= rods[i] <= 1000 sum(rods[i]) <= 100*@data Time limit: @time_limit ms Memory limit: @memory_limit KB","[30, 100, 1000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& rods) { int sum = 0; for (int rod : rods) { sum += rod; } int dp[sum + 1]; dp[0] = 0; for (int i = 1; i <= sum; i++) { dp[i] = -1; } for (int rod : rods) { int dpCopy[sum + 1]; copy(dp, dp + (sum + 1), dpCopy); for (int i = 0; i <= sum - rod; i++) { if (dpCopy[i] < 0) continue; dp[i + rod] = max(dp[i + rod], dpCopy[i]); dp[abs(i - rod)] = max(dp[abs(i - rod)], dpCopy[i] + min(i, rod)); } } return dp[0]; } int solve2(vector& rods) { int n = (int)rods.size(); long long best = 0; unsigned long long totalStates = 1ULL; bool overflow = false; for (int i = 0; i < n; ++i) { if (totalStates > ULLONG_MAX / 3ULL) { overflow = true; break; } totalStates *= 3ULL; } if (!overflow) { for (unsigned long long idx = 0; idx < totalStates; ++idx) { unsigned long long t = idx; long long L = 0, R = 0; for (int j = 0; j < n; ++j) { unsigned long long d = t % 3ULL; t /= 3ULL; if (d == 1ULL) L += rods[j]; else if (d == 2ULL) R += rods[j]; } if (L == R && L > best) best = L; } if (best > INT_MAX) best = INT_MAX; return (int)best; } if (n >= 63) n = 62; unsigned long long limit = (n >= 64 ? ~0ULL : ((n == 64) ? ~0ULL : ((1ULL << n) - 1ULL))); for (unsigned long long Lmask = 0; Lmask <= limit; ++Lmask) { long long sumL = 0; for (int j = 0; j < n; ++j) if ((Lmask >> j) & 1ULL) sumL += rods[j]; unsigned long long comp = limit ^ Lmask; unsigned long long Rmask = comp; while (true) { long long sumR = 0; for (int j = 0; j < n; ++j) if ((Rmask >> j) & 1ULL) sumR += rods[j]; if (sumL == sumR && sumL > best) best = sumL; if (Rmask == 0) break; Rmask = (Rmask - 1) & comp; } } if (best > INT_MAX) best = INT_MAX; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }",dp,hard 203,"# Problem Statement You are given an array $d_1, d_2, \dots, d_n$ consisting of $n$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $sum_1$, the sum of elements of the second part be $sum_2$ and the sum of elements of the third part be $sum_3$. Among all possible ways to split the array you have to choose a way such that $sum_1 = sum_3$ and $sum_1$ is maximum possible. More formally, if the first part of the array contains $a$ elements, the second part of the array contains $b$ elements and the third part contains $c$ elements, then: $$ sum_1 = \sum\limits_{1 \le i \le a}d_i, $$ $$ sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i, $$ $$ sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i. $$ The sum of an empty array is $0$. Your task is to find a way to split the array such that $sum_1 = sum_3$ and $sum_1$ is maximum possible. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &d) { // write your code here } }; ``` where: - return: the maximum possible value of sum1, considering that the condition sum1=sum3 must be met. # Example 1: - Input: n = 5 d = [1, 3, 1, 1, 4] - Output: 5 # Constraints: - $1 \leq n \leq @data$ - $1 \leq d[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &d) { int x = 0, y = n - 1; long long sumx = 0, sumy = 0; long long ans = 0; while (x <= y) { if (sumx < sumy) sumx += d[x++]; else sumy += d[y--]; if (sumx == sumy && sumx > ans) ans = sumx; } return ans; } long long solve2(int &n, vector &d) { long long ans = 0; long long s1 = 0; for (int a = 0; a <= n; ++a) { if (a > 0) s1 += (long long)d[a - 1]; long long s3 = 0; for (int c = 0; c <= n - a; ++c) { if (c > 0) s3 += (long long)d[n - c]; if (s1 == s3 && s1 > ans) ans = s1; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","binary,data_structures,two_pointers",medium 204,"# Problem Statement One day, Vogons wanted to build a new hyperspace highway through a distant system with $n$ planets. The $i$-th planet is on the orbit $a_i$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed. Vogons have two machines to do that. - The first machine in one operation can destroy any planet at cost of $1$ Triganic Pu. - The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $c$ Triganic Pus. Vogons can use each machine as many times as they want. Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project? The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &c, vector &a) { // write your code here } }; ``` where: - return: the minimum cost of destroying all planets. # Example 1: - Input: n = 10, c = 1 a = [2, 1, 4, 5, 2, 4, 5, 5, 1, 2] - Output: 4 # Constraints: - $1 \leq n\leq @data$ - $1 \leq c\leq 10$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &c, vector &a) { sort(a.begin(), a.end()); int ans = 0; for (int i = 0; i < a.size(); i++) { int cnt = 1; while (i + 1 < a.size() && a[i] == a[i + 1]) { i++; cnt++; } ans += min(cnt, c); } return ans; } int solve2(int &n, int &c, vector &a) { long long ans = 0; for (int i = 0; i < (int)a.size(); i++) { bool seen = false; for (int k = 0; k < i; k++) { if (a[k] == a[i]) { seen = true; break; } } if (seen) continue; long long cnt = 0; for (int j = i; j < (int)a.size(); j++) { if (a[j] == a[i]) cnt++; } ans += min(cnt, c); } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, c; cin >> n >> c; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, c, a); // output cout << result << ""\n""; return 0; }","sort,greedy",medium 205,"# Problem Statement On the board Ivy wrote down all integers from $l$ to $r$, inclusive. In an operation, she does the following: - pick two numbers $x$ and $y$ on the board, erase them, and in their place write the numbers $3x$ and $\lfloor \frac{y}{3} \rfloor$. (Here $\lfloor \bullet \rfloor$ denotes rounding down to the nearest integer). What is the minimum number of operations Ivy needs to make all numbers on the board equal $0$? We have a proof that this is always possible. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &l, int &r) { // write your code here } }; ``` where: the minimum number of operations needed to make all numbers on the board equal 0. - return: # Example 1: - Input: l = 1, r = 3 - Output: 5 # Constraints: - $1 \leq l \leq r \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 1000000, 100000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &l, int &r) { int ans = 0; int mn = -1; for (int x = 1, t = 1; x <= r; x *= 3, t++) { if (l >= x) mn = t; ans += max(0, min(r, 3 * x - 1) - max(l, x) + 1) * t; } ans += mn; return ans; } int solve2(int &l, int &r) { long long ans = 0; for (int n = l; n <= r; ++n) { int t = n; while (t > 0) { ans++; t /= 3; } } int t = l; while (t > 0) { ans++; t /= 3; } if (ans > INT_MAX) return INT_MAX; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int l, r; cin >> l >> r; // solve Solution solution; auto result = solution.solve(l, r); // output cout << result << ""\n""; return 0; }","sort,two_pointers",hard 206,"# Problem Statement You are given a full binary tree of `n` nodes (rooted at node `1`). For each node `u (1 ≤ u ≤ n)`, define a function `f_u : R^+ -> R^+`: - If `u` is a leaf, then `f_u(x) = x`; - Otherwise, let its left and right children be `l_u` and `r_u`, then `f_u(x) = (f_{l_u}(x))^{f_{r_u}(x)}`. For two nodes `u` and `v`, define the strict order `u ≺ v` as: - If `f_u(x) < f_v(x)` as `x → ∞`, then `u ≺ v`; - If `f_u(x) = f_v(x)` as `x → ∞`, then break ties by index: `u < v` implies `u ≺ v`. It can be shown that for any two distinct nodes `u` and `v`, exactly one of `u ≺ v` or `v ≺ u` holds. You need to sort all nodes by `≺` and output a permutation `p` of length `n` such that for every `1 ≤ i < n`, `p_i ≺ p_{i+1}`. The main function of the solution is defined as: ```cpp class Solution { public: vector solve(int &n, vector &L, vector &R) { // write your code here } }; ``` where: - `n`: number of nodes (odd); - `L[i], R[i]`: the left and right child of node `i`, `0` if `i` is a leaf; - return: the nodes in increasing order by `≺`. # Example 1 - Input: ``` n = 3 L,R: 2 3 0 0 0 0 ``` - Output: ``` 2 3 1 ``` # Constraints - $1 \le n \le @data$ (and `n` is odd) - The input is guaranteed to be a full binary tree rooted at `1` - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &n, vector &L, vector &R) { int N = n; vector deg(N + 1, 0); vector fa(N + 1, 0); for (int i = 1; i <= N; i++) { if (L[i] && R[i]) deg[i] = 2; if (L[i]) fa[L[i]] = i; if (R[i]) fa[R[i]] = i; } struct PSTNode { int l, r, num; unsigned long long val; }; vector t; t.reserve(((N > 1 ? (N - 1) / 2 : 0) + 5) * 18); t.push_back({0, 0, 0, 0}); int cnt = 0; auto add = [&](auto &&self, int &p, int pre, int Lb, int Rb, int k, unsigned long long x) -> void { t.push_back(t[pre]); p = ++cnt; t[p].val += x; t[p].num++; if (Lb == Rb) return; int mid = (Lb + Rb) >> 1; if (k <= mid) self(self, t[p].l, t[pre].l, Lb, mid, k, x); else self(self, t[p].r, t[pre].r, mid + 1, Rb, k, x); }; auto findDiff = [&](auto &&self, int p, int pre, int Lb, int Rb) -> bool { if (Lb == Rb) return t[p].num > t[pre].num; int mid = (Lb + Rb) >> 1; if (t[t[p].r].val == t[t[pre].r].val) return self(self, t[p].l, t[pre].l, Lb, mid); else return self(self, t[p].r, t[pre].r, mid + 1, Rb); }; unsigned long long A = std::mt19937_64(std::chrono::steady_clock::now().time_since_epoch().count())(); auto shift = [&](unsigned long long x) -> unsigned long long { x ^= A; x ^= x << 13; x ^= x >> 7; x ^= x << 11; x ^= A; return x; }; vector h(N + 1, 0); vector rt(N + 1, 0), rk(N + 1, 0); auto upd = [&](int u) { h[u] = h[L[u]] + shift(h[R[u]]); unsigned long long w = shift(h[R[u]]); add(add, rt[u], rt[L[u]], 1, N, rk[R[u]], w); }; auto cmp = [&](int x, int y) { if (h[x] == h[y]) return x > y; return findDiff(findDiff, rt[x], rt[y], 1, N); }; priority_queue, decltype(cmp)> q(cmp); for (int i = 1; i <= N; i++) { if (deg[i] == 0) { h[i] = 1; q.emplace(i); } } vector ans; ans.reserve(N); int lst = 0, tot = 0; while (!q.empty()) { int u = q.top(); q.pop(); ans.push_back(u); if (h[u] != h[lst]) tot++; lst = u; rk[u] = tot; int f = fa[u]; if (f != 0) { deg[f]--; if (deg[f] == 0) { upd(f); q.emplace(f); } } } return ans; } vector solve2(int &n, vector &L, vector &R) { int N = n; auto rdepth = [&](int u) -> int { int d = 0; while (u && R[u]) { u = R[u]; d++; } return d; }; function cmp = [&](int a, int b) -> int { if (a == b) return 0; int da = rdepth(a), db = rdepth(b); if (da < db) return -1; if (da > db) return 1; if (da == 0) return 0; int ua = a, ub = b; for (int j = 0; j < da; j++) { int la = L[ua], lb = L[ub]; int c = cmp(la, lb); if (c != 0) return c; ua = R[ua]; ub = R[ub]; } return 0; }; vector ans; ans.reserve(N); for (int t = 0; t < N; t++) { int best = 0; for (int i = 1; i <= N; i++) { bool used = false; for (int k = 0; k < (int)ans.size(); k++) if (ans[k] == i) { used = true; break; } if (used) continue; if (best == 0) best = i; else { int c = cmp(i, best); if (c < 0 || (c == 0 && i < best)) best = i; } } ans.push_back(best); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector L(n + 1), R(n + 1); for (int i = 1; i <= n; i++) cin >> L[i] >> R[i]; // solve Solution solution; auto result = solution.solve(n, L, R); // output for (int i = 0; i < (int)result.size(); i++) cout << result[i] << "" \n""[i + 1 == (int)result.size()]; return 0; }","data_structures,graph",hard 207,"Given two 0-indexed integer arrays nums1 and nums2 with the same length, return a list answer of size 2 where: answer[0] is a list of all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct integers in nums2 which are not present in nums1. The integers in each list must be returned in ascending order. solution main function ```cpp class Solution { public: vector> solve(vector& nums1, vector& nums2) { } }; ``` Example 1: Input: nums1 = [1,2,3], nums2 = [2,4,6] Output: [[1,3],[4,6]] Example 2: Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2] Output: [[3],[]] Constraints: 1 <= nums1.length == nums2.length <= @data -@data <= nums1[i], nums2[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 125], [64000, 6400, 1000]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector> solve(vector& nums1, vector& nums2) { set set1(nums1.begin(),nums1.end()); set set2(nums2.begin(),nums2.end()); vector temp; for (const auto & item: set1) { if (set2.find(item)==set2.end()) { temp.push_back(item); } } vector temp2; for (const auto & item: set2) { if (set1.find(item)==set1.end()) { temp2.push_back(item); } } sort(temp.begin(),temp.end()); sort(temp2.begin(),temp2.end()); return {temp, temp2}; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector a,b; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } for(int i=1;i<=n;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output // cout << result << ""\n""; for(auto it:result) { for(auto i:it) cout<& nums) { } }; ``` Example 1: Input: nums = [2,1,3,4,5,2] Output: 7 Example 2: Input: nums = [2,3,5,1,3,2] Output: 5 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: long long solve1(vector& nums) { long long ans = 0; for (int i = 0; i < nums.size(); i += 2) { int currentStart = i; while (i + 1 < nums.size() && nums[i + 1] < nums[i]) { i++; } for (int currentIndex = i; currentIndex >= currentStart; currentIndex -= 2) { ans += nums[currentIndex]; } } return ans; } long long solve2(vector& nums) { long long ans = 0; int n = (int)nums.size(); while (true) { int minIdx = -1; int minVal = 0; for (int i = 0; i < n; ++i) { if (nums[i] > 0) { if (minIdx == -1 || nums[i] < minVal) { minIdx = i; minVal = nums[i]; } } } if (minIdx == -1) break; ans += (long long)minVal; if (minIdx - 1 >= 0) nums[minIdx - 1] = 0; nums[minIdx] = 0; if (minIdx + 1 < n) nums[minIdx + 1] = 0; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout< using namespace std; class Solution { public: int solve1(int &n, char &c, string &s) { int ans = 0, x = 0; for (int t = 0; t < 2; t++) { for (int i = n - 1; i >= 0; i--) { if (s[i] == 'g') x = 0; else x++; if (s[i] == c && t) ans = max(ans, x); } } return ans; } int solve2(int &n, char &c, string &s) { if (c == 'g') return 0; int ans = 0; for (int i = 0; i < n; i++) { if (s[i] != c) continue; int steps = 1; int j = i + 1; if (j == n) j = 0; while (s[j] != 'g') { steps++; j++; if (j == n) j = 0; } if (steps > ans) ans = steps; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; char c; cin >> c; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, c, s); // output cout << result << ""\n""; return 0; }","two_pointers,binary",medium 210,"# Problem Statement You are given an array of integers $a_1,a_2,\dots,a_n$. You may repeatedly perform the following operation: - Choose indices $1 \le i \le j \le n$; - Update $a_j \leftarrow a_j \oplus a_i$ (bitwise XOR). There are $q$ queries. For each query $(l,r)$, you are allowed to use only indices inside $[l,r]$. Determine whether the subarray $a_l,\dots,a_r$ can be transformed into a strictly increasing sequence using any number of such operations. The main function of the solution is defined as: ```cpp class Solution { public: vector solve(int &n, int &q, vector &a, vector> &queries) { // write your code here } }; ``` where: - `n`: length of the array - `q`: number of queries - `a`: the array - `queries`: list of `{l, r}` (1-based) - return: an array of strings, each is ""YES"" or ""NO"" # Example - Input: ``` n = 4, q = 4 a = [1, 2, 2, 1] queries = [(1,1),(1,2),(1,3),(1,4)] ``` - Output: ``` [""YES"",""YES"",""YES"",""YES""] ``` # Constraints - $1 \le n \le @data$ - $1 \le q \le @data$ - $1 \le a_i < 2^{20}$ - $1 \le l \le r \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1500,"[[512, 200, 100], [4096, 1600, 800], [32768, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int K = 20; vector solve1(int &n, int &q, vector &a, vector> &queries) { int vx[20] = {0}; int vy[20] = {0}; auto kth = [&](int r, int k) -> int { if (k == -1) return -1; int cnt = 0, ans = 0; for (int i = 0; i < K; i++) cnt += (vx[i] && vy[i] <= r); for (int i = K - 1; i >= 0; i--) if (vx[i] && vy[i] <= r) { cnt--; if (((ans >> i) & 1) != ((k >> cnt) & 1)) ans ^= vx[i]; } return ans; }; auto rankv = [&](int r, int k) -> int { if (k == -1) return -1; int ans = 0; for (int i = K - 1; i >= 0; i--) if (vx[i] && vy[i] <= r) ans = (ans << 1) | ((k >> i) & 1); return ans; }; auto calc_best_r = [&](int l) -> int { int pos[20], pc = 0; for (int i = 0; i < K; i++) if (vx[i]) pos[pc++] = vy[i]; sort(pos, pos + pc); int curVal = -1; int last = l; int used = 0; for (int t = 0; t < pc; t++) { int p = pos[t]; if (p <= last) { used++; continue; } int rk = rankv(last, curVal); int cap = (1 << used) - 1 - rk; if (cap < 0) return last - 1; int block = p - last; if (cap < block) return last + cap; rk += block; curVal = kth(last, rk); used++; last = p; } int rk = rankv(last, curVal); int cap = (1 << used) - 1 - rk; if (cap < 0) return last - 1; int tail = n - last; return last + min(tail, cap); }; vector bestR(n, 0); for (int i = n - 1; i >= 0; i--) { int x = a[i], y = i; for (int j = K - 1; j >= 0; j--) { if ((x >> j) & 1) { if (!vx[j]) { vx[j] = x; vy[j] = y; break; } if (y < vy[j]) { swap(x, vx[j]); swap(y, vy[j]); } x ^= vx[j]; } } bestR[i] = calc_best_r(i); } vector res; res.reserve(q); for (int i = 0; i < q; i++) { int l = queries[i][0], r = queries[i][1]; l--; res.push_back(r <= bestR[l] ? ""YES"" : ""NO""); } return res; } vector solve2(int &n, int &q, vector &a, vector> &queries) { vector res; res.reserve(q); for (int qi = 0; qi < q; ++qi) { int l = queries[qi][0] - 1; int r = queries[qi][1]; int vx[20] = {0}; int vy[20] = {0}; auto kth = [&](int rr, int k) -> int { if (k == -1) return -1; int cnt = 0, ans = 0; for (int i = 0; i < K; i++) cnt += (vx[i] && vy[i] <= rr); for (int i = K - 1; i >= 0; i--) if (vx[i] && vy[i] <= rr) { cnt--; if (((ans >> i) & 1) != ((k >> cnt) & 1)) ans ^= vx[i]; } return ans; }; auto rankv = [&](int rr, int k) -> int { if (k == -1) return -1; int ans = 0; for (int i = K - 1; i >= 0; i--) if (vx[i] && vy[i] <= rr) ans = (ans << 1) | ((k >> i) & 1); return ans; }; auto calc_best_r = [&](int ll) -> int { int pos[20], pc = 0; for (int i = 0; i < K; i++) if (vx[i]) pos[pc++] = vy[i]; sort(pos, pos + pc); int curVal = -1; int last = ll; int used = 0; for (int t = 0; t < pc; t++) { int p = pos[t]; if (p <= last) { used++; continue; } int rk = rankv(last, curVal); int cap = (1 << used) - 1 - rk; if (cap < 0) return last - 1; int block = p - last; if (cap < block) return last + cap; rk += block; curVal = kth(last, rk); used++; last = p; } int rk = rankv(last, curVal); int cap = (1 << used) - 1 - rk; if (cap < 0) return last - 1; int tail = n - last; return last + min(tail, cap); }; for (int i = n - 1; i >= l; --i) { int x = a[i], y = i; for (int j = K - 1; j >= 0; --j) { if ((x >> j) & 1) { if (!vx[j]) { vx[j] = x; vy[j] = y; break; } if (y < vy[j]) { swap(x, vx[j]); swap(y, vy[j]); } x ^= vx[j]; } } } int br = calc_best_r(l); res.push_back(r <= br ? ""YES"" : ""NO""); } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, q; cin >> n >> q; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector> queries(q); for (int i = 0; i < q; i++) cin >> queries[i][0] >> queries[i][1]; // solve Solution solution; auto result = solution.solve(n, q, a, queries); // output for (int i = 0; i < (int)result.size(); i++) cout << result[i] << ""\n""; return 0; }",data_structures,hard 211,"You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step. A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process. solution main function ```cpp class Solution { public: int solve(vector& flips) { } }; ``` Example 1: Input: flips = [3,2,4,1,5] Output: 2 Example 2: Input: flips = [4,1,2,3] Output: 1 Constraints: n == flips.length 1 <= n <= @data flips is a permutation of the integers in the range [1, n]. Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& flips) { int n = flips.size(); int s1 = 0; int s2 = 0; int ans = 0; for (int i = 0; i < n; i++) { s1 += i + 1; s2 += flips[i]; if (s1 == s2) { ans++; } } return ans; } int solve2(vector& flips) { int n = (int)flips.size(); int ans = 0; for (int i = 0; i < n; ++i) { int mx = 0; for (int j = 0; j <= i; ++j) { if (flips[j] > mx) mx = flips[j]; } if (mx == i + 1) ++ans; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return the value of $k$. # Example 1: - Input: n = 4 a = [10, -9, -3, 4] - Output: 6 # Constraints: - $2 \leq n \leq @data$ - $-10^9 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { long long c1 = 0, c2 = 0; for (int i = 0; i < n; i++) { long long pre1 = c1, pre2 = c2; c1 = max({pre1 + a[i], abs(pre2 + a[i])}); c2 = pre2 + a[i]; } return c1; } long long solve2(int &n, vector &a) { if (n <= 24) { long long ans = LLONG_MIN; unsigned long long total = 1ULL << n; for (unsigned long long mask = 0; mask < total; ++mask) { long long c = 0; for (int i = 0; i < n; ++i) { long long s = c + (long long)a[i]; if ((mask >> i) & 1ULL) c = s >= 0 ? s : -s; else c = s; } if (c > ans) ans = c; } return ans; } else { long long best = 0, sum = 0; for (int i = 0; i < n; ++i) { long long v1 = best + (long long)a[i]; long long v2 = sum + (long long)a[i]; if (v2 < 0) v2 = -v2; long long nb = v1 > v2 ? v1 : v2; sum += (long long)a[i]; best = nb; } return best; } } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",dp,medium 213,"# Problem Statement A permutation $b$ is considered a riffle shuffle of a permutation $a$ if $\|a\|=\|b\|$ and there exists $k$ ($1\le k<\|a\|$) such that both $a_1,a_2,\dots,a_k$ and $a_{k+1},a_{k+2},\dots,a_{\|a\|}$ are subsequences of $b$. You are given a permutation $p$ of length $n$ where some values are replaced with $-1$. Determine the number of ways to replace each $-1$ with an integer so that $p$ becomes a riffle shuffle of $[1,2,\dots,n]$ (the sorted permutation). Output the number of ways modulo $998244353$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &p) { // write your code here } }; ``` where: - `n`: the length of the permutation. - `p`: an array of length `n`. Each `p[i]` is either `-1` or an integer in `[1, n]`. All elements different from `-1` are pairwise distinct. - return: the number of valid completions modulo `998244353`. # Example 1: - Input: ``` n = 5 p = [-1, -1, -1, 2, -1] ``` - Output: ``` 6 ``` # Constraints: - $1 \leq n \leq @data$ - $p[i] \in \{-1\} \cup [1,n]$, and all known values are distinct - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 287, 240], [6400, 2300, 1920]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { private: static constexpr int MOD = 998244353; struct Mint { int x; Mint(long long v = 0) { v %= Solution::MOD; if (v < 0) v += Solution::MOD; x = (int)v; } Mint& operator+=(const Mint& o){ x += o.x; if (x >= Solution::MOD) x -= Solution::MOD; return *this; } Mint& operator-=(const Mint& o){ x -= o.x; if (x < 0) x += Solution::MOD; return *this; } Mint& operator*=(const Mint& o){ x = (int)((long long)x * o.x % Solution::MOD); return *this; } friend Mint operator+(Mint a, const Mint& b){ return a += b; } friend Mint operator-(Mint a, const Mint& b){ return a -= b; } friend Mint operator*(Mint a, const Mint& b){ return a *= b; } static Mint pow(Mint a, long long e){ Mint r = 1; while (e){ if (e & 1) r *= a; a *= a; e >>= 1; } return r; } static Mint inv(Mint a){ return pow(a, Solution::MOD - 2); } }; inline static vector FAC{1, 1}, IFAC{1, 1}; inline static int MAX_DONE = 1; static void grow(int need) { int m = MAX_DONE; while (m < need) m <<= 1; if (m <= MAX_DONE) return; FAC.resize(m + 1); IFAC.resize(m + 1); for (int i = MAX_DONE + 1; i <= m; i++) FAC[i] = FAC[i - 1] * Mint(i); IFAC[m] = Mint::inv(FAC[m]); for (int i = m - 1; i > MAX_DONE; i--) IFAC[i] = IFAC[i + 1] * Mint(i + 1); MAX_DONE = m; } static inline Mint nCr(int n, int r) { if (r < 0 || r > n) return Mint(0); grow(n); return FAC[n] * IFAC[r] * IFAC[n - r]; } public: int solve1(int &n, vector &p) { vector a(n); for (int i = 0; i < n; i++) { int v = p[i]; a[i] = (v == -1 ? -1 : v - 1); } bool allFixedSorted = true; for (int i = 0; i < n; i++) if (a[i] != -1 && a[i] != i) { allFixedSorted = false; break; } if (allFixedSorted) { vector pow2(n + 1); pow2[0] = 1; for (int i = 1; i <= n; i++) pow2[i] = pow2[i - 1] * Mint(2); int last = -1; Mint ans = 0; for (int i = 0; i <= n; i++) { if (i == n || a[i] != -1) { int len = i - last - 1; ans += pow2[len] - Mint(len) - Mint(1); last = i; } } ans += Mint(1); int out = ans.x; if (out < 0) out += MOD; return out; } vector side(n, 0); bool seenDiff = false; for (int i = 0; i < n; i++) { if (a[i] == -1) continue; if (a[i] < i) side[i] = 0; if (a[i] > i) side[i] = 1; if (a[i] == i) side[i] = seenDiff ? 1 : 0; if (a[i] != i) seenDiff = true; } int last = -1; vector> ranges; for (int i = 0; i < n; i++) { if (a[i] == -1) continue; if (last == -1) { last = i; continue; } if (side[i] && !side[last]) { int mn = last - a[last]; int mx = mn + (i - last); int L = a[i] - mx; int R = a[i] - mn + 1; ranges.push_back({L, R}); } if (!side[i] && side[last]) { int mx = i - a[i]; int mn = mx - (i - last); int L = a[last] - mx; int R = a[last] - mn + 1; ranges.push_back({L, R}); } last = i; } int L = 0, R = n - 1; for (auto &pr : ranges) { L = max(L, pr.first); R = min(R, pr.second); } L = max(L, 0); R = min(R, n - 1); Mint coef = 1; vector score(n, Mint(0)); if (L <= R) for (int k = L; k <= R; k++) score[k] = Mint(1); last = -1; for (int i = 0; i < n; i++) { if (a[i] == -1) continue; bool prevSide = (last == -1 ? 0 : side[last]); int spaces = i - last - 1; if ((side[i] && prevSide) || (!side[i] && !prevSide)) { int cnt = (last == -1 ? a[i] : a[i] - a[last] - 1); coef *= nCr(spaces, cnt); } if (side[i] && !prevSide) { for (int k = L; k <= R; k++) { int placed = (last == -1 ? 0 : last - a[last]); int need = a[i] - (k + placed); score[k] *= nCr(spaces, need); } } if (!side[i] && prevSide) { for (int k = L; k <= R; k++) { int big = i - a[i] + k - 1; int need = big - a[last]; score[k] *= nCr(spaces, need); } } last = i; } if (last != -1) { for (int k = L; k <= R; k++) { if (!side[last]) { score[k] *= nCr(n - last - 1, k - a[last] - 1); } else { score[k] *= nCr(n - last - 1, n - 1 - a[last]); } } } Mint ans = 0; for (int i = 0; i < n; i++) ans += score[i]; ans *= coef; return ans.x; } int solve2(int &n, vector &p) { int m = 0; for (int i = 0; i < n; i++) if (p[i] == -1) m++; for (int i = 0; i < n; i++) if (p[i] != -1) p[i] = -(p[i] + n + 1); int pos = 0; for (int v = 1; v <= n; v++) { bool present = false; for (int i = 0; i < n; i++) { int w = p[i]; if (w == -1) continue; if (w < -1) w = -w - n - 1; if (w == v) { present = true; break; } } if (!present) { while (pos < n && p[pos] != -1) pos++; if (pos < n) { p[pos] = v; pos++; } } } auto isRiffle = [&]() -> bool { for (int k = 1; k <= n - 1; k++) { int lastR = 0, lastB = k; bool good = true; for (int i = 0; i < n; i++) { int val = p[i]; if (val < -1) val = -val - n - 1; if (val <= k) { if (val <= lastR) { good = false; break; } lastR = val; } else { if (val <= lastB) { good = false; break; } lastB = val; } } if (good) return true; } return false; }; auto next_perm = [&]() -> bool { int pivot_idx = -1; bool have_prev = false; int prev_val = 0; for (int i = n - 1; i >= 0; --i) { if (p[i] > 0) { if (have_prev) { if (p[i] < prev_val) { pivot_idx = i; break; } } prev_val = p[i]; have_prev = true; } } if (pivot_idx == -1) return false; int pivot_val = p[pivot_idx]; int succ_idx = -1; for (int i = n - 1; i > pivot_idx; --i) { if (p[i] > 0 && p[i] > pivot_val) { succ_idx = i; break; } } int t = p[succ_idx]; p[succ_idx] = p[pivot_idx]; p[pivot_idx] = t; int left = pivot_idx + 1; while (left < n && p[left] <= 0) ++left; int right = n - 1; while (right >= 0 && p[right] <= 0) --right; while (left < right) { int tmp = p[left]; p[left] = p[right]; p[right] = tmp; int j = left + 1; while (j < n && p[j] <= 0) ++j; left = j; j = right - 1; while (j >= 0 && p[j] <= 0) --j; right = j; } return true; }; int ans = 0; while (true) { if (isRiffle()) { ans++; if (ans >= MOD) ans -= MOD; } if (!next_perm()) break; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector p(n); for (int i = 0; i < n; i++) cin >> p[i]; // solve Solution solution; auto result = solution.solve(n, p); // output cout << result << ""\n""; return 0; }",math,hard 214,"You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where: The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right. The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces. Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false. solution main function ```cpp class Solution { public: bool solve(string start, string target) { } }; ``` Example 1: Input: start = ""_L__R__R_"", target = ""L______RR"" Output: 1 Example 2: Input: start = ""R_L_"", target = ""__LR"" Output: 0 Constraints: n == start.length == target.length 1 <= n <= @data start and target consist of the characters 'L', 'R', and '_'. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 150]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve1(string start, string target) { int startLength = start.size(); int startIndex = 0, targetIndex = 0; while (startIndex < startLength || targetIndex < startLength) { while (startIndex < startLength && start[startIndex] == '_') { startIndex++; } while (targetIndex < startLength && target[targetIndex] == '_') { targetIndex++; } if (startIndex == startLength || targetIndex == startLength) { return startIndex == startLength && targetIndex == startLength; } if (start[startIndex] != target[targetIndex] || (start[startIndex] == 'L' && startIndex < targetIndex) || (start[startIndex] == 'R' && startIndex > targetIndex)) return false; startIndex++; targetIndex++; } return true; } bool solve2(string start, string target) { int n = (int)start.size(); if ((int)target.size() != n) return false; int i = 0, j = 0; while (true) { while (i < n && start[i] == '_') ++i; while (j < n && target[j] == '_') ++j; if (i == n || j == n) { if (i == n && j == n) break; return false; } if (start[i] != target[j]) return false; ++i; ++j; } i = 0; j = 0; while (true) { while (i < n && start[i] != 'L') ++i; while (j < n && target[j] != 'L') ++j; if (i == n || j == n) { if (i == n && j == n) break; return false; } if (i < j) return false; ++i; ++j; } i = 0; j = 0; while (true) { while (i < n && start[i] != 'R') ++i; while (j < n && target[j] != 'R') ++j; if (i == n || j == n) { if (i == n && j == n) break; return false; } if (i > j) return false; ++i; ++j; } return true; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string a,b; cin>>a>>b; // solve Solution solution; int result = solution.solve(a,b); // output cout << result << ""\n""; return 0; }","two_pointers,string",medium 215,"There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. solution main function ```cpp class Solution { public: int solve(vector>& edges) { // write your code here } }; ``` Example 1: Input: edges = [[1,2],[2,3],[4,2]] Output: 2 Constraints: 2 <= n <= @data edges.length == n - 1 edges[i].length == 2 1 <= ui, vi <= n ui ! = vi Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& edges) { return edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1] ? edges[0][0] : edges[0][1]; } int solve2(vector>& edges) { int a = edges[0][0]; int b = edges[0][1]; int cntA = 0, cntB = 0; for (size_t i = 0; i < edges.size(); ++i) { cntA += (edges[i][0] == a) || (edges[i][1] == a); cntB += (edges[i][0] == b) || (edges[i][1] == b); } return cntA >= cntB ? a : b; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector > edge; for(int i=1;i>x>>y; vector temp; temp.push_back(x); temp.push_back(y); edge.push_back(temp); } // solve Solution solution; auto result = solution.solve(edge); // output cout << result << ""\n""; return 0; }",graph,easy 216,"You are given two integers n and m that consist of the same number of digits. You can perform the following operations any number of times: Choose any digit from n that is not 9 and increase it by 1. Choose any digit from n that is not 0 and decrease it by 1. The integer n must not be a prime number at any point, including its original value and after each operation. The cost of a transformation is the sum of all values that n takes throughout the operations performed. Return the minimum cost to transform n into m. If it is impossible, return -1. solution main function ```cpp class Solution { public: int solve(int n, int m) { } }; ``` Example 1: Input: n = 10, m = 12 Output: 85 Example 2: Input: n = 4, m = 8 Output: -1 Constraints: 1 <= n, m <= @data n and m consist of the same number of digits. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; vector isPrime; void generatePrimes() { if (!isPrime.empty()) return; isPrime.resize(1e5 + 1, 1); isPrime[0] = isPrime[1] = 0; for (int i = 2; i <= 1e5; i++) { if (isPrime[i]) { for (int j = 2 * i; j <= 1e5; j += i) { isPrime[j] = 0; } } } } class Solution { public: int solve1(int n, int m) { generatePrimes(); if (isPrime[n] || isPrime[m]) return -1; priority_queue, vector>, greater>> q; unordered_set visited; q.push({n, n}); while (!q.empty()) { auto [steps, curr] = q.top(); q.pop(); if (visited.count(curr)) continue; visited.insert(curr); if (curr == m) return steps; string s = to_string(curr); for (int i = 0; i < s.length(); i++) { char original = s[i]; if (s[i] < '9') { s[i]++; int next = stoi(s); if (!isPrime[next] && !visited.count(next)) { q.push({steps + next, next}); } s[i] = original; } if (s[i] > '0' && !(i == 0 && s[i] == '1')) { s[i]--; int next = stoi(s); if (!isPrime[next] && !visited.count(next)) { q.push({steps + next, next}); } s[i] = original; } } } return -1; } int solve2(int n, int m) { auto is_prime = [](int x) -> bool { if (x < 2) return false; if (x % 2 == 0) return x == 2; for (int d = 3; 1LL * d * d <= x; d += 2) { if (x % d == 0) return false; } return true; }; auto digits_len = [](int x) -> int { int len = 0; do { ++len; x /= 10; } while (x); return len; }; if (is_prime(n) || is_prime(m)) return -1; int L = digits_len(n); int low = 1; for (int i = 1; i < L; ++i) low *= 10; int high = low * 10 - 1; const long long INF = (1LL << 60); static long long dist[10000]; static unsigned char vis[10000]; for (int i = low; i <= high; ++i) { dist[i] = INF; vis[i] = 0; } dist[n] = n; for (;;) { int u = -1; long long best = INF; for (int i = low; i <= high; ++i) { if (!vis[i] && dist[i] < best) { best = dist[i]; u = i; } } if (u == -1) break; if (u == m) return (int)dist[u]; vis[u] = 1; string s = to_string(u); for (int i = 0; i < (int)s.size(); ++i) { char orig = s[i]; if (s[i] < '9') { s[i] = orig + 1; int v = stoi(s); if (!is_prime(v)) { if (!vis[v] && dist[v] > dist[u] + v) dist[v] = dist[u] + v; } s[i] = orig; } if (s[i] > '0' && !(i == 0 && s[i] == '1')) { s[i] = orig - 1; int v = stoi(s); if (!is_prime(v)) { if (!vis[v] && dist[v] > dist[u] + v) dist[v] = dist[u] + v; } s[i] = orig; } } } return -1; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; // solve Solution solution; auto result = solution.solve(n,m); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(string s, int x, int y) { int aCount = 0; int bCount = 0; int lesser = min(x, y); int result = 0; for (char c : s) { if (c > 'b') { result += min(aCount, bCount) * lesser; aCount = 0; bCount = 0; } else if (c == 'a') { if (x < y && bCount > 0) { bCount--; result += y; } else { aCount++; } } else { if (x > y && aCount > 0) { aCount--; result += x; } else { bCount++; } } } result += min(aCount, bCount) * lesser; return result; } int solve2(string s, int x, int y) { long long result = 0; char p1a, p1b; int v1, v2; if (x >= y) { p1a = 'a'; p1b = 'b'; v1 = x; v2 = y; } else { p1a = 'b'; p1b = 'a'; v1 = y; v2 = x; } int w = 0; for (int i = 0; i < (int)s.size(); ++i) { s[w++] = s[i]; if (w >= 2 && s[w - 2] == p1a && s[w - 1] == p1b) { w -= 2; result += v1; } } int w2 = 0; for (int i = 0; i < w; ++i) { s[w2++] = s[i]; if (w2 >= 2) { if (x >= y) { if (s[w2 - 2] == 'b' && s[w2 - 1] == 'a') { w2 -= 2; result += y; } } else { if (s[w2 - 2] == 'a' && s[w2 - 1] == 'b') { w2 -= 2; result += x; } } } } return (int)result; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int x,y; string s; cin>>x>>y>>s; // solve Solution solution; auto result = solution.solve(s,x,y); // output cout< solve(string boxes) { } }; ``` Example 1: Input: boxes = ""110"" Output: [1,1,3] Example 2: Input: boxes = ""001011"" Output: [11,8,5,4,3,4] Constraints: n == boxes.length 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(string boxes) { int n = boxes.size(); vector answer(n, 0); int ballsToLeft = 0, movesToLeft = 0; int ballsToRight = 0, movesToRight = 0; for (int i = 0; i < n; i++) { answer[i] += movesToLeft; ballsToLeft += boxes[i] - '0'; movesToLeft += ballsToLeft; int j = n - 1 - i; answer[j] += movesToRight; ballsToRight += boxes[j] - '0'; movesToRight += ballsToRight; } return answer; } vector solve2(string boxes) { int n = (int)boxes.size(); vector answer(n, 0); for (int i = 0; i < n; ++i) { long long moves = 0; for (int j = 0; j < n; ++j) { if (boxes[j] == '1') { long long d = (long long)j - i; if (d < 0) d = -d; moves += d; } } answer[i] = (moves > INT_MAX ? INT_MAX : (int)moves); } return answer; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output // cout << result << ""\n""; for(auto it:result) printf(""%d "",it); return 0; }",string,medium 219,"You are given an integer n. There is an undirected graph with n vertices, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting vertices ai and bi. Return the number of complete connected components of the graph. A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph. A connected component is said to be complete if there exists an edge between every pair of its vertices. solution main function ```cpp class Solution { public: int solve(int n, vector>& edges) { // write your code here } }; ``` Example 1: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] Output: 3 Example 2: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] Output: 1 Constraints: 1 <= n <= @data 0 <= edges.length <= 3*n edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no repeated edges. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 120]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int find(vector& G, int n) { while (G[n] >= 0){ n = G[n]; } return n; } int solve(int n, vector>& edges) { vector G(n,-1); vector edge(n,0); int cnt = 0; for (int i=0; i using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > g; for(int i=1;i<=m;i++) { vector temp; int x,y; cin>>x>>y; temp.push_back(x); temp.push_back(y); g.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,g); // output cout<& nums, int k) { } }; ``` Example 1: Input: nums = [90], k = 1 Output: 0 Example 2: Input: nums = [9,4,1,7], k = 2 Output: 2 Constraints: 1 <= k <= nums.length <= @data 0 <= nums[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums, int k) { sort(nums.begin(),nums.end()); int sum=INT_MAX; int l=0,r=k-1; while(r& nums, int k) { int n = (int)nums.size(); if (k <= 1) return 0; for (int i = 0; i < n - 1; ++i) { int minIdx = i; int minVal = nums[i]; for (int j = i + 1; j < n; ++j) { if (nums[j] < minVal) { minVal = nums[j]; minIdx = j; } } if (minIdx != i) { int tmp = nums[i]; nums[i] = nums[minIdx]; nums[minIdx] = tmp; } } int ans = INT_MAX; for (int l = 0, r = k - 1; r < n; ++l, ++r) { int diff = nums[r] - nums[l]; if (diff < ans) ans = diff; if (ans == 0) break; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k;cin>>n>>k; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,k); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { private: static const long long MOD = 1e9 + 7; vector factorial; vector invFactorial; long long power(long long base, int exponent) { long long result = 1; while (exponent > 0) { if (exponent & 1) { result = (result * base) % MOD; } exponent >>= 1; base = (base * base) % MOD; } return result; } void precalculateFactorials(int n) { factorial.resize(n + 1); invFactorial.resize(n + 1); factorial[0] = invFactorial[0] = 1; for (int i = 1; i <= n; i++) { factorial[i] = (factorial[i - 1] * i) % MOD; invFactorial[i] = power(factorial[i], MOD - 2); } } long long factorial_mod(int x) { long long res = 1; for (int i = 2; i <= x; ++i) res = (res * i) % MOD; return res; } public: int solve1(int n, int goal, int k) { precalculateFactorials(n); int sign = 1; long long answer = 0; for (int i = n; i >= k; i--) { long long temp = power(i - k, goal - k); temp = (temp * invFactorial[n - i]) % MOD; temp = (temp * invFactorial[i - k]) % MOD; answer = (answer + sign * temp + MOD) % MOD; sign *= -1; } return (factorial[n] * answer) % MOD; } int solve2(int n, int goal, int k) { long long fact_n = factorial_mod(n); long long answer = 0; long long sign = 1; for (int i = n; i >= k; --i) { int x = i - k; long long powTerm = power(x, goal - k); long long denom1 = factorial_mod(n - i); long long denom2 = factorial_mod(x); long long inv1 = power(denom1, MOD - 2); long long inv2 = power(denom2, MOD - 2); long long temp = powTerm % MOD; temp = (temp * inv1) % MOD; temp = (temp * inv2) % MOD; answer = (answer + sign * temp) % MOD; if (answer < 0) answer += MOD; sign = -sign; } long long res = (fact_n * answer) % MOD; return (int)res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,goal,k; cin>>n>>goal>>k; // solve Solution solution; auto result = solution.solve(n,goal,k); // output cout << result << ""\n""; return 0; }",math,hard 222,"There is an undirected graph of n nodes. You are given a 2D array edges, where edges[i] = [ui, vi, lengthi] describes an edge between node ui and node vi with a traversal time of lengthi units. Additionally, you are given an array disappear, where disappear[i] denotes the time when the node i disappears from the graph and you won't be able to visit it. Note that the graph might be disconnected and might contain multiple edges. Return the array answer, with answer[i] denoting the minimum units of time required to reach node i from node 0. If node i is unreachable from node 0 then answer[i] is -1. solution main function ```cpp class Solution { public: vector solve(int n, vector>& edges, vector& disappear) { } }; ``` Example 1: Input: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5] Output: [0,-1,4] Example 2: Input: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5] Output: [0,2,3] Constraints: 1 <= n <= @data 0 <= edges.length <= 10^5 edges[i] == [ui, vi, lengthi] 0 <= ui, vi <= n - 1 1 <= lengthi <= 10^5 disappear.length == n 1 <= disappear[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(int n, vector>& v, vector& d) { priority_queue,vector>,greater>>q; vector>adj[n]; for(int i=0;idist(n,INT_MAX); vectorvis(n,0); dist[0]=0; while(!q.empty()) { pairp=q.top(); q.pop(); int t=p.first,s=p.second; if(vis[s]==1) continue; if(t>=d[s]) continue; vis[s]=1; for(auto i:adj[s]) { if(t+i.secondans; for(int i=0;i solve2(int n, vector>& v, vector& d) { const int INF = INT_MAX / 2; vector dist(n, INF); if (n == 0) return dist; if (0 < d[0]) dist[0] = 0; for (int it = 0; it < n - 1; ++it) { bool updated = false; for (size_t ei = 0; ei < v.size(); ++ei) { int a = v[ei][0]; int b = v[ei][1]; int w = v[ei][2]; int du = dist[a]; int dv = dist[b]; if (du < d[a]) { long long cand = (long long)du + (long long)w; if (cand < d[b] && cand < dv) { dist[b] = cand > INF ? INF : (int)cand; updated = true; } } if (dv < d[b]) { long long cand = (long long)dv + (long long)w; if (cand < d[a] && cand < dist[a]) { dist[a] = cand > INF ? INF : (int)cand; updated = true; } } } if (!updated) break; } for (int i = 0; i < n; ++i) { if (!(dist[i] < d[i])) dist[i] = -1; } return dist; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,k; cin>>n>>m; vector > edge; vector< int > val; for(int i=1,x,y,z;i<=m;i++) { scanf(""%d"",&x); scanf(""%d"",&y); scanf(""%d"",&z); vector temp; temp.push_back(x); temp.push_back(y); temp.push_back(z); edge.push_back(temp); } for(int i=1,x;i<=n;i++) { scanf(""%d"",&x); val.push_back(x); } // solve Solution solution; auto result = solution.solve(n,edge,val); // output for(auto it:result) cout<& nums, int goal) { } }; ``` Example 1: Input: nums = [1,0,1,0,1], goal = 2 Output: 4 Example 2: Input: nums = [0,0,0,0,0], goal = 0 Output: 15 Constraints: 1 <= nums.length <= @data nums[i] is either 0 or 1. 0 <= goal <= nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums, int goal) { return slidingWindowAtMost(nums, goal) - slidingWindowAtMost(nums, goal - 1); } int solve2(vector& nums, int goal) { if (goal < 0) return 0; long long ans = 0; int n = (int)nums.size(); for (int i = 0; i < n; ++i) { int sum = 0; for (int j = i; j < n; ++j) { sum += nums[j]; if (sum == goal) ++ans; else if (sum > goal) break; } } if (ans > (long long)numeric_limits::max()) return numeric_limits::max(); if (ans < (long long)numeric_limits::min()) return numeric_limits::min(); return (int)ans; } private: int slidingWindowAtMost(vector &nums, int goal){ int start = 0, currentSum = 0, totalCount = 0; for (int end = 0; end < nums.size(); end++) { currentSum += nums[end]; while (start <= end && currentSum > goal) { currentSum -= nums[start++]; } totalCount += end - start + 1; } return totalCount; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,goal; cin>>n>>goal; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num,goal); // output cout< using namespace std; class Solution { public: string solve1(int &n, string &s) { return (s[0] != s[n - 1]) ? ""YES"" : ""NO""; } string solve2(int &n, string &s) { for (int split = 1; split < n; ++split) { if (s[0] != s[n - 1]) return ""YES""; } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","greedy,string",medium 225,"Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [2,5,6,9,10] Output: 2 Example 2: Input: nums = [7,5,6,8,3] Output: 1 Constraints: 2 <= nums.length <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int solve1(vector &nums) { int min = 1e8; int max = 0; for (int e : nums) { if (e < min) min = e; if (e > max) max = e; } return gcd(min, max); } int solve2(vector& nums) { int mn = INT_MAX; int mx = INT_MIN; for (int e : nums) { if (e < mn) mn = e; if (e > mx) mx = e; } long long a = mn; long long b = mx; if (a < 0) a = -a; if (b < 0) b = -b; if (a == 0 && b == 0) return 0; if (a == 0) return (int)b; if (b == 0) return (int)a; long long d = a < b ? a : b; while (d >= 1) { if (a % d == 0 && b % d == 0) return (int)d; --d; } return 0; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n;cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout<> &a) { // write your code here } }; ``` where: - `n`: the number of players, `m`: the number of throws, `x`: the initial player with the ball - `a`: the distance and direction of each throw, `a[i].first` represents the distance of the $i$-th throw, `a[i].second` represents the direction of the $i$-th throw, `a[i].second` is '0' for clockwise, '1' for counterclockwise, '?' for unknown - return: the number of players who could have the ball # Example 1: - Input: n = 6, m = 3, x = 2 a = [(2,'?'), (2,'?'), (2,'?')] - Output: 3 # Constraints: - $2 \leq n \leq @data$ - $1 \leq m \leq @data$ - $1 \leq x \leq n$ - $1 \leq a[i].first \leq n - 1$ - $a[i].second is '0' or '1' or '?'$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 5000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 256]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, int &m, int &x, vector> &a) { vector dp(n); x--; dp[x] = 1; for (int i = 0; i < m; i++) { auto [r, c] = a[i]; vector g(n); for (int j = 0; j < n; j++) { if (dp[j]) { if (c != '1') g[(j + r) % n] = 1; if (c != '0') g[(j - r + n) % n] = 1; } } dp = g; } return count(dp.begin(), dp.end(), 1); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m, x; cin >> n >> m >> x; vector> a(m); for (int i = 0; i < m; i++) cin >> a[i].first >> a[i].second; // solve Solution solution; auto result = solution.solve(n, m, x, a); // output cout << result << ""\n""; return 0; }","dp,search",medium 227,"Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [a_i, b_i, weight_i] represents a bidirectional and weighted edge between nodes a_i and b_i. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order. solution main function ```cpp class Solution { public: vector> solve(int n, vector>& edges) { // write your code here } }; ``` Example 1: Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]] Output: [[0,1],[2,3,4,5]] Example 2: Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]] Output: [[],[0,1,2,3]] Constraints: 2 <= n <= @data 1 <= edges.length <= min(4*n, n * (n - 1) / 2) edges[i].length == 3 0 <= from_i < to_i < n 1 <= weight_i <= 1000 All pairs (a_i, b_i) are distinct Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int p[1010]; int find(int a) { if (a != p[a]) p[a] = find(p[a]); return p[a]; } int work1(int n, vector>& edges, int k) { for (int i = 0; i < n; i ++ ) p[i] = i; int cost = 0, cnt = 0; for (auto& e:edges) { if (e[3] == k) continue; int f1 = find(e[1]), f2 = find(e[2]); if (f1 != f2) { cost += e[0]; cnt ++; if (cnt == n - 1) break; p[f1] = f2; } } if (cnt == n - 1) return cost; else return INT_MAX; } int work2(int n, vector>& edges, int k) { for (int i = 0; i < n; i ++ ) p[i] = i; int cost = 0, cnt = 0; for (auto& e : edges) { if (e[3] == k) { cost += e[0]; cnt ++; p[e[1]] = e[2]; break; } } for (auto& e: edges) { int f1 = find(e[1]), f2 = find(e[2]); if (f1 != f2) { cost += e[0]; cnt ++; if (cnt == n - 1) break; p[f1] = f2; } } if (cnt == n - 1) return cost; else return INT_MAX; } int pp[200005]; int findp(int a) { while (a != pp[a]) { pp[a] = pp[pp[a]]; a = pp[a]; } return a; } int kruskal_exclude(int n, vector>& edges, int skip) { for (int i = 0; i < n; ++i) pp[i] = i; long long cost = 0; int cnt = 0; for (auto &e : edges) { if (e[3] == skip) continue; int f1 = findp(e[1]), f2 = findp(e[2]); if (f1 != f2) { pp[f1] = f2; cost += e[0]; ++cnt; if (cnt == n - 1) break; } } if (cnt == n - 1) return (int)cost; return INT_MAX; } int kruskal_force(int n, vector>& edges, int force) { for (int i = 0; i < n; ++i) pp[i] = i; long long cost = 0; int cnt = 0; for (auto &e : edges) { if (e[3] == force) { int f1 = findp(e[1]), f2 = findp(e[2]); if (f1 != f2) { pp[f1] = f2; cost += e[0]; ++cnt; } break; } } for (auto &e : edges) { int f1 = findp(e[1]), f2 = findp(e[2]); if (f1 != f2) { pp[f1] = f2; cost += e[0]; ++cnt; if (cnt == n - 1) break; } } if (cnt == n - 1) return (int)cost; return INT_MAX; } vector> solve1(int n, vector>& edges) { int m = edges.size(); for (int i = 0; i < m; i ++ ) { auto& e = edges[i]; swap(e[0], e[2]); e.push_back(i); } sort(edges.begin(), edges.end()); int min_cost = work1(n, edges, -1); vector> ans(2); for (int i = 0; i < m; i ++ ) { if (work1(n, edges, i) > min_cost) ans[0].push_back(i); else if (work2(n, edges, i) == min_cost) ans[1].push_back(i); } return ans; } vector> solve2(int n, vector>& edges) { int m = edges.size(); for (int i = 0; i < m; ++i) { auto &e = edges[i]; int w = e[2], u = e[0], v = e[1]; e[0] = w; e[1] = u; e[2] = v; e.push_back(i); } sort(edges.begin(), edges.end()); int base = kruskal_exclude(n, edges, -1); vector> ans(2); for (int i = 0; i < m; ++i) { if (kruskal_exclude(n, edges, i) > base) ans[0].push_back(i); else if (kruskal_force(n, edges, i) == base) ans[1].push_back(i); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > edge; for(int i=1;i<=m;i++) { int x,y,z; cin>>x>>y>>z; vector temp; temp.push_back(x); temp.push_back(y); temp.push_back(z); edge.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,edge); // output for(auto it:result) { sort(it.begin(),it.end()); for(auto x:it) cout<>& grid) { } }; ``` Example 1: Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] Output: 3 Example 2: Input: grid = [[3,2,4],[2,1,9],[1,1,7]] Output: 0 Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 1000 4 <= m * n <= @data 1 <= grid[i][j] <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& grid) { int M = grid.size(), N = grid[0].size(); vector> dp(M, vector(2, 0)); for (int i = 0; i < M; i++) { dp[i][0] = 1; } int maxMoves = 0; for (int j = 1; j < N; j++) { for (int i = 0; i < M; i++) { if (grid[i][j] > grid[i][j - 1] && dp[i][0] > 0) { dp[i][1] = max(dp[i][1], dp[i][0] + 1); } if (i - 1 >= 0 && grid[i][j] > grid[i - 1][j - 1] && dp[i - 1][0] > 0) { dp[i][1] = max(dp[i][1], dp[i - 1][0] + 1); } if (i + 1 < M && grid[i][j] > grid[i + 1][j - 1] && dp[i + 1][0] > 0) { dp[i][1] = max(dp[i][1], dp[i + 1][0] + 1); } maxMoves = max(maxMoves, dp[i][1] - 1); } for (int k = 0; k < M; k++) { dp[k][0] = dp[k][1]; dp[k][1] = 0; } } return maxMoves; } int solve2(vector>& grid) { int M = (int)grid.size(); int N = (int)grid[0].size(); const uint32_t BASE_MASK = (1u << 20) - 1u; const uint32_t DP_SHIFT = 20u; const uint32_t DP_MASK = (1u << 12) - 1u; for (int i = 0; i < M; ++i) { uint32_t orig = (uint32_t)grid[i][0] & BASE_MASK; grid[i][0] = (int)(orig | (1u << DP_SHIFT)); } int maxMoves = 0; for (int j = 1; j < N; ++j) { for (int i = 0; i < M; ++i) { uint32_t origCur = (uint32_t)grid[i][j] & BASE_MASK; uint32_t best = 0u; if (i - 1 >= 0) { uint32_t prevOrig = (uint32_t)grid[i - 1][j - 1] & BASE_MASK; uint32_t prevDp = ((uint32_t)grid[i - 1][j - 1] >> DP_SHIFT) & DP_MASK; if (prevDp > 0u && origCur > prevOrig) { uint32_t cand = prevDp + 1u; if (cand > best) best = cand; } } { uint32_t prevOrig = (uint32_t)grid[i][j - 1] & BASE_MASK; uint32_t prevDp = ((uint32_t)grid[i][j - 1] >> DP_SHIFT) & DP_MASK; if (prevDp > 0u && origCur > prevOrig) { uint32_t cand = prevDp + 1u; if (cand > best) best = cand; } } if (i + 1 < M) { uint32_t prevOrig = (uint32_t)grid[i + 1][j - 1] & BASE_MASK; uint32_t prevDp = ((uint32_t)grid[i + 1][j - 1] >> DP_SHIFT) & DP_MASK; if (prevDp > 0u && origCur > prevOrig) { uint32_t cand = prevDp + 1u; if (cand > best) best = cand; } } grid[i][j] = (int)(origCur | (best << DP_SHIFT)); if (best > 0u) { int moves = (int)best - 1; if (moves > maxMoves) maxMoves = moves; } } } return maxMoves; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > mat; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } mat.push_back(temp); } // solve Solution solution; auto result = solution.solve(mat); // output cout << result << ""\n""; return 0; }",dp,medium 229,"# Problem Statement Given an array $a$ of $n$ integers. Choose as many elements as possible such that the difference between the largest and the smallest chosen elements is at most $5$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the maximum possible number of chosen elements. # Example 1: - Input: n = 6 a = [100, 4, 200, 1, 3, 2] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, vector &a) { int ans = 0; sort(a.begin(), a.end()); for (int i = 0, j = 0; i < n; i += 1) { while (j < n and a[j] <= a[i] + 5) j += 1; ans = max(ans, j - i); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","sort,two_pointers",hard 230,"You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k. The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket. Return the maximum tastiness of a candy basket. solution main function ```cpp class Solution { public: int solve(vector& price, int k) { } }; ``` Example 1: Input: price = [13,5,1,8,21,2], k = 3 Output: 8 Example 2: Input: price = [1,3,1], k = 2 Output: 2 Constraints: 2 <= k <= price.length <= @data 1 <= price[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool canweplace(vector&stalls,int dis,int k){ int cntcows=1; int lastcow=stalls[0]; for(int i=0;i=dis){ cntcows++; lastcow=stalls[i]; } if(cntcows==k) return true; } return false; } int solve1(vector& prices, int k) { int n=prices.size(); sort(prices.begin(),prices.end()) ; int low=1, high=prices[n-1]-prices[0]; int ans=-1; while(low<=high){ int mid=low+(high-low)/2; if(canweplace(prices,mid,k)==true) { ans=mid; low=mid+1; } else high=mid-1; } return high; } int solve2(vector& prices, int k) { int n = (int)prices.size(); sort(prices.begin(), prices.end()); int best = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int d = prices[j] - prices[i]; if (d <= best) continue; int cnt = 1; int last = prices[0]; for (int t = 1; t < n && cnt < k; ++t) { if (prices[t] - last >= d) { ++cnt; last = prices[t]; } } if (cnt >= k) best = d; } } return best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,k); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { int n = s.length(); int min_deletions = 0; int b_count = 0; for (int i = 0; i < n; i++) { if (s[i] == 'b') { b_count++; } else { min_deletions = min(min_deletions + 1, b_count); } } return min_deletions; } int solve2(string s) { int n = (int)s.size(); long long best = (long long)n; for (int p = 0; p <= n; ++p) { long long deletions = 0; for (int i = 0; i < p; ++i) if (s[i] == 'b') ++deletions; for (int i = p; i < n; ++i) if (s[i] == 'a') ++deletions; if (deletions < best) best = deletions; } if (best < 0) return 0; if (best > INT_MAX) return INT_MAX; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout< &a) { // write your code here } }; ``` where: - return: the minimum number of operations K1o0n needs to restore his pie after the terror of Noobish_Monk. # Example 1: - Input: n = 5, k = 3, a = [3, 1, 1] - Output: 2 # Constraints: - $2 \leq k \leq @data$ - $1 \leq n \leq 10^9$ - $1 \leq a[i] \leq n - 1$ - $\sum_{i=1}^k a[i] = n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &k, vector &a) { int max = *max_element(a.begin(), a.end()); int ans = 2 * (n - max) - (k - 1); return ans; } int solve2(int &n, int &k, vector &a) { int idx = 0; int mx = a[0]; for (int i = 1; i < k; ++i) { if (a[i] > mx) { mx = a[i]; idx = i; } } long long merges = (long long)n - mx; long long splits = 0; for (int i = 0; i < k; ++i) { if (i == idx) continue; splits += (long long)a[i] - 1; } long long ans = merges + splits; if (ans < INT_MIN) ans = INT_MIN; if (ans > INT_MAX) ans = INT_MAX; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector a(k); for (int i = 0; i < k; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, k, a); // output cout << result << ""\n""; return 0; }",sort,easy 233,"There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The answer is modulus 998244353. solution main function ```cpp class Solution { public: int solve(int m,int n) { } }; ``` Example 1: Input: m = 3, n = 7 Output: 28 Example 2: Input: m = 3, n = 2 Output: 3 Constraints: 1 <= m, n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: const long long mod=998244353; int power(long long x,long long y) { long long temp=1; while(y) { if(y&1) temp=temp*x%mod; x=x*x%mod; y>>=1; } return temp; } int solve1(int m,int n) { long long ans = 1,tx=1,ty=1; for (int x = n, y = 1; y < m; ++x, ++y) { tx=tx*x%mod; ty=ty*y%mod; } return tx*power(ty,mod-2)%mod; } int solve2(int m,int n) { long long total = (long long)m + (long long)n - 2; long long k = (long long)min(m - 1, n - 1); if (k == 0) return 1; long long ans = 1; long long num = total - k + 1; for (long long i = 1; i <= k; ++i, ++num) { ans = ans * (num % mod) % mod; ans = ans * power(i % mod, mod - 2) % mod; } return (int)(ans % mod); } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; // solve Solution solution; auto result = solution.solve(n,m); // output cout< &a) { // write your code here } }; ``` where: - return: the value of a1 in the end if both players play optimally. # Example 1: - Input: n = 2, a = [1, 2] - Output: 2 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); return a[n / 2]; } int solve2(int &n, vector &a) { int k = n / 2; int l = 0, r = n - 1; while (l <= r) { int mid = l + (r - l) / 2; int pivot = a[mid]; int lt = l, gt = r, i = l; while (i <= gt) { if (a[i] < pivot) { swap(a[i], a[lt]); ++i; ++lt; } else if (a[i] > pivot) { swap(a[i], a[gt]); --gt; } else { ++i; } } if (k < lt) { r = lt - 1; } else if (k > gt) { l = gt + 1; } else { return a[k]; } } return a[k]; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",game,medium 235,"# Problem Statement In the snake exhibition, there are $n$ rooms (numbered $0$ to $n - 1$) arranged in a circle, with a snake in each room. The rooms are connected by $n$ conveyor belts, and the $i$-th conveyor belt connects the rooms $i$ and $(i+1) \bmod n$. In the other words, rooms $0$ and $1$, $1$ and $2$, $\ldots$, $n-2$ and $n-1$, $n-1$ and $0$ are connected with conveyor belts. The $i$-th conveyor belt is in one of three states: - If it is clockwise, snakes can only go from room $i$ to $(i+1) \bmod n$. - If it is anticlockwise, snakes can only go from room $(i+1) \bmod n$ to $i$. - If it is off, snakes can travel in either direction. Each snake wants to leave its room and come back to it later. A room is **returnable** if the snake there can leave the room, and later come back to it using the conveyor belts. How many such **returnable** rooms are there? The main function of the solution is: ```cpp class Solution { public: int solve(int &n, string &s) { // write your code here } }; ``` where: - `n` is the number of rooms, - `s` is a string of length $n$ that represents the state of each conveyor belt. If the $i$-th conveyor belt is clockwise, `s[i] = '>'`; if it is counterclockwise, `s[i] = '<'`; if it is off, `s[i] = '-'`. - The return value is the number of returnable rooms. # Example 1 - Input: n = 5 s = "">>>>>"" - Output: 5 # Constraints - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, string &s) { int ans = 0; bool flaga = 1, flagb = 1; for (int i = 0; i < n; i++) if (s[i] != '-') { if (s[i] == '>') flaga = 0; if (s[i] == '<') flagb = 0; } if (flaga || flagb) return n; else { for (int i = 0; i < n; i++) if (s[i] == '-' || s[(i + 1) % n] == '-') ans++; return ans; } } int solve2(int &n, string &s) { long long ans = 0; for (int i = 0; i < n; ++i) { bool okCW = true; int j = i; for (int steps = 0; steps < n; ++steps) { if (s[j] == '<') { okCW = false; break; } j = (j + 1) % n; } if (okCW) { ans++; continue; } bool okCCW = true; j = i; for (int steps = 0; steps < n; ++steps) { int left = (j - 1 + n) % n; if (s[left] == '>') { okCCW = false; break; } j = left; } if (okCCW) { ans++; continue; } if (s[i] == '-' || s[(i - 1 + n) % n] == '-') ans++; } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }",graph,hard 236,"Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""zzazz"" Output: 0 Example 2: Input: s = ""mbadm"" Output: 2 Constraints: 1 <= s.length <= @data s consists of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int lcs(string& s1, string& s2, int m, int n) { vector dp(n + 1), dpPrev(n + 1); for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { dp[j] = 0; } else if (s1[i - 1] == s2[j - 1]) { dp[j] = 1 + dpPrev[j - 1]; } else { dp[j] = max(dpPrev[j], dp[j - 1]); } } dpPrev = dp; } return dp[n]; } int solve1(string s) { int n = s.length(); string sReverse = s; reverse(sReverse.begin(), sReverse.end()); return n - lcs(s, sReverse, n, n); } int solve2(string s) { int n = (int)s.size(); for (int k = 0; k <= n - 1; ++k) { unsigned __int128 total = 1; total <<= k; for (unsigned __int128 mask = 0; mask < total; ++mask) { int i = 0, j = n - 1, used = 0; bool ok = true; while (i < j) { if (s[i] == s[j]) { ++i; --j; } else { if (used == k) { ok = false; break; } bool chooseLeft = ((mask >> used) & 1) == 0; ++used; if (chooseLeft) ++i; else --j; } } if (ok) return k; } } return 0; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s;cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout< solve(int n, int m, vector &num) { // write your code here } }; ``` Pass in parameters: 2 integers n,m and an array num Return parameters: Modify `num` in place to become the m-th next permutation after the given permutation. The returned array is not used by the runner. Example 1: Input: n=5,m=3,num=[1, 2, 3, 4, 5] Output: [1, 2, 4, 5, 3] Constraints: 0 using namespace std; #include using namespace std; class Solution { public: vector solve1(int n, int m, vector &num) { for(int i=1;i<=m;++i) next_permutation(num.begin(),num.end()); return num; } vector solve2(int n, int m, vector &num) { if (n <= 1 || m <= 0) return num; for (int t = 0; t < m; ++t) { int i = n - 2; while (i >= 0 && num[i] >= num[i + 1]) --i; if (i < 0) { int l = 0, r = n - 1; while (l < r) { int tmp = num[l]; num[l] = num[r]; num[r] = tmp; ++l; --r; } continue; } int j = n - 1; while (num[j] <= num[i]) --j; int tmp = num[i]; num[i] = num[j]; num[j] = tmp; int l = i + 1, r = n - 1; while (l < r) { int tt = num[l]; num[l] = num[r]; num[r] = tt; ++l; --r; } } return num; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector num; for (int i = 1; i <=n; i++) { int x; cin >> x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(n,m,num); // output for(auto it :num) cout< 0, replace the ith number with the sum of the next k numbers. If k < 0, replace the ith number with the sum of the previous k numbers. If k == 0, replace the ith number with 0. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! solution main function ```cpp class Solution { public: vector solve(vector& code, int k) { } }; ``` Example 1: Input: code = [5,7,1,4], k = 3 Output: [12,10,16,13] Example 2: Input: code = [1,2,3,4], k = 0 Output: [0,0,0,0] Constraints: n == code.length 1 <= n <= @data 1 <= code[i] <= @data -(n - 1) <= k <= n - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector& code, int k) { int n= code.size(); vectorans(n,0); if(k==0) return ans; int start; int end; int step; if(k>0){ start=1; end=k; step=1; } else{ start=-1; end=k; step=-1; } for(int i=0; i solve2(vector& code, int k) { int n = (int)code.size(); vector ans(n, 0); if (k == 0) return ans; if (k > 0) { for (int i = 0; i < n; ++i) { long long s = 0; for (int t = 1; t <= k; ++t) { int idx = i + t; if (idx >= n) idx -= n; s += code[idx]; } ans[i] = (int)s; } } else { for (int i = 0; i < n; ++i) { long long s = 0; for (int t = -1; t >= k; --t) { int idx = i + t; if (idx < 0) idx += n; s += code[idx]; } ans[i] = (int)s; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; vector a; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } // solve Solution solution; auto result = solution.solve(a,k); // output // cout << result << ""\n""; for(auto it:result) cout< &a) { // write your code here } }; ``` where: - the return value is the maximum value he can obtain # Example 1: - Input: n = 2 a = [1, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); a.erase(unique(a.begin(), a.end()), a.end()); int ans = 0; for (int i = 0, j = 0; i < a.size(); i++) { while (j < a.size() && a[j] < a[i] + n) j++; ans = max(ans, j - i); } return ans; } int solve2(int &n, vector &a) { int ans = 0; for (int i = 0; i < (int)a.size(); i++) { long long L = (long long)a[i]; long long R = L + (long long)n - 1; int cnt = 0; for (int j = 0; j < (int)a.size(); j++) { long long vj = (long long)a[j]; if (vj >= L && vj <= R) { bool seen = false; for (int k = 0; k < j; k++) { long long vk = (long long)a[k]; if (vk >= L && vk <= R && vk == vj) { seen = true; break; } } if (!seen) cnt++; } } if (cnt > ans) ans = cnt; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","two_pointers,binary,greedy,sort",hard 240,"You are given an integer n, the number of teams in a tournament that has strange rules: If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. Return the number of matches played in the tournament until a winner is decided. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 7 Output: 6 Example 2: Input: n = 14 Output: 13 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { return n - 1; } int solve2(int n) { long long teams = n; long long matches = 0; while (teams > 1) { if ((teams & 1LL) == 0) { matches += teams / 2; teams /= 2; } else { matches += (teams - 1) / 2; teams = (teams - 1) / 2 + 1; } } if (matches > INT_MAX) return INT_MAX; if (matches < INT_MIN) return INT_MIN; return static_cast(matches); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout<> solve(vector& nums) { } }; ``` Example 1: Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] Example 2: Input: nums = [4,4,3,2,1] Output: [[4,4]] Constraints: 1 <= nums.length <= @data -100 <= nums[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB","[5, 10, 15]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector temp; vector> ans; void dfs(int cur, int last, vector& nums) { if (cur == nums.size()) { if (temp.size() >= 2) { ans.push_back(temp); } return; } if (nums[cur] >= last) { temp.push_back(nums[cur]); dfs(cur + 1, nums[cur], nums); temp.pop_back(); } if (nums[cur] != last) { dfs(cur + 1, last, nums); } } vector> solve1(vector& nums) { dfs(0, INT_MIN, nums); return ans; } vector> solve2(vector& nums) { int n = (int)nums.size(); vector> ans; vector idx; int j = 0; while (true) { int s0 = idx.empty() ? 0 : (idx.back() + 1); int last = idx.empty() ? INT_MIN : nums[idx.back()]; if (j < n) { if (nums[j] >= last) { bool dup = false; for (int k = s0; k < j; ++k) { if (nums[k] == nums[j]) { dup = true; break; } } if (!dup) { idx.push_back(j); if ((int)idx.size() >= 2) { vector seq; seq.reserve(idx.size()); for (int t : idx) seq.push_back(nums[t]); ans.push_back(move(seq)); } j = j + 1; continue; } } ++j; continue; } else { if (idx.empty()) break; int p = idx.back(); idx.pop_back(); j = p + 1; continue; } } return ans; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output sort(result.begin(),result.end()); for(auto it:result) { for(auto t:it) cout< solve(string s) { } }; ``` Example 1: Input: s = ""AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"" Output: [""AAAAACCCCC"",""CCCCCAAAAA""] Example 2: Input: s = ""AAAAAAAAAAAAA"" Output: [""AAAAAAAAAA""] Constraints: 1 <= s.length <= @data s[i] is either 'A', 'C', 'G', or 'T'. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[400, 200, 109], [3200, 1600, 875], [25600, 12800, 7000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { const int L = 10; unordered_map bin = {{'A', 0}, {'C', 1}, {'G', 2}, {'T', 3}}; public: vector solve(string s) { vector ans; int n = s.length(); if (n <= L) { return ans; } int x = 0; for (int i = 0; i < L - 1; ++i) { x = (x << 2) | bin[s[i]]; } unordered_map cnt; for (int i = 0; i <= n - L; ++i) { x = ((x << 2) | bin[s[i + L - 1]]) & ((1 << (L * 2)) - 1); if (++cnt[x] == 2) { ans.push_back(s.substr(i, L)); } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string str; cin >> str; // solve Solution solution; auto result = solution.solve(str); // output sort(result.begin(), result.end()); for (size_t i = 0; i < result.size(); i++) { if (i) cout << ' '; cout << result[i]; } return 0; } ","string,bit_manipulation",medium 243,"Given a 2D grid of size m x n, you should find the matrix answer of size m x n. The cell answer[r][c] is calculated by looking at the diagonal values of the cell grid[r][c]: Let leftAbove[r][c] be the number of distinct values on the diagonal to the left and above the cell grid[r][c] not including the cell grid[r][c] itself. Let rightBelow[r][c] be the number of distinct values on the diagonal to the right and below the cell grid[r][c], not including the cell grid[r][c] itself. Then answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|. A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached. For example, in the below diagram the diagonal is highlighted using the cell with indices (2, 3) colored gray: Red-colored cells are left and above the cell. Blue-colored cells are right and below the cell. solution main function ```cpp class Solution { public: vector> solve(vector>& grid) { } }; ``` Example 1: Input: grid = [[1,2,3],[3,1,5],[3,2,1]] Output: [[1,1,0],[1,0,1],[0,1,1]] Example 2: Input: grid = [[1]] Output: [[0]] Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data 1 <= grid[i][j] <= 50 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector> solve1(vector>& grid) { int width = grid[0].size(); int length = grid.size(); for (int i = 0 ;i < width ;i++) { unordered_map> elementMap; makeElementMap(elementMap, grid, 0, i); int left = 0; int right = elementMap.size(); int j = 0; while((i+j < width) && (j < length)) { int element = grid[j][i+j]; auto position = elementMap[element]; if (position.second == j) { right -= 1; } grid[j][i+j] = abs(left - right); if (position.first == j) { left += 1; } j += 1; } } for (int i = 1 ;i < length ;i++) { unordered_map> elementMap; makeElementMap(elementMap, grid, i, 0); int left = 0; int right = elementMap.size(); int j = 0; while((i+j < length) && (j < width)) { int element = grid[i+j][j]; auto position = elementMap[element]; if (position.second == j) { right -= 1; } grid[i+j][j] = abs(left - right); if (position.first == j) { left += 1; } j += 1; } } return grid; } void makeElementMap(unordered_map>& elementMap, vector>& grid, int startX, int startY) { int offset = 0; while ((startX + offset < grid.size()) && (startY + offset < grid[0].size())) { int element = grid[startX+offset][startY+offset]; if (0 == elementMap.count(element)) { elementMap[element] = std::pair(offset, offset); } else { elementMap[element].second = offset; } offset += 1; } } vector> solve2(vector>& grid) { int m = grid.size(); int n = grid[0].size(); const int B = 1000; for (int r = 0; r < m; ++r) { for (int c = 0; c < n; ++c) { int leftDistinct = 0; int maxLeft = min(r, c); for (int k = 1; k <= maxLeft; ++k) { int vr = r - k; int vc = c - k; int val = grid[vr][vc] % B; bool seen = false; for (int q = 1; q < k; ++q) { int pr = r - q; int pc = c - q; if ((grid[pr][pc] % B) == val) { seen = true; break; } } if (!seen) leftDistinct++; } int rightDistinct = 0; int maxRight = min(m - 1 - r, n - 1 - c); for (int k = 1; k <= maxRight; ++k) { int vr = r + k; int vc = c + k; int val = grid[vr][vc] % B; bool seen = false; for (int q = 1; q < k; ++q) { int pr = r + q; int pc = c + q; if ((grid[pr][pc] % B) == val) { seen = true; break; } } if (!seen) rightDistinct++; } int ans = leftDistinct - rightDistinct; if (ans < 0) ans = -ans; grid[r][c] += ans * B; } } for (int r = 0; r < m; ++r) { for (int c = 0; c < n; ++c) { grid[r][c] /= B; } } return grid; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > s; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - the return value is the maximum number of rounds Egor can win # Example 1: - Input: n = 5, l = 3, r = 10 a = [2, 1, 11, 3, 7] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq l \leq r \leq 10^9$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 90, 64], [6400, 720, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &l, int &r, vector &a) { int start = 0; int current_sum = 0; int max_rounds = 0; for (int end = 0; end < n; ++end) { current_sum += a[end]; while (current_sum > r && start <= end) { current_sum -= a[start]; ++start; } if (current_sum >= l && current_sum <= r) { ++max_rounds; current_sum = 0; start = end + 1; } } return max_rounds; } int solve2(int &n, int &l, int &r, vector &a) { long long L = l, R = r; int ans = 0; int i = 0; while (i < n) { long long sum = 0; bool found = false; for (int j = i; j < n; ++j) { sum += (long long)a[j]; if (sum >= L && sum <= R) { ++ans; i = j + 1; found = true; break; } if (sum > R) break; } if (!found) ++i; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, l, r; cin >> n >> l >> r; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, l, r, a); // output cout << result << ""\n""; return 0; }","two_pointers,dp,math",hard 245,"There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 0-indexed 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree. You are also given a positive integer k, and a 0-indexed array of non-negative integers nums of length n, where nums[i] represents the value of the node numbered i. Alice wants the sum of values of tree nodes to be maximum, for which Alice can perform the following operation any number of times (including zero) on the tree: Choose any edge [u, v] connecting the nodes u and v, and update their values as follows: nums[u] = nums[u] XOR k nums[v] = nums[v] XOR k Return the maximum possible sum of the values Alice can achieve by performing the operation any number of times. solution main function ```cpp class Solution { public: long long solve(vector& nums, int k, vector>& edges) { } }; ``` Example 1: Input: nums = [1,2,1], k = 3, edges = [[0,1],[0,2]] Output: 6 Example 2: Input: nums = [2,3], k = 7, edges = [[0,1]] Output: 9 Constraints: 2 <= n == nums.length <= @data 1 <= k <= 10^9 0 <= nums[i] <= 10^9 edges.length == n - 1 edges[i].length == 2 0 <= edges[i][0], edges[i][1] <= n - 1 The input is generated such that edges represent a valid tree. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: typedef long long ll; long long solve1(vector& nums, int k, vector>& edges) { ll sum=0,cnt=0,sacrificeVal=1e18; for(int ele:nums){ if((ele^k)>ele){ sum+=(ele^k); sacrificeVal=min(sacrificeVal,1LL*((ele^k)-ele)); cnt++; } else{ sum+=ele; sacrificeVal=min(sacrificeVal,1LL*(ele-(ele^k))); } } if(cnt&1) return sum-sacrificeVal; return sum; } long long solve2(vector& nums, int k, vector>& edges) { ll sum = 0; ll minAbsDiff = LLONG_MAX; int posCount = 0; for (int x : nums) { int y = x ^ k; ll d = (ll)y - (ll)x; if (d > 0) { sum += (ll)y; posCount++; if (d < minAbsDiff) minAbsDiff = d; } else { sum += (ll)x; d = -d; if (d < minAbsDiff) minAbsDiff = d; } } if (posCount & 1) sum -= minAbsDiff; return sum; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; vector num; vector > e; cin>>n>>k; for(int i=1,x;i<=n;i++) { cin>>x; num.push_back(x); } for(int i=1;i temp; for(int j=1;j<=2;j++) { int x; cin>>x; temp.push_back(x); } e.push_back(temp); } // solve Solution solution; auto result = solution.solve(num,k,e); // output cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int numBottles, int numExchange) { int consumedBottles = 0; while (numBottles >= numExchange) { int K = numBottles / numExchange; consumedBottles += numExchange * K; numBottles -= numExchange * K; numBottles += K; } return consumedBottles + numBottles; } int solve2(int numBottles, int numExchange) { long long full = numBottles; long long empty = 0; long long consumed = 0; while (full > 0) { consumed++; full--; empty++; if (empty >= numExchange) { empty -= numExchange; full++; } } return (int)consumed; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; // solve Solution solution; auto result = solution.solve(n,m); // output cout << result << ""\n""; // for(auto it:result) cout<> &constraints) { // write your code here } }; ``` where: - `constraints[i] = {k_i, l_i, r_i}` with 0 ≤ k_i ≤ n-1 and 1 ≤ l_i ≤ r_i ≤ n. - return: number of valid permutations modulo 998244353. # Example: - Input: - n = 4, m = 3 - constraints = [(0,1,1), (1,3,3), (2,4,4)] - Output: - 2 # Constraints: - $2 \leq n \leq @data$ - $0 \leq m \leq 1000$ - $0 \leq k_i \leq n-1$ - $1 \leq l_i \leq r_i \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[2000, 100000, 1000000]",1000,"[[500, 250, 150], [4000, 2000, 1200], [32000, 16000, 9600]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { inline static const uint32_t MOD = 998244353u; inline static vector fac{1}; inline static int initedUpTo = 0; static uint32_t qpow(uint32_t a, long long b) { uint64_t base = a % MOD; uint64_t res = 1 % MOD; while (b > 0) { if (b & 1) res = (res * base) % MOD; base = (base * base) % MOD; b >>= 1; } return (uint32_t)res; } static void ensure(int needN) { if (needN <= initedUpTo) return; fac.resize(needN + 1); for (int i = max(1, initedUpTo + 1); i <= needN; ++i) fac[i] = (uint32_t)((uint64_t)fac[i - 1] * (uint64_t)i % MOD); initedUpTo = needN; } static uint32_t qry1(int l, int r, int k, uint32_t invL) { if (l > r) return 1; if (k < l) return qpow((uint32_t)(k + 1), r - l + 1); if (k > r) { ensure(r + 1); return (uint32_t)((uint64_t)fac[r + 1] * invL % MOD); } ensure(max(k + 1, l)); uint32_t part = (uint32_t)((uint64_t)fac[k + 1] * invL % MOD); uint32_t powPart = qpow((uint32_t)(k + 1), r - k); return (uint32_t)((uint64_t)part * powPart % MOD); } static uint32_t qry2(int l, int r, int k, int x, uint32_t invL) { uint32_t A = qry1(l, r, k, invL); uint32_t B = qry1(l, r, x, invL); uint32_t C = (A + MOD - B); if (C >= MOD) C -= MOD; return C % MOD; } public: long long solve1(int &n, int &m, vector> &constraints) { struct Restr { int l, r, k; }; vector a; a.reserve(m); vector v; vector tvals; for (int i = 0; i < m; ++i) { int k = constraints[i][0]; int l = constraints[i][1]; int r = constraints[i][2]; --l; if (l >= 0) v.push_back(l); if (r < n) v.push_back(r); tvals.push_back(k); a.push_back({l, r, k}); } v.push_back(n - 1); tvals.push_back(-1); tvals.push_back(n - 1); sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); sort(tvals.begin(), tvals.end()); tvals.erase(unique(tvals.begin(), tvals.end()), tvals.end()); int V = (int)v.size(); vector r1(V, (int)tvals.size() - 1); vector r2(V, 0); for (auto &it : a) { if (it.k == n - 1 && it.r < n - 1) return 0; int idx = (int)(lower_bound(tvals.begin(), tvals.end(), it.k) - tvals.begin()); if (it.l >= 0) { int posIdx = (int)(lower_bound(v.begin(), v.end(), it.l) - v.begin()); r1[posIdx] = min(r1[posIdx], idx); } if (it.r < n) { int posIdx = (int)(lower_bound(v.begin(), v.end(), it.r) - v.begin()); r2[posIdx] = max(r2[posIdx], idx); } } int T = (int)tvals.size(); vector dp(T + 2, 0), pref(T + 2, 0); dp[1] = 1u; int lastL = 0; for (int i = 0; i < V; ++i) { int pos = v[i]; ensure(lastL); uint32_t invL = qpow(fac[lastL], MOD - 2); pref.assign(T + 2, 0); for (int j = 1; j < T; ++j) { uint32_t s = pref[j - 1] + dp[j]; if (s >= MOD) s -= MOD; pref[j] = s; } vector ndp(T + 2, 0); int r1v = r1[i]; int r2v = r2[i]; for (int j = 1; j < T; ++j) { if (j > r2v && j <= r1v) { uint32_t left = (uint32_t)((uint64_t)dp[j] * qry1(lastL, pos, tvals[j], invL) % MOD); uint32_t right = (uint32_t)((uint64_t)pref[j - 1] * qry2(lastL, pos, tvals[j], tvals[j - 1], invL) % MOD); uint32_t s = left + right; if (s >= MOD) s -= MOD; ndp[j] = s; } else { ndp[j] = 0; } } dp.swap(ndp); lastL = pos + 1; } uint32_t ans = 0; for (int j = 1; j <= T; ++j) { uint32_t s = ans + dp[j]; if (s >= MOD) s -= MOD; ans = s; } return (long long)(ans % MOD); } long long solve2(int &n, int &m, vector> &constraints) { if (m == 0) { uint64_t ans = 1; for (int i = 2; i <= n; ++i) ans = (ans * i) % MOD; return (long long)ans; } vector p(n); for (int i = 0; i < n; ++i) p[i] = i + 1; uint32_t ans = 0; do { bool ok = true; for (int j = 0; j < m && ok; ++j) { int k = constraints[j][0]; int l = constraints[j][1]; int r = constraints[j][2]; int x = 0; for (int i = 1; i <= n; ++i) { int mx = 0; for (int a = 0; a < i; ++a) { int cnt = 0; int pa = p[a]; for (int b = a + 1; b < i; ++b) { if (pa > p[b]) ++cnt; } if (cnt > mx) mx = cnt; } if (mx <= k) ++x; if (x > r) break; int remain = n - i; if (x + remain < l) { x = -1; break; } } if (x < l || x > r) ok = false; } if (ok) { ans += 1; if (ans >= MOD) ans -= MOD; } } while (next_permutation(p.begin(), p.end())); return (long long)(ans % MOD); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; vector> cons(m); for (int i = 0; i < m; i++) { int k, l, r; cin >> k >> l >> r; cons[i] = {k, l, r}; } // solve Solution solution; auto result = solution.solve(n, m, cons); // output cout << result << ""\n""; return 0; }","dp,math",hard 248,"Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive) solution main function ```cpp class Solution { public: vector solve(vector& nums) { } }; ``` Example 1: Input: nums = [0,2,1,5,3,4] Output: [0,1,2,4,5,3] Example 2: Input: nums = [5,0,1,2,3,4] Output: [4,5,0,1,2,3] Constraints: 1 <= nums.length <= @data 0 <= nums[i] < nums.length The elements in nums are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector& nums) { vectoranswer(nums.size()); for(int i = 0 ;i solve2(vector& nums) { int n = (int)nums.size(); vector ans(n); for (int i = 0; i < n; ++i) { int j = nums[i]; ans[i] = nums[j]; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output for(auto it:result) cout<>& rectangles) { } }; ``` Example 1: Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]] Output: 6 Example 2: Input: rectangles = [[0,0,1000000000,1000000000]] Output: 49 Constraints: 1 <= rectangles.length <= @data rectanges[i].length == 4 0 <= xi1, yi1, xi2, yi2 <= 10^9 xi1 <= xi2 yi1 <= yi2 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: long long func(vector>& intervals, int m) { if(intervals.empty()) return 0; sort(intervals.begin(), intervals.end()); long long area = 0; int prev = -1; for(auto& it : intervals) { long long height = (long long)max(0, (it.second - max(prev, it.first))); area += height; prev = max(prev, it.second); } return area; } int solve1(vector>& rectangles) { const int MOD = 1e9 + 7; vector> lines; for(auto& rect : rectangles) { lines.push_back({rect[0], 0, rect[1], rect[3]}); lines.push_back({rect[2], 1, rect[1], rect[3]}); } sort(lines.begin(), lines.end()); int prev_x = lines[0][0]; long long total_area = 0; vector> intervals; for(const auto& line : lines) { long long width = (long long)(line[0] - prev_x); long long height = func(intervals, width); total_area += width * height; if(line[1] == 1) { auto it = find(intervals.begin(), intervals.end(), make_pair(line[2], line[3])); if(it != intervals.end()) { intervals.erase(it); } } else { intervals.push_back({line[2], line[3]}); } prev_x = line[0]; } return total_area % MOD; } int solve2(vector>& rectangles) { const long long MOD = 1000000007LL; int n = (int)rectangles.size(); if (n == 0) return 0; if (n >= 63) { int k = 31; int m = n - k; long long ans = 0; unsigned long long limL = 1ULL << k; unsigned long long limR = 1ULL << m; for (unsigned long long ml = 1; ml < limL; ++ml) { long long x1l = LLONG_MIN, y1l = LLONG_MIN, x2l = LLONG_MAX, y2l = LLONG_MAX; for (int i = 0; i < k; ++i) if (ml & (1ULL << i)) { x1l = max(x1l, (long long)rectangles[i][0]); y1l = max(y1l, (long long)rectangles[i][1]); x2l = min(x2l, (long long)rectangles[i][2]); y2l = min(y2l, (long long)rectangles[i][3]); } long long wl = x2l - x1l, hl = y2l - y1l; if (wl <= 0 || hl <= 0) continue; long long areal = ((wl % MOD) * (hl % MOD)) % MOD; int bl = __builtin_popcountll(ml); long long signl = (bl & 1) ? 1 : -1; ans = (ans + signl * areal) % MOD; } for (unsigned long long mr = 1; mr < limR; ++mr) { long long x1r = LLONG_MIN, y1r = LLONG_MIN, x2r = LLONG_MAX, y2r = LLONG_MAX; for (int j = 0; j < m; ++j) if (mr & (1ULL << j)) { const auto &rc = rectangles[k + j]; x1r = max(x1r, (long long)rc[0]); y1r = max(y1r, (long long)rc[1]); x2r = min(x2r, (long long)rc[2]); y2r = min(y2r, (long long)rc[3]); } long long wr = x2r - x1r, hr = y2r - y1r; if (wr <= 0 || hr <= 0) continue; long long arear = ((wr % MOD) * (hr % MOD)) % MOD; int br = __builtin_popcountll(mr); long long signr = (br & 1) ? 1 : -1; ans = (ans + signr * arear) % MOD; } for (unsigned long long ml = 1; ml < limL; ++ml) { long long x1l = LLONG_MIN, y1l = LLONG_MIN, x2l = LLONG_MAX, y2l = LLONG_MAX; for (int i = 0; i < k; ++i) if (ml & (1ULL << i)) { x1l = max(x1l, (long long)rectangles[i][0]); y1l = max(y1l, (long long)rectangles[i][1]); x2l = min(x2l, (long long)rectangles[i][2]); y2l = min(y2l, (long long)rectangles[i][3]); } long long wl = x2l - x1l, hl = y2l - y1l; if (wl <= 0 || hl <= 0) continue; int bl = __builtin_popcountll(ml); long long signl = (bl & 1) ? 1 : -1; for (unsigned long long mr = 1; mr < limR; ++mr) { long long x1 = x1l, y1 = y1l, x2 = x2l, y2 = y2l; for (int j = 0; j < m; ++j) if (mr & (1ULL << j)) { const auto &rc = rectangles[k + j]; x1 = max(x1, (long long)rc[0]); y1 = max(y1, (long long)rc[1]); x2 = min(x2, (long long)rc[2]); y2 = min(y2, (long long)rc[3]); } long long w = x2 - x1, h = y2 - y1; if (w <= 0 || h <= 0) continue; long long area = ((w % MOD) * (h % MOD)) % MOD; int br = __builtin_popcountll(mr); long long sign = ((bl + br) & 1) ? 1 : -1; ans = (ans + sign * area) % MOD; } } if (ans < 0) ans += MOD; return (int)ans; } unsigned long long limit = 1ULL << n; long long ans = 0; for (unsigned long long mask = 1; mask < limit; ++mask) { long long x1 = LLONG_MIN, y1 = LLONG_MIN, x2 = LLONG_MAX, y2 = LLONG_MAX; for (int i = 0; i < n; ++i) if (mask & (1ULL << i)) { x1 = max(x1, (long long)rectangles[i][0]); y1 = max(y1, (long long)rectangles[i][1]); x2 = min(x2, (long long)rectangles[i][2]); y2 = min(y2, (long long)rectangles[i][3]); } long long w = x2 - x1, h = y2 - y1; if (w <= 0 || h <= 0) continue; long long area = ((w % MOD) * (h % MOD)) % MOD; int bits = __builtin_popcountll(mask); if (bits & 1) ans += area; else ans -= area; ans %= MOD; } if (ans < 0) ans += MOD; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector > s; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=4;j++) { int x; cin>>x; temp.push_back(x); } s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }",data_structures,hard 250,"# Problem Statement Freya the Frog is traveling on the 2D coordinate plane. She is currently at point $(0,0)$ and wants to go to point $(x,y)$. In one move, she chooses an integer $d$ such that $0 \leq d \leq k$ and jumps $d$ spots forward in the direction she is facing. Initially, she is facing the positive $x$ direction. After every move, she will alternate between facing the positive $x$ direction and the positive $y$ direction (i.e., she will face the positive $y$ direction on her second move, the positive $x$ direction on her third move, and so on). What is the minimum amount of moves she must perform to land on point $(x,y)$? The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &x, int &y, int &k) { // write your code here } }; ``` where: - return: the number of jumps Freya needs to make on a new line. # Example 1: - Input: x = 9, y = 11, k = 3 - Output: 8 # Constraints: - $0 \leq x, y \leq @data$ - $1 \leq k \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &x, int &y, int &k) { x = (x + k - 1) / k; y = (y + k - 1) / k; return max(2 * x - 1, 2 * y); } int solve2(int &x, int &y, int &k) { long long lx = x; long long ly = y; long long lk = k; long long cx = 0; long long cy = 0; long long moves = 0; bool dirX = true; while (cx < lx || cy < ly) { if (dirX) { long long need = lx - cx; if (need > 0) { long long step = need < lk ? need : lk; cx += step; } } else { long long need = ly - cy; if (need > 0) { long long step = need < lk ? need : lk; cy += step; } } ++moves; dirX = !dirX; } if (moves > INT_MAX) return INT_MAX; return (int)moves; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int x, y, k; cin >> x >> y >> k; // solve Solution solution; auto result = solution.solve(x, y, k); // output cout << result << ""\n""; return 0; }",math,medium 251,"# Problem Statement Anya lives in the Flower City. By order of the city mayor, she has to build a fence for herself. The fence consists of $n$ planks, each with a height of $a_i$ meters. According to the order, the heights of the planks must **not increase**. In other words, it is true that $a_i \ge a_j$ for all $i < j$. Anya became curious whether her fence is symmetrical with respect to the diagonal. In other words, will she get the same fence if she lays all the planks horizontally in the same order. Help Anya and determine whether her fence is symmetrical. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, vector &a) { // write your code here } }; ``` where: - return ""YES"" if the fence is symmetrical, otherwise return ""NO"". # Example 1: - Input: n = 5 a = [5, 4, 3, 2, 1] - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - $a$ is non-increasing - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { for (int i = 0, j = n; i < n; i++) { while (j > 0 && a[j - 1] <= i) { j--; } if (a[i] != j) { return ""NO""; } } return ""YES""; } string solve2(int &n, vector &a) { for (int i = 0; i < n; ++i) { long long cnt = 0; int threshold = i + 1; for (int j = 0; j < n; ++j) { if (a[j] >= threshold) ++cnt; } if ((long long)a[i] != cnt) return ""NO""; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",sort,medium 252,"# Problem Statement You are given a sequence $a$, consisting of $n$ integers, where the $i$-th element of the sequence is equal to $a_i$. You are also given two integers $x$ and $y$ ($x \le y$). A pair of integers $(i, j)$ is considered interesting if the following conditions are met: - $1 \le i < j \le n$; - if you simultaneously remove the elements at positions $i$ and $j$ from the sequence $a$, the sum of the remaining elements is at least $x$ and at most $y$. Your task is to determine the number of interesting pairs of integers for the given sequence $a$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, long long &x, long long &y, vector &a) { // write your code here } }; ``` where: - return: the number of interesting pairs of integers, please use `long long` type to avoid overflow # Example 1: - Input: n = 4, x = 8, y = 10 a = [4, 6, 3, 6] - Output: 4 # Constraints: - $3 \leq n \leq @data$ - $1 \leq x \leq y \leq 10^14$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, long long &x, long long &y, vector &a) { long long sum = 0; for (int i = 0; i < n; i++) sum += a[i]; sort(a.begin(), a.end()); long long res = 0; for (int i = n - 1, l = 0, r = 0; i >= 0; i--) { while (r < i && sum - a[i] - a[r] >= x) r++; while (l < r && sum - a[l] - a[i] > y) l++; if (l >= i) break; res += min(r, i) - l; } return res; } long long solve2(int &n, long long &x, long long &y, vector &a) { long long sum = 0; for (int i = 0; i < n; i++) sum += a[i]; long long res = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { long long rem = sum - (long long)a[i] - (long long)a[j]; if (rem >= x && rem <= y) res++; } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; long long x, y; cin >> n >> x >> y; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, x, y, a); // output cout << result << ""\n""; return 0; }","two_pointers,binary,sort",medium 253,"# Problem Statement You are given a cyclic array $a_1, a_2, \ldots, a_n$. You can perform the following operation on $a$ at most $n - 1$ times: - Let $m$ be the current size of $a$, you can choose any two adjacent elements where the previous one is no greater than the latter one (In particular, $a_m$ and $a_1$ are adjacent and $a_m$ is the previous one), and delete exactly one of them. In other words, choose an integer $i$ ($1 \leq i \leq m$) where $a_i \leq a_{(i \bmod m) + 1}$ holds, and delete exactly one of $a_i$ or $a_{(i \bmod m) + 1}$ from $a$. Your goal is to find the minimum number of operations needed to make all elements in $a$ equal. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the minimum number of operations needed to make all elements in a equal. # Example 1: - Input: n = 3, a = [1, 2, 3] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { void siftDown(vector &a, int n, int i) { while (true) { int largest = i; int l = (i << 1) + 1; int r = l + 1; if (l < n && a[l] > a[largest]) largest = l; if (r < n && a[r] > a[largest]) largest = r; if (largest == i) break; int tmp = a[i]; a[i] = a[largest]; a[largest] = tmp; i = largest; } } void heapSort(vector &a, int n) { for (int i = (n >> 1) - 1; i >= 0; --i) siftDown(a, n, i); for (int i = n - 1; i > 0; --i) { int tmp = a[0]; a[0] = a[i]; a[i] = tmp; siftDown(a, i, 0); } } public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int ans = 0; int res = 0; int zhi = a[0]; for (int i = 0; i <= n - 1; i++) { if (a[i] == zhi) { res++; } else { ans = max(ans, res); zhi = a[i]; res = 1; } } ans = max(ans, res); return n - ans; } int solve2(int &n, vector &a) { heapSort(a, n); int ans = 0; int res = 0; int zhi = a[0]; for (int i = 0; i <= n - 1; i++) { if (a[i] == zhi) { res++; } else { ans = max(ans, res); zhi = a[i]; res = 1; } } ans = max(ans, res); return n - ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",sort,easy 254,"You are given an array nums consisting of positive integers. We call a subarray of an array complete if the following condition is satisfied: The number of distinct elements in the subarray is equal to the number of distinct elements in the whole array. Return the number of complete subarrays. A subarray is a contiguous non-empty part of an array. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [1,3,1,2,2] Output: 4 Example 2: Input: nums = [5,5,5,5] Output: 10 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 2000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { unordered_map mp, all; for(auto n: nums) all[n]++; int front = 0, back = 0, ans = 0; while(front < nums.size()){ mp[nums[front]]++; while(back <= front && mp.size() == all.size()){ if(--mp[nums[back]] == 0) mp.erase(nums[back]); back++; ans += (nums.size() - front); } front++; } return ans; } int solve2(vector& nums) { int n = (int)nums.size(); int dtot = 0; for (int i = 0; i < n; ++i) { bool first = true; for (int j = 0; j < i; ++j) { if (nums[j] == nums[i]) { first = false; break; } } if (first) ++dtot; } long long ans = 0; for (int l = 0; l < n; ++l) { int start_r = l + dtot - 1; if (start_r < l) start_r = l; for (int r = start_r; r < n; ++r) { int d = 0; for (int k = l; k <= r; ++k) { bool first = true; for (int t = l; t < k; ++t) { if (nums[t] == nums[k]) { first = false; break; } } if (first) { ++d; if (d == dtot) break; } } if (d == dtot) ++ans; } } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< solve(int n, int x, int y) { } }; ``` Example 1: Input: n = 3, x = 1, y = 3 Output: [6,0,0] Example 2: Input: n = 5, x = 2, y = 4 Output: [10,8,2,0,0] Constraints: 2 <= n <= @data 1 <= x, y <= n Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve(int n, int x, int y) { if(x>y) return solve(n, y, x); vector res(n, 0); for(int i=1;i<=n;i++){ for(int j=1;j=1) res[idx-1]+=2; } } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int x,y,n; cin>>n>>x>>y; // solve Solution solution; auto result = solution.solve(n,x,y); // output for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return ""YES"" without quotation marks if it is possible to make all the elements equal after any number of operations; otherwise, return ""NO"" without quotation marks. # Example 1: - Input: n = 3, a = [3, 2, 1] - Output: YES # Constraints: - $3 \leq n \leq @data$ - $1 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { int s1 = 0; int s2 = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) s1 += a[i]; else s2 += a[i]; } int c1 = (n + 1) / 2; int c2 = n / 2; if (s1 % c1 == 0 && s2 % c2 == 0 && s1 / c1 == s2 / c2) return ""YES""; else return ""NO""; } string solve2(int &n, vector &a) { long long s0 = 0, s1 = 0; for (int i = 0; i < n; ++i) { if ((i & 1) == 0) s0 += a[i]; else s1 += a[i]; } int c0 = (n + 1) / 2; int c1 = n / 2; if (s0 % c0 != 0 || s1 % c1 != 0) return ""NO""; long long x = s0 / c0; if (s1 / c1 != x) return ""NO""; long long carry = 0; for (int i = 0; i < n; i += 2) carry += (long long)a[i] - x; if (carry != 0) return ""NO""; carry = 0; for (int i = 1; i < n; i += 2) carry += (long long)a[i] - x; if (carry != 0) return ""NO""; return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",math,medium 257,"# Problem Statement Petya organized a strange birthday party. He invited $n$ friends and assigned an integer $k_i$ to the $i$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $m$ unique presents available, the $j$-th present costs $c_j$ dollars ($1 \le c_1 \le c_2 \le \ldots \le c_m$). It's **not** allowed to buy a single present more than once. For the $i$-th friend Petya can either buy them a present $j \le k_i$, which costs $c_j$ dollars, or just give them $c_{k_i}$ dollars directly. Help Petya determine the minimum total cost of hosting his party. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, int &m, vector &k, vector &c) { // write your code here } }; ``` where: - return: the minimum total cost of hosting the party, please use `long long` to avoid overflow # Example 1: - Input: n = 5, m = 4 k = [2, 3, 4, 3, 2] c = [3, 5, 12, 20] - Output: 30 # Constraints: - $1 \leq n, m \leq @data$ - $1 \leq k[i] \leq m$ - $1 \leq c[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &m, vector &k, vector &c) { sort(k.begin(), k.end()); long long ans = 0; for (int i = n - 1; i >= 0; i--) { ans += c[min(k[i] - 1, n - 1 - i)]; } return ans; } long long solve2(int &n, int &m, vector &k, vector &c) { sort(k.begin(), k.end(), greater()); long long ans = 0; int p = 1; for (int i = 0; i < n; i++) { if (p <= k[i]) { ans += c[p - 1]; p++; } else { ans += c[k[i] - 1]; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; vector k(n), c(m); for (int i = 0; i < n; i++) cin >> k[i]; for (int i = 0; i < m; i++) cin >> c[i]; // solve Solution solution; auto result = solution.solve(n, m, k, c); // output cout << result << ""\n""; return 0; }","binary,dp,sort,two_pointers",hard 258,"You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1. For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator. Replace the array nums with newNums. Repeat the entire process starting from step 1. Return the triangular sum of nums. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [1,2,3,4,5] Output: 8 Example 2: Input: nums = [5] Output: 5 Constraints: 1 <= nums.length <= @data 0 <= nums[i] <= 9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int result = 0; int m = nums.size() - 1; int mck = 1, exp2 = 0, exp5 = 0; int inv[] = {0, 1, 0, 7, 0, 0, 0, 3, 0, 9}; int pow2mod10[] = {6, 2, 4, 8}; for (int k = 0; true; k++) { if (!exp2 || !exp5) { int mCk_ = exp2 ? mck * pow2mod10[exp2 % 4] : exp5 ? mck * 5 : mck; result = (result + mCk_ * nums[k]) % 10; } if (k == m) return result; int mul = m - k; while (mul % 2 == 0) { mul /= 2; exp2++; } while (mul % 5 == 0) { mul /= 5; exp5++; } mck = mck * mul % 10; int div = k + 1; while (div % 2 == 0) { div /= 2; exp2--; } while (div % 5 == 0) { div /= 5; exp5--; } mck = mck * inv[div % 10] % 10; } } int solve2(vector& nums) { int n = (int)nums.size(); for (int len = n; len > 1; --len) { for (int i = 0; i < len - 1; ++i) { int x = nums[i] + nums[i + 1]; nums[i] = x >= 10 ? x - 10 : x; } } return nums[0]; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout<><<"" s2 ="">>><"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - n is even - No arrow points outside the grid - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 160, 64], [6400, 1280, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, string &s1, string &s2) { bool flag = 0; for (int i = 0; i < n - 1; i++) { if (i % 2 == 0 && s2[i] == '<' && s1[i + 1] == '<') flag = 1; if (i % 2 == 1 && s2[i + 1] == '<' && s1[i] == '<') flag = 1; } return flag ? ""NO"" : ""YES""; } string solve2(int &n, string &s1, string &s2) { auto isVis = [&](int r, int i) -> bool { char ch = (r == 0 ? s1[i] : s2[i]); return ch == 'A' || ch == 'B'; }; auto dir = [&](int r, int i) -> int { char ch = (r == 0 ? s1[i] : s2[i]); if (ch == '>' || ch == 'A') return 1; return -1; }; auto mark = [&](int r, int i) { if (r == 0) { if (s1[i] == '>') s1[i] = 'A'; else if (s1[i] == '<') s1[i] = 'B'; } else { if (s2[i] == '>') s2[i] = 'A'; else if (s2[i] == '<') s2[i] = 'B'; } }; mark(0, 0); if (n - 1 == 0 && isVis(1, n - 1)) return ""YES""; bool changed = true; while (changed) { changed = false; for (int r = 0; r < 2; ++r) { for (int i = 0; i < n; ++i) { if (!isVis(r, i)) continue; if (i > 0 && dir(r, i - 1) < 0) { int j = i - 2; if (j >= 0 && !isVis(r, j)) { mark(r, j); if (r == 1 && j == n - 1) return ""YES""; changed = true; } } if (i + 1 < n && dir(r, i + 1) > 0) { int j = i + 2; if (j < n && !isVis(r, j)) { mark(r, j); if (r == 1 && j == n - 1) return ""YES""; changed = true; } } int rr = 1 - r; int j = i + dir(rr, i); if (j >= 0 && j < n && !isVis(rr, j)) { mark(rr, j); if (rr == 1 && j == n - 1) return ""YES""; changed = true; } } } } return isVis(1, n - 1) ? ""YES"" : ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s1, s2; cin >> s1 >> s2; // solve Solution solution; auto result = solution.solve(n, s1, s2); // output cout << result << ""\n""; return 0; }","dp,graph,search",hard 260,"You are given a binary string s that contains at least one '1'. You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination. Return a string representing the maximum odd binary number that can be created from the given combination. Note that the resulting string can have leading zeros. solution main function ```cpp class Solution { public: string solve(string s) { } }; ``` Example 1: Input: s = ""010"" Output: ""001"" Example 2: Input: s = ""010"" Output: ""001"" Constraints: 1 <= s.length <= @data s consists only of '0' and '1'. s contains at least one '1' Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: string solve1(string s) { const int N = s.length(); char* arr = new char[N + 1]; strcpy(arr, s.c_str()); int left = 0; int right = N - 1; while(left <= right) { if (arr[left] == '1') { left++; } if (arr[right] == '0') { right--; } if (left <= right && arr[left] == '0' && arr[right] == '1') { arr[left] = '1'; arr[right] = '0'; } } arr[left - 1] = '0'; arr[N - 1] = '1'; return arr; } string solve2(string s) { const size_t n = s.size(); size_t ones = 0; for (size_t i = 0; i < n; ++i) { if (s[i] == '1') ++ones; } if (n == 0) return s; for (size_t i = 0; i + 1 < n; ++i) s[i] = '0'; size_t k = ones ? (ones - 1) : 0; for (size_t i = 0; i < k; ++i) s[i] = '1'; s[n - 1] = ones ? '1' : '0'; return s; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string str; cin>>str; // solve Solution solution; auto result = solution.solve(str); // output cout << result << ""\n""; // for(auto it:result) cout<> solve(vector& products, string searchWord){ } }; ``` Example 1: Input: products = [""mobile"",""mouse"",""moneypot"",""monitor"",""mousepad""], searchWord = ""mouse"" Output: [[""mobile"",""moneypot"",""monitor""],[""mobile"",""moneypot"",""monitor""],[""mouse"",""mousepad""],[""mouse"",""mousepad""],[""mouse"",""mousepad""]] Example 2: Input: products = [""havana""], searchWord = ""havana"" Output: [[""havana""],[""havana""],[""havana""],[""havana""],[""havana""],[""havana""]] Constraints: 1 <= products.length <= @data 1 <= products[i].length <= 3000 1 <= sum(products[i].length) <= 2 * 10^4 All the strings of products are unique. products[i] consists of lowercase English letters. 1 <= searchWord.length <= @data searchWord consists of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector> solve1(vector& products, string searchWord) { sort(products.begin(), products.end()); string query; auto iter_last = products.begin(); vector> ans; for (char ch : searchWord) { query += ch; auto iter_find = lower_bound(iter_last, products.end(), query); vector selects; for (int i = 0; i < 3; ++i) { if (iter_find + i < products.end() && (*(iter_find + i)).find(query) == 0) { selects.push_back(*(iter_find + i)); } } ans.push_back(move(selects)); iter_last = iter_find; } return ans; } vector> solve2(vector& products, string searchWord) { string query; vector> ans; for (char ch : searchWord) { query += ch; int idx1 = -1, idx2 = -1, idx3 = -1; for (size_t i = 0; i < products.size(); ++i) { const string& s = products[i]; if (s.size() < query.size()) continue; bool ok = true; for (size_t j = 0; j < query.size(); ++j) { if (s[j] != query[j]) { ok = false; break; } } if (!ok) continue; if (idx1 == -1 || s < products[idx1]) { idx3 = idx2; idx2 = idx1; idx1 = (int)i; } else if (idx2 == -1 || s < products[idx2]) { idx3 = idx2; idx2 = (int)i; } else if (idx3 == -1 || s < products[idx3]) { idx3 = (int)i; } } vector selects; if (idx1 != -1) selects.push_back(products[idx1]); if (idx2 != -1) selects.push_back(products[idx2]); if (idx3 != -1) selects.push_back(products[idx3]); ans.push_back(move(selects)); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector dic; string bas; for(int i=1;i<=n;i++) { cin>>bas; dic.push_back(bas); } cin>>bas; // solve Solution solution; auto result = solution.solve(dic,bas); // output for(auto it:result) { for(auto str:it) cout<& plants, int capacity) { } }; ``` Example 1: Input: plants = [2,2,3,3], capacity = 5 Output: 14 Example 2: Input: plants = [1,1,1,4,2,3], capacity = 4 Output: 30 Constraints: n == plants.length 1 <= n <= @data 1 <= plants[i] <= 10^6 max(plants[i]) <= capacity <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& p, int capacity) { int ans=0,c=capacity; for(int i=0;i=p[i]) ans++; else{ ans+=i; ans+=i+1; c=capacity; } c=c-p[i]; } return ans; } int solve2(vector& p, int capacity) { long long steps = 0; int pos = -1; long long water = capacity; int n = (int)p.size(); for (int i = 0; i < n; ++i) { steps += (long long)(i - pos); pos = i; water -= p[i]; if (i + 1 < n && water < p[i + 1]) { steps += (long long)(pos + 1); pos = -1; water = capacity; } } return (int)steps; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,m); // output // for(auto it:result) cout< &a, vector &b) { // write your code here } }; ``` where: - the return value is a 64-bit integer representing the maximum difference $D$ # Example 1: - Input: n = 4, m = 6 a = [6, 1, 2, 4] b = [3, 5, 1, 7, 2, 3] - Output: 16 # Constraints: - $1 \leq n \leq m \leq @data$ - $1 \leq a[i], b[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &m, vector &a, vector &b) { sort(b.begin(), b.end()); sort(a.begin(), a.end()); long long ans = 0; int l1 = 0, l2 = 0, r1 = n - 1, r2 = m - 1; for (int i = 0; i < n; i++) { if ((r2 >= 0) && (b[r2] - a[l1] > a[r1] - b[l2])) ans += b[r2] - a[l1], r2--, l1++; else ans += a[r1] - b[l2], r1--, l2++; } return ans; } long long solve2(int &n, int &m, vector &a, vector &b) { long long ans = 0; for (int t = 0; t < n; ++t) { int minAIdx = -1, maxAIdx = -1; int minAVal = INT_MAX, maxAVal = INT_MIN; for (int i = 0; i < n; ++i) { if (a[i] != -1) { if (a[i] < minAVal) { minAVal = a[i]; minAIdx = i; } if (a[i] > maxAVal) { maxAVal = a[i]; maxAIdx = i; } } } int minBIdx = -1, maxBIdx = -1; int minBVal = INT_MAX, maxBVal = INT_MIN; for (int i = 0; i < m; ++i) { if (b[i] != -1) { if (b[i] < minBVal) { minBVal = b[i]; minBIdx = i; } if (b[i] > maxBVal) { maxBVal = b[i]; maxBIdx = i; } } } long long diff1 = llabs((long long)maxBVal - (long long)minAVal); long long diff2 = llabs((long long)maxAVal - (long long)minBVal); if (diff1 > diff2) { ans += diff1; a[minAIdx] = -1; b[maxBIdx] = -1; } else { ans += diff2; a[maxAIdx] = -1; b[minBIdx] = -1; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector b(m); for (int i = 0; i < m; i++) cin >> b[i]; // solve Solution solution; auto result = solution.solve(n, m, a, b); // output cout << result << ""\n""; return 0; }","two_pointers,data_structures,greedy,sort",hard 264,"# Problem Statement You are given two integers $n$ and $m$. An array $a_1,a_2,\dots,a_n$ is called snake if and only if: - All elements are integers between $0$ and $m$; - $a_1+a_2+\cdots+a_n = m$; - $a_n = \max([a_1,a_2,\dots,a_n])$. Define the function $f(a)$ by the following pseudocode: ``` function f(array a): pos := 1 res := 0 let nxt[x] be the smallest index y such that y > x and a[y] > a[x], or undefined if no such y exists while pos < n: if a[pos] < a[n]: res += a[nxt[pos]] - a[pos] pos := nxt[pos] else: pos += 1 return res ``` Your task is to compute the sum of $f(a)$ over all snake arrays of length $n$ with sum $m$, modulo $10^9+7$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, int &m) { // write your code here } }; ``` where: - `n`: length of the array, - `m`: total sum of the array, - return: the sum of `f(a)` over all snake arrays, modulo $10^9+7$. # Example 1: - Input: ``` n = 2 m = 5 ``` - Output: ``` 9 ``` # Constraints: - $2 \leq n \leq @data$ - $0 \leq m \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 200000]",1000,"[[1000, 200, 100], [8000, 1600, 800], [64000, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve(int &n, int &m) { using ll = long long; const int MOD = 1000000007; int MXN = n + m + 7; static bool inited = false; vector F(MXN), I(MXN); auto power = [&](ll a, ll b) { ll res = 1; while (b) { if (b & 1) res = (res * a) % MOD; a = (a * a) % MOD; b >>= 1; } return res; }; auto prep = [&]() { if (inited) return; inited = true; F[0] = 1; for (int i = 1; i < MXN; i++) F[i] = F[i - 1] * i % MOD; vector invs(MXN); invs[0] = invs[1] = 1; for (int i = 2; i < MXN; i++) invs[i] = (MOD - MOD / i) * invs[MOD % i] % MOD; I[0] = 1; for (int i = 1; i < MXN; i++) I[i] = I[i - 1] * invs[i] % MOD; }; auto C = [&](int N, int R) -> ll { if (R < 0 || R > N) return 0; return F[N] * I[R] % MOD * I[N - R] % MOD; }; auto g = [&](int nn, int mm, int l) -> ll { if (nn == 0) return mm == 0; ll ans = 0; for (int t = 0; t <= nn && 1LL * t * (l + 1) <= mm; t++) { ll add = C(nn, t) * C(mm + nn - 1 - t * (l + 1), nn - 1) % MOD; if (t & 1) ans = (ans + MOD - add) % MOD; else ans = (ans + add) % MOD; } return ans; }; prep(); ll inv = power(n - 1, MOD - 2); ll ans = 0; for (int x = 0; x <= m; x++) { ll g1 = g(n - 1, m - x, x); ll g2 = g(n - 2, m - 2 * x, x); ans = (ans + 1LL * x % MOD * ((g1 + g2 * (n - 1LL)) % MOD)) % MOD; ll bad = 0; bad = (bad + 1LL * (m - x) % MOD * g1 % MOD * inv) % MOD; bad = (bad + 1LL * x % MOD * g2) % MOD; bad = (bad + 1LL * max(0, m - 2 * x) % MOD * g2) % MOD; ans = (ans + MOD - bad) % MOD; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; // solve Solution solution; auto result = solution.solve(n, m); // output cout << result << ""\n""; return 0; }",math,hard 265,"We are playing the Guessing Game. The game will work as follows: I pick a number between 1 and n. You guess a number. If you guess the right number, you win the game. If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing. Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game. Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 10 Output: 16 Example 2: Input: n = 1 Output: 0 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[8, 50, 200]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { vector> dp(n+1, vector(n+1, 0)); for(int len=2; len<=n; ++len){ for(int begin=0; begin<=n-len; ++begin){ int end = begin + len; for(int i=begin; i memo; function f = [&](int l, int r)->int { if (l >= r) return 0; long long key = (static_cast(l) << 32) ^ static_cast(r); auto it = memo.find(key); if (it != memo.end()) return it->second; int best = INT_MAX; for (int k = l; k <= r; ++k) { int left = f(l, k - 1); int right = f(k + 1, r); long long cur = static_cast(k) + max(left, right); if (cur < best) best = static_cast(cur); } memo[key] = best; return best; }; return f(1, n); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }","math,dp",medium 266,"# Problem Statement You are given a sequence `a` of `n` positive integers. For any sequence `b = [b1, b2, …, bk]`, define the cost: - `cost(b) = ceil(bk / min(b1, b2, …, bk))` For a partition of a sequence `c` into one or more contiguous subsequences whose concatenation equals `c`, define the total cost as the sum of the costs of all parts. Let `f(c)` be the minimum total cost over all possible partitions of `c`. Compute: - Sum of `f([a_l, a_{l+1}, …, a_r])` over all `1 ≤ l ≤ r ≤ n`. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: the length of the array - `a`: the array of positive integers - return: the sum of `f` over all contiguous subsequences of `a` # Example 1: - Input: `n = 5` `a = [3, 1, 4, 1, 5]` - Output: `21` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^{18}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { vector st; vector realind; vector i2, i3, prevind; long long ans = 0; const int N = 150; vector dp(N); for (int i = 0; i < n; i++) { long long x = a[i]; while (!st.empty() && st.back() >= x) { st.pop_back(); realind.pop_back(); i2.pop_back(); i3.pop_back(); prevind.pop_back(); } st.push_back(x); if (realind.empty()) prevind.push_back(-1); else prevind.push_back(realind.back()); realind.push_back(i); long long half = (x + 1) / 2; long long third = (x + 2) / 3; int idx2 = (int)(lower_bound(st.begin(), st.end(), half) - st.begin()); int idx3 = (int)(lower_bound(st.begin(), st.end(), third) - st.begin()); i2.push_back(idx2); i3.push_back(idx3); for (int j = 0; j < N; j++) dp[j] = i + 2; dp[0] = (int)st.size(); ans += i - prevind.back(); for (int j = 0; j < N; j++) { if (j > 1) { ans += 1LL * j * (prevind[dp[j - 1]] - prevind[dp[j]]); } if (dp[j] == 0) break; if (j + 1 < N) dp[j + 1] = min(dp[j + 1], dp[j] - 1); if (j + 2 < N) dp[j + 2] = min(dp[j + 2], i2[dp[j] - 1]); if (j + 3 < N) dp[j + 3] = min(dp[j + 3], i3[dp[j] - 1]); } } return ans; } long long solve2(int &n, vector &a) { long long ans = 0; vector dp; dp.reserve(n + 1); for (int l = 0; l < n; l++) { dp.clear(); dp.push_back(0); for (int len = 1; len <= n - l; len++) { long long last = a[l + len - 1]; long long best = LLONG_MAX; long long mn = LLONG_MAX; for (int s = len; s >= 1; s--) { long long v = a[l + s - 1]; if (v < mn) mn = v; __int128 num = (__int128)last + (__int128)mn - 1; long long cost = (long long)(num / mn); long long cand = dp[s - 1] + cost; if (cand < best) best = cand; } dp.push_back(best); ans += best; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,data_structures",hard 267,"Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. solution main function ```cpp class Solution { public: bool solve(string s, string t) { } }; ``` Example 1: Input: s = ""ab#c"", t = ""ad#c"" Output: 1 Example 2: Input: s = ""ab##"", t = ""c#d#"" Output: 1 Constraints: 1 <= s.length, t.length <= @data s and t only contain lowercase letters and '#' characters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve1(string S, string T) { int i = S.length() - 1, j = T.length() - 1, back; while (true) { back = 0; while (i >= 0 && (back > 0 || S[i] == '#')) { back += S[i] == '#' ? 1 : -1; i--; } back = 0; while (j >= 0 && (back > 0 || T[j] == '#')) { back += T[j] == '#' ? 1 : -1; j--; } if (i >= 0 && j >= 0 && S[i] == T[j]) { i--; j--; } else { break; } } return i == -1 && j == -1; } bool solve2(string S, string T) { int kS = 0; for (int i = 0, n = (int)S.size(); i < n; ++i) { if (S[i] == '#') { if (kS > 0) --kS; } else { S[kS++] = S[i]; } } int kT = 0; for (int i = 0, n = (int)T.size(); i < n; ++i) { if (T[i] == '#') { if (kT > 0) --kT; } else { T[kT++] = T[i]; } } if (kS != kT) return false; for (int i = 0; i < kS; ++i) { if (S[i] != T[i]) return false; } return true; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string a,b; cin>>a>>b; // solve Solution solution; auto result = solution.solve(a,b); // output cout << result << ""\n""; return 0; }","string,two_pointers",easy 268,"There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i]. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node). Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order. solution main function ```cpp class Solution { public: vector solve(vector>& graph) { // write your code here } }; ``` Example 1: Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] Output: [2,4,5,6] Example 2: Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]] Output: [4] Constraints: n == graph.length 1 <= n <= @data 0 <= graph[i].length <= n 0 <= graph[i][j] <= n - 1 graph[i] is sorted in a strictly increasing order. The graph may contain self-loops. The number of edges in the graph will be in the range [1, 4 * n]. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector>& graph) { int n = graph.size(); vector vis(n); vector safe(n); auto dfs = [&](auto dfs, int u) -> void { vis[u] = true; for(int v : graph[u]) { if(!vis[v]) { dfs(dfs, v); if(!safe[v]) { safe[u] = false; return ; } } else if(!safe[v]) { safe[u] = false; return ; } } safe[u] = true; }; for(int i = 0;i < n;i ++) { if(!vis[i]) dfs(dfs, i); } vector ans; for(int i = 0;i < n;i ++) { if(safe[i]) ans.push_back(i); } return move(ans); } vector solve2(vector>& graph) { int n = (int)graph.size(); bool changed = true; while (changed) { changed = false; for (int i = 0; i < n; ++i) { if (!graph[i].empty()) { bool allSafe = true; for (int k = 0; k < (int)graph[i].size(); ++k) { int v = graph[i][k]; if (v < 0 || v >= n || !graph[v].empty()) { allSafe = false; break; } } if (allSafe) { graph[i].clear(); changed = true; } } } } vector ans; for (int i = 0; i < n; ++i) { if (graph[i].empty()) ans.push_back(i); } return move(ans); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > g; vector e[n+1]; for(int i=1;i<=m;i++) { int x,y; cin>>x>>y; e[x].push_back(y); } for(int i=0;i using namespace std; #include using namespace std; class Solution { public: int solve1(int n, int start) { int num = start; for(int i = 1 ; i < n; i++){ num = num ^ (start + 2 * i); } return num; } int solve2(int n, int start) { int res = 0; for (int i = 0; i < n; ++i) { long long term = (long long)start + ((long long)i << 1); res ^= (int)term; } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,start;cin>>n>>start; // solve Solution solution; auto result = solution.solve(n,start); // output // for(auto it:result) cout< using namespace std; class Solution { public: int solve1(int &n, string &s) { int l = 0, r = n; while (l < r && s[l] == 'B') l += 1; while (l < r && s[r - 1] == 'A') r -= 1; return max(0, r - l - 1); } int solve2(int &n, string &s) { int firstA = 0; while (firstA < n && s[firstA] != 'A') firstA += 1; if (firstA == n) return 0; int lastB = n - 1; while (lastB >= 0 && s[lastB] != 'B') lastB -= 1; if (lastB < 0) return 0; int ans = lastB - firstA; return ans < 0 ? 0 : ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","greedy,string,two_pointers",hard 271,"# Problem Statement For all integers $x \ge 1$ and $k \ge 2$, let $v_k(x!)$ be the number of trailing zeros in the base-$k$ representation of $x!$, i.e., the largest integer $i$ such that $k^i$ divides $x!$. For a prime $p$, we have $$ v_p(x!)=\sum_{j=1}^{\infty} \left\lfloor \frac{x}{p^j} \right\rfloor. $$ If $k$ is not prime and $k=\prod p_i^{e_i}$ is its prime factorization, then $$ v_k(x!)=\min_i \left\lfloor \frac{v_{p_i}(x!)}{e_i} \right\rfloor. $$ For any two positive integers $a,b$ and any $k\ge 2$, define the weight $$ w_k(a,b)= \begin{cases} \min\big(v_k(a!), v_k(b!)\big), & v_k(a!) \ne v_k(b!),\\ 10^{100}, & \text{otherwise.} \end{cases} $$ Then define $$ f_m(a,b)=\min_{2\le k\le m} w_k(a,b). $$ Given two integers $n$ and $m$, compute $$ \sum_{1\le x \le n-1} f_m(x,n). $$ The result is strictly less than $10^{100}$ under the given constraints. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, int &m) { // write your code here } }; ``` where: - `n`: upper bound for the sum (we sum over `x=1..n-1`) - `m`: upper bound for base `k` (we minimize over `k=2..m`) - return: the value of `sum_{x=1}^{n-1} f_m(x, n)` # Example: - Input: ``` n = 6 m = 7 ``` - Output: ``` 1 ``` # Constraints: - $2 \leq n \leq @data$ - $n \leq m \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 100000, 10000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &m) { const int INF = 1000000005; if (n <= 2) return 0; int limSmall = (int)floor(sqrt((long double)max(n, m))) + 5; vector is_comp(limSmall + 1, false); vector smallPrimes; for (int i = 2; 1LL * i * i <= limSmall; ++i) { if (!is_comp[i]) { for (long long j = 1LL * i * i; j <= limSmall; j += i) is_comp[(int)j] = true; } } for (int i = 2; i <= limSmall; ++i) if (!is_comp[i]) smallPrimes.push_back(i); auto isPrime = [&](int x) -> bool { if (x < 2) return false; for (int p : smallPrimes) { if (1LL * p * p > x) break; if (x % p == 0) return false; } return true; }; auto legendre = [&](int p, int x) -> int { int res = 0; while (x) { x /= p; res += x; } return res; }; auto factorize = [&](int x) -> vector> { vector> f; for (int p : smallPrimes) { if (1LL * p * p > x) break; if (x % p == 0) { int c = 0; while (x % p == 0) x /= p, ++c; f.push_back({p, c}); } } if (x > 1) f.push_back({x, 1}); return f; }; int q = n; while (q >= 2 && !isPrime(q)) --q; if (q >= n) return 0; int g = n - q; vector>> facts(g + 1); for (int y = q; y <= n; ++y) facts[y - q] = factorize(y); vector plist; plist.reserve(g * 4 + 8); for (int i = 0; i <= g; ++i) for (auto &pr : facts[i]) plist.push_back(pr.first); sort(plist.begin(), plist.end()); plist.erase(unique(plist.begin(), plist.end()), plist.end()); if (plist.empty()) return 0; unordered_map pid; pid.reserve(plist.size() * 2); for (int i = 0; i < (int)plist.size(); ++i) pid[plist[i]] = i; int sq = (int)floor(sqrt((long double)m)); vector idxSmall, idxBig; for (int i = 0; i < (int)plist.size(); ++i) { if (plist[i] <= sq) idxSmall.push_back(i); else idxBig.push_back(i); } int P = (int)plist.size(); vector vpN(P, 0), vpX(P, 0), limE(P, 0); for (int i = 0; i < P; ++i) { int p = plist[i]; vpN[i] = legendre(p, n); if (plist[i] <= sq) { long long pw = p; while (pw <= m) { ++limE[i]; pw *= p; } } } for (int i = 0; i < P; ++i) vpX[i] = legendre(plist[i], q); vector> vpN_div(P); for (int idx : idxSmall) { vpN_div[idx].resize(limE[idx] + 1); for (int e = 1; e <= limE[idx]; ++e) vpN_div[idx][e] = vpN[idx] / e; } long long ans = 0; for (int off = 0; off < g; ++off) { int best = INF; for (int idx : idxBig) { if (vpX[idx] != vpN[idx]) best = min(best, vpX[idx]); if (best == 0) break; } if (best != 0) { for (int idx : idxSmall) { if (vpX[idx] == vpN[idx]) continue; int a = vpX[idx]; for (int e = 1; e <= limE[idx]; ++e) { int ax = a / e; if (ax != vpN_div[idx][e]) best = min(best, ax); if (best == 0) break; } if (best == 0) break; } } if (best == INF) best = 0; ans += best; if (off + 1 < g) { int yIdx = off + 1; for (auto &pr : facts[yIdx]) { int id = pid[pr.first]; vpX[id] += pr.second; } } } return ans; } long long solve2(int &n, int &m) { if (n <= 2) return 0; const long long INF = numeric_limits::max() / 4; auto legendre = [&](long long p, long long t) -> long long { long long res = 0; while (t) { t /= p; res += t; } return res; }; auto vk = [&](long long t, int base) -> long long { long long temp = base; long long minVal = INF; if ((temp & 1LL) == 0) { long long e = 0; while ((temp & 1LL) == 0) { temp >>= 1; ++e; } long long v = legendre(2, t); long long cand = v / e; if (cand < minVal) minVal = cand; } for (long long p = 3; p * p <= temp; p += 2) { if (temp % p == 0) { long long e = 0; while (temp % p == 0) { temp /= p; ++e; } long long v = legendre(p, t); long long cand = v / e; if (cand < minVal) minVal = cand; } } if (temp > 1) { long long v = legendre(temp, t); if (v < minVal) minVal = v; } if (minVal == INF) minVal = 0; return minVal; }; long long ans = 0; for (int x = 1; x <= n - 1; ++x) { long long best = INF; for (int k = 2; k <= m; ++k) { long long a = vk(x, k); long long b = vk(n, k); if (a != b) { long long w = a < b ? a : b; if (w < best) best = w; if (best == 0) break; } } if (best == INF) best = 0; ans += best; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; // solve Solution solution; auto result = solution.solve(n, m); // output cout << result << ""\n""; return 0; }",math,hard 272,"# Problem Statement You are given a binary array $a$ of $n$ elements, a binary array is an array consisting only of $0$s and $1$s. A blank space is a segment of **consecutive** elements consisting of only $0$s. Your task is to find the length of the longest blank space. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return the length of the longest blank space. # Example 1: - Input: n = 5 a = [1, 0, 0, 1, 0] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a_i \leq 1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int ans = 0; int t = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) t++; else t = 0; ans = max(ans, t); } return ans; } int solve2(int &n, vector &a) { int ans = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) { int t = 0; for (int j = i; j < n && a[j] == 0; j++) t++; ans = max(ans, t); } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (auto &x : a) cin >> x; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",greedy,easy 273,"Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [3,4,5,2] Output: 12 Example 2: Input: nums = [1,5,4,5] Output: 16 Constraints: 2 <= nums.length <= @data 1 <= nums[i] <= 10^3 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int biggest = 0; int secondBiggest = 0; for (int num : nums) { if (num > biggest) { secondBiggest = biggest; biggest = num; } else { secondBiggest = max(secondBiggest, num); } } return (biggest - 1) * (secondBiggest - 1); } int solve2(vector& nums) { int n = (int)nums.size(); long long best = LLONG_MIN; for (int i = 0; i < n; ++i) { long long ai = (long long)nums[i] - 1; for (int j = i + 1; j < n; ++j) { long long bj = (long long)nums[j] - 1; long long prod = ai * bj; if (prod > best) best = prod; } } if (best < INT_MIN) return INT_MIN; if (best > INT_MAX) return INT_MAX; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector num; cin>>n; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout< using namespace std; class Solution { public: int solve(int &n, string &s) { int p = s.find(""**""); if (p == -1) p = n; int ans = 0; for (int i = 0; i < p; i++) if (s[i] == '@') ans++; return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","greedy,dp",medium 275,"# Problem Statement: You are given a checkerboard of size $2*n \times 2*n$, i. e. it has $2*n$ rows and $2*n$ columns. The rows of this checkerboard are numbered from $-n$ to $n$ from bottom to top. The columns of this checkerboard are numbered from $-n$ to $n$ from left to right. The notation $(r, c)$ denotes the cell located in the $r$-th row and the $c$-th column. There is a king piece at position $(0, 0)$ and it wants to get to position $(a, b)$ as soon as possible. In this problem our king is lame. Each second, the king makes exactly one of the following five moves. - Skip move. King's position remains unchanged. - Go up. If the current position of the king is $(r, c)$ he goes to position $(r + 1, c)$. - Go down. Position changes from $(r, c)$ to $(r - 1, c)$. - Go right. Position changes from $(r, c)$ to $(r, c + 1)$. - Go left. Position changes from $(r, c)$ to $(r, c - 1)$. King is **not allowed** to make moves that put him outside of the board. The important consequence of the king being lame is that he is **not allowed** to make the same move during two consecutive seconds. For example, if the king goes right, the next second he can only skip, go up, down, or left. What is the minimum number of seconds the lame king needs to reach position $(a, b)$? The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &a, int &b) { // write your code here } }; ``` Where: - `n` is an integer representing the size of the chessboard. - `a` and `b` are integers representing the target position coordinates. - The function should return an integer representing the minimum time (in seconds) required for the king to reach the target position. # Example 1 - Input: n = 100 a = -4 b = 1 - Output: 7 # Constraints: - $0 < n \leq @data$ - $-n \leq a \leq n$ - $-n \leq b \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, int &a, int &b) { a = abs(a), b = abs(b); return min(a, b) * 2 + max(0, 2 * abs(b - a) - 1); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; int a; cin >> a; int b; cin >> b; // solve Solution solution; auto result = solution.solve(n, a, b); // output cout << result << ""\n""; return 0; }","greedy,math",hard 276,"Given an integer num, return a string of its base 7 representation. solution main function ```cpp class Solution { public: string solve(int num) { } }; ``` Example 1: Input: num = 100 Output: ""202"" Example 2: Input: num = -7 Output: ""-10"" Constraints: -@data <= num <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 10000000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: string str; char sign; string solve(int num) { if(num < 0) {num *= -1; sign='n';} if(num == 0){ return to_string(0);} while(num > 0) { str.push_back( '0' + (num%7) ); num = num/7; } if(sign=='n') str.push_back('-'); std::reverse(str.begin(), str.end()); return str ; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin >> n; // solve Solution solution; auto result = solution.solve(n); // output cout << result; return 0; }",math,easy 277,"# Problem Statement You are given an array $a$ of $n$ elements $a_1, a_2, \ldots, a_n$. You can perform the following operation any number (possibly $0$) of times: - Choose two integers $i$ and $j$, where $1 \le i, j \le n$, and assign $a_i := a_j$. Find the minimum number of operations required to make the array $a$ satisfy the condition: - For every pairwise distinct triplet of indices $(x, y, z)$ ($1 \le x, y, z \le n$, $x \ne y$, $y \ne z$, $x \ne z$), there exists a non-degenerate triangle with side lengths $a_x$, $a_y$ and $a_z$, i.e. $a_x + a_y > a_z$, $a_y + a_z > a_x$ and $a_z + a_x > a_y$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the minimum number of operations required. # Example 1: - Input: n = 7 a = [1, 2, 3, 4, 5, 6, 7] - Output: 3 # Constraints: - $3 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int ans = n - 1; for (int i = 1; i < n; i++) { int pos = lower_bound(a.begin(), a.end(), a[i] + a[i - 1]) - a.begin(); ans = min(ans, i - 1 + n - pos); } return ans; } int solve2(int &n, vector &a) { sort(a.begin(), a.end()); int ans = n - 1; for (int i = 1; i < n; i++) { long long s = (long long)a[i - 1] + (long long)a[i]; int changes_small = i - 1; int changes_large = 0; for (int j = 0; j < n; j++) { if ((long long)a[j] >= s) changes_large++; } ans = min(ans, changes_small + changes_large); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","binary,sort,math,two_pointers",hard 278,"Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for: i - k <= r <= i + k, j - k <= c <= j + k, and (r, c) is a valid position in the matrix. solution main function ```cpp class Solution { public: vector> solve(vector>& mat, int k) { } }; ``` Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1 Output: [[12,21,16],[27,45,33],[24,39,28]] Example 2: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2 Output: [[45,45,45],[45,45,45],[45,45,45]] Constraints: m == mat.length n == mat[i].length 1 <= m, n, k <= @data 1 <= mat[i][j] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector> solve1(vector>& mat, int k) { const int h = mat.size(), w = mat[0].size(); vector< vector > integralImg = vector< vector >(h, vector< int >(w, 0) ); vector< vector > outputImg = vector< vector >(h, vector< int >(w, 0) ); for( int y = 0 ; y < h ; y++){ int pixelSum = 0; for( int x = 0 ; x < w ;x++){ pixelSum += mat[y][x]; integralImg[y][x] = pixelSum; if( y > 0 ){ integralImg[y][x] += integralImg[y-1][x]; } } } for( int y = 0 ; y < h ; y++){ const int minRow = max(0, y-k), maxRow = min(h-1, y+k); for( int x = 0 ; x < w ;x++){ const int minCol = max(0, x-k), maxCol = min(w-1, x+k); outputImg[y][x] = integralImg[maxRow][maxCol]; if( minRow > 0 ){ outputImg[y][x] -= integralImg[minRow-1][maxCol]; } if( minCol > 0 ){ outputImg[y][x] -= integralImg[maxRow][minCol-1]; } if( (minRow > 0) && (minCol > 0) ){ outputImg[y][x] += integralImg[minRow-1][minCol-1]; } } } return outputImg; } vector> solve2(vector>& mat, int k) { const int h = mat.size(), w = mat[0].size(); vector> outputImg(h, vector(w, 0)); for (int y = 0; y < h; y++) { const int minRow = max(0, y - k), maxRow = min(h - 1, y + k); for (int x = 0; x < w; x++) { const int minCol = max(0, x - k), maxCol = min(w - 1, x + k); long long s = 0; for (int r = minRow; r <= maxRow; r++) { for (int c = minCol; c <= maxCol; c++) { s += mat[r][c]; } } outputImg[y][x] = (int)s; } } return outputImg; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,k; cin>>n>>m>>k; vector > s; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s,k); // output // for(auto it:result) cout<& rowSum, vector& colSum,vector >& ans) { } }; ``` Example 1: Input: rowSum = [3,8], colSum = [4,7] Output: [[3,0],[1,7]] Example 2: Input: rowSum = [5,7,10], colSum = [8,6,8] Output: [[0,5,0],[6,1,0],[2,0,8]] Constraints: 1 <= rowSum.length * colSum.length <= @data 0 <= rowSum[i], colSum[i] <= 10^8 sum(rowSum) == sum(colSum) Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: void solve1(vector& rowSum, vector& colSum,vector >& ans) { int N = rowSum.size(); int M = colSum.size(); int i = 0, j = 0; while (i < N && j < M) { ans[i][j] = min(rowSum[i], colSum[j]); rowSum[i] -= ans[i][j]; colSum[j] -= ans[i][j]; rowSum[i] == 0 ? i++ : j++; } } void solve2(vector& rowSum, vector& colSum, vector >& ans) { int n = (int)rowSum.size(); int m = (int)colSum.size(); for (int i = 0; i < n; ++i) { for (int j = 0; j < m && rowSum[i] > 0; ++j) { int put = rowSum[i] < colSum[j] ? rowSum[i] : colSum[j]; if (put > 0) { ans[i][j] = put; rowSum[i] -= put; colSum[j] -= put; } } } } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector< int > a,b; vector > ans; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) temp.push_back(0); ans.push_back(temp); } for(int i=1,x;i<=n;i++) { cin>>x; a.push_back(x); } for(int i=1,x;i<=m;i++) { cin>>x; b.push_back(x); } vector< int > x,y; x=a; y=b; // solve Solution solution; solution.solve(a,b,ans); // for(auto it:ans) // { // for(auto x:it) cout< &ind, string &c, string &res) { // write your code here } }; ``` where: - return: the lexicographically smallest string s that can be obtained by rearranging the indices in the array ind and the letters in the string c as you like. The result should be stored in the variable res. # Example 1: - Input: n = 1, m = 2 s = ""a"" ind = [1, 1] c = ""cb"" - Output: b # Constraints: - $1 \leq n, m \leq @data$ - $s, c$ consists of lowercase Latin letters - $1 \leq ind[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: void solve1(int &n, int &m, string &s, vector &ind, string &c, string &res) { sort(ind.begin(), ind.end()); sort(c.begin(), c.end()); int last = 0, cnt = 0; for (int i = 0; i < m; i++) { if (ind[i] != last) { s[ind[i] - 1] = c[cnt++]; last = ind[i]; } } res = s; } void solve2(int &n, int &m, string &s, vector &ind, string &c, string &res) { const int REM = INT_MAX; const char USED = '{'; while (true) { int minIdx = REM; for (int i = 0; i < m; i++) { if (ind[i] < minIdx) minIdx = ind[i]; } if (minIdx == REM) break; char minChar = USED; int posChar = -1; for (int i = 0; i < m; i++) { if (c[i] < minChar) { minChar = c[i]; posChar = i; } } if (posChar != -1) { s[minIdx - 1] = minChar; c[posChar] = USED; } for (int i = 0; i < m; i++) { if (ind[i] == minIdx) ind[i] = REM; } } res = s; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; string s; cin >> s; vector ind(m); for (int i = 0; i < m; i++) { cin >> ind[i]; } string c; cin >> c; // solve Solution solution; string result; solution.solve(n, m, s, ind, c, result); // output cout << result << ""\n""; return 0; }","data_structures,greedy,sort",hard 281,"# Problem Statement Amidst skyscrapers in the bustling metropolis of Metro Manila, the newest Noiph mall in the Philippines has just been completed! The construction manager, Penchick, ordered a state-of-the-art monument to be built with $n$ pillars. The heights of the monument's pillars can be represented as an array $h$ of $n$ positive integers, where $h_i$ represents the height of the $i$-th pillar for all $i$ between $1$ and $n$. Penchick wants the heights of the pillars to be in **non-decreasing** order, i.e. $h_i \le h_{i + 1}$ for all $i$ between $1$ and $n - 1$. However, due to confusion, the monument was built such that the heights of the pillars are in **non-increasing** order instead, i.e. $h_i \ge h_{i + 1}$ for all $i$ between $1$ and $n - 1$. Luckily, Penchick can modify the monument and do the following operation on the pillars as many times as necessary: - Modify the height of a pillar to any positive integer. Formally, choose an index $1\le i\le n$ and a positive integer $x$. Then, assign $h_i := x$. Help Penchick determine the minimum number of operations needed to make the heights of the monument's pillars **non-decreasing**. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &h) { // write your code here } }; ``` where: - return a single integer representing the minimum number of operations needed to make the heights of the pillars non-decreasing. # Example 1: - Input: n = 5 a = [5, 3, 2, 4, 1] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq h[i] \leq n$ - $h[i] \geq h[i + 1]$ for all $i$ between $1$ and $n - 1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &h) { int ans = n; int l = -1; int c = 0; for (int i = 0; i < n; i++) { if (h[i] == l) c++; else c = 1; l = h[i]; ans = min(ans, n - c); } return ans; } int solve2(int &n, vector &h) { int best = 0; for (int i = 0; i < n; i++) { int cnt = 0; int v = h[i]; for (int j = 0; j < n; j++) { if (h[j] == v) cnt++; } if (cnt > best) best = cnt; } return n - best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,greedy,math",hard 282,"You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val. Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points. solution main function ```cpp class Solution { public: int solve(vector>& points) { // write your code here } }; ``` Example 1: Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] Output: 20 Example 2: Input: points = [[3,12],[-2,5],[-4,1]] Output: 18 Constraints: 1 <= points.length <= @data -10^6 <= xi, yi <= 10^6 All pairs (xi, yi) are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& points) { int n = points.size(); vector visited(n, false); vector minDist(n, INT_MAX); minDist[0] = 0; int result = 0; for (int i = 0; i < n; ++i) { int minCost = INT_MAX; int currentNode = -1; for (int j = 0; j < n; ++j) { if (!visited[j] && minDist[j] < minCost) { minCost = minDist[j]; currentNode = j; } } visited[currentNode] = true; result += minCost; for (int j = 0; j < n; ++j) { if (!visited[j]) { int dist = abs(points[currentNode][0] - points[j][0]) + abs(points[currentNode][1] - points[j][1]); minDist[j] = min(minDist[j], dist); } } } return result; } int solve2(vector>& points) { int n = points.size(); if (n <= 1) return 0; long long result = 0; int k = 1; while (k < n) { int bestIdx = -1; int bestCost = INT_MAX; for (int j = k; j < n; ++j) { int minToSet = INT_MAX; for (int i = 0; i < k; ++i) { long long dx = (long long)points[i][0] - points[j][0]; if (dx < 0) dx = -dx; long long dy = (long long)points[i][1] - points[j][1]; if (dy < 0) dy = -dy; long long dist = dx + dy; if (dist < minToSet) minToSet = (int)dist; } if (minToSet < bestCost) { bestCost = minToSet; bestIdx = j; } } result += bestCost; if (bestIdx != k) { swap(points[k], points[bestIdx]); } ++k; } return (int)result; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector > g; for(int i=1;i<=n;i++) { vector temp; int x,y; cin>>x>>y; temp.push_back(x); temp.push_back(y); g.push_back(temp); } // solve Solution solution; auto result = solution.solve(g); // output cout< using namespace std; class Solution { public: int solve1(int &p1, int &p2, int &p3) { int s = p1 + p2 + p3, m = max({p1, p2, p3}); if (s % 2) { return -1; } else { return min(s - m, s / 2); } } int solve2(int &p1, int &p2, int &p3) { long long s = (long long)p1 + p2 + p3; if (s & 1LL) return -1; long long maxD = min(s / 2, (long long)p1 + p2); for (long long D = maxD; D >= 0; --D) { long long U1 = min((long long)p1, D); long long U2 = min((long long)p2, D); long long U3 = min((long long)p3, D); long long L1 = (long long)(p1 & 1); long long L2 = (long long)(p2 & 1); long long L3 = (long long)(p3 & 1); if (U1 < L1 || U2 < L2 || U3 < L3) continue; long long U1p = U1 - ((U1 ^ (long long)p1) & 1LL); long long U2p = U2 - ((U2 ^ (long long)p2) & 1LL); long long U3p = U3 - ((U3 ^ (long long)p3) & 1LL); long long Smin = L1 + L2 + L3; long long Smax = U1p + U2p + U3p; long long need = 2 * D; if (Smin <= need && need <= Smax) { return (int)D; } } return -1; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int p1, p2, p3; cin >> p1 >> p2 >> p3; // solve Solution solution; auto result = solution.solve(p1, p2, p3); // output cout << result << ""\n""; return 0; }","math,dp",medium 284,"Given two integers, num and t. A number x is achievable if it can become equal to num after applying the following operation at most t times: Increase or decrease x by 1, and simultaneously increase or decrease num by 1. Return the maximum possible value of x. solution main function ```cpp class Solution { public: int solve(int num, int t) { } }; ``` Example 1: Input: num = 4, t = 1 Output: 6 Example 2: Input: num = 3, t = 2 Output: 7 Constraints: 1 <= num, t <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int num, int t) { return num+t*2; } int solve2(int num, int t) { long long candidate = (long long)num + 2LL * (long long)t; long long diff = candidate - (long long)num; if ((diff & 1LL) != 0) candidate--; long long bound = 2LL * (long long)t; if (llabs(candidate - (long long)num) > bound) { candidate = (candidate > num) ? (long long)num + bound : (long long)num - bound; } long long d = llabs(candidate - (long long)num); if ((d & 1LL) || (d / 2LL > (long long)t)) { long long c = candidate; while (true) { c--; long long dd = llabs(c - (long long)num); if (((dd & 1LL) == 0) && (dd / 2LL <= (long long)t)) { candidate = c; break; } } } if (candidate > INT_MAX) return INT_MAX; if (candidate < INT_MIN) return INT_MIN; return (int)candidate; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int x,y; cin>>x>>y; // solve Solution solution; auto result = solution.solve(x,y); // output // for(auto it:result) cout< using namespace std; class Solution { public: int solve1(int &n, int &m, int &k, string &s) { int cnt = 0, ans = 0; int r = 0; for (int l = 1; l <= n; l++) { if (s[l - 1] == '1') cnt = 0; else { if (s[l - 1] == '0' && l > r) cnt++; if (cnt == m) { ans++; cnt = 0; r = l + k - 1; } } } return ans; } int solve2(int &n, int &m, int &k, string &s) { int ans = 0; int zero_cnt = 0; int i = 0; while (i < n) { if (s[i] == '1') { zero_cnt = 0; ++i; } else { ++zero_cnt; if (zero_cnt == m) { ++ans; int end = i + k - 1; if (end >= n) end = n - 1; for (int j = i; j <= end; ++j) s[j] = '1'; zero_cnt = 0; i = end + 1; } else { ++i; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m, k; cin >> n >> m >> k; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, m, k, s); // output cout << result << ""\n""; return 0; }","two_pointers,data_structures",medium 286,"# Problem Statement Jonathan is fighting against DIO's Vampire minions. There are $n$ of them with strengths $a_1, a_2, \dots, a_n$. Denote $(l, r)$ as the group consisting of the vampires with indices from $l$ to $r$. Jonathan realizes that the strength of any such group is in its weakest link, that is, the bitwise AND. More formally, the strength level of the group $(l, r)$ is defined as $$ f(l,r) = a_l \and a_{l+1} \and a_{l+2} \and \ldots \and a_r. $$ Here, $\and$ denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Because Jonathan would like to defeat the vampire minions fast, he will divide the vampires into contiguous groups, such that each vampire is in **exactly** one group, and the **sum** of strengths of the groups is **minimized**. Among all ways to divide the vampires, he would like to find the way with the **maximum** number of groups. Given the strengths of each of the $n$ vampires, find the **maximum number** of groups among all possible ways to divide the vampires with the smallest sum of strengths. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the maximum number of groups among all possible ways to divide the vampires with the smallest sum of strengths. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int all = ~0; for (int i = 0; i < n; i++) all &= a[i]; if (all != 0) { return 1; } int ans = 0; int res = ~0; for (int i = 0; i < n; i++) { res &= a[i]; if (res == 0) { ans++; res = ~0; } } return ans; } int solve2(int &n, vector &a) { if (n <= 1) return n; bool tooBig = false; unsigned long long total = 1ULL; for (int i = 1; i <= n - 1; i++) { if (i < 64) total <<= 1; else { tooBig = true; break; } } if (tooBig) { int all = ~0; for (int i = 0; i < n; i++) all &= a[i]; if (all != 0) return 1; int ans = 0; int res = ~0; for (int i = 0; i < n; i++) { res &= a[i]; if (res == 0) { ans++; res = ~0; } } return ans; } long long bestSum = LLONG_MAX; int bestGroups = 0; for (unsigned long long mask = 0; mask < total; ++mask) { long long sum = 0; int groups = 0; int cur = ~0; for (int i = 0; i < n; i++) { cur &= a[i]; bool cut = (i == n - 1) || (((mask >> i) & 1ULL) != 0); if (cut) { sum += (long long)cur; groups++; cur = ~0; } } if (sum < bestSum) { bestSum = sum; bestGroups = groups; } else if (sum == bestSum && groups > bestGroups) { bestGroups = groups; } } return bestGroups; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","bit_manipulation,two_pointers,greedy",hard 287,"# Problem Statement You are given an array $a$ of $n$ non-negative integers and an integer $x$. You can do the following two-step operation any (possibly zero) number of times: 1. Choose an index $i$ ($1 \leq i \leq n$). 2. Increase $a_i$ by $x$, in other words $a_i := a_i + x$. Find the maximum value of the $\operatorname{MEX}$ of $a$ if you perform the operations optimally. The $\operatorname{MEX}$ (minimum excluded value) of an array is the smallest non-negative integer that is not in the array. For example: - The $\operatorname{MEX}$ of $[2,2,1]$ is $0$ because $0$ is not in the array. - The $\operatorname{MEX}$ of $[3,1,0,1]$ is $2$ because $0$ and $1$ are in the array but $2$ is not. - The $\operatorname{MEX}$ of $[0,3,1,2]$ is $4$ because $0$, $1$, $2$ and $3$ are in the array but $4$ is not. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &x, vector &a) { // write your code here } }; ``` where: - return: the maximum value of the $\operatorname{MEX}$ of $a$ if you perform the operations optimally. # Example 1: - Input: n = 6, x = 3, a = [0, 3, 2, 1, 5, 2] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq x \leq 10^6$ - $0 \leq a[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &x, vector &a) { vector cnt(n + 1, 0); for (int i = 0; i < n; i++) if (a[i] <= n) cnt[a[i]]++; for (int i = 0; i <= n; i++) { if (cnt[i] == 0) return i; if (i + x <= n) cnt[i + x] += cnt[i] - 1; } } int solve2(int &n, int &x, vector &a) { for (int i = 0; i <= n; i++) { bool flag = false; for (int j = 0; j < n; j++) { if (a[j] < i) a[j] += (i - a[j] + x - 1) / x * x; if (a[j] == i) { flag = true, a[j] = 1E9; break; } } if (flag == false) return i; } } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, x; cin >> n >> x; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, x, a); // output cout << result << ""\n""; return 0; }",math,medium 288,"# Problem Statement You are given a game with $n$ piles of stones. A configuration is valid if each pile has an integer number of stones between $1$ and $m$ (inclusive). Some indices from $1$ to $n$ are marked as good (it is guaranteed that index $1$ is always good). Alice and Bob alternately take turns for $n-1$ turns with Alice going first. In each turn: - Choose an integer $i$ such that $1 \le i \le p$ (where $p$ is the number of piles left) and $i$ is good, then remove the $i$-th pile completely. After removal, the piles are re-indexed from $1$ to $p-1$. The game ends when only one pile remains. Let $x$ be the number of stones in the final remaining pile. Alice wants to maximize $x$, while Bob wants to minimize it. Both play optimally. Compute the sum of $x$ over all valid configurations modulo $10^9+7$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, int &m, int &k, vector &good) { // write your code here } }; ``` where: - `n`: number of piles - `m`: upper bound on stones per pile - `k`: number of good indices - `good`: strictly increasing array of size `k`, `good[0] = 1`, and `1 = c1 < c2 < ... < ck ≤ n` - return: the sum of $x$ over all valid configurations modulo $10^9+7$ # Example: - Input: n = 2, m = 3 k = 1 good = [1] - Output: 18 # Constraints: - $1 \le n \le 20$ - $1 \le m \le @data$ - $1 \le k \le n$, and good indices satisfy $1=c_1 using namespace std; class Solution { public: long long solve1(int &n, int &m, int &k, vector &good) { const int MOD = 1000000007; int goodMask = 0; for (int idx : good) { if (idx >= 1 && idx <= n) { goodMask |= (1 << (idx - 1)); } } vector> dpPrev(1 << 1); dpPrev[0][0] = 0; dpPrev[0][1] = 0; dpPrev[1][0] = 1; dpPrev[1][1] = 1; for (int len = 2; len <= n; ++len) { const int stateCount = 1 << len; vector> dpCurr(stateCount); const int goodMaskLen = goodMask & ((1 << len) - 1); for (int mask = 0; mask < stateCount; ++mask) { bool aliceRes = false; bool bobRes = true; for (int pos = 0; pos < len; ++pos) { if ((goodMaskLen >> pos) & 1) { int afterMask = ((mask >> (pos + 1)) << pos) | (mask & ((1 << pos) - 1)); aliceRes = aliceRes || (dpPrev[afterMask][1] != 0); bobRes = bobRes && (dpPrev[afterMask][0] != 0); } } dpCurr[mask][0] = static_cast(aliceRes); dpCurr[mask][1] = static_cast(bobRes); } dpPrev.swap(dpCurr); } vector countByOnes(n + 1, 0); const int fullStates = 1 << n; for (int mask = 0; mask < fullStates; ++mask) { if (dpPrev[mask][0]) { countByOnes[__builtin_popcount(static_cast(mask))] += 1; } } auto modPow = [&](long long a, int e) -> long long { long long res = 1 % MOD; long long base = (a % MOD + MOD) % MOD; int exp = e; while (exp > 0) { if (exp & 1) res = (res * base) % MOD; base = (base * base) % MOD; exp >>= 1; } return res; }; long long answer = 0; for (int val = 1; val <= m; ++val) { for (int ones = 0; ones <= n; ++ones) { if (countByOnes[ones] == 0) continue; long long ways = (modPow(val - 1, n - ones) * modPow(m - val + 1, ones)) % MOD; answer = (answer + ways * (countByOnes[ones] % MOD)) % MOD; } } return answer; } long long solve2(int &n, int &m, int &k, vector &good) { const int MOD = 1000000007; int goodMask = 0; for (int idx : good) { if (idx >= 1 && idx <= n) { goodMask |= (1 << (idx - 1)); } } vector prevA(1 << 1), prevB(1 << 1); prevA[0] = 0; prevB[0] = 0; prevA[1] = 1; prevB[1] = 1; for (int len = 2; len <= n; ++len) { const int stateCount = 1 << len; vector currA(stateCount), currB(stateCount); const int goodMaskLen = goodMask & ((1 << len) - 1); for (int mask = 0; mask < stateCount; ++mask) { uint8_t aRes = 0; uint8_t bRes = 1; for (int pos = 0; pos < len; ++pos) { if ((goodMaskLen >> pos) & 1) { int lower = mask & ((1 << pos) - 1); int upper = mask >> (pos + 1); int afterMask = (upper << pos) | lower; aRes = static_cast(aRes | (prevB[afterMask] != 0)); bRes = static_cast(bRes & (prevA[afterMask] != 0)); } } currA[mask] = aRes; currB[mask] = bRes; } prevA.swap(currA); prevB.swap(currB); } vector countByOnes(n + 1, 0); const int fullStates = 1 << n; for (int mask = 0; mask < fullStates; ++mask) { if (prevA[mask]) { countByOnes[__builtin_popcount(static_cast(mask))] += 1; } } auto modPow = [&](long long a, int e) -> long long { long long res = 1 % MOD; long long base = (a % MOD + MOD) % MOD; int exp = e; while (exp > 0) { if (exp & 1) res = (res * base) % MOD; base = (base * base) % MOD; exp >>= 1; } return res; }; long long answer = 0; for (int val = 1; val <= m; ++val) { long long lowPow = modPow(val - 1, n); long long highPowBase = m - val + 1; for (int ones = 0; ones <= n; ++ones) { if (countByOnes[ones] == 0) continue; long long ways = (modPow(highPowBase, ones) * modPow(val - 1, n - ones)) % MOD; answer = (answer + ways * (countByOnes[ones] % MOD)) % MOD; } } return answer; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; int k; cin >> k; vector good(k); for (int i = 0; i < k; i++) cin >> good[i]; // solve Solution solution; auto result = solution.solve(n, m, k, good); // output cout << result << ""\n""; return 0; }",dp,hard 289,"# Problem Statement Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$. Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - `n` is the number of coins - `a` is the array of coin values - return the minimum number of pockets needed # Example 1: - Input: n = 6 a = [1, 2, 4, 3, 3, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int ans = 0, pre = 0, cnt = 0; for (int i = 0; i < n; i++) { if (a[i] == pre) { cnt++; ans = max(ans, cnt); } else { cnt = 1; pre = a[i]; ans = max(ans, cnt); } } return ans; } int solve2(int &n, vector &a) { int ans = 0; for (int i = 0; i < n; i++) { int cnt = 0; int val = a[i]; for (int j = 0; j < n; j++) { if (a[j] == val) { cnt++; } } if (cnt > ans) { ans = cnt; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,sort",medium 290,"Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, ""ace"" is a subsequence of ""abcde"". solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""aabca"" Output: 3 Example 2: Input: s = ""adc"" Output: 0 Constraints: 3 <= s.length <= @data s consists of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { vector first; first.resize(26, -1); vector last; last.resize(26, -1); for (int i = 0; i < s.size(); i++) { int curr = s[i] - 'a'; if (first[curr] == - 1) { first[curr] = i; } last[curr] = i; } int ans = 0; for (int i = 0; i < 26; i++) { if (first[i] == -1) { continue; } unordered_set between; for (int j = first[i] + 1; j < last[i]; j++) { between.insert(s[j]); } ans += between.size(); } return ans; } int solve2(string s) { int n = (int)s.size(); int ans = 0; for (int c = 0; c < 26; c++) { int f = -1; for (int i = 0; i < n; i++) { if (s[i] == char('a' + c)) { f = i; break; } } if (f == -1) continue; int l = -1; for (int i = n - 1; i >= 0; i--) { if (s[i] == char('a' + c)) { l = i; break; } } if (l <= f) continue; unsigned int mask = 0u; for (int i = f + 1; i < l; i++) { mask |= 1u << (unsigned int)(s[i] - 'a'); } int cnt = 0; while (mask) { cnt += (mask & 1u) ? 1 : 0; mask >>= 1; } ans += cnt; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { int curr = 1, prev = 0, ans = 0; for (int i = 1; i < s.length(); i++) if (s[i] == s[i-1]) curr++; else ans += min(curr, prev), prev = curr, curr = 1; return ans + min(curr, prev); } int solve2(string s) { int n = (int)s.size(); int ans = 0; for (int i = 1; i < n; ++i) { if (s[i] != s[i - 1]) { int l = i - 1, r = i; char lc = s[l], rc = s[r]; while (l >= 0 && r < n && s[l] == lc && s[r] == rc) { ++ans; --l; ++r; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout< using namespace std; #include using namespace std; class Solution { public: long long solve1(int k, int n) { long long sum = 0,base = 1; for (int i = 0;i <= 10;i++){ sum += ((n >> i) & 1) * base; base *= k; } return sum; } long long solve2(int k, int n) { if (k == 1) return n; long long sum = 0, base = 1; while (n > 0) { if (n & 1) sum += base; n >>= 1; if (n == 0) break; base *= (long long)k; } return sum; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int k,N; cin >> k >> N; // solve Solution solution; auto result = solution.solve(k,N); // output cout << result << ""\n""; return 0; }",math,hard 293,"You are given two identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 2 Output: 2 Example 2: Input: n = 100 Output: 14 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { int tmp = sqrt(2*n); if(tmp * (tmp + 1) >= 2 * n){return tmp;} return tmp + 1; } int solve2(int n) { long long sum = 0; int k = 0; while (sum < n) { ++k; sum += k; } return k; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout<>& relation, int k) { // write your code here } }; ``` Example 1: Input: n = 5, base = [[0, 2], [2, 1], [3, 4], [2, 3], [1, 4], [2, 0], [0, 4]], k = 3 Output: 3 Example 2: Input: n = 3, relation = [[0,2],[2,1]], k = 2 Output: 0 Constraints: 2 <= n <= @data 1 <= k <= @data 1 <= relation.length <= 10*@data, and relation[i].length == 2 0 <= relation[i][0],relation[i][1] < n and relation[i][0]! = relation[i][1] Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: const long long mod=998244353; int solve(int n, vector>& relation, int k) { vector dp(n); dp[0] = 1; for (int i = 0; i < k; i++) { vector nxt(n); for (auto& edge : relation) { int src = edge[0], dst = edge[1]; nxt[dst] = (nxt[dst]+dp[src])%mod; } dp = nxt; } return dp[n - 1]; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,k; cin>>n>>m; vector< vector > relation; for(int i=1,x,y;i<=m;i++) { cin>>x>>y; vector temp; temp.push_back(x); temp.push_back(y); relation.push_back(temp); } cin>>k; // solve Solution solution; auto result = solution.solve(n,relation,k); // output cout << result << ""\n""; return 0; }","dp,graph",hard 295,"The middle order and post order of a binary tree are given. Find its preordering. (Convention tree nodes are represented by different capital letters). solution main function ```cpp class Solution { public: string solve(string mid,string suf) { // write your code here } }; ``` Pass in parameters: Two strings of uppercase letters representing the middle and back order of a binary tree Return parameters: A string representing the first order of a binary tree. Example 1: Input: mid=""BADC"",suf=""BDCA"" Output: ""ABCD"" Constraints: The string length is less than or equal to @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[3, 5, 8]",1000,"[[64, 64, 64], [64, 64, 64], [256, 128, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: string solve(string mid, string suf) { if (mid.size() == 0) return """"; char ch = suf[suf.size() - 1]; int k = mid.find(ch); return string(1, ch) + solve(mid.substr(0, k), suf.substr(0, k)) + solve(mid.substr(k + 1), suf.substr(k, mid.size() - k - 1)); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string mid,suf;cin>>mid>>suf; // solve Solution solution; auto result = solution.solve(mid,suf); // output cout << result << ""\n""; return 0; }",tree,easy 296,"Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. solution main function ```cpp class Solution { public: int solve(vector>& grid) { } }; ``` Example 1: Input: grid = [[1,2,3],[4,5,6],[7,8,9]] Output: 13 Example 2: Input: grid = [[7]] Output: 7 Constraints: n == grid.length == grid[i].length 1 <= n <= @data -99 <= grid[i][j] <= 99 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& grid) { int N = grid.size(); int prev_min1 = -1, prev_min2 = -1; for (int r = N - 1; r >= 0; --r) { int cur_min1 = -1, cur_min2 = -1; for (int c = 0; c < N; ++c) { if (r < N - 1) grid[r][c] += prev_min1 == c ? grid[r + 1][prev_min2] : grid[r + 1][prev_min1]; if (cur_min1 == -1 || grid[r][c] < grid[r][cur_min1]) { cur_min2 = cur_min1; cur_min1 = c; } else if (cur_min2 == -1 || grid[r][c] < grid[r][cur_min2]) cur_min2 = c; } prev_min1 = cur_min1; prev_min2 = cur_min2; } return grid[0][prev_min1]; } int solve2(vector>& grid) { int n = grid.size(); if (n == 0) return 0; for (int r = 1; r < n; ++r) { for (int c = 0; c < n; ++c) { int best = INT_MAX; for (int k = 0; k < n; ++k) { if (k == c) continue; if (grid[r - 1][k] < best) best = grid[r - 1][k]; } long long val = (long long)grid[r][c] + (long long)best; if (val > INT_MAX) grid[r][c] = INT_MAX; else if (val < INT_MIN) grid[r][c] = INT_MIN; else grid[r][c] = (int)val; } } int ans = grid[n - 1][0]; for (int c = 1; c < n; ++c) { if (grid[n - 1][c] < ans) ans = grid[n - 1][c]; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector > num; for(int i=1;i<=n;i++) { vector temp; for(int i=1;i<=n;i++) { int x; cin>>x; temp.push_back(x); } num.push_back(temp); } // solve Solution solution; auto result = solution.solve(num); // output cout< &a) { // write your code here } }; ``` Where: - `n` is an integer representing the number of boxes. - `s` is a string, where $s[i] = 1$ if the $i$-th box is covered with a lid, and $s[i] = 0$ otherwise. - `a` is an integer array, where $a[i]$ is the number of magazines in the $i$-th box. - The function should return an integer, representing the maximum number of magazines Monocarp can save from the rain. # Example 1 - Input: n = 4 s = ""0111"" a = [5, 4, 5, 1] - Output: 14 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, string &s, vector &a) { for (int i = 0, j = -1; i < n; i++) { if (s[i] == '0') j = i; else if (j >= 0 && a[i] < a[j]) { swap(s[i], s[j]); j = i; } } int ans = 0; for (int i = 0; i < n; i++) if (s[i] == '1') ans += a[i]; return ans; } int solve2(int &n, string &s, vector &a) { long long ans = 0; for (int i = 0; i < n; i++) if (s[i] == '1') ans += a[i]; for (int i = 0; i < n; i++) { if (s[i] == '0') { int j = i + 1; if (j < n && s[j] == '1') { int minv = INT_MAX; while (j < n && s[j] == '1') { if (a[j] < minv) minv = a[j]; j++; } int delta = a[i] - minv; if (delta > 0) ans += delta; i = j - 1; } } } if (ans > INT_MAX) return INT_MAX; if (ans < INT_MIN) return INT_MIN; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, s, a); // output cout << result << ""\n""; return 0; }","dp,greedy",hard 298,"# Problem Statement An array `b` is called good if there do not exist indices `1 ≤ i < j ≤ |b|` such that `b_j - b_i = 1`. You are given an integer array `a` of length `n`. Determine the minimum number of elements that need to be removed from `a` so that it becomes a good array. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: the length of the array - `a`: the array of integers - return: the minimum number of elements to remove so that the array is good # Example 1: - Input: ``` n = 5 a = [1, 2, 3, 4, 5] ``` - Output: ``` 2 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 10000, 100000]",1000,"[[200, 150, 75], [1600, 1200, 600], [12800, 9600, 4800]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, vector &a) { for (int i = 0; i < n; i++) a[i]--; vector> at(n); for (int i = 0; i < n; i++) at[a[i]].push_back(i); int ans = 0; for (int v = 0; v + 1 < n; v++) { int mx = (int)min(at[v].size(), at[v + 1].size()); int low = 0, high = mx + 1; while (low + 1 < high) { int mid = (low + high) >> 1; bool ok = true; for (int j = 0; j < mid; j++) { if (at[v][j] > at[v + 1][(int)at[v + 1].size() - mid + j]) { ok = false; break; } } if (ok) low = mid; else high = mid; } ans += low; at[v + 1].resize((int)at[v + 1].size() - low); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,data_structures",hard 299,"Given an array of integers arr, compute the sum of the sums of all contiguous subarrays of odd length. Return the result modulo 998244353. solution main function ```cpp class Solution { public: int solve(vector& arr) { } }; ``` Example 1: Input: arr = [1,4,2,5,3] Output: 58 Example 2: Input: arr = [1,2] Output: 3 Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: #define ll long long const ll mod= 998244353; int solve1(vector& arr) { int n = int(arr.size()); ll answer = 0; for (int i = 0; i < n; ++i) { ll left = i, right = n - i - 1; answer += arr[i] * (left / 2ll + 1ll)%mod * (right / 2ll + 1ll)%mod; answer%=mod; answer += arr[i] * ((left + 1ll) / 2ll)%mod * ((right + 1ll) / 2ll)%mod; answer%=mod; } return answer; } int solve2(vector& arr) { int n = (int)arr.size(); ll ans = 0; for (int i = 0; i < n; ++i) { ll sum = 0; for (int j = i; j < n; ++j) { sum += arr[j]; if (((j - i + 1) & 1) != 0) { ans += (sum % mod); if (ans >= mod) ans %= mod; } } } return (int)(ans % mod); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; vector num; cin>>n; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout<> &b) { // write your code here } }; ``` where: - `n`: the number of shelves, `k`: the number of bottles - `bottle`: the brand index $b_i$ and cost $c_i$ of each bottle - return: the maximum amount he can earn # Example 1: - Input: n = 3, k = 3 bottle = [(2, 6), (2, 7), (1, 15)] - Output: 28 # Constraints: - $1 \leq n, k \leq @data$ - $1 \leq bottle[i].first \leq k$ - $1 \leq bottle[i].second \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 400, 80], [6400, 3200, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &k, vector> &bottle) { n = min(n, k); vector s(k); for (int i = 0; i < k; i++) { int b = bottle[i].first; int c = bottle[i].second; b--; s[b] += c; } sort(s.begin(), s.end(), greater()); int ans = accumulate(s.begin(), s.begin() + n, 0); return ans; } int solve2(int &n, int &k, vector> &bottle) { n = min(n, k); if (k <= 0 || n <= 0) return 0; sort(bottle.begin(), bottle.end(), [](const pair &x, const pair &y) { return x.first < y.first; }); long long ans = 0; for (int t = 0; t < n; ++t) { long long bestSum = 0; int bestL = -1, bestR = -1; int i = 0; while (i < k) { int j = i; int brand = bottle[i].first; long long sum = 0; while (j < k && bottle[j].first == brand) { sum += bottle[j].second; ++j; } if (sum > bestSum) { bestSum = sum; bestL = i; bestR = j; } i = j; } ans += bestSum; if (bestSum == 0) break; for (int p = bestL; p < bestR; ++p) bottle[p].second = 0; } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector> bottle(k); for (int i = 0; i < k; i++) cin >> bottle[i].first >> bottle[i].second; // solve Solution solution; auto result = solution.solve(n, k, bottle); // output cout << result << ""\n""; return 0; }","greedy,sort",easy 301,"There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes. Return the maximum number of nodes you can reach from node 0 without visiting a restricted node. Note that node 0 will not be a restricted node. solution main function ```cpp class Solution { public: int solve(int n, vector>& edges, vector& restricted) { // write your code here } }; ``` Example 1: Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5] Output: 4 Example 2: Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1] Output: 3 Constraints: 2 <= n <= @data edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree. 1 <= restricted.length < n 1 <= restricted[i] < n All the values of restricted are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[2343, 234, 64], [18750, 1875, 187], [150000, 15000, 1500]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { bool markNode(vector>& edges, int x) { bool changed = false; for (auto &e : edges) { if (e[0] == x) { e[0] = -2; changed = true; } if (e[1] == x) { e[1] = -2; changed = true; } } return changed; } vector p,sz; vector r; public: int find(int x) { if (p[x] != x) p[x] = find(p[x]); return p[x]; } void unionSet(int a, int b) { a = find(a), b = find(b); if (a != b) { if (sz[a] > sz[b]) swap(a, b); p[a] = b, sz[b] += sz[a]; } } int solve1(int n, vector>& edges, vector& restricted) { for (int i = 0; i <= n; i ++ ) p.push_back(i),sz.push_back(1),r.push_back(false); for (auto &x : restricted) r[x] = true; for (auto &e : edges) if (!r[e[1]] && !r[e[0]]) unionSet(e[0], e[1]); return sz[find(0)]; } int solve2(int n, vector>& edges, vector& restricted) { for (int r : restricted) { for (auto &e : edges) { if (e[0] == r) e[0] = -1; if (e[1] == r) e[1] = -1; } } int cnt = 1; markNode(edges, 0); bool changed; do { changed = false; for (auto &e : edges) { if (e[0] == -2 && e[1] >= 0) { if (markNode(edges, e[1])) { cnt++; changed = true; } } if (e[1] == -2 && e[0] >= 0) { if (markNode(edges, e[0])) { cnt++; changed = true; } } } } while (changed); return cnt; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > e; vector re; for(int i=1;i>x>>y; vector temp; temp.push_back(x); temp.push_back(y); e.push_back(temp); } for(int i=1;i<=m;i++) { int x; cin>>x; re.push_back(x); } // solve Solution solution; auto result = solution.solve(n,e,re); // output cout< solve(int &k, int &q, vector &a, vector &n) { // write your code here } }; ``` where: - `k` represents the length of `a`, `q` represents the length of `n` - `a` represents the increasing sequence of integers, `n` represents the number of players - return the array of the number of winners for each `n`, and the length is `q` # Example 1: - Input: k = 2, q = 1 a = [3, 5] n = [5] - Output: [2] # Constraints: - $1 \leq k, q \leq @data$ - $1 \leq a[i], n[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",1000,"[[100, 64, 64], [800, 160, 80], [6400, 1280, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve(int &k, int &q, vector &a, vector &n) { int p = a[0]; vector ans(q); for (int i = 0; i < q; i++) ans[i] = min(p - 1, n[i]); return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int k, q; cin >> k >> q; vector a(k), n(q); for (int i = 0; i < k; i++) cin >> a[i]; for (int i = 0; i < q; i++) cin >> n[i]; // solve Solution solution; auto result = solution.solve(k, q, a, n); // output for (auto &x : result) cout << x << "" ""; cout << ""\n""; return 0; }","greedy,data_structures,binary",hard 303,"You are given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 13 Output: 4 Example 2: Input: n = 2 Output: 2 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { int cnt = 0; vector v(40, 0); for(int i=1;i<=n;i++){ int x = i; int sum = 0; while(x){ sum += x%10; x/=10; } v[sum]++; } int maxi = *max_element(v.begin(), v.end()); for(auto i : v){ if (i == maxi) cnt++; } return cnt; } int solve2(int n) { int d = 0; int t = n; while (t) { d++; t /= 10; } int maxSum = 9 * d; int maxi = 0; for (int s = 1; s <= maxSum; ++s) { int cnt = 0; for (long long i = 1; i <= n; ++i) { int x = (int)i; int sum = 0; while (x) { sum += x % 10; x /= 10; } if (sum == s) cnt++; } if (cnt > maxi) maxi = cnt; } int ans = 0; for (int s = 1; s <= maxSum; ++s) { int cnt = 0; for (long long i = 1; i <= n; ++i) { int x = (int)i; int sum = 0; while (x) { sum += x % 10; x /= 10; } if (sum == s) cnt++; } if (cnt == maxi) ans++; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n;cin>>n; // solve Solution solution; auto result = solution.solve(n); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int n, int k) { int res = 0; for (; n > 0; n /= k) res += n % k; return res; } int solve2(int n, int k) { long long nn = n; int res = 0; while (nn > 0) { long long q = nn / k; int r = (int)(nn - q * k); res += r; nn = q; } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m;cin>>n>>m; // solve Solution solution; auto result = solution.solve(n,m); // output // for(auto it:result) cout< solve(int &n, int &q, vector &a, vector> &queries) { // write your code here } }; ``` Where: - `n` is an integer representing the size of the array $a$. - `q` is an integer representing the number of queries. - `a` is a vector of integers, representing the initial array. - `queries` is a vector of pairs, where each pair represents a query of the given type and value. - The function should return a vector of long long integers, representing the sum of the array after processing each query. # Example 1: - Input: n = 1 q = 1 a = [1] queries = [(1, 1)] - Output: [2] # Constraints: - $1 \leq n, q \leq @data$ - $1 \leq a[i] \leq 10^9$ - $1 \leq x_j \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 400, 160], [6400, 3200, 1280]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &n, int &q, vector &a, vector> &queries) { int cnt[2]{}; long long sum[2]{}; for (int i = 0; i < n; i++) { int x = a[i]; cnt[x % 2]++; sum[x % 2] += x; } vector ans; for (int i = 0; i < q; i++) { int t = queries[i].first; int x = queries[i].second; sum[t] += 1LL * x * cnt[t]; if (x % 2) { cnt[!t] += cnt[t]; sum[!t] += sum[t]; cnt[t] = sum[t] = 0; } ans.push_back(sum[0] + sum[1]); } return ans; } vector solve2(int &n, int &q, vector &a, vector> &queries) { vector ans; ans.reserve(q); for (int i = 0; i < q; i++) { int t = queries[i].first; int x = queries[i].second; long long s = 0; if (t == 0) { for (int j = 0; j < n; j++) { if ((a[j] & 1) == 0) a[j] += x; s += a[j]; } } else { for (int j = 0; j < n; j++) { if ((a[j] & 1) == 1) a[j] += x; s += a[j]; } } ans.push_back(s); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, q; cin >> n >> q; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector> queries(q); for (int i = 0; i < q; i++) cin >> queries[i].first >> queries[i].second; // solve Solution solution; auto result = solution.solve(n, q, a, queries); // output for (auto &x : result) cout << x << ""\n""; return 0; }",math,medium 306,"You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1. A subarray is a contiguous part of an array. solution main function ```cpp class Solution { public: int solve(vector& nums, int k) { } }; ``` Example 1: Input: nums = [0,1,0], k = 1 Output: 2 Example 2: Input: nums = [1,1,0], k = 2 Output: -1 Constraints: 1 <= nums.length <= @data 1 <= k <= nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums, int k) { int ans = 0; int n = nums.size(); int cnt = 0; for(int i=0;i=k&&nums[i-k]>1) { cnt^=1; nums[i-k]-=2; } if(nums[i]==cnt) { if(i+k>n) return -1; cnt^=1; nums[i]+=2; ans++; } } return ans; } int solve2(vector& nums, int k) { int n = (int)nums.size(); int ans = 0; for(int i = 0; i + k <= n; ++i) { if((nums[i] & 1) == 0) { ++ans; for(int j = 0; j < k; ++j) { nums[i + j] ^= 1; } } } for(int i = n - k + 1; i < n; ++i) { if(i >= 0 && ((nums[i] & 1) == 0)) return -1; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; int result = solution.solve(num,k); // output cout<& prices, int money) { } }; ``` Example: Input: prices = [1,2,2], money = 3 Output: 0 Explanation: Buy chocolates with prices 1 and 2, leaving 0 money. Constraints: 2 <= prices.length <= @data 1 <= prices[i] <= @data 1 <= money <= 2*@data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& prices, int money) { int prices1=INT_MAX,prices2=INT_MAX; for(auto k : prices){ if(k money ? money : money-prices1-prices2; } int solve2(vector& prices, int money) { long long minSum = LLONG_MAX; int n = (int)prices.size(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { long long s = (long long)prices[i] + (long long)prices[j]; if (s < minSum) minSum = s; } } if (minSum > (long long)money) return money; return (int)((long long)money - minSum); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } cin>>k; // solve Solution solution; auto result = solution.solve(s,k); // output cout << result << ""\n""; // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: const long long mod=998244353; int solve(int n) { long long C = 1; vector inv(n+3); inv[0]=inv[1]=1; for(int i=2;i<=n+1;i++) inv[i]=((mod-mod/i)*inv[mod%i])%mod; for (int i = 0; i < n; ++i) { C = C * 2ll%mod * (2ll * i + 1ll)%mod * inv[i+2]%mod; } return (int)C; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< using namespace std; class Solution { public: string solve1(string &s) { int n = s.size(); for (int i = 0; i < n; i++) { int k = i; for (int j = i; j < n && j < i + 10; j++) { if (s[j] - j > s[k] - k) { k = j; } } while (k > i) { s[k]--; swap(s[k - 1], s[k]); k--; } } return s; } string solve2(string &s) { int n = s.size(); for (int i = 1; i < n; i++) { int j = i; while (j > 0 && s[j] > '0' && s[j] - 1 > s[j - 1]) { s[j]--; swap(s[j - 1], s[j]); j--; } } return s; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string s; cin >> s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }","string,greedy,math",hard 310,"# Problem Statement There is a grid, consisting of $2$ rows and $n$ columns. Each cell of the grid is either free or blocked. A free cell $y$ is reachable from a free cell $x$ if at least one of these conditions holds: - $x$ and $y$ share a side; - there exists a free cell $z$ such that $z$ is reachable from $x$ and $y$ is reachable from $z$. A connected region is a set of free cells of the grid such that all cells in it are reachable from one another, but adding any other free cell to the set violates this rule. The given grid contains at most $1$ connected region. Your task is to calculate the number of free cells meeting the following constraint: - if this cell is blocked, the number of connected regions becomes exactly $3$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, string &s1, string &s2) { // write your code here } }; ``` where: - `s1` and `s2` are two strings of two rows of the grid, each character is `.` or `x`, `.` means free, `x` means blocked - return the maximum number of free cells that meet the condition # Example 1: - Input: n = 8 s1 = "".......x"" s2 = "".x.xx..."" - Output: 1 # Constraints: - $1 \leq n \leq @data$ - The given grid contains at most $1$ connected region - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, string &s1, string &s2) { int ans = 0; for (int i = 1; i < n - 1; i++) { if (s1[i] == '.' && s1[i - 1] == '.' && s1[i + 1] == '.' && s2[i] == '.' && s2[i - 1] == 'x' && s2[i + 1] == 'x') ans++; if (s2[i] == '.' && s2[i - 1] == '.' && s2[i + 1] == '.' && s1[i] == '.' && s1[i - 1] == 'x' && s1[i + 1] == 'x') ans++; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s1, s2; cin >> s1 >> s2; // solve Solution solution; auto result = solution.solve(n, s1, s2); // output cout << result << ""\n""; return 0; }",two_pointers,medium 311,"Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [3,10,5,25,2,8] Output: 28 Example 2: Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70] Output: 127 Constraints: 1 <= nums.length <= @data 0 <= nums[i] <= 2^31 - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[200, 64, 64], [1600, 320, 160], [12800, 2560, 1280]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int n=nums.size(),maxv=*max_element(nums.begin(),nums.end()); if(maxv==0) return 0; int high=31-__builtin_clz(maxv); int ans=0,mask=0; unordered_setseen; for(int i=high;i>=0;i--){ seen.clear(); mask|=1<& nums) { int n = (int)nums.size(); int ans = 0; for (int i = 0; i < n; ++i) { int xi = nums[i]; for (int j = i; j < n; ++j) { int v = xi ^ nums[j]; if (v > ans) ans = v; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; int result = solution.solve(num); // output cout< using namespace std; class Solution { public: int solve1(int &n, int &m, int &x1, int &y1, int &x2, int &y2) { int ans = min((x1 != 1) + (x1 != n) + (y1 != 1) + (y1 != m), (x2 != 1) + (x2 != n) + (y2 != 1) + (y2 != m)); return ans; } int solve2(int &n, int &m, int &x1, int &y1, int &x2, int &y2) { int deg1; if (((x1 == 1) || (x1 == n)) && ((y1 == 1) || (y1 == m))) deg1 = 2; else if ((x1 == 1) || (x1 == n) || (y1 == 1) || (y1 == m)) deg1 = 3; else deg1 = 4; int deg2; if (((x2 == 1) || (x2 == n)) && ((y2 == 1) || (y2 == m))) deg2 = 2; else if ((x2 == 1) || (x2 == n) || (y2 == 1) || (y2 == m)) deg2 = 3; else deg2 = 4; return deg1 < deg2 ? deg1 : deg2; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; int x1, x2, y1, y2; cin >> x1 >> y1 >> x2 >> y2; // solve Solution solution; auto result = solution.solve(n, m, x1, y1, x2, y2); // output cout << result << ""\n""; return 0; }",graph,easy 313,"# Problem Statement Pak Chanek has an array $a$ of $n$ positive integers. Since he is currently learning how to calculate the floored average of two numbers, he wants to practice it on his array $a$. While the array $a$ has at least two elements, Pak Chanek will perform the following three-step operation: 1. Pick two different indices $i$ and $j$ ($1 \leq i, j \leq |a|$; $i \neq j$), note that $|a|$ denotes the current size of the array $a$. 2. Append $\lfloor \frac{a_i+a_j}{2} \rfloor$$^{\text{∗}}$ to the end of the array. 3. Remove elements $a_i$ and $a_j$ from the array and concatenate the remaining parts of the array. For example, suppose that $a=[5,4,3,2,1,1]$. If we choose $i=1$ and $j=5$, the resulting array will be $a=[4,3,2,1,3]$. If we choose $i=4$ and $j=3$, the resulting array will be $a=[5,4,1,1,2]$. After all operations, the array will consist of a single element $x$. Find the maximum possible value of $x$ if Pak Chanek performs the operations optimally. $^{\text{∗}}$$\lfloor x \rfloor$ denotes the floor function of $x$, which is the greatest integer that is less than or equal to $x$. For example, $\lfloor 6 \rfloor = 6$, $\lfloor 2.5 \rfloor=2$, $\lfloor -3.6 \rfloor=-4$ and $\lfloor \pi \rfloor=3$ The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return:the maximum possible value of x after all numbers have been picked. # Example 1: - Input: n = 5 a = [1, 7, 8, 4, 5] - Output: 6 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int ans = a[0]; for (int i = 1; i < n; i++) { ans = (ans + a[i]) / 2; } return ans; } int solve2(int &n, vector &a) { while (a.size() >= 2) { int idx1 = -1, idx2 = -1; int m1 = INT_MAX, m2 = INT_MAX; for (size_t i = 0; i < a.size(); ++i) { int v = a[i]; if (v < m1) { m2 = m1; idx2 = idx1; m1 = v; idx1 = (int)i; } else if (v < m2) { m2 = v; idx2 = (int)i; } } int val = (m1 + m2) / 2; if (idx1 > idx2) swap(idx1, idx2); a.erase(a.begin() + idx2); a.erase(a.begin() + idx1); a.push_back(val); } return a.empty() ? 0 : a[0]; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","data_structures,greedy,math,sort",hard 314,"# Problem Statement There is an $n \times m$ grid. Each cell can contain any number of indistinguishable tokens. Initially, there are $k$ tokens, the $i$-th of which is at cell $(x_i, y_i)$ ($1 \le x_i \le n$, $1 \le y_i \le m$). Two players, Mimo and Yuyu, play a game alternately. On a turn, a player chooses a token $c$ currently in the grid and a sequence of distinct cells $(a_1,b_1),(a_2,b_2),\dots,(a_p,b_p)$ ($p \ge 2$) such that: - $c$ is located at $(a_1,b_1)$, - adjacent cells in the sequence are grid-adjacent: $|a_{i+1}-a_i| + |b_{i+1}-b_i| = 1$, - columns are non-increasing: $b_1 \ge b_2 \ge \dots \ge b_p$, - the last cell is in column 1: $b_p = 1$, - and $b_1 > b_2$ (thus $b_2 = b_1 - 1$). Then the player removes $c$ from $(a_1,b_1)$ and adds 1 token to each of $(a_2,b_2),\dots,(a_p,b_p)$. The player who cannot move loses. Mimo moves first. Determine the winner assuming optimal play. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, int &m, int &k, vector &xs, vector &ys) { // write your code here } }; ``` where: - `n`, `m`: grid dimensions, - `k`: number of tokens, - `xs[i]`, `ys[i]`: position of the i-th token, - return: `""Mimo""` if the first player wins, otherwise `""Yuyu""`. # Example 1: - Input: n = 6, m = 4, k = 3 (2,3), (4,2), (6,4) - Output: Mimo # Constraints: - $1 \le n, m, k \le @data$ - $1 \le x_i \le n$, $1 \le y_i \le m$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 128]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, int &m, int &k, vector &xs, vector &ys) { if (k == 0) return ""Yuyu""; if (n == 1) { int parity = 0; for (int i = 0; i < k; i++) { if (ys[i] == 2) parity ^= 1; } return parity ? ""Mimo"" : ""Yuyu""; } vector parity_by_col(m + 1, 0); for (int i = 0; i < k; i++) { int y = ys[i]; if (y > 1) parity_by_col[y] ^= 1; } for (int col = 2; col <= m; col++) { if (parity_by_col[col]) return ""Mimo""; } return ""Yuyu""; } string solve2(int &n, int &m, int &k, vector &xs, vector &ys) { if (k == 0) return ""Yuyu""; if (n == 1) { int parity = 0; for (int i = 0; i < k; i++) { if (ys[i] == 2) parity ^= 1; } return parity ? ""Mimo"" : ""Yuyu""; } int size = k; for (int i = size / 2 - 1; i >= 0; --i) { int idx = i; while (true) { int left = idx * 2 + 1; if (left >= size) break; int largest = left; int right = left + 1; if (right < size && ys[right] > ys[left]) largest = right; if (ys[idx] >= ys[largest]) break; int tmp = ys[idx]; ys[idx] = ys[largest]; ys[largest] = tmp; idx = largest; } } for (int end = size - 1; end >= 1; --end) { int tmp = ys[0]; ys[0] = ys[end]; ys[end] = tmp; int idx = 0; while (true) { int left = idx * 2 + 1; if (left >= end) break; int largest = left; int right = left + 1; if (right < end && ys[right] > ys[left]) largest = right; if (ys[idx] >= ys[largest]) break; int tmp2 = ys[idx]; ys[idx] = ys[largest]; ys[largest] = tmp2; idx = largest; } } int i = 0; while (i < k) { int y = ys[i]; int cnt = 1; int j = i + 1; while (j < k && ys[j] == y) { cnt++; j++; } if (y >= 2 && (cnt & 1)) return ""Mimo""; i = j; } return ""Yuyu""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m, k; cin >> n >> m >> k; vector xs(k), ys(k); for (int i = 0; i < k; i++) cin >> xs[i] >> ys[i]; // solve Solution solution; auto result = solution.solve(n, m, k, xs, ys); // output cout << result << ""\n""; return 0; }",math,hard 315,"You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls. solution main function ```cpp class Solution { public: int solve(int lowLimit, int highLimit) { } }; ``` Example 1: Input: lowLimit = 1, highLimit = 10 Output: 2 Example 2: Input: lowLimit = 5, highLimit = 15 Output: 2 Constraints: 1 <= lowLimit <= highLimit <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { private: int digitSum(int n) { int s = 0; for (; n > 0; n /= 10) s += n % 10; return s; } int maxDigitSum(int n) { int digits = 0; for (; n > 0; n /= 10) ++digits; return digits * 9; } int sum(int n) { int s = 0; for(; n > 0; n /= 10){ s += n % 10; } return s; } public: int solve1(int lowLimit, int highLimit) { int cnt[46] ={0}; int m = 0; for (int n = lowLimit; n<=highLimit; n++) { int box = sum(n); cnt[box]++; m = max(m, cnt[box]); } return m; } int solve2(int lowLimit, int highLimit) { int maxS = maxDigitSum(highLimit); int best = 0; for (int s = 1; s <= maxS; ++s) { int cnt = 0; int curSum = digitSum(lowLimit); for (int x = lowLimit; x <= highLimit; ++x) { if (curSum == s) ++cnt; if (x == highLimit) break; int y = x; while (y % 10 == 9) { curSum -= 9; y /= 10; } curSum += 1; } if (cnt > best) best = cnt; } return best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m;cin>>n>>m; // solve Solution solution; auto result = solution.solve(n,m); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { int sum = 0, product = 1; for (; n > 0; n /= 10) { sum += n % 10; product *= n % 10; } return product - sum; } int solve2(int n) { long long sum = 0, product = 1; while (n > 0) { int d = n % 10; sum += d; product *= d; n /= 10; } long long ans = product - sum; return static_cast(ans); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { int MOD = 1000000007; vector> dpCurrState = vector>(2, vector(3, 0)); vector> dpNextState = vector>(2, vector(3, 0)); dpCurrState[0][0] = 1; for (int len = 0; len < n; ++len) { for (int totalAbsences = 0; totalAbsences <= 1; ++totalAbsences) { for (int consecutiveLates = 0; consecutiveLates <= 2; ++consecutiveLates) { dpNextState[totalAbsences][0] = (dpNextState[totalAbsences][0] + dpCurrState[totalAbsences][consecutiveLates]) % MOD; if (totalAbsences < 1) { dpNextState[totalAbsences + 1][0] = (dpNextState[totalAbsences + 1][0] + dpCurrState[totalAbsences][consecutiveLates]) % MOD; } if (consecutiveLates < 2) { dpNextState[totalAbsences][consecutiveLates + 1] = (dpNextState[totalAbsences][consecutiveLates + 1] + dpCurrState[totalAbsences][consecutiveLates]) % MOD; } } } dpCurrState = dpNextState; dpNextState = vector>(2, vector(3, 0)); } int count = 0; for (int totalAbsences = 0; totalAbsences <= 1; ++totalAbsences) { for (int consecutiveLates = 0; consecutiveLates <= 2; ++consecutiveLates) { count = (count + dpCurrState[totalAbsences][consecutiveLates]) % MOD; } } return count; } int solve2(int n) { const int MOD = 1000000007; long long c00 = 1, c01 = 0, c02 = 0, c10 = 0, c11 = 0, c12 = 0; for (int i = 0; i < n; ++i) { long long n00 = 0, n01 = 0, n02 = 0, n10 = 0, n11 = 0, n12 = 0; long long sum0 = (c00 + c01 + c02) % MOD; long long sum1 = (c10 + c11 + c12) % MOD; n00 = (n00 + sum0) % MOD; n10 = (n10 + sum1) % MOD; n10 = (n10 + sum0) % MOD; n01 = (n01 + c00) % MOD; n02 = (n02 + c01) % MOD; n11 = (n11 + c10) % MOD; n12 = (n12 + c11) % MOD; c00 = n00; c01 = n01; c02 = n02; c10 = n10; c11 = n11; c12 = n12; } long long ans = (c00 + c01 + c02 + c10 + c11 + c12) % MOD; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }",dp,hard 318,"You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​. In one operation, you will create a new array arr, and for each i: If i % 2 == 0, then arr[i] = perm[i / 2]. If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]. You will then assign arr​​​​ to perm. Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 2 Output: 1 Example 2: Input: n = 4 Output: 2 Constraints: 2 <= n <= @data n​​​​​​ is even. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { int halfLen = n >> 1; int ret = 0; int num1Id = 1; do{ if(num1Id < halfLen) num1Id <<= 1; else num1Id = (num1Id << 1) - n + 1; ++ret; }while(num1Id != 1); return ret; } int solve2(int n) { auto gcdll = [](long long a, long long b) { while (b) { long long t = a % b; a = b; b = t; } return a; }; int half = n >> 1; auto nextpos = [half](int i) { if (i < half) return i << 1; return ((i - half) << 1) + 1; }; long long ans = 1; for (int i = 0; i < n; ++i) { int j = nextpos(i); int len = 1; while (j != i) { j = nextpos(j); ++len; } long long g = gcdll(ans, (long long)len); ans = (ans / g) * (long long)len; } return (int)ans; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout<>& grid) { } }; ``` Example 1: Input: grid = [[0,1,1],[1,1,0],[1,1,0]] Output: 2 Example 2: Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data 2 <= m * n <= @data grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 0 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[4000, 2000, 1000], [32000, 16000, 8000], [256000, 128000, 64000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& grid) { int m = grid.size(); int n = grid[0].size(); vector> distance(m, vector(n, INT_MAX)); deque> dq; distance[0][0] = 0; dq.push_front({0, 0}); vector> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; while (!dq.empty()) { auto [x, y] = dq.front(); dq.pop_front(); for (auto [dx, dy] : directions) { int nx = x + dx, ny = y + dy; if (nx >= 0 && nx < m && ny >= 0 && ny < n) { int newDist = distance[x][y] + grid[nx][ny]; if (newDist < distance[nx][ny]) { distance[nx][ny] = newDist; if (grid[nx][ny] == 0) { dq.push_front({nx, ny}); } else { dq.push_back({nx, ny}); } } } } } return distance[m-1][n-1]; } int solve2(vector>& grid) { int m = grid.size(); int n = grid[0].size(); long long mn = 1LL * m * n; long long maxSafe = (INT_MAX - 1000) / 2; long long INFcost = mn + 5; if (INFcost > maxSafe) INFcost = maxSafe; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { grid[i][j] = (int)(INFcost * 2 + (grid[i][j] & 1)); } } grid[0][0] = 0; for (;;) { bool any = false; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int cur = grid[i][j] >> 1; if (i + 1 < m) { int bit = grid[i + 1][j] & 1; int nb = grid[i + 1][j] >> 1; int val = cur + bit; if (val < nb) { grid[i + 1][j] = (val << 1) | bit; any = true; } } if (j + 1 < n) { int bit = grid[i][j + 1] & 1; int nb = grid[i][j + 1] >> 1; int val = cur + bit; if (val < nb) { grid[i][j + 1] = (val << 1) | bit; any = true; } } if (i - 1 >= 0) { int bit = grid[i - 1][j] & 1; int nb = grid[i - 1][j] >> 1; int val = cur + bit; if (val < nb) { grid[i - 1][j] = (val << 1) | bit; any = true; } } if (j - 1 >= 0) { int bit = grid[i][j - 1] & 1; int nb = grid[i][j - 1] >> 1; int val = cur + bit; if (val < nb) { grid[i][j - 1] = (val << 1) | bit; any = true; } } } } for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { int cur = grid[i][j] >> 1; if (i + 1 < m) { int bit = grid[i + 1][j] & 1; int nb = grid[i + 1][j] >> 1; int val = cur + bit; if (val < nb) { grid[i + 1][j] = (val << 1) | bit; any = true; } } if (j + 1 < n) { int bit = grid[i][j + 1] & 1; int nb = grid[i][j + 1] >> 1; int val = cur + bit; if (val < nb) { grid[i][j + 1] = (val << 1) | bit; any = true; } } if (i - 1 >= 0) { int bit = grid[i - 1][j] & 1; int nb = grid[i - 1][j] >> 1; int val = cur + bit; if (val < nb) { grid[i - 1][j] = (val << 1) | bit; any = true; } } if (j - 1 >= 0) { int bit = grid[i][j - 1] & 1; int nb = grid[i][j - 1] >> 1; int val = cur + bit; if (val < nb) { grid[i][j - 1] = (val << 1) | bit; any = true; } } } } if (!any) break; } return grid[m - 1][n - 1] >> 1; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > s; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - the return value is the maximum score you can get # Example 1: - Input: n = 3 a = [5, 4, 5] - Output: 7 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int mx1 = 0, mx2 = 0, cnt1 = 0, cnt2 = 0; for (int i = 0; i < n; i++) { if (i % 2) { mx1 = max(mx1, a[i]); cnt1++; } else { mx2 = max(mx2, a[i]); cnt2++; } } return max(mx1 + cnt1, mx2 + cnt2); } int solve2(int &n, vector &a) { long long mx_even = 0, mx_odd = 0; int cnt_even = 0, cnt_odd = 0; for (int i = 0; i < n; ++i) { if ((i & 1) == 0) { if ((long long)a[i] > mx_even) mx_even = a[i]; cnt_even++; } else { if ((long long)a[i] > mx_odd) mx_odd = a[i]; cnt_odd++; } } long long ans = max(mx_even + cnt_even, mx_odd + cnt_odd); if (ans > INT_MAX) return INT_MAX; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,greedy",hard 321,"# Problem Statement Gridlandia has been hit by flooding and now has to reconstruct all of it's cities. Gridlandia can be described by an $n \times m$ matrix. Initially, all of its cities are in economic collapse. The government can choose to rebuild certain cities. Additionally, any collapsed city which has at least one vertically neighboring rebuilt city and at least one horizontally neighboring rebuilt city can ask for aid from them and become rebuilt **without help from the government**. More formally, collapsed city positioned in $(i, j)$ can become rebuilt if **both** of the following conditions are satisfied: - At least one of cities with positions $(i + 1, j)$ and $(i - 1, j)$ is rebuilt; - At least one of cities with positions $(i, j + 1)$ and $(i, j - 1)$ is rebuilt. If the city is located on the border of the matrix and has only one horizontally or vertically neighbouring city, then we consider only that city. The government wants to know the minimum number of cities it has to rebuild such that **after some time** all the cities can be rebuild. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &m) { // write your code here } }; ``` where: - `n` is the column number of the cities, and `m` is the row number of the cities - return the minimum number of cities that need to be rebuilt # Example 1: - Input: n = 2, m = 2 - Output: 2 # Constraints: - $1 \leq n, m \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 1000000, 100000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &m) { return max(n, m); } int solve2(int &n, int &m) { if (n == 1) return m; if (m == 1) return n; return (n > m) ? n : m; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; // solve Solution solution; auto result = solution.solve(n, m); // output cout << result << ""\n""; return 0; }","math,sort,data_structures",hard 322,"# Problem Statement Monocarp is working on his new site, and the current challenge is to make the users pick strong passwords. Monocarp decided that strong passwords should satisfy the following conditions: - password should consist only of lowercase Latin letters and digits; - there should be no digit that comes after a letter (so, after each letter, there is either another letter or the string ends); - all digits should be sorted in the non-decreasing order; - all letters should be sorted in the non-decreasing order. Note that it's allowed for the password to have only letters or only digits. Monocarp managed to implement the first condition, but he struggles with the remaining ones. Can you help him to verify the passwords? The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, string &s) { // write your code here } }; ``` where: - return ""YES"" if the given password is strong and ""NO"" otherwise. # Example 1: - Input: n = 4 s = ""12ac"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, string &s) { if (is_sorted(s.begin(), s.end())) { return ""YES""; } return ""NO""; } string solve2(int &n, string &s) { char prevDigit = 0; char prevLetter = 0; bool seenLetter = false; for (size_t i = 0; i < s.size(); ++i) { char c = s[i]; if (c >= '0' && c <= '9') { if (seenLetter) { return ""NO""; } if (prevDigit && c < prevDigit) { return ""NO""; } prevDigit = c; } else if (c >= 'a' && c <= 'z') { if (prevLetter && c < prevLetter) { return ""NO""; } prevLetter = c; seenLetter = true; } else { return ""NO""; } } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","sort,string",easy 323,"You are given a 0-indexed integer array nums and a positive integer k. You can apply the following operation on the array any number of times: Choose any element of the array and flip a bit in its binary representation. Flipping a bit means changing a 0 to 1 or vice versa. Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k. Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2 you can flip the fourth bit and obtain (1101)2. solution main function ```cpp class Solution { public: int solve(vector& nums, int k) { } }; ``` Example 1: Input: nums = [2,1,3,4], k = 1 Output: 2 Example 2: Input: nums = [2,0,2,0], k = 0 Output: 0 Constraints: 1 <= nums.length <= @data 0 <= nums[i] <= 10^6 0 <= k <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums, int k) { int finalXor = 0; for (int n : nums) { finalXor = finalXor ^ n; } return __builtin_popcount(finalXor ^ k); } int solve2(vector& nums, int k) { int x = 0; for (int v : nums) x ^= v; unsigned int ux = (unsigned int)x, uk = (unsigned int)k; int cnt = 0; while (ux > 0 || uk > 0) { cnt += (int)((ux ^ uk) & 1u); ux >>= 1; uk >>= 1; } return cnt; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; vector num; for(int i=1;i<=n;i++) { int x;cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num,k); // output cout << result << ""\n""; // for(auto it:result) printf(""%d "",it); return 0; }",bit_manipulation,medium 324,"# Problem Statement Dima Vatrushin is a math teacher at school. He was sent on vacation for $n$ days for his good work. Dima has long dreamed of going to a ski resort, so he wants to allocate several **consecutive days** and go skiing. Since the vacation requires careful preparation, he will only go for **at least $k$ days**. You are given an array $a$ containing the weather forecast at the resort. That is, on the $i$-th day, the temperature will be $a_i$ degrees. Dima was born in Siberia, so he can go on vacation only if the temperature does not rise above $q$ degrees throughout the vacation. Unfortunately, Dima was so absorbed in abstract algebra that he forgot how to count. He asks you to help him and count the number of ways to choose vacation dates at the resort. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, int &k, int &q, vector &a) { // write your code here } }; ``` where: - return: the number of ways for Dima to choose vacation dates at the resort, please use `long long` type. # Example 1: - Input: n = 3, k = 1, q = 15 a = [-5, 0, -10] - Output: 6 # Constraints: - $1 \leq k \leq n \leq @data$ - $-10^9 \leq a[i], q \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &k, int &q, vector &a) { long long ans = 0; int suf = 0; for (auto x : a) { suf = x <= q ? suf + 1 : 0; ans += max(0, suf - k + 1); } return ans; } long long solve2(int &n, int &k, int &q, vector &a) { long long ans = 0; for (int i = 0; i < n; ++i) { if (a[i] > q) continue; int len = 0; for (int j = i; j < n; ++j) { if (a[j] > q) break; ++len; if (len >= k) ++ans; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k, q; cin >> n >> k >> q; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, k, q, a); // output cout << result << ""\n""; return 0; }","math,two_pointers",medium 325,"# Problem Statement Mocha likes arrays, so before her departure, Chamo gave her an array $a$ consisting of $n$ positive integers as a gift. Mocha doesn't like arrays containing different numbers, so Mocha decides to use magic to change the array. Mocha can perform the following three-step operation some (possibly, zero) times: 1. Choose indices $l$ and $r$ ($1 \leq l \lt r \leq n$) 2. Let $x$ be the median$^\dagger$ of the subarray $[a_l, a_{l+1},\ldots, a_r]$ 3. Set all values $a_l, a_{l+1},\ldots, a_r$ to $x$ Suppose $a=[1,2,3,4,5]$ initially: - If Mocha chooses $(l,r)=(3,4)$ in the first operation, then $x=3$, the array will be changed into $a=[1,2,3,3,5]$. - If Mocha chooses $(l,r)=(1,3)$ in the first operation, then $x=2$, the array will be changed into $a=[2,2,2,4,5]$. Mocha will perform the operation until the array contains only the same number. Mocha wants to know what is the maximum possible value of this number. $^\dagger$ The median in an array $b$ of length $m$ is an element that occupies position number $\lfloor \frac{m+1}{2} \rfloor$ after we sort the elements in non-decreasing order. For example, the median of $[3,1,4,1,5]$ is $3$ and the median of $[5,25,20,24]$ is $20$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - the return value is the maximum value of the same number at the end # Example 1: - Input: n = 5 a = [1, 2, 3, 4, 5] - Output: 4 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int mx = 0; for (int i = 0; i < n; i++) { if (i + 1 < n && a[i + 1] >= a[i]) mx = max(mx, a[i]); if (i + 2 < n && a[i + 2] >= a[i]) mx = max(mx, a[i]); if (i - 1 >= 0 && a[i - 1] >= a[i]) mx = max(mx, a[i]); if (i - 2 >= 0 && a[i - 2] >= a[i]) mx = max(mx, a[i]); } return mx; } int solve2(int &n, vector &a) { int ans = 0; for (int i = 0; i + 1 < n; ++i) { int m2 = a[i] < a[i + 1] ? a[i] : a[i + 1]; if (m2 > ans) ans = m2; } for (int i = 0; i + 2 < n; ++i) { int x = a[i], y = a[i + 1], z = a[i + 2]; if (x > y) { int t = x; x = y; y = t; } if (y > z) { int t = y; y = z; z = t; } if (x > y) { int t = x; x = y; y = t; } int med3 = y; if (med3 > ans) ans = med3; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","binary,greedy",hard 326,"# Problem Statement Doremy's new city is under construction! The city can be regarded as a simple undirected graph with $n$ vertices. The $i$-th vertex has altitude $a_i$. Now Doremy is deciding which pairs of vertices should be connected with edges. Due to economic reasons, there should be no self-loops or multiple edges in the graph. Due to safety reasons, there should not be **pairwise distinct** vertices $u$, $v$, and $w$ such that $a_u \leq a_v \leq a_w$ and the edges $(u,v)$ and $(v,w)$ exist. Under these constraints, Doremy would like to know the maximum possible number of edges in the graph. Can you help her? Note that the constructed graph is allowed to be disconnected. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - return the maximum possible number of edges in the graph. # Example 1: - Input: n = 4 a = [2,2,3,1] - Output: 3 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { sort(a.begin(), a.end()); long long ans = n / 2; for (int i = 0; i < n; i++) { if(i == n - 1 || a[i] != a[i + 1]) ans = max(ans, (long long) (i + 1) * (n - i - 1)); } return ans; } long long solve2(int &n, vector &a) { long long ans = n / 2; for (int i = 0; i < n; i++) { int cnt_le = 0; for (int j = 0; j < n; j++) { if (a[j] <= a[i]) cnt_le++; } long long left = cnt_le; long long right = n - cnt_le; long long prod = left * right; if (prod > ans) ans = prod; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",graph,hard 327,"The factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1. We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order. For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11. Given an integer n, return the clumsy factorial of n. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 4 Output: 7 Example 2: Input: n = 10 Output: 12 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(int n) { if (n == 1) { return 1; } else if (n == 2) { return 2; } else if (n == 3) { return 6; } else if (n == 4) { return 7; } if (n % 4 == 0) { return n + 1; } else if (n % 4 <= 2) { return n + 2; } else { return n - 1; } } int solve2(int n) { long long res = 0; long long term = n; int sign = 1; int op_idx = 0; for (int a = n - 1; a >= 1; --a) { int op = op_idx % 4; if (op == 0) { term = term * a; } else if (op == 1) { term = term / a; } else { res += sign * term; sign = (op == 2 ? 1 : -1); term = a; } ++op_idx; } res += sign * term; return (int)res; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< &a) { // write your code here } }; ``` where: - return: the minimum number of operations required. # Example 1: - Input: n = 5 a = [1, 3, 5, 7, 9] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int ans = 0, flag = 0; long long mx = -1; for (int i = 0; i < n; i++) { if (a[i] % 2 == 1) flag = 1; } if (!flag) { return 0; } for (int i = 0; i < n; i++) { if (a[i] % 2 == 0) ans++; if (a[i] % 2 == 1) mx = max(mx, 1ll * a[i]); } sort(a.begin(), a.end()); for (int i = 0; i < n; i++) { if (a[i] % 2 == 1) continue; if (a[i] > mx) { ans++; break; } mx += a[i]; } return ans; } int solve2(int &n, vector &a) { int cntOdd = 0, cntEven = 0; long long mx = -1; for (int i = 0; i < n; i++) { if (a[i] % 2 == 1) { cntOdd++; if (mx < a[i]) mx = a[i]; } else cntEven++; } if (cntOdd == 0) return 0; bool changed = true; while (changed) { changed = false; for (int i = 0; i < n; i++) { if ((a[i] % 2 == 0) && (a[i] <= mx)) { mx += a[i]; a[i] |= 1; changed = true; } } } for (int i = 0; i < n; i++) { if (a[i] % 2 == 0) return cntEven + 1; } return cntEven; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",constructive_algorithms,medium 329,"You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings. Return the minimum number of extra characters left over if you break up s optimally. solution main function ```cpp class Solution { public: int solve(string s, vector& dictionary) { } }; ``` Example 1: Input: s = ""leetscode"", dictionary = [""leet"",""code"",""leetcode""] Output: 1 Example 2: Input: s = ""sayhelloworld"", dictionary = [""hello"",""world""] Output: 3 Constraints: 1 <= s.length <= @data 1 <= dictionary.length <= @data 1 <= dictionary[i].length <= 50 dictionary[i] and s consists of only lowercase English letters dictionary contains distinct words Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(string s, vector& dictionary) { int n = s.size(), m = dictionary.size(); vector dp(n + 1); for (int i = 0; i <= n; i++) dp[i] = i; auto func = [&](int p, int q) { if (p + dictionary[q].size() > n) return false; for (int i = 0; i < dictionary[q].size(); i++) { if (s[p + i] != dictionary[q][i]) return false; } return true; }; for (int i = 0; i < n; i++) { for (int j = 0; j < dictionary.size(); j++) { if (func(i, j)) { dp[i + dictionary[j].size()] = min(dp[i], dp[i + dictionary[j].size()]); } } dp[i + 1] = min(dp[i] + 1, dp[i + 1]); } return dp[n]; } int solve2(string s, vector& dictionary) { int n = (int)s.size(); int ring[51]; ring[0] = 0; for (int i = 1; i <= n; ++i) { int best = ring[(i - 1) % 51] + 1; for (int j = 0; j < (int)dictionary.size(); ++j) { int len = (int)dictionary[j].size(); if (len <= i) { bool ok = true; int start = i - len; for (int k = 0; k < len; ++k) { if (s[start + k] != dictionary[j][k]) { ok = false; break; } } if (ok) { int cand = ring[(i - len) % 51]; if (cand < best) best = cand; } } } ring[i % 51] = best; } return ring[n % 51]; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector dic; string s; for(int i=1;i<=n;i++) { cin>>s; dic.push_back(s); } cin>>s; // solve Solution solution; auto result = solution.solve(s,dic); // output cout< &a) { // write your code here } }; ``` where: - return: the number of suitable pairs, please return the result as long long type # Example 1: - Input: n = 3, l = 4, r = 7 a = [5, 1, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i], l, r \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &l, int &r, vector &a) { sort(a.begin(), a.end()); long long ans = 0; for (int i = 0, L = n, R = n; i < n; i++) { while (L && a[L - 1] + a[i] >= l) L--; while (R && a[R - 1] + a[i] > r) R--; ans += min(i, R) - min(i, L); } return ans; } long long solve2(int &n, int &l, int &r, vector &a) { long long ans = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { long long s = (long long)a[i] + (long long)a[j]; if (s >= l && s <= r) ans++; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, l, r; cin >> n >> l >> r; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, l, r, a); // output cout << result << ""\n""; return 0; }","two_pointers,math,binary,data_structures",easy 331,"# Problem Statement You are given a sequence $a=[a_1,a_2,\dots,a_n]$ consisting of $n$ **positive** integers. Let's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by $a[l,r]$ a segment of the sequence $a$ with the left end in $l$ and the right end in $r$, i.e. $a[l,r]=[a_l, a_{l+1}, \dots, a_r]$. For example, if $a=[31,4,15,92,6,5]$, then $a[2,5]=[4,15,92,6]$, $a[5,5]=[6]$, $a[1,6]=[31,4,15,92,6,5]$ are segments. We split the given sequence $a$ into segments so that: - each element is in **exactly** one segment; - the sums of elements for all segments are **equal**. For example, if $a$ = $[55,45,30,30,40,100]$, then such a sequence can be split into three segments: $a[1,2]=[55,45]$, $a[3,5]=[30, 30, 40]$, $a[6,6]=[100]$. Each element belongs to exactly segment, the sum of the elements of each segment is $100$. Let's define thickness of split as the length of the longest segment. For example, the thickness of the split from the example above is $3$. Find the minimum thickness among all possible splits of the given sequence of $a$ into segments in the required way. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the minimum thickness # Example 1: - Input: n = 6 a = [55,45,30,30,40,100] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 5000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, vector &a) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; int ans = n; auto check = [&](int p) -> int { int tem = 0; int mx = 0; for (int l = 1, r = 1; l <= n;) { while (r <= n && tem + a[r - 1] <= p) tem += a[(r++) - 1]; if (tem != p) return n; mx = max(r - l, mx); l = r; tem = 0; } return mx; }; for (int i = 1; i * i <= sum && i <= n; i++) { if (sum % i == 0) ans = min(ans, check(sum / i)); if (sum % i == 0 && (sum / i) != i && sum / i <= n) ans = min(ans, check(i)); } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,math,two_pointers",easy 332,"# Problem Statement Kinich wakes up to the start of a new day. He turns on his phone, checks his mailbox, and finds a mysterious present. He decides to unbox the present. Kinich unboxes an array $a$ with $n$ integers. Initially, Kinich's score is $0$. He will perform the following operation any number of times: - Select two indices $i$ and $j$ $(1 \leq i < j \leq n)$ such that neither $i$ nor $j$ has been chosen in any previous operation and $a_i = a_j$. Then, add $1$ to his score. Output the maximum score Kinich can achieve after performing the aforementioned operation any number of times. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the maximum score achievable. # Example 1: - Input: n = 2 a = [2, 2] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int ans = 0; int pre = -1, cnt = 0; for (int i = 0; i < n; i++) { if (pre == -1) { pre = a[i]; cnt++; } else { if (a[i] == pre) { cnt++; } else { ans += cnt / 2; pre = a[i]; cnt = 1; } } } ans += cnt / 2; return ans; } int solve2(int &n, vector &a) { int ans = 0; for (int i = 0; i < n; i++) { if (a[i] <= 0) continue; for (int j = i + 1; j < n; j++) { if (a[j] <= 0) continue; if (a[j] == a[i]) { ans++; a[i] = 0; a[j] = 0; break; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",implementation,easy 333,"You are given an undirected, connected tree of n nodes labeled from 0 to n - 1. The tree is represented as an adjacency list graph, where graph[i] is a list of all nodes connected with node i by an edge. Return the length of the shortest walk that visits every node. You may start and stop at any node, revisit nodes multiple times, and reuse edges. solution main function ```cpp class Solution { public: int solve(vector>& graph) { } }; ``` Example 1: Input: graph = [[1,2,3],[0],[0],[0]] Output: 4 Example 2: Input: graph = [[1],[0,2],[1,3],[2]] Output: 3 Constraints: n == graph.length 1 <= n <= @data graph is an undirected connected tree with exactly n - 1 edges. graph[i] does not contain i. If graph[a] contains b, then graph[b] contains a. Time limit: @time_limit ms Memory limit: @memory_limit KB","[4, 8, 12]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { int bfs_far(const std::vector>& g, int start, int& farNode) { int n = g.size(); unsigned long long visited = 0ULL; unsigned long long frontier = 0ULL; visited |= (1ULL << start); frontier |= (1ULL << start); unsigned long long lastFront = frontier; int dist = 0; while (frontier) { unsigned long long next = 0ULL; for (int u = 0; u < n; ++u) { if ((frontier >> u) & 1ULL) { const auto& adj = g[u]; for (int v : adj) { if (((visited >> v) & 1ULL) == 0ULL) { next |= (1ULL << v); } } } } if (next == 0ULL) break; visited |= next; lastFront = next; frontier = next; dist++; } int node = 0; for (; node < n; ++node) { if ((lastFront >> node) & 1ULL) break; } farNode = node; return dist; } public: int dp[13][5000]; int solve1(std::vector>& graph) { int n = graph.size(); memset(dp, -1, sizeof(dp)); queue> q; for (int i = 0; i < n; ++i) { q.push({i, (1 << i)}); dp[i][(1 << i)] = 0; } while (!q.empty()) { auto [node, visited] = q.front(); q.pop(); for (int neigh : graph[node]) { int new_visited = visited | (1 << neigh); if (dp[neigh][new_visited] == -1) { dp[neigh][new_visited] = dp[node][visited] + 1; q.push({neigh, new_visited}); } } } int all_visited = (1 << n) - 1; int ans = INT_MAX; for (int i = 0; i < n; ++i) { if (dp[i][all_visited] != -1) { ans = std::min(ans, dp[i][all_visited]); } } return ans; } int solve2(std::vector>& graph) { int n = graph.size(); if (n <= 1) return 0; int farNode1 = 0; bfs_far(graph, 0, farNode1); int farNode2 = 0; int diameter = bfs_far(graph, farNode1, farNode2); long long ans = 2LL * (n - 1) - (long long)diameter; if (ans < 0) ans = 0; if (ans > INT_MAX) ans = INT_MAX; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector> e(n); for(int i=1;i>x>>y; e[x].push_back(y); e[y].push_back(x); } // solve Solution solution; auto result = solution.solve(e); // output // for(auto it:result) cout<& vals, vector>& edges, int k) { } }; ``` Example 1: Input: vals = [1,2,3,4,10,-10,-20], edges = [[0,1],[1,2],[1,3],[3,4],[3,5],[3,6]], k = 2 Output: 16 Example 2: Input: vals = [-5], edges = [], k = 0 Output: -5 Constraints: n == vals.length 1 <= n <= @data -10^4 <= vals[i] <= 10^4 0 <= edges.length <= min(n * (n - 1) / 2, 10^5) edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi 0 <= k <= n - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& vals, vector>& edges, int k) { vector adj[vals.size() + 1]; for (int i = 0; i < edges.size(); i++) { adj[edges[i][0]].push_back(vals[edges[i][1]]); adj[edges[i][1]].push_back(vals[edges[i][0]]); } int ans = INT_MIN; for (int i = 0; i < vals.size(); i++) { int temp = vals[i]; sort(adj[i].begin(), adj[i].end(), greater()); for (int j = 0; j < k && j < adj[i].size(); j++) { if (adj[i][j] < 0) break; temp += adj[i][j]; } ans = max(ans, temp); } return ans; } int solve2(vector& vals, vector>& edges, int k) { int n = (int)vals.size(); long long ans = LLONG_MIN; for (int c = 0; c < n; ++c) { long long sum = (long long)vals[c]; int taken = 0; int prev_val = INT_MAX; int prev_id = INT_MAX; while (taken < k) { int best_id = -1; int best_val = INT_MIN; for (size_t i = 0; i < edges.size(); ++i) { int u = edges[i][0]; int v = edges[i][1]; if (u == c) { int nid = v; int nv = vals[nid]; if (nv > 0) { if (nv < prev_val || (nv == prev_val && nid < prev_id)) { if (nv > best_val || (nv == best_val && nid > best_id)) { best_val = nv; best_id = nid; } } } } else if (v == c) { int nid = u; int nv = vals[nid]; if (nv > 0) { if (nv < prev_val || (nv == prev_val && nid < prev_id)) { if (nv > best_val || (nv == best_val && nid > best_id)) { best_val = nv; best_id = nid; } } } } } if (best_id == -1) break; sum += best_val; prev_val = best_val; prev_id = best_id; ++taken; } if (sum > ans) ans = sum; } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,k; cin>>n>>m; vector > edge; vector< int > val; for(int i=1,x,y,z;i<=m;i++) { scanf(""%d"",&x); scanf(""%d"",&y); vector temp; temp.push_back(x); temp.push_back(y); edge.push_back(temp); } cin>>k; for(int i=1,x;i<=n;i++) { scanf(""%d"",&x); val.push_back(x); } // solve Solution solution; auto result = solution.solve(val,edge,k); // output // for(auto it:result) cout<>& grid) { // write your code here } }; ``` Example 1: Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Example 2: Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data grid[i][j] is either 0 or 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { int dx[4] = {0,0,1,-1}; int dy[4] = {1,-1,0,0}; int m,n; public: int solve1(vector>& grid) { int ret = 0; m = grid.size(),n = grid[0].size(); queue>q; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) if(grid[i][j] == 1) { if(i == 0 || j == 0 || i == m - 1 || j == n - 1) { q.push({i, j}); grid[i][j] = 2; } } while(q.size()) { auto [a,b] = q.front(); q.pop(); for(int i = 0;i<4;i++) { int x = a+dx[i],y = b+dy[i]; if(x>=0&&x=0&&y>& grid) { int m = (int)grid.size(); int n = (int)grid[0].size(); for(int i = 0; i < m; i++) { if(grid[i][0] == 1) grid[i][0] = 2; if(grid[i][n - 1] == 1) grid[i][n - 1] = 2; } for(int j = 0; j < n; j++) { if(grid[0][j] == 1) grid[0][j] = 2; if(grid[m - 1][j] == 1) grid[m - 1][j] = 2; } bool changed = true; while(changed) { changed = false; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(grid[i][j] == 1) { if((i > 0 && grid[i - 1][j] == 2) || (i + 1 < m && grid[i + 1][j] == 2) || (j > 0 && grid[i][j - 1] == 2) || (j + 1 < n && grid[i][j + 1] == 2)) { grid[i][j] = 2; changed = true; } } } } } int ret = 0; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) if(grid[i][j] == 1) ret++; return ret; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > g; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } g.push_back(temp); } // solve Solution solution; auto result = solution.solve(g); // output cout< &a) { // write your code here } }; ``` where: - return: the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array. # Example 1: - Input: n = 5 a = [1, 1, 1, 1, 1] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int j = 0; sort(a.begin(), a.end()); for (int i = 0; i < n; i++) { if (a[i] > a[j]) j++; } return j; } int solve2(int &n, vector &a) { for (int i = 0; i < n - 1; i++) { int mi = i; int mv = a[i]; for (int j = i + 1; j < n; j++) { if (a[j] < mv) { mv = a[j]; mi = j; } } if (mi != i) swap(a[i], a[mi]); } int j = 0; for (int i = 0; i < n; i++) { if (a[i] > a[j]) j++; } return j; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","math,sort",medium 337,"# Problem Statement You are given an integer $n$ and an array $a$ of length $n$. Each element $a_i$ is either $-1$ or an integer from $1$ to $n$. A permutation $p$ of $\{0, 1, \dots, n-1\}$ is compatible with $a$ if, for every index $i$ such that $a_i \neq -1$, we have $p_i = a_i - 1$. A compatible permutation is called valid if there exists an integer $k$, with $0 \leq k \leq n-2$, such that: - the elements of $p$ whose values are at most $k$, read from left to right, are in increasing order; - the elements of $p$ whose values are greater than $k$, read from left to right, are in increasing order. Count the number of distinct valid compatible permutations modulo $998244353$. # Function Signature ```cpp class Solution { public: int solve(int &n, vector &a); }; ``` where: - $n$ is the length of the array. - $a$ is the array of fixed values and unknown positions. - The function returns the number of valid compatible permutations modulo $998244353$. # Example 1 **Input: ** $n = 2$, $a = [2, 1]$ **Output:** $1$ **Explanation:** The only compatible permutation is $[1, 0]$. For $k = 0$, the values at most $0$ form $[0]$, and the values greater than $0$ form $[1]$. Both are increasing, so the permutation is valid. # Example 2 **Input: ** $n = 3$, $a = [-1, -1, -1]$ **Output:** $5$ **Explanation:** All positions are unknown. Among the six permutations of $\{0,1,2\}$, all except $[2,1,0]$ satisfy the condition for at least one valid $k$. Therefore the answer is $5$. # Constraints - $2 \leq n \leq @data$ - Each $a_i$ is either $-1$ or an integer between $1$ and $n$, inclusive. - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[300, 1500, 3000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &n, vector &a) { const int MOD = 998244353; vector b = a; for (int &x : b) if (x != -1) --x; auto modpow = [&](long long base, long long exp) { long long res = 1 % MOD; base %= MOD; if (base < 0) base += MOD; while (exp > 0) { if (exp & 1LL) res = (res * base) % MOD; base = (base * base) % MOD; exp >>= 1LL; } return (int)res; }; vector fac(n + 1), ifac(n + 1); fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (long long)fac[i - 1] * i % MOD; ifac[n] = modpow(fac[n], MOD - 2); for (int i = n; i >= 1; i--) ifac[i - 1] = (long long)ifac[i] * i % MOD; auto C = [&](int N, int R) -> int { if (R < 0 || R > N) return 0; return (long long)fac[N] * ifac[R] % MOD * ifac[N - R] % MOD; }; long long ans = 0; for (int k = 0; k < n - 1; k++) { long long res = 1; int spaces = 0; int less = -1; int more = k; for (int j = 0; j < n; j++) { if (b[j] == -1) { spaces++; continue; } if (b[j] <= k) { int need = b[j] - less - 1; res = res * C(spaces, need) % MOD; more += spaces - need; less = b[j]; } else { int need = b[j] - more - 1; res = res * C(spaces, need) % MOD; less += spaces - need; more = b[j]; } spaces = 0; if (res == 0) { } } res = res * C(spaces, k - less) % MOD; ans += res; if (ans >= MOD) ans -= MOD; } bool sorted = true; for (int i = 0; i < n; i++) { if (b[i] != -1 && b[i] != i) { sorted = false; break; } } if (sorted) { ans -= (n - 2); ans %= MOD; if (ans < 0) ans += MOD; } return (int)(ans % MOD); } }; #endif ","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; int result = solution.solve(n, a); // output cout << result << ""\n""; return 0; } ","combinatorics,dp",hard 338,"# Problem Statement Today, Cat and Fox found an array $a$ consisting of $n$ non-negative integers. Define the loneliness of $a$ as the **smallest** positive integer $k$ ($1 \le k \le n$) such that for any two positive integers $i$ and $j$ ($1 \leq i, j \leq n - k +1$), the following holds: $$ a_i | a_{i+1} | \ldots | a_{i+k-1} = a_j | a_{j+1} | \ldots | a_{j+k-1}, $$ where $x | y$ denotes the bitwise OR of $x$ and $y$. In other words, for every $k$ consecutive elements, their bitwise OR should be the same. Note that the loneliness of $a$ is well-defined, because for $k = n$ the condition is satisfied. Cat and Fox want to know how lonely the array $a$ is. Help them calculate the loneliness of the found array. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the loneliness of the given array. # Example 1: - Input: n = 3 a = [2, 2, 2] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int ans = 1; for (int j = 0; j < 20; j++) { int lst = -1; for (int i = 0; i < n; i++) { if (a[i] >> j & 1) { ans = max(ans, i - lst); lst = i; } } if (lst != -1) ans = max(ans, n - lst); } return ans; } int solve2(int &n, vector &a) { for (int k = 1; k <= n; k++) { int target = 0; for (int p = 0; p < k; p++) target |= a[p]; bool ok = true; for (int i = 1; i <= n - k; i++) { int cur = 0; for (int p = i; p < i + k; p++) cur |= a[p]; if (cur != target) { ok = false; break; } } if (ok) return k; } return n; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","bit_manipulation,binary,two_pointers,math",medium 339,"You are given a string s consisting only of uppercase English letters. You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings ""AB"" or ""CD"" from s. Return the minimum possible length of the resulting string that you can obtain. Note that the string concatenates after removing the substring and could produce new ""AB"" or ""CD"" substrings. solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""ABFCACDB"" Output: 2 Example 2: Input: s = ""ACBBD"" Output: 5 Constraints: 1 <= s.length <= @data s consists only of uppercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { int writePtr = 0; vector charArray(s.begin(), s.end()); for (int readPtr = 0; readPtr < s.length(); readPtr++) { charArray[writePtr] = charArray[readPtr]; if (writePtr > 0 && (charArray[writePtr - 1] == 'A' || charArray[writePtr - 1] == 'C') && charArray[writePtr] == charArray[writePtr - 1] + 1) { writePtr--; } else { writePtr++; } } return writePtr; } int solve2(string s) { size_t i = 0; while (i + 1 < s.size()) { char a = s[i], b = s[i + 1]; if ((a == 'A' && b == 'B') || (a == 'C' && b == 'D')) { s.erase(i, 2); if (i > 0) i--; } else { i++; } } return (int)s.size(); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return YES if a is kalindrome and NO otherwise # Example 1: - Input: n = 2 a = [1, 2] - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a) { int i, flag, p; flag = 0; for (i = 0; i < n / 2; i++) { if (a[i] != a[n - i - 1]) { p = i; flag = 1; break; } } auto check = [&](int x, int n) { int i, j; i = 0; j = n - i - 1; while (i < j) { if (a[i] == x) { i++; continue; } if (a[j] == x) { j--; continue; } if (a[i] == a[j]) { i++; j--; continue; } return 0; } return 1; }; if (!flag) { return ""YES""; } else { if (check(a[i], n) | check(a[n - i - 1], n)) return ""YES""; else return ""NO""; } } string solve2(int &n, vector &a) { int i = 0, j = n - 1; while (i < j && a[i] == a[j]) { i++; j--; } if (i >= j) return ""YES""; auto check = [&](int x) { int l = 0, r = n - 1; while (l < r) { if (a[l] == x) { l++; continue; } if (a[r] == x) { r--; continue; } if (a[l] == a[r]) { l++; r--; continue; } return false; } return true; }; for (int t = 0; t < n; t++) { if (check(a[t])) return ""YES""; } return ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,two_pointers",medium 341,"# Problem Statement Given a rooted tree `T` with `n` vertices (rooted at `1`) and an integer array `a` of length `n`, count the number of permutations `p` of length `n` that satisfy: - For every vertex `u (1 ≤ u ≤ n)`, there are exactly `a[u]` ancestors `v` of `u` such that `p[v] < p[u]`. It is guaranteed that the input is selected such that at least one valid permutation exists. Return the answer modulo `998244353`. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &fa, vector &a) { // write your code here } }; ``` where: - `fa` is a parent array of size `n + 1` (1-indexed), with `fa[1] = 0`, and for `2 ≤ i ≤ n`, `fa[i]` is the parent of node `i`. - `a` is a 1-indexed array of size `n`, where `0 ≤ a[i] < depth(i)`, and `depth(1) = 1`. - The function returns the number of valid permutations modulo `998244353`. # Example - Input: - n = 5 - fa = [0, 0, 1, 2, 3, 4] // 1-indexed, fa[1]=0, parents for 2..n: 1 2 3 4 - a = [0, 1, 2, 3, 4] - Output: - 1 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a[i] < depth(i)$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[1000, 500, 250], [8000, 4000, 2000], [64000, 32000, 16000]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &fa, vector &a) { const int MOD = 998244353; using ll = long long; vector> G(n + 1); for (int i = 2; i <= n; i++) G[fa[i]].push_back(i); vector siz(n + 1), hson(n + 1, 0); function dfs = [&](int u) { siz[u] = 1; hson[u] = 0; for (int v : G[u]) { dfs(v); siz[u] += siz[v]; if (siz[v] > siz[hson[u]]) hson[u] = v; } }; dfs(1); vector fact(n + 1), ifac(n + 1); fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = (ll)fact[i - 1] * i % MOD; auto mod_pow = [&](ll x, ll e) { ll r = 1; while (e) { if (e & 1) r = r * x % MOD; x = x * x % MOD; e >>= 1; } return r; }; ifac[n] = (int)mod_pow(fact[n], MOD - 2); for (int i = n - 1; i >= 0; i--) ifac[i] = (ll)ifac[i + 1] * (i + 1) % MOD; auto C = [&](int x, int y) -> int { if (x < 0 || x > y) return 0; return (ll)fact[y] * ifac[x] % MOD * ifac[y - x] % MOD; }; struct Seg { int base; vector len; void init(int need) { base = 1; while (base < need) base <<= 1; len.assign(base * 2, 0); for (int i = 0; i < base; i++) len[i + base] = 1; for (int i = base - 1; i >= 1; i--) len[i] = len[i << 1] + len[i << 1 | 1]; } int qpos(int k) { int u = 1; while (u < base) { if (len[u << 1] >= k) u <<= 1; else { k -= len[u << 1]; u = u << 1 | 1; } } return u - base; } int gpos(int leaf) { int ans = 1, x = leaf + base; while (x > 1) { if (x & 1) ans += len[x ^ 1]; x >>= 1; } return ans; } void add(int leaf, int v) { int x = leaf + base; len[x] += v; while (x > 1) { x >>= 1; len[x] = len[x << 1] + len[x << 1 | 1]; } } } T; T.init(n + 3); for (int i = 1; i <= n; i++) a[i]++; vector>> vec(n + 1); vector cnt(T.base, 0), upd, posi; ll ans = 1; function work = [&](int u) { vector pth; for (int v = u; v; v = hson[v]) { pth.push_back(v); for (int w : G[v]) if (w != hson[v]) work(w); } reverse(pth.begin(), pth.end()); upd.clear(); posi.clear(); for (int v : pth) { for (int w : G[v]) if (w != hson[v]) { for (auto &pr : vec[w]) { int t = T.qpos(pr.first); posi.push_back(t); ans = ans * C(pr.second, cnt[t] + pr.second) % MOD; cnt[t] += pr.second; } vec[w].clear(); } int p = T.qpos(a[v]), q = T.qpos(a[v] + 1); cnt[q] += cnt[p] + 1; cnt[p] = 0; posi.push_back(q); upd.push_back(p); T.add(p, -1); } for (int i : posi) if (cnt[i]) { vec[u].push_back({ T.gpos(i), cnt[i] }); cnt[i] = 0; } for (int i : upd) T.add(i, 1); upd.clear(); posi.clear(); }; work(1); return (int)(ans % MOD); } int solve2(int &n, vector &fa, vector &a) { const int MOD = 998244353; vector ord(n); for (int i = 0; i < n; i++) ord[i] = i + 1; long long ans = 0; do { bool ok = true; for (int i = 0; i < n && ok; i++) { int u = ord[i]; int cnt = 0; for (int x = fa[u]; x; x = fa[x]) { for (int j = 0; j < i; j++) if (ord[j] == x) { cnt++; break; } } if (cnt != a[u]) ok = false; } if (ok) { ans++; if (ans >= MOD) ans -= MOD; } } while (next_permutation(ord.begin(), ord.end())); return (int)(ans % MOD); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector fa(n + 1, 0), a(n + 1, 0); for (int i = 2; i <= n; i++) cin >> fa[i]; for (int i = 1; i <= n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, fa, a); // output cout << result << ""\n""; return 0; }","data_structures,tree",hard 342,"# Problem Statement Given a binary string $s$ of length $n$, consisting of characters 0 and 1. Let's build a **square** table of size $n \times n$, consisting of 0 and 1 characters as follows. In the first row of the table write the original string $s$. In the second row of the table write cyclic shift of the string $s$ by one to the right. In the third row of the table, write the cyclic shift of line $s$ by two to the right. And so on. Thus, the row with number $k$ will contain a cyclic shift of string $s$ by $k$ to the right. The rows **are numbered from $0$ to $n - 1$ top-to-bottom**. In the resulting table we need to find the rectangle consisting only of ones that has the largest area. We call a rectangle the set of all cells $(i, j)$ in the table, such that $x_1 \le i \le x_2$ and $y_1 \le j \le y_2$ for some integers $0 \le x_1 \le x_2 < n$ and $0 \le y_1 \le y_2 < n$. Recall that the cyclic shift of string $s$ by $k$ to the right is the string $s_{n-k+1} \ldots s_n s_1 s_2 \ldots s_{n-k}$. For example, the cyclic shift of the string ""01011"" by $0$ to the right is the string itself ""01011"", its cyclic shift by $3$ to the right is the string ""01101"". The main function of the solution is defined as: ```cpp class Solution { public: long long solve(string &s) { // write your code here } }; ``` where: - return value is a 64-bit integer representing the area of the largest rectangle # Example 1: - Input: s = ""101"" - Output: 2 # Constraints: - $1 \leq s.length \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 400, 80], [6400, 3200, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(string &s) { int n = s.size(); if (count(s.begin(), s.end(), '0') == 0) return 1LL * n * n; s = s + s; long long ans = 0; for (int i = 0, j; i < n; i++) { if (s[i] == '1') { j = i; while (s[j] == '1') j++; int d = j - i + 1; ans = max(ans, 1LL * (d / 2) * (d - d / 2)); i = j; } } return ans; } long long solve2(string &s) { int n = s.size(); if (count(s.begin(), s.end(), '0') == 0) return 1LL * n * n; long long best = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') { int len = 0; while (len < n && s[(i + len) % n] == '1') len++; if (len > best) best = len; } } long long d = best + 1; long long a = d / 2; long long b = d - a; return a * b; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string s; cin >> s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }","two_pointers,math,string",hard 343,"Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it into some number of substrings such that: Each substring is balanced. Return the maximum number of balanced strings you can obtain. solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""RLRRLLRLRL"" Output: 4 Example 2: Input: s = ""RLRRRLLRLL"" Output: 2 Constraints: 2 <= s.length <= @data s[i] is either 'L' or 'R'. s is a balanced string. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(string s) { int x=0,l=0,r=0,n=s.size(); for(int i=0;i using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< using namespace std; class Solution { public: int solve1(int &n) { string s = to_string(n); s = 'k' + s; n = s.size() - 1; int tem = pow(10, n - 1); int sum = 0; int ans = 0; int num = 0; for (int i = 1; i <= n; i++) num = num * 10 + (s[i] - '0'); for (int i = 1; i <= n; i++) { int d = s[i] - '0'; ans += sum * 45 * tem; sum = sum * 10 + d; ans += max(0, (d - 1 + 1) * (d - 1) / 2) * tem; num %= tem; ans += d * (num + 1); tem /= 10; } return ans; } int solve2(int &n) { long long total = 0; for (int i = 1; i <= n; ++i) { int x = i; int s = 0; while (x) { s += x % 10; x /= 10; } total += s; } return (int)total; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }","math,dp",easy 345,"There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. solution main function ```cpp class Solution { public: vector> solve(int n, vector>& connections) { // write your code here } }; ``` Example 1: Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]] Output: [[1,3]] Example 2: Input: n = 2, connections = [[0,1]] Output: [[0,1]] Constraints: 2 <= n <= @data n - 1 <= connections.length <= 10^5 0 <= a[i], b[i] <= n - 1 a[i] != b[i] All undirected connections are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 10000]",1000,"[[100, 64, 64], [800, 500, 275], [6400, 4000, 2200]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector > solve(int n, vector >& connections) { vector> dict(n); for(auto& edge:connections){ dict[edge[0]].emplace_back(edge[1]); dict[edge[1]].emplace_back(edge[0]); } vector id(n, -1); vector> res; dfs(0, 0, -1, id, dict, res); return res; } int dfs(int node, int nodeId, int par, vector& id, vector>& dict, vector>& res){ id[node] = nodeId; for(int next:dict[node]){ if(next == par) continue; else if(id[next] == -1) id[node] = min(id[node], dfs(next, nodeId+1, node, id, dict, res)); else id[node] = min(id[next], id[node]); } if(id[node] == nodeId && node != 0) res.push_back({par, node}); return id[node]; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n, m; cin >> n >> m; vector> edge; for (int i = 1; i <= m; i++) { int x, y; cin >> x >> y; edge.push_back({x, y}); } // solve Solution solution; auto result = solution.solve(n, edge); // output for (auto &it : result) { if (it.size() != 2) { cout << ""__INVALID__""; return 0; } if (it[0] > it[1]) swap(it[0], it[1]); } sort(result.begin(), result.end()); for (auto &it : result) { cout << it[0] << ' ' << it[1] << ' '; } return 0; } ",graph,easy 346,"You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules: The chosen integers have to be in the range [1, n]. Each integer can be chosen at most once. The chosen integers should not be in the array banned. The sum of the chosen integers should not exceed maxSum. Return the maximum number of integers you can choose following the mentioned rules. solution main function ```cpp class Solution { public: int solve(vector& banned, int n, int maxSum) { } }; ``` Example 1: Input: banned = [1,6,5], n = 5, maxSum = 6 Output: 2 Example 2: Input: banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 Output: 0 Constraints: 1 <= banned.length <= @data 1 <= banned[i], n <= @data 1 <= maxSum <= @data^2 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& banned, int n, int maxSum) { sort(banned.begin(), banned.end()); int sum = 0, res = 0, it = 0, len = banned.size(); for (int i = 1; i <= n; i++) { if (it < len && banned[it] == i) { while (it < len && banned[it] == i) { it++; } } else { sum += i; if (sum <= maxSum) { res++; } else { return res; } } } return res; } int solve2(vector& banned, int n, int maxSum) { long long sum = 0; int res = 0; int m = (int)banned.size(); for (int i = 1; i <= n; ++i) { bool isBanned = false; for (int j = 0; j < m; ++j) { if (banned[j] == i) { isBanned = true; break; } } if (isBanned) continue; if (sum + i <= (long long)maxSum) { sum += i; ++res; } else { return res; } } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,mx; cin>>n>>m>>mx; vector s; for(int i=1,x;i<=m;i++) { cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,n,mx); // output cout< using namespace std; class Solution { public: int solve1(int &n, string &a, string &b) { int la = '0', lb = '0', ans = 0; for (int i = 0; i < n; ++i) { if (b[i] == '1' && (lb == '1' || a[i] == '0')) { ++ans; lb = b[i] = '0'; } if (a[i] == '1' && la == '1') { ++ans; la = a[i] = '0'; } la = b[i]; lb = a[i]; } return ans; } int solve2(int &n, string &a, string &b) { int ans = 0; for (int i = 0; i < n; ++i) { if (b[i] == '1') { if (a[i] == '0') { ++ans; } else if (i > 0 && a[i - 1] == '1') { ++ans; a[i - 1] = '0'; } else if (i + 1 < n && a[i + 1] == '1') { ++ans; a[i + 1] = '0'; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string a, b; cin >> a >> b; // solve Solution solution; auto result = solution.solve(n, a, b); // output cout << result << ""\n""; return 0; }","search,dp,graph",easy 348,"Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 12 Output: 3 Example 2: Input: n = 13 Output: 2 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool isPerfectSquare(int x) { int y = sqrt(x); return y * y == x; } bool checkAnswer4(int x) { while (x % 4 == 0) { x /= 4; } return x % 8 == 7; } int solve1(int n) { if (isPerfectSquare(n)) { return 1; } if (checkAnswer4(n)) { return 4; } for (int i = 1; i * i <= n; i++) { int j = n - i * i; if (isPerfectSquare(j)) { return 2; } } return 3; } int solve2(int n) { if (isPerfectSquare(n)) { return 1; } int limit = (int)std::sqrt((double)n); for (int i = 1; i <= limit; ++i) { int r = n - i * i; if (r >= 0 && isPerfectSquare(r)) { return 2; } } for (int i = 1; i <= limit; ++i) { int rem_i = n - i * i; if (rem_i < 0) break; int limit_j = (int)std::sqrt((double)rem_i); for (int j = 1; j <= limit_j; ++j) { int rem = rem_i - j * j; if (rem > 0 && isPerfectSquare(rem)) { return 3; } } } return 4; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< using namespace std; class Solution { private: typedef long long ll; static const int MAXN = 10010; static const int MOD = 998244353; struct mint { int x; mint(void) : x(0) {} mint(int _x) : x(_x) {} mint operator + (int ot) const { return x+ot>=Solution::MOD ? x+ot-Solution::MOD : x+ot; } mint operator - (void) const { return x ? Solution::MOD-x : 0; } mint operator - (int ot) const { return x < ot ? x+Solution::MOD-ot : x-ot; } mint operator * (int ot) const { return (int)(1ll*x*ot%Solution::MOD); } mint operator += (int ot) { return *this = *this + ot; } mint operator -= (int ot) { return *this = *this - ot; } mint operator *= (int ot) { return *this = *this * ot; } operator int(void) const { return x; } }; static inline mint mpow(mint a, ll b) { mint ret=1; while(b) { if(b&1) ret=ret*a; a=a*a; b>>=1; } return ret; } static inline mint inv(mint x) { return mpow(x, Solution::MOD-2); } inline static mint fac[MAXN+10], ifac[MAXN+10], invInt[MAXN+10]; inline static bool fac_inited = false; static inline void ensure_fac() { if (fac_inited) return; fac[0]=1; for(int i=1; i<=MAXN; i++) fac[i]=fac[i-1]*i; ifac[MAXN]=inv(fac[MAXN]); for(int i=MAXN; i>=1; i--) ifac[i-1]=ifac[i]*i; invInt[0] = 0; invInt[1] = 1; for (int i=2;i<=MAXN;i++) invInt[i] = fac[i-1]*ifac[i]; fac_inited = true; } static inline mint ncr(int n ,int r) { if(0<=r && r<=n) return fac[n]*ifac[n-r]*ifac[r]; return 0; } static inline mint sumC_range(int m, int L, int R) { if (L>R) return 0; if (L<0) L=0; if (R>m) R=m; if (L>R) return 0; mint cur = ncr(m, L); mint sum = cur; for (int j=L; jR) return 0; if (L<0) L=0; if (R>m) R=m; if (L>R) return 0; mint base = sumC_range(m, L, R); int loBad = max(L, m - K + 1); int hiBad = min(R, K - 1); if (loBad <= hiBad) { mint badSum = sumC_range(m, loBad, hiBad); int cnt = hiBad - loBad + 1; mint add = (int)cnt; add *= (int)ncr(m, K); base += (int)add; base += (Solution::MOD - (int)badSum); } return base; } static inline mint f(int x, int y, int K) { if(x<0 || y<0) return 0; if(K>x+y) return 0; if(x>=K || y>=K) return ncr(x+y, x); return ncr(x+y, K); } static inline mint g(int x, int y, int X, int Y, int Z, int K) { if(x<0 || y<0) return 0; if(K-X<=x || K-Y+Z<=y) return ncr(x+y, x); if(K-X>x+y) return 0; return ncr(x+y, K-X); } public: long long solve(int &X, int &Y, int &K, string &S) { ensure_fac(); const int n = X + Y; auto C = [&](int x, int y)->mint { if (x >= 0 && y >= 0 && x >= y) return ncr(x, y); return 0; }; auto f_bin = [&](int a, int b, int c)->mint { if (a < 0 || b < 0) return 0; if (c <= max(a, b)) return ncr(a + b, a); return ncr(a + b, c); }; auto g_bin = [&](int a, int b, int c)->mint { return ncr(a + b, a) - (int)f_bin(a, b, c); }; vector P((X + 2) * (Y + 2), 0); auto pid = [&](int i, int j)->int { return i * (Y + 2) + j; }; auto getP = [&](int i, int j)->mint { if (i < 0 || i > X + 1 || j < 0 || j > Y + 1) return 0; return P[pid(i, j)]; }; for (int i = 0; i <= X + 1; ++i) { for (int j = 0; j <= Y + 1; ++j) { P[pid(i, j)] = f_bin(i, j, K); if (i > 0 && j < Y) P[pid(i, j)] += (int)getP(i - 1, j + 1); } } auto solve_prefix = [&](int m, int flip_pos)->mint { int nx = X, ny = Y; for (int i = 0; i < m; ++i) { char ch = (i == flip_pos ? '1' : S[i]); if (ch == '0') nx--; else ny--; } if (nx < 0 || ny < 0) return 0; int ptr = -1; int c0 = 0, c1 = 0, lis = 0; for (int i = 0; i < m; ++i) { char ch = (i == flip_pos ? '1' : S[i]); if (ch == '0') { c0++; if (lis < c0) lis = c0; } else { lis++; c1++; } if (lis == K && ptr == -1) { ptr = i; c0 = c1 = lis = 0; } } if (ptr == -1) { mint res = 0; int total_rem = n - m - 1; int l = 1; for (int r = total_rem; r >= K; --r, ++l) { if (l + lis < K) continue; if (l - K + lis >= K - c0) continue; int L_c0 = l - K + lis; int L_c1 = l - L_c0; res += g_bin(L_c0, L_c1 - 1, K - c0) * (int)f_bin(nx - L_c0, ny - L_c1, K); L_c0 = K - c0; L_c1 = l - L_c0; res += g_bin(L_c0 - 1, L_c1, K - c0) * (int)f_bin(nx - L_c0, ny - L_c1, K); int pL = l - K + lis + 1, pR = K - c0 - 1; if (pL < l - ny) pL = l - ny; if (pR > nx) pR = nx; if (pL <= pR) { mint ways = f_bin(pL, l - pL, K - c0); ways += (int)Solution::MOD - (int)f_bin(pL - 1, l - pL, K - c0); ways += (int)Solution::MOD - (int)f_bin(pL, l - pL - 1, K - c0); int npL = nx - pR, npR = nx - pL; mint right_tot = getP(npR, r - npR); if (npL > 0) right_tot += (int)Solution::MOD - (int)getP(npL - 1, r - npL + 1); res += right_tot * (int)ways; } } return res; } return (lis + ny >= K) ? ncr(nx + ny, nx) : f_bin(nx, ny, K - c0); }; mint ans = 0; for (int p = 0; p < n; ++p) { if (S[p] == '0') { ans += (int)solve_prefix(p + 1, p); } } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int x, y, k; cin >> x >> y >> k; string a; cin >> a; // solve Solution solution; auto result = solution.solve(x, y, k, a); // output cout << result << ""\n""; return 0; }","string,dp",hard 350,"# Problem Statement The heroic outlaw Robin Hood is famous for taking from the rich and giving to the poor. Robin encounters $n$ people starting from the $1$-st and ending with the $n$-th. The $i$-th person has $a_i$ gold. If $a_i \ge k$, Robin will take all $a_i$ gold, and if $a_i=0$, Robin will give $1$ gold if he has any. Robin starts with $0$ gold. Find out how many people Robin gives gold to. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &k, vector &a) { // write your code here } }; ``` where: - return:the number of people that will get gold from Robin Hood. # Example 1: - Input: n = 2, k = 2, a = [2, 0] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $1 \leq k \leq 1000$ - $0 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &k, vector &a) { int cnt = 0, sum = 0; for (int i = 0; i < n; i++) { int x = a[i]; if (x >= k) sum += x; else if (x == 0 && sum) cnt++, sum--; } return cnt; } int solve2(int &n, int &k, vector &a) { long long sum = 0; int cnt = 0; int i = 0; while (i < n) { int x = a[i]; if (x >= k) { sum += x; } else if (x == 0) { if (sum > 0) { cnt++; sum--; } } i++; } return cnt; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, x; cin >> n >> x; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, x, a); // output cout << result << ""\n""; return 0; }",math,easy 351,"Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. solution main function ```cpp class Solution { public: bool solve(string s, vector& wordDict) { } }; ``` Example 1: Input: s = ""leetcode"", wordDict = [""leet"",""code""] Output: 1 Example 2: Input: s = ""applepenapple"", wordDict = [""apple"",""pen""] Output: 1 Constraints: 1 <= s.length <= @data 1 <= wordDict.length <= @data 1 <= wordDict[i].length <= 20 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve(string s, vector& wordDict) { vector dp(s.size() + 1, false); dp[0] = true; for (int i = 1; i < dp.size(); i++) { for (auto w : wordDict) { int len = w.size(); if (i - len >= 0) { if (dp[i - len] && s.substr(i - len, len) == w) { dp[i] = true; break; } } } } return dp.back(); } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector dic; string s; for(int i=1;i<=n;i++) { cin>>s; dic.push_back(s); } cin>>s; // solve Solution solution; int result = solution.solve(s,dic); // output cout< &u, vector &v, vector &w) { // write your code here } }; ``` where: - `n`: number of vertices - `m`: number of edges - `u[i], v[i]`: endpoints of the i-th edge (1-indexed vertices) - `w[i]`: weight of the i-th edge - return: the minimum total cost # Example: - Input: ``` n = 4, m = 3 edges: 1 2 3 1 3 2 1 4 1 ``` - Output: ``` 8 ``` # Constraints: - $1 \leq n \leq @data$ - $0 \leq m \leq @data$ - $1 \leq u[i], v[i] \leq n$ - $1 \leq w[i] \leq 10^9$ - The graph is connected (except possibly when `n = 1`, `m = 0`) - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1000, 500, 250], [8000, 4000, 2000], [64000, 32000, 16000]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &m, vector &u, vector &v, vector &w) { if (m == 0) { return 0LL; } long long ans = 0; vector deg(n, 0); for (int i = 0; i < m; i++) { --u[i]; --v[i]; deg[u[i]] += 1; deg[v[i]] += 1; ans += (long long) w[i]; } struct DSU { vector p; explicit DSU(int n) : p(n) { iota(p.begin(), p.end(), 0); } int get(int x) { return (x == p[x] ? x : (p[x] = get(p[x]))); } void unite_force(int x, int y) { x = get(x); y = get(y); if (x != y) p[x] = y; } }; int tot = n + m; vector> tree(tot); DSU dsu(n); vector rt(n); iota(rt.begin(), rt.end(), 0); for (int i = 0; i < m; i++) { int x = dsu.get(u[i]); int y = dsu.get(v[i]); int cur = n + i; if (x == y) { tree[rt[x]].push_back(cur); tree[cur].push_back(rt[x]); rt[x] = cur; } else { tree[rt[x]].push_back(cur); tree[cur].push_back(rt[x]); tree[rt[y]].push_back(cur); tree[cur].push_back(rt[y]); dsu.unite_force(x, y); rt[y] = cur; } } int root = n + m - 1; vector parent(tot, -1); vector order; order.reserve(tot); queue q; q.push(root); parent[root] = -1; while (!q.empty()) { int vtx = q.front(); q.pop(); order.push_back(vtx); for (int to : tree[vtx]) { if (to == parent[vtx]) continue; parent[to] = vtx; q.push(to); } } const int INF = 1000000007; vector up(tot, INF); for (int vtx : order) { if (vtx >= n) { up[vtx] = min(up[vtx], w[vtx - n]); } if (parent[vtx] != -1) { up[vtx] = min(up[vtx], up[parent[vtx]]); } } vector cnt(tot, 0); for (int i = 0; i < n; i++) { if (deg[i] % 2 == 1) cnt[i] = 1; } for (int i = (int) order.size() - 1; i >= 0; i--) { int vtx = order[i]; ans += (long long) up[vtx] * (cnt[vtx] / 2); if (parent[vtx] != -1) { cnt[parent[vtx]] += cnt[vtx] % 2; } } return ans; } long long solve2(int &n, int &m, vector &u, vector &v, vector &w) { if (m == 0) return 0LL; long long base = 0; for (int i = 0; i < m; i++) { --u[i]; --v[i]; base += (long long) w[i]; } vector deg(n, 0); for (int i = 0; i < m; i++) { deg[u[i]] ^= 1; deg[v[i]] ^= 1; } struct DSU { vector p; explicit DSU(int n) : p(n) { iota(p.begin(), p.end(), 0); } int find(int x) { while (x != p[x]) x = p[x] = p[p[x]]; return x; } void unite(int a, int b) { a = find(a); b = find(b); if (a != b) p[a] = b; } }; int tot = n + m; vector> g(tot); DSU dsu(n); vector top(n); iota(top.begin(), top.end(), 0); for (int i = 0; i < m; i++) { int x = dsu.find(u[i]); int y = dsu.find(v[i]); int cur = n + i; if (x == y) { g[top[x]].push_back(cur); g[cur].push_back(top[x]); top[x] = cur; } else { g[top[x]].push_back(cur); g[cur].push_back(top[x]); g[top[y]].push_back(cur); g[cur].push_back(top[y]); dsu.unite(x, y); int r = dsu.find(x); top[r] = cur; } } int root = n + m - 1; vector parent(tot, -1), order; order.reserve(tot); queue q; q.push(root); parent[root] = -1; while (!q.empty()) { int vtx = q.front(); q.pop(); order.push_back(vtx); for (int to : g[vtx]) if (to != parent[vtx]) { parent[to] = vtx; q.push(to); } } const int INF = 1000000007; vector up(tot, INF); for (int vtx : order) { if (vtx >= n) up[vtx] = min(up[vtx], w[vtx - n]); if (parent[vtx] != -1) up[vtx] = min(up[vtx], up[parent[vtx]]); } vector cnt(tot, 0); for (int i = 0; i < n; i++) cnt[i] = deg[i]; long long ans = base; for (int i = (int)order.size() - 1; i >= 0; i--) { int vtx = order[i]; ans += (long long) (cnt[vtx] / 2) * (long long) up[vtx]; if (parent[vtx] != -1) cnt[parent[vtx]] += cnt[vtx] & 1; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; vector u(m), v(m), w(m); for (int i = 0; i < m; i++) { cin >> u[i] >> v[i] >> w[i]; } // solve Solution solution; auto result = solution.solve(n, m, u, v, w); // output cout << result << ""\n""; return 0; }","graph,greedy",hard 353,"# Problem Statement The square still has a rectangular shape of $n \times m$ meters. However, the picture is about to get more complicated now. Let $a_{i,j}$ be the $j$-th square in the $i$-th row of the pavement. You are given the picture of the squares: - if $a_{i,j} = $ ""\*"", then the $j$-th square in the $i$-th row should be **black**; - if $a_{i,j} = $ ""."", then the $j$-th square in the $i$-th row should be **white**. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles: - $1 \times 1$ tiles — each tile costs $x$ burles and covers exactly $1$ square; - $1 \times 2$ tiles — each tile costs $y$ burles and covers exactly $2$ adjacent squares of the **same row**. **Note that you are not allowed to rotate these tiles or cut them into $1 \times 1$ tiles.** **You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.** What is the smallest total price of the tiles needed to cover all the white squares? The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &m, int &x, int &y, vector> &a) { // write your code here } }; ``` where: - return: the smallest total price of the tiles needed to cover all the white squares in burles. # Example 1: - Input: n = 1, m = 1, x = 10, y = 1 a = ""."" - Output: 10 # Constraints: - $1 \leq n * m \leq @data$ - $1 \leq x, y \leq 10^3$ - $a[i][j] \in \{'.', '*'\}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &m, int &x, int &y, vector> &a) { int ans = 0; y = min(y, 2 * x); for (int i = 0; i < n; ++i) { for (int l = 0, r; l < m;) { if (a[i][l] == '*') ++l; else { for (r = l; r < m && a[i][r] == '.'; ++r) ; ans += (r - l) / 2 * y + (r - l) % 2 * x; l = r; } } } return ans; } int solve2(int &n, int &m, int &x, int &y, vector> &a) { long long ans = 0; int yy = y; if (yy > 2 * x) yy = 2 * x; for (int i = 0; i < n; ++i) { for (int j = 0; j < m;) { if (a[i][j] == '*') { ++j; } else { if (j + 1 < m && a[i][j + 1] == '.') { ans += yy; j += 2; } else { ans += x; ++j; } } } } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n,m,x,y; cin >> n >> m >> x >> y; vector> a(n, vector(m)); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) cin >> a[i][j]; // solve Solution solution; auto result = solution.solve(n, m, x, y, a); // output cout << result << ""\n""; return 0; }","greedy,dp,two_pointers",medium 354,"You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands. solution main function ```cpp class Solution { public: int solve(vector>& grid1, vector>& grid2) { // write your code here } }; ``` Example 1: Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] Output: 3 Example 2: Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] Output: 2 Constraints: m == grid1.length == grid2.length n == grid1[i].length == grid2[i].length 1 <= m, n <= @data grid1[i][j] and grid2[i][j] are either 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 500]",1000,"[[100, 78, 64], [800, 625, 375], [6400, 5000, 3000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& grid1, vector>& grid2) { int m = grid1.size(), n = grid1[0].size(); int count = 0; auto dfs = [&](int x, int y, auto& dfs) -> bool { if (x < 0 || y < 0 || x >= m || y >= n ) { return true; } if( grid2[x][y] == 0) return true; grid2[x][y] = 0; bool isSubIsland = grid1[x][y] == 1; isSubIsland &= dfs(x + 1, y, dfs); isSubIsland &= dfs(x - 1, y, dfs); isSubIsland &= dfs(x, y + 1, dfs); isSubIsland &= dfs(x, y - 1, dfs); return isSubIsland; }; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid2[i][j] == 1) { if (dfs(i, j, dfs)) { ++count; } } } } return count; } int solve2(vector>& grid1, vector>& grid2) { int m = (int)grid1.size(); if (m == 0) return 0; int n = (int)grid1[0].size(); int count = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid2[i][j] == 1) { bool ok = (grid1[i][j] == 1); grid2[i][j] = 2; bool grew = true; while (grew) { grew = false; for (int x = 0; x < m; ++x) { for (int y = 0; y < n; ++y) { if (grid2[x][y] == 1) { if ((x > 0 && grid2[x - 1][y] == 2) || (x + 1 < m && grid2[x + 1][y] == 2) || (y > 0 && grid2[x][y - 1] == 2) || (y + 1 < n && grid2[x][y + 1] == 2)) { grid2[x][y] = 2; grew = true; if (grid1[x][y] == 0) ok = false; } } } } } if (ok) ++count; for (int x = 0; x < m; ++x) { for (int y = 0; y < n; ++y) { if (grid2[x][y] == 2) grid2[x][y] = 0; } } } } } return count; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > g1,g2; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } g1.push_back(temp); } for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } g2.push_back(temp); } // solve Solution solution; auto result = solution.solve(g1,g2); // output cout<& cookies, int k) { } }; ``` Example: Input: cookies = [1,2,3], k = 2 Output: 3 Explanation: Give bags [1,2] to one child and [3] to the other child. Constraints: 2 <= cookies.length <= 8 1 <= cookies[i] <= @data 2 <= k <= cookies.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[4, 6, 8]",1000,"[[400, 64, 64], [3200, 160, 80], [25600, 1280, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int foo; int helper(vector& cookies, int k, vector& children, int index) { if (index == cookies.size()) { foo = min(foo, *max_element(children.begin(), children.end())); return foo; } int ans = INT_MAX; for (int i = 0; i < k; ++i) { children[i] += cookies[index]; if (children[i] < foo) ans = min(ans, helper(cookies, k, children, index + 1)); children[i] -= cookies[index]; if (children[i] == 0) break; } return ans; } int solve1(vector& cookies, int k) { foo = INT_MAX; vector children(k, 0); helper(cookies, k, children, 0); return foo; } int solve2(vector& cookies, int k) { int n = (int)cookies.size(); if (k >= n) { long long mx = 0; for (int i = 0; i < n; ++i) if (mx < cookies[i]) mx = cookies[i]; if (mx > INT_MAX) return INT_MAX; return (int)mx; } long long totalStates = 1; for (int i = 0; i < n; ++i) totalStates *= (long long)k; long long sumAll = 0; for (int i = 0; i < n; ++i) sumAll += (long long)cookies[i]; long long best = sumAll; for (long long m = 0; m < totalStates; ++m) { long long maxSum = 0; bool prune = false; for (int j = 0; j < k; ++j) { long long tmp = m; long long s = 0; for (int t = 0; t < n; ++t) { int d = (int)(tmp % k); if (d == j) s += (long long)cookies[t]; if (s >= best) { maxSum = best; prune = true; break; } tmp /= k; } if (s > maxSum) maxSum = s; if (prune) break; } if (!prune && maxSum < best) best = maxSum; } if (best > INT_MAX) return INT_MAX; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,k); // output cout << result << ""\n""; // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - `n`: length of the sequence a - `a`: array of positive integers - return: the minimal total cost f(a) # Example 1: - Input: ``` n = 5 a = [3, 1, 4, 1, 5] ``` - Output: ``` 2 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^{18}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 400000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve(int &n, vector &a) { vector seq; seq.reserve(n); for (int i = 0; i < n; i++) { while (!seq.empty() && a[i] <= seq.back()) seq.pop_back(); seq.push_back(a[i]); } const int m = (int)seq.size(); const int INF = 1e9; vector dp(m + 1, INF); dp[0] = 0; for (int i = 0; i < m; i++) { for (int cost = 1; cost <= 3; cost++) { long long limit = seq[i] * 1ll * cost; int p = (int)(upper_bound(seq.begin(), seq.end(), limit) - seq.begin()); dp[p] = min(dp[p], dp[i] + cost); } } return dp[m]; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,dp",hard 357,"# Problem Statement Even in university, students need to relax. That is why Sakurakos teacher decided to go on a field trip. It is known that all of the students will be walking in one line. The student with index $i$ has some topic of interest which is described as $a_i$. As a teacher, you want to minimise the disturbance of the line of students. The disturbance of the line is defined as the number of neighbouring people with the same topic of interest. In other words, disturbance is the number of indices $j$ ($1 \le j < n$) such that $a_j = a_{j + 1}$. In order to do this, you can choose index $i$ ($1\le i\le n$) and swap students at positions $i$ and $n-i+1$. You can perform any number of swaps. Your task is to determine the minimal amount of disturbance that you can achieve by doing the operation described above any number of times. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - the return value is the minimal amount of disturbance that you can achieve by doing the operation described above any number of times # Example 1: - Input: n = 5 a = [1, 1, 1, 2, 3] - Output: 1 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int ans = 0; for (int i = 1; i <= n - 1 - i; i++) { int x = a[i]; int y = a[n - 1 - i]; int z = a[i - 1]; int w = a[n - i]; ans += min((x == z) + (y == w), (x == w) + (y == z)); } if (n % 2 == 0) ans += (a[n / 2 - 1] == a[n / 2]); return ans; } int solve2(int &n, vector &a) { int m = n / 2; int add = 0; if (n % 2 == 0) { add += (a[m - 1] == a[m]); } else { add += (a[m] == a[m - 1]); add += (a[m] == a[m + 1]); } if (m <= 1) return add; int dp0 = 0, dp1 = 0; for (int j = 1; j <= m - 1; ++j) { int Lp = a[j - 1]; int Rp = a[n - j]; int L = a[j]; int R = a[n - 1 - j]; int c00 = (Lp == L) + (Rp == R); int c01 = (Lp == R) + (Rp == L); int c10 = (Rp == L) + (Lp == R); int c11 = (Rp == R) + (Lp == L); int ndp0 = min(dp0 + c00, dp1 + c10); int ndp1 = min(dp0 + c01, dp1 + c11); dp0 = ndp0; dp1 = ndp1; } return min(dp0, dp1) + add; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,greedy,two_pointers",hard 358,"You are given two integers n and x. You have to construct an array of positive integers nums of size n where for every 0 <= i < n - 1, nums[i + 1] is greater than nums[i], and the result of the bitwise AND operation between all elements of nums is x. Return the minimum possible value of nums[n - 1]. solution main function ```cpp class Solution { public: long long solve(int n, int x) { } }; ``` Example 1: Input: n = 3, x = 4 Output: 6 Example 2: Input: n = 2, x = 7 Output: 15 Constraints: 1 <= n, x <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 100000, 100000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: long long solve1(int n, int x) { long long result = x, mask; --n; for (mask = 1; n > 0; mask <<= 1) { if ((mask & x) == 0) { result |= (n & 1) * mask; n >>= 1; } } return result; } long long solve2(int n, int x) { unsigned long long ux = (unsigned long long)x; unsigned long long curr = ux; for (int i = 1; i < n; ++i) { unsigned long long t = curr + 1ULL; while ((t & ux) != ux) { ++t; } curr = t; } return (long long)curr; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,x; cin>>n>>x; // solve Solution solution; auto result = solution.solve(n,x); // output cout << result << ""\n""; return 0; }",math,hard 359,"# Problem Statement Today, Sakurako was studying arrays. An array $a$ of length $n$ is considered good if and only if: - the array $a$ is increasing, meaning $a_{i - 1} < a_i$ for all $2 \le i \le n$; - the differences between adjacent elements are increasing, meaning $a_i - a_{i-1} < a_{i+1} - a_i$ for all $2 \le i < n$. Sakurako has come up with boundaries $l$ and $r$ and wants to construct a good array of maximum length, where $l \le a_i \le r$ for all $a_i$. Help Sakurako find the maximum length of a good array for the given $l$ and $r$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &l, int &r) { // write your code here } }; ``` where: - return:the length of the longest good array Sakurako can form given l and r. # Example 1: - Input: l = 1, r = 2 - Output: 2 # Constraints: - $1 \leq l \leq r \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 1000000, 1000000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &l, int &r) { int n = r - l; int a = sqrt(2 * n); while (a * (a + 1) / 2 <= n) { a++; } return a; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int l, r; cin >> l >> r; // solve Solution solution; auto result = solution.solve(l, r); // output cout << result << ""\n""; return 0; }",math,easy 360,"# Problem Statement Given $N$, $V$, an array $v$ of length $N$ representing the volume of items, and an array $w$ of length $N$ representing the value of items: There are $N$ items and a backpack with a capacity of $V$. Each item can only be used once. The $i$-th item has a volume of $v[i]$ and a value of $w[i]$. Determine which items to put in the backpack such that the **total volume does not exceed the backpack's capacity** and the **total value is maximized**. Return the maximum total value. The solution's main function is: ```cpp class Solution { public: int solve(int &N, int &V, vector &v, vector &w) { // write your code here } }; ``` where: - `N` is the number of items, - `V` is the capacity of the backpack, - `v` is the array of item volumes, - `w` is the array of item values. # Example 1 - Input: N = 3 V = 4 v = [4, 3, 1] w = [1, 2, 1] - Output: 3 # Constraints: - $1 \leq N, V, v[i], w[i] \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve(int &N, int &V, vector &v, vector &w) { vectordp(V+1); for(int i=0;i=v[i];j--) dp[j]=max(dp[j],dp[j-v[i]]+w[i]); return dp[V]; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int N, V; cin >> N >> V; vector v, w; for (int i = 0; i < N; i++) { int x; cin >> x; v.push_back(x); } for (int i = 0; i < N; i++) { int x; cin >> x; w.push_back(x); } // solve Solution solution; auto result = solution.solve(N, V, v, w); // output cout << result << ""\n""; return 0; }",dp,easy 361,"# Problem Statement: You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved. Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by **one or several** messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions. Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. **It is guaranteed that the dialog begins with the question of the client.** You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, string &s) { // write your code here } }; ``` Where: - `n` is an integer representing the number of messages in the conversation. - `s` is a string where each character represents the type of a message: - `'Q'` for a customer query. - `'A'` for a manager's response. - The return value is a string: `""YES""` if the dialog may correspond to the rules of work, and `""NO""` otherwise. # Example 1: - Input: n = 3 s = ""QAA"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, string &s) { int cur = 0; for (int i=n-1;i>=0;i--) { if (s[i] == 'A') cur++; else cur--; if (cur < 0) return ""NO""; } return ""YES""; } string solve2(int &n, string &s) { for (int i = 0; i < n; ++i) { long long a = 0, q = 0; for (int j = i; j < n; ++j) { if (s[j] == 'A') a++; else q++; } if (a < q) return ""NO""; } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","greedy,math",medium 362,"# Problem Statement There are $n$ flowers in a row, the $i$-th of them initially has a positive height of $h_i$ meters. Every second, the wind will blow from the left, causing the height of some flowers to decrease. Specifically, every second, for each $i$ from $1$ to $n$, in this order, the following happens: - If $i = n$ or $h_i > h_{i + 1}$, the value of $h_i$ changes to $\max(0, h_i - 1)$. How many seconds will pass before $h_i=0$ for all $1 \le i \le n$ for the first time? The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &h) { // write your code here } }; ``` where: - return: the number of seconds that will pass before hi=0 for all 1≤i≤n. # Example 1: - Input: n = 3 h = [1, 1, 2] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq h[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &h) { int ans = 0; for (int i = n - 1; i >= 0; i--) { ans = max(ans, i + h[i]); } return ans; } int solve2(int &n, vector &h) { long long seconds = 0; long long pos = 0; for (int i = 0; i < n; i++) if (h[i] > 0) ++pos; while (pos > 0) { ++seconds; for (int i = 0; i < n; i++) { if (i == n - 1 || h[i] > h[i + 1]) { if (h[i] > 0) { --h[i]; if (h[i] == 0) --pos; } } } } if (seconds > INT_MAX) return INT_MAX; return (int)seconds; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","dp,sort",medium 363,"The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. For example, the beauty of ""abaacc"" is 3 - 1 = 2. Given a string s, return the sum of beauty of all of its substrings. solution main function ```cpp class Solution { public: int solve(string s) { } }; ``` Example 1: Input: s = ""aabcb"" Output: 5 Example 2: Input: s = ""aabcbaa"" Output: 17 Constraints: 1 <= s.length <= @data s consists of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: paircalMinAndMax(int freq[]){ int minCnt=INT_MAX; int maxCnt=0; for(int i=0;i<26;++i){ if(freq[i]!=0){ minCnt=min(minCnt,freq[i]); maxCnt=max(maxCnt,freq[i]); } } return {maxCnt,minCnt}; } int solve1(string s) { int sum=0; for(int i=0;icnt=calMinAndMax(freq); int maxCnt=cnt.first; int minCnt=cnt.second; sum+=(maxCnt-minCnt); } } return sum; } int solve2(string s) { long long sum = 0; int n = (int)s.size(); for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { int maxCnt = 0; int minCnt = INT_MAX; for (int k = i; k <= j; ++k) { bool seen = false; for (int p = i; p < k; ++p) { if (s[p] == s[k]) { seen = true; break; } } if (seen) continue; int cnt = 0; for (int l = i; l <= j; ++l) { if (s[l] == s[k]) ++cnt; } if (cnt > maxCnt) maxCnt = cnt; if (cnt < minCnt) minCnt = cnt; } sum += (long long)(maxCnt - minCnt); } } if (sum > INT_MAX) return INT_MAX; if (sum < INT_MIN) return INT_MIN; return (int)sum; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout<>& grid) { } }; ``` Example 1: Input: grid = [[1,0,0],[0,0,0],[0,0,1]] Output: 2 Example 2: Input: grid = [[0,1],[0,1],[0,0]] Output: 1 Constraints: m == grid.length n == grid[i].length 1 <= m * n <= @data 0 <= grid[i][j] <= 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector>& grid){ int m=grid.size(); int n=grid[0].size(); int k=0; for(int i=0;i>& grid){ int m = (int)grid.size(); int n = (int)grid[0].size(); long long rowCost = 0; for(int i = 0; i < m; ++i){ int l = 0, r = n - 1; while(l < r){ if(grid[i][l] != grid[i][r]) ++rowCost; ++l; --r; } } long long colCost = 0; for(int j = 0; j < n; ++j){ int u = 0, d = m - 1; while(u < d){ if(grid[u][j] != grid[d][j]) ++colCost; ++u; --d; } } long long ans = rowCost < colCost ? rowCost : colCost; if(ans > INT_MAX) return INT_MAX; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > s; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< using namespace std; class Solution { public: string solve1(int &n, string &s) { int cnt = 0; for (auto x : s) if (x == 'U') cnt++; return (cnt % 2) ? ""YES"" : ""NO""; } string solve2(int &n, string &s) { int m = n; long long moves = 0; while (true) { int idx = -1; for (int i = 0; i < n; ++i) if (s[i] == 'U') { idx = i; break; } if (idx == -1) break; int before = m; s[idx] = '#'; --m; ++moves; if (before >= 3) { int left = idx; do { left = (left - 1 + n) % n; } while (s[left] == '#'); int right = idx; do { right = (right + 1) % n; } while (s[right] == '#'); s[left] = (s[left] == 'U') ? 'D' : 'U'; s[right] = (s[right] == 'U') ? 'D' : 'U'; } } return (moves % 2) ? ""YES"" : ""NO""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }",greedy,medium 366,"# Problem Statement After a trip with Sakurako, Kousuke was very scared because he forgot about his programming assignment. In this assignment, the teacher gave him an array $a$ of $n$ integers and asked him to calculate the number of **non-overlapping** segments of the array $a$, such that each segment is considered beautiful. A segment $[l,r]$ is considered beautiful if $a_l + a_{l+1} + \dots + a_{r-1} + a_r=0$. For a fixed array $a$, your task is to compute the maximum number of non-overlapping beautiful segments. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - the return value is the maximum value of the same number at the end # Example 1: - Input: n = 5 a = [2, 1, -3, 2, 1] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $-10^4 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 160, 80], [6400, 1280, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { set s; s.insert(0); int sum = 0, ans = 0; for (int i = 0; i < n; i++) { sum += a[i]; ans += s.count(sum) ? (s.clear(), s.insert(0), sum = 0, 1) : 0; s.insert(sum); } return ans; } int solve2(int &n, vector &a) { int ans = 0; int s = 0; for (int i = 0; i < n; ++i) { long long sum = 0; bool found = false; for (int k = i; k >= s; --k) { sum += (long long)a[k]; if (sum == 0) { found = true; break; } } if (found) { ++ans; s = i + 1; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","data_structures,dp,greedy,math",easy 367,"There is A crossing pawn at $A$on the board that needs to go to the target $B$point. Pawn walking rules: can go down, or right. At the same time, there is an opposing horse at the $C$point on the board, and the point where the horse is located and all the points reachable by the jump step are called the control point of the opposing horse. Therefore, it is called ""horse blocking the river and pawn"". The board is represented by coordinates, $A$point $(0, 0)$, $B$point $(n, m)$, and the same horse position coordinates need to be given. Now you are asked to calculate the number of paths that the pawn can take from point $A$to point $B$, assuming that the position of the horse is fixed, not that the pawn moves one step at a time. solution main function ```cpp class Solution { public: long long solve(int n, int m, int x, int y) { // write your code here } }; ``` Pass in parameters: Four integers, $n,m,x,y$, represent the coordinates of point B and horse, respectively. Return parameters: An integer indicating the number of all paths. Example 1: Input: n=6,m=6,x=3,y=3 Output: 6 Constraints: 0 using namespace std; #include using namespace std; class Solution { public: long long solve1(int n, int m, int x, int y) { int bx = n + 2, by = m + 2, mx = x + 2, my = y + 2; vector f(by + 1, 0); f[2] = 1; auto check = [&](int i, int j) { if (i == mx && j == my) return true; return (abs(mx - i) + abs(my - j) == 3) && (max(abs(mx - i), abs(my - j)) == 2); }; for (int i = 2; i <= bx; i++) { for (int j = 2; j <= by; j++) { if (check(i, j)) { f[j] = 0; } else { f[j] += f[j - 1]; } } } return f[by]; } long long solve2(int n, int m, int x, int y) { auto inside = [&](long long xi, long long yi) -> bool { return xi >= 0 && xi <= n && yi >= 0 && yi <= m; }; auto comb = [&](long long N, long long K) -> __int128 { if (K < 0 || K > N) return 0; if (K == 0 || K == N) return 1; if (K > N - K) K = N - K; __int128 res = 1; for (long long i = 1; i <= K; ++i) { res = res * (N - i + 1) / i; } return res; }; auto getPoint = [&](int id) -> pair { switch (id) { case 0: return {x, y}; case 1: return {x + 1, y + 2}; case 2: return {x + 2, y + 1}; case 3: return {x + 2, y - 1}; case 4: return {x + 1, y - 2}; case 5: return {x - 1, y - 2}; case 6: return {x - 2, y - 1}; case 7: return {x - 2, y + 1}; case 8: return {x - 1, y + 2}; } return {0, 0}; }; __int128 total = 0; for (int mask = 0; mask < (1 << 9); ++mask) { int cnt = __builtin_popcount(mask); __int128 sign = (cnt % 2 == 0) ? 1 : -1; long long px[9], py[9]; int k = 0; bool invalid = false; for (int i = 0; i < 9; ++i) { if (mask & (1 << i)) { auto p = getPoint(i); if (!inside(p.first, p.second)) { invalid = true; break; } px[k] = p.first; py[k] = p.second; ++k; } } if (invalid) continue; for (int i = 0; i < k; ++i) { int best = i; for (int j = i + 1; j < k; ++j) { if (px[j] < px[best] || (px[j] == px[best] && py[j] < py[best])) best = j; } if (best != i) { swap(px[i], px[best]); swap(py[i], py[best]); } } bool chain = true; for (int i = 1; i < k; ++i) { if (py[i] < py[i - 1]) { chain = false; break; } } if (!chain) continue; __int128 ways = 1; long long prevx = 0, prevy = 0; for (int t = 0; t <= k; ++t) { long long cx = (t < k) ? px[t] : n; long long cy = (t < k) ? py[t] : m; long long dx = cx - prevx, dy = cy - prevy; if (dx < 0 || dy < 0) { ways = 0; break; } ways *= comb(dx + dy, dx); prevx = cx; prevy = cy; } total += sign * ways; } long long ans = (long long)total; return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,x,y; cin>>n>>m>>x>>y; // solve Solution solution; auto result = solution.solve(n, m, x, y); // output cout << result ; return 0; }",dp,medium 368,"You need to maintain an undirected simple graph. You are required to add and delete an edge, as well as query whether two points are connected. 0: Add an edge. It is guaranteed that it does not exist. 1: Delete an edge. It is guaranteed that it exists. 2: Query whether two points are connected. n represents the total number of nodes (1-n). edges[i] = [op, a, b], where op represents the operation, and a and b represent the two points involved in the operation. For each query with op = 2, Y or N indicate whether the two nodes are connected., store the result in a vector array and return it. solution main function ```cpp class Solution { public: vector solve(int n, vector>& edges) { } }; ``` Example 1: Input: n = 200, edges = [[2,123,127],[0,123,127],[2,123,127],[1,127,123],[2,123,127]] Output: ['N','Y','N'] Constraints: 2 <= n <= @data edges[i].size ==3 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; typedef long long ll; class Solution { public: struct MDF { int l, r, u, v; }; vector qu,qv,fa,siz; int m=0, qC = 1, mC=0; map, int> t; vector mdf; vector> his; vector ans; int F(int u) { return fa[u] == u ? u : F(fa[u]); } bool Merge(int u, int v) { u = F(u), v = F(v); if (u == v) return false; if (siz[u] < siz[v]) swap(u, v); his.push_back({ siz[u], siz[u] }); his.push_back({ fa[v], fa[v] }); siz[u] += siz[v], fa[v] = u; return true; } void Undo() { for (int i = 0; i < 2; i++) { his.back().first = his.back().second; his.pop_back(); } } void DFS(int l, int r, vector mdf) { vector ml, mr; int mid = (l + r )>> 1, mC = 0; for (auto [L, R, u, v] : mdf) { if (l >= L && r <= R) mC += Merge(u, v); else { if (L <= mid) ml.push_back({ L, R, u, v }); if (R > mid) mr.push_back({ L, R, u, v }); } } if (l == r) { ans.push_back(F(qu[l]) == F(qv[l]) ? 'Y' : 'N'); while (mC--) Undo(); return; } DFS(l, mid, ml), DFS(mid + 1, r, mr); while (mC--) Undo(); } vector solve(int n, vector>& edges) { int m=edges.size(); int lim = max(n,m); qu.resize(lim+10,0); qv.resize(lim+10,0); fa.resize(lim+10,0); siz.resize(lim+10,0); for (int i = 1; i <= n; i++) fa[i] = i, siz[i] = 1; for(auto it:edges) { int op=it[0], x=it[1], y=it[2]; if (x > y) swap(x, y); if (op == 0) t[ { x, y }] = qC; else if (op == 1) { mdf.push_back({ t[{ x, y }], qC - 1, x, y }); t.erase({ x, y }); } else { qu[qC] = x, qv[qC] = y; qC++; } } for (auto [x, y] : t) { auto [u, v] = x; mdf.push_back({ y, qC - 1, u, v }); } if (qC > 1) DFS(1, qC - 1, mdf); return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector< vector > edge; for(int i=1,x,y,z;i<=m;i++) { scanf(""%d%d%d"",&x,&y,&z); vector temp; temp.push_back(x); temp.push_back(y); temp.push_back(z); edge.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,edge); // output for(auto it:result) cout<>& edges) { // write your code here } }; ``` Example 1: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]] Output: 2 Example 2: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]] Output: 0 Constraints: 1 <= n <= @data 1 <= edges.length <= min(10^5, 3 * n * (n - 1) / 2) edges[i].length == 3 1 <= typei <= 3 1 <= ui < vi <= n All tuples (typei, ui, vi) are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int getRoot(vector& par,int x){ int root = x; while(par[root]!=root){ root = par[root]; } while(par[x]!=root){ int tmp = par[x]; par[x] = root; x = tmp; } return root; } bool merge(vector& par,int x,int y){ int _x = getRoot(par,x); int _y = getRoot(par,y); if(_x!=_y){ par[_x]=_y; return true; } return false; } int solve1(int n, vector>& edges) { vectorpar1 = vector(n+1,0); vectorpar2; int ans = 0; int cnt1 = n,cnt2; for(int i =1;i<=n;i++){ par1[i] = i; } for(int i = 0;i>& edges) { vector parent(n + 1); auto init = [&](){ for (int i = 1; i <= n; ++i) parent[i] = i; }; auto findp = [&](int x){ while (parent[x] != x) x = parent[x]; return x; }; auto mergep = [&](int a, int b){ int ra = findp(a), rb = findp(b); if (ra == rb) return false; parent[ra] = rb; return true; }; init(); int comp = n; int used3A = 0; for (size_t i = 0; i < edges.size(); ++i) { int t = edges[i][0], u = edges[i][1], v = edges[i][2]; if (t == 3) { if (mergep(u, v)) { used3A++; comp--; } } } int used1 = 0; for (size_t i = 0; i < edges.size(); ++i) { int t = edges[i][0], u = edges[i][1], v = edges[i][2]; if (t == 1) { if (mergep(u, v)) { used1++; comp--; } } } if (comp != 1) return -1; int usedA = used3A + used1; init(); comp = n; int used3B = 0; for (size_t i = 0; i < edges.size(); ++i) { int t = edges[i][0], u = edges[i][1], v = edges[i][2]; if (t == 3) { if (mergep(u, v)) { used3B++; comp--; } } } int used2 = 0; for (size_t i = 0; i < edges.size(); ++i) { int t = edges[i][0], u = edges[i][1], v = edges[i][2]; if (t == 2) { if (mergep(u, v)) { used2++; comp--; } } } if (comp != 1) return -1; int usedB = used3B + used2; long long total = (long long)edges.size(); long long kept = (long long)usedA + (long long)usedB - (long long)used3B; long long removable = total - kept; if (removable < 0) return -1; if (removable > INT_MAX) return (int)removable; return (int)removable; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector > e; for(int i=1;i<=m;i++) { int x,y,z; cin>>x>>y>>z; vector temp; temp.push_back(x); temp.push_back(y); temp.push_back(z); e.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,e); // output cout<& cost, vector& time) { } }; ``` Example 1: Input: cost = [1,2,3,2], time = [1,2,3,2] Output: 3 Example 2: Input: cost = [2,3,4,2], time = [1,1,1,1] Output: 4 Constraints: 1 <= cost.length <= @data cost.length == time.length 1 <= cost[i] <= 10^6 1 <= time[i] <= 500 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve(vector& cost, vector& time) { int maxCost = accumulate(cost.begin(), cost.end(), 0); vector dp(cost.size()+1, maxCost); dp[0] = 0; for (int end=0; end0; wall--) { dp[wall] = min(dp[wall], dp[max(wall-time[end]-1, 0)] + cost[end]); } } return dp[cost.size()]; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector a,b; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } for(int i=1;i<=n;i++) { int x; cin>>x; b.push_back(x); } // solve Solution solution; auto result = solution.solve(a,b); // output cout << result << ""\n""; return 0; }",dp,hard 371,"Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang. A boomerang is a set of three points that are all distinct and not in a straight line. solution main function ```cpp class Solution { public: bool solve(vector>& points) { } }; ``` Example 1: Input: points = [[1,1],[2,3],[3,2]] Output: 1 Example 2: Input: points = [[1,1],[2,2],[3,3]] Output: 0 Constraints: points.length == 3 points[i].length == 2 0 <= xi, yi <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[20, 50, 100]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve1(vector>& p) { return (p[0][0] - p[1][0]) * (p[0][1] - p[2][1]) != (p[0][0] - p[2][0]) * (p[0][1] - p[1][1]); } bool solve2(vector>& p) { if ((p[0][0]==p[1][0] && p[0][1]==p[1][1]) || (p[0][0]==p[2][0] && p[0][1]==p[2][1]) || (p[1][0]==p[2][0] && p[1][1]==p[2][1])) { return false; } long long x1 = p[0][0], y1 = p[0][1]; long long x2 = p[1][0], y2 = p[1][1]; long long x3 = p[2][0], y3 = p[2][1]; __int128 dx21 = (__int128)x2 - x1; __int128 dy31 = (__int128)y3 - y1; __int128 dx31 = (__int128)x3 - x1; __int128 dy21 = (__int128)y2 - y1; __int128 cross = dx21 * dy31 - dx31 * dy21; return cross != 0; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input vector> s; for(int i=1;i<=3;i++) { vector temp; for(int j=1;j<=2;j++) { int x; cin>>x; temp.push_back(x); } s.push_back(temp); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout<>& grid, int health) { } }; ``` Example 1: Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1 Output: 1 Example 2: Input: grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3 Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data 2 <= m * n 1 <= health <= m + n grid[i][j] is either 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 20, 50]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve(vector>& grid, int health) { int n=grid.size(); int m=grid[0].size(); priority_queue>, vector>>>qu; vector>vis(n,vector(m,0)); if(grid[0][0]==1){ qu.push({health-1,{0,0}}); } else{ qu.push({health,{0,0}}); } vis[0][0]=1; while(!qu.empty()){ int val=qu.top().first; int row=qu.top().second.first; int col=qu.top().second.second; if(row==n-1 && col==m-1){ if(val>=1){ return true; } } qu.pop(); int drow[4]={0,-1,0,1}; int dcol[4]={-1,0,1,0}; for(int i=0;i<4;i++){ int n_row=row+drow[i]; int n_col=col+dcol[i]; if(n_row>=0 && n_row=0 && n_col=0 && n_row=0 && n_col using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; vector> g; cin>>n>>m; for(int i=1;i<=n;i++) { vector temp; for(int j=1;j<=m;j++) { int x; cin>>x; temp.push_back(x); } g.push_back(temp); } int h;cin>>h; // solve Solution solution; auto result = solution.solve(g,h); // output // for(auto it:result) cout< &good) { // write your code here } }; ``` where: - `n`: number of piles - `m`: upper bound on stones per pile (in this version, `m ∈ {1,2}`) - `k`: number of good indices - `good`: strictly increasing array of size `k` listing good indices (guaranteed `good[0] = 1`) - return: the sum of final remaining stones $x$ over all valid configurations, modulo $10^9+7$ # Example 1: - Input: n = 2, m = 2 k = 1 good = [1] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $1 \leq m \leq 2$ - $1 \leq k \leq n$ - $1 = \text{good}[0] < \text{good}[1] < \cdots < \text{good}[k-1] \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 15, 20]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &m, int &k, vector &good) { const int MOD = 1000000007; auto mod_pow = [&](long long a, int e) -> long long { long long r = 1 % MOD; a %= MOD; while (e > 0) { if (e & 1) r = (r * a) % MOD; a = (a * a) % MOD; e >>= 1; } return r; }; int S = 0; for (int x : good) S |= (1 << (x - 1)); if (m == 1) { return 1; } auto remove_bit = [&](int x, int pos) -> int { int lower = x & ((1 << pos) - 1); int upper = x >> (pos + 1); return lower | (upper << pos); }; vector> ok(n); ok[n - 1].assign(2, 0); ok[n - 1][0] = 0; ok[n - 1][1] = 1; for (int i = n - 2; i >= 0; --i) { int p = n - i; int sz = 1 << p; ok[i].assign(sz, 0); if (i & 1) { std::fill(ok[i].begin(), ok[i].end(), 1); for (int mask = 0; mask < sz; ++mask) { unsigned char val = 1; for (int pos = 0; pos < p; ++pos) { if ((S >> pos) & 1) { int T = remove_bit(mask, pos); if (!ok[i + 1][T]) { val = 0; break; } } } ok[i][mask] = val; } } else { for (int mask = 0; mask < sz; ++mask) { unsigned char val = 0; for (int pos = 0; pos < p; ++pos) { if ((S >> pos) & 1) { int T = remove_bit(mask, pos); if (ok[i + 1][T]) { val = 1; break; } } } ok[i][mask] = val; } } } vector cnt(n + 1, 0); int full = 1 << n; for (int mask = 0; mask < full; ++mask) { if (ok[0][mask]) { cnt[__builtin_popcount((unsigned)mask)]++; } } long long ans = 0; for (int iVal = 1; iVal <= m; ++iVal) { for (int j = 0; j <= n; ++j) { long long ways = mod_pow(iVal - 1, n - j) * mod_pow(m - iVal + 1, j) % MOD; ans = (ans + ways * cnt[j]) % MOD; } } return (ans % MOD + MOD) % MOD; } long long solve2(int &n, int &m, int &k, vector &good) { const int MOD = 1000000007; auto mod_pow = [&](long long a, long long e) -> long long { long long r = 1 % MOD; a %= MOD; while (e > 0) { if (e & 1) r = (r * a) % MOD; a = (a * a) % MOD; e >>= 1; } return r; }; if (m == 1) { return 1; } auto isGood = [&](int pos) -> bool { return binary_search(good.begin(), good.end(), pos + 1); }; auto remove_bit = [&](unsigned long long mask, int pos) -> unsigned long long { unsigned long long lower = mask & ((1ull << pos) - 1); unsigned long long upper = mask >> (pos + 1); return lower | (upper << pos); }; vector prev(2, 0); prev[0] = 0; prev[1] = 1; for (int p = 2; p <= n; ++p) { size_t sz = 1ull << p; size_t psz = sz >> 1; vector curr(sz, 0); bool aliceTurn = ((n - p) % 2 == 0); for (unsigned long long mask = 0; mask < sz; ++mask) { if (aliceTurn) { unsigned char val = 0; for (int pos = 0; pos < p; ++pos) { if (isGood(pos)) { unsigned long long child = remove_bit(mask, pos); if (prev[(size_t)child]) { val = 1; break; } } } curr[(size_t)mask] = val; } else { unsigned char val = 1; for (int pos = 0; pos < p; ++pos) { if (isGood(pos)) { unsigned long long child = remove_bit(mask, pos); if (!prev[(size_t)child]) { val = 0; break; } } } curr[(size_t)mask] = val; } } prev.swap(curr); } long long W = 0; if (n == 1) { W = prev[1]; } else { size_t sz = 1ull << n; for (size_t i = 0; i < sz; ++i) { W += prev[i]; if (W >= MOD) W -= MOD; } } long long ans = (mod_pow(2, n) + W) % MOD; return (ans + MOD) % MOD; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; int k; cin >> k; vector good(k); for (int i = 0; i < k; i++) cin >> good[i]; // solve Solution solution; auto result = solution.solve(n, m, k, good); // output cout << result << ""\n""; return 0; }","dp,math",hard 374,"You are given a 0-indexed integer array nums. The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n. Return the xor-beauty of nums. solution main function ```cpp class Solution { public: int solve(vector& nums) { } }; ``` Example 1: Input: nums = [1,4] Output: 5 Example 2: Input: nums = [15,45,20,2,34,35,5,44,32,30] Output: 34 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int ans = 0; for(int num: nums) ans ^= num; return ans; } int solve2(vector& nums) { int n = (int)nums.size(); int ans = 0; for (int i = 0; i < n; ++i) { int ni = nums[i]; for (int j = 0; j < n; ++j) { int v = ni | nums[j]; for (int k = 0; k < n; ++k) { ans ^= (v & nums[k]); } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< x$, then $p_i \leftarrow p_i - 1$. It can be proven that positions always remain within $[1,n]$. Each position $x$ has a value $a_x$. For a final position array $p = [p_1,\dots,p_n]$, define $$ score(p) = \sum_{i=1}^n a_{p_i}. $$ Over all distinct final position arrays $p$ reachable by placing attractions, compute the sum of $score(p)$, modulo $998244353$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: number of people and the length of array `a` - `a`: array of length `n`, where `a[x-1] = a_x` - return: sum of `score(p)` over all reachable distinct `p`, modulo `998244353` # Example 1: - Input: ``` n = 2 a = [5, 10] ``` - Output: ``` 45 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 400, 160], [6400, 3200, 1280]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve(int &n, vector &a) { const int MOD = 998244353; auto norm = [&](long long x) -> long long { x %= MOD; if (x < 0) x += MOD; return x; }; auto qpow = [&](long long A, long long B) -> long long { long long r = 1; while (B) { if (B & 1) r = r * A % MOD; A = A * A % MOD; B >>= 1; } return r; }; vector s(n + 1, 0), t(n + 1, 0); for (int i = 1; i <= n; i++) { int ai = (int)norm(a[i - 1]); s[i] = s[i - 1] + ai; if (s[i] >= MOD) s[i] -= MOD; t[i] = (t[i - 1] + s[i]) % MOD; } if (n == 1) return norm(a[0]); if (n == 2) return norm(3LL * ( (long long)norm(a[0]) + (long long)norm(a[1]) )); long long ans = 0; for (int zl = 0; zl <= 1; zl++) { for (int zr = 0; zr <= 1; zr++) { int m = n - 1 - zl - zr; if (m < 0) continue; long long ways = 1; for (int c = 0; c * 2 <= m; c++) { int c1 = m - 2 * c; if (c1 == 0 && zr == 1) { } else { long long inv_c1p1 = qpow(c1 + 1, MOD - 2); long long s1 = ( ( (long long)t[n] - t[c1] - t[n - c1 - 1] ) % MOD + MOD ) % MOD; s1 = s1 * ( (n - zl - zr) % MOD ) % MOD * inv_c1p1 % MOD; s1 = ( s1 + 1LL * zl * s[n - c1] ) % MOD; s1 = ( s1 + 1LL * zr * ( ( (long long)s[n] - s[c1] + MOD ) % MOD ) ) % MOD; ans = (ans + s1 * ways) % MOD; } if ((c + 1) * 2 <= m) { long long num = 1LL * (m - 2 * c) * (m - 2 * c - 1) % MOD; long long den1 = qpow(m - c, MOD - 2); long long den2 = qpow(c + 1, MOD - 2); ways = ways * num % MOD * den1 % MOD * den2 % MOD; } } } } return norm(ans); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",math,hard 376,"# Problem Statement You are given an array of integers `a1, a2, ..., an` and an integer `X`. You may perform the following operation zero or more times: - Select index `i`, and increase `ai` by one. Let `a'` be the final array. Your goal is to perform the smallest number of operations such that `a'1 & a'2 & ... & a'n = X`, where `&` denotes the bitwise AND operation. There are `q` independent queries `X1, X2, ..., Xq`. For each query `X = Xi`, compute the minimal number of operations. Each query is processed independently from the same initial array `a`. The main function of the solution is defined as: ```cpp class Solution { public: vector solve(int &n, vector &a, int &q, vector &x) { // write your code here } }; ``` where: - `n`: length of the array - `a`: the initial array, with `0 ≤ a[i] < 10 * n` - `q`: number of queries - `x`: query values, each `0 ≤ x[i] < 10 * n` - return: an array of `q` answers (operations count) for each query # Example: - Input: ``` n = 5, q = 4 a = [6, 4, 7, 5, 4] x = [0, 2, 4, 6] ``` - Output: ``` [1, 8, 0, 5] ``` # Constraints: - `2 ≤ n ≤ @data` - `1 ≤ q ≤ @data` - `0 ≤ a[i] < 10 * n` - `0 ≤ x[i] < 10 * n` - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[1000, 500, 200], [8000, 4000, 1600], [64000, 32000, 12800]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int &n, vector &a, int &q, vector &xs) { int K = __lg(10 * n) + 1; constexpr int inf = 1E9; vector cnt(K + 1); vector mx(K + 1); for (int i = 0; i < n; i++) { for (int j = 0; j <= K; j++) { cnt[j] += a[i] >> j & 1; if (~a[i] >> j & 1) { if ((a[i] & ((1 << j) - 1)) >= (mx[j] & ((1 << j) - 1))) { mx[j] = a[i]; } } } } vector ans(q); for (int k = 0; k < K; k++) { vector sum(1 << (K - 1 - k)); vector cnt(1 << (K - 1 - k)); for (int i = 0; i < n; i++) { if (~a[i] >> k & 1) { sum[a[i] >> (k + 1)] += a[i] & ((1 << k) - 1); cnt[a[i] >> (k + 1)]++; } } for (int i = 1; i < (1 << (K - 1 - k)); i *= 2) { for (int j = 0; j < (1 << (K - 1 - k)); j += 2 * i) { for (int l = 0; l < i; l++) { sum[j + l] += sum[i + j + l]; cnt[j + l] += cnt[i + j + l]; } } } for (int i = 0; i < q; i++) { if (xs[i] >> k & 1) { int mask = xs[i] >> (k + 1); ans[i] += (long long)(xs[i] & ((2 << k) - 1)) * cnt[mask] - sum[mask]; } } } for (int i = 0; i < q; i++) { int t = -1; for (int j = K - 1; j >= 0; j--) { if (xs[i] >> j & 1) { if (cnt[j] < n) { break; } } else { if (cnt[j] == n) { t = j; break; } } } if (t == -1) { continue; } int res = inf; auto get = [&](int x) { int mask = xs[i] & ~x; if (mask) { int j = __lg(mask); x &= ~((1 << j) - 1); x |= xs[i] & ((2 << j) - 1); } return x; }; for (int j = t + 1; j <= K; j++) { if (cnt[j] < n - 1) { int x = get(mx[j]); int y = x; y |= 1 << j; y &= ~((1 << j) - 1); res = min(res, get(y) - x); } } ans[i] += res; } return ans; } vector solve2(int &n, vector &a, int &q, vector &xs) { vector ans(q); for (int qi = 0; qi < q; ++qi) { int X = xs[qi]; long long sum0 = 0; int all_and = -1; for (int i = 0; i < n; ++i) { long long y = a[i]; while (true) { int missing = (~(int)y) & X; if (missing == 0) break; int j = __builtin_ctz(missing); long long upper = ((((unsigned long long)y) >> j) + 1ULL) << j; y = upper | (long long)(X & (int)((1LL << j) - 1)); } sum0 += (y - a[i]); all_and &= (int)y; } int bmask = all_and & (~X); if (bmask == 0) { ans[qi] = sum0; continue; } long long best_extra = LLONG_MAX; for (int i = 0; i < n; ++i) { long long y = a[i]; while (true) { int missing = (~(int)y) & X; if (missing == 0) break; int j = __builtin_ctz(missing); long long upper = ((((unsigned long long)y) >> j) + 1ULL) << j; y = upper | (long long)(X & (int)((1LL << j) - 1)); } long long z = y; while (true) { int vio1 = (~(int)z) & X; int vio0 = ((int)z) & bmask; if (vio1 == 0 && vio0 == 0) break; int j = 32; if (vio1) { int j1 = __builtin_ctz(vio1); if (j1 < j) j = j1; } if (vio0) { int j2 = __builtin_ctz(vio0); if (j2 < j) j = j2; } if ((X >> j) & 1) { long long upper = ((((unsigned long long)z) >> j) + 1ULL) << j; z = upper | (long long)(X & (int)((1LL << j) - 1)); } else { long long upper = ((((unsigned long long)z) >> (j + 1)) + 1ULL) << (j + 1); z = upper | (long long)(X & (int)((1LL << (j + 1)) - 1)); } } long long extra = z - y; if (extra < best_extra) best_extra = extra; } ans[qi] = sum0 + best_extra; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, q; cin >> n >> q; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector x(q); for (int i = 0; i < q; i++) cin >> x[i]; // solve Solution solution; auto result = solution.solve(n, a, q, x); // output for (int i = 0; i < (int)result.size(); i++) cout << result[i] << ""\n""; return 0; }","bit_manipulation,data_structures",hard 377,"Given a graph with n vertices (numbered 1 to n) and m undirected edges with non-negative weights, please calculate the distance from vertex s to each vertex. The data guarantees that you can reach any point starting from s. The `edges` array represents the edges in the graph. `edges[i] = [a, b, c]` indicates that there is an undirected edge with a weight of `c` between node `a` and node `b`. solution main function ```cpp class Solution { public: vector solve(int n,int s, vector>& edges) { } }; ``` Example 1: Input: n = 4, s = 1, edges = [[1,2,2],[2,3,2],[2,4,1],[1,3,5],[3,4,3],[1,4,4]] Output: [0,2,4,3] Constraints: 2 <= n <= @data edges.size <=5*@data edges[i].size ==3 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 100, 64], [3200, 800, 80], [25600, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: vector solve1(int n,int s, vector>& edges) { const int INF=1e8; priority_queue,vector >,greater > > q; vector > > v; vector dis,vis; v.resize(n+10); dis.resize(n+10,INF); vis.resize(n+10,false); dis[s]=0; q.push(make_pair(0,s)); for(auto it:edges) { int x=it[0],y=it[1],t=it[2]; v[x].push_back(make_pair(y,t)); v[y].push_back(make_pair(x,t)); } while(!q.empty()) { pair s=q.top(); int x=s.second; q.pop(); if(vis[x]) continue; vis[x]=true; for(int i=0;idis[x]+v[x][i].second) { dis[v[x][i].first]=dis[x]+v[x][i].second; q.push(make_pair(dis[v[x][i].first],v[x][i].first)); } } } vector ans; for(int i=1;i<=n;i++) ans.push_back(dis[i]); return ans; } vector solve2(int n,int s, vector>& edges) { const int INF = 0x3f3f3f3f; vector dis(n, INF); dis[s-1] = 0; bool changed = true; for(int it=0; it INT_MAX/2 ? INT_MAX/2 : (int)cand; changed = true; } } if(dis[v] < INF/2) { long long cand = (long long)dis[v] + (long long)w; if(cand < dis[u]) { dis[u] = cand > INT_MAX/2 ? INT_MAX/2 : (int)cand; changed = true; } } } } return dis; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m,s; cin>>n>>m>>s; vector< vector > edges; for(int i=1,x,y,z;i<=m;i++) { cin>>x>>y>>z; vector temp; temp.push_back(x); temp.push_back(y); temp.push_back(z); edges.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,s,edges); // output for(int i=0;i> &a) { // write your code here } }; ``` where: - the return value is the minimum number of times Sakurako must use her magic, and it is of type long long # Example 1: - Input: n = 2 a = [[-1, 2], [3, 0]] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $-10^5 \leq a[i][j] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector> &a) { long long ans = 0; for (int i = -n + 1; i <= n - 1; i++) { int mi = 0; for (int j = max(0, i); j < n && j - i < n; j++) mi = min(mi, a[j - i][j]); ans += mi; } return -ans; } long long solve2(int &n, vector> &a) { long long ans = 0; for (int r = 0; r < n; r++) { int mi = 0; for (int k = 0; r + k < n && k < n; k++) mi = min(mi, a[r + k][k]); ans += mi; } for (int c = 1; c < n; c++) { int mi = 0; for (int k = 0; k < n && c + k < n; k++) mi = min(mi, a[k][c + k]); ans += mi; } return -ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector> a(n, vector(n)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> a[i][j]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,dp",hard 379,"# Problem Statement There are $n$ cows participating in a coding tournament. Cow $i$ has a Cowdeforces rating of $a_i$ (all distinct), and is initially in position $i$. The tournament consists of $n-1$ matches as follows: - The first match is between the cow in position $1$ and the cow in position $2$. - Subsequently, each match $i$ is between the cow in position $i+1$ and the winner of match $i-1$. - In each match, the cow with the higher Cowdeforces rating wins and proceeds to the next match. You are the owner of cow $k$. For you, winning the tournament is not important; rather, you want your cow to win in as many matches as possible. As an acquaintance of the tournament organizers, you can ask them to swap the position of your cow with another cow **only once**, or you can choose to do nothing. Find the maximum number of wins your cow can achieve. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &k, vector &a) { // write your code here } }; ``` where: - return: the maximum number of wins cow k can achieve if you choose to swap (or do nothing) optimally. # Example 1: - Input: n = 6, k = 1 a = [12, 10, 14, 11, 8, 3] - Output: 1 # Constraints: - $2 \leq n \leq @data$ - $1 \leq k \leq n$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &k, vector &a) { int pos1 = -1, pos2 = -1; for (int i = 0; i < n; i++) { if (a[i] > a[k - 1]) { if (pos1 == -1) pos1 = i + 1; else { pos2 = i + 1; break; } } } int ans = 0; if (pos1 == -1) ans = n - 1; else if (pos2 == -1) { if (pos1 < k) { int tem = k - pos1; if (pos1 == 1) tem--; ans = max({pos1 - 2, tem, 0}); } else { ans = max(0, pos1 - 2); } } else { if (pos1 < k) { if (pos2 > k) { int tem = k - pos1; if (pos1 == 1) tem--; ans = max({pos1 - 2, tem, 0}); } else if (k > pos2) { int tem = pos2 - pos1; if (pos1 == 1) tem--; ans = max({pos1 - 2, tem, 0}); } } else if (k < pos1) { ans = max(0, pos1 - 2); } } return ans; } int solve2(int &n, int &k, vector &a) { int r = a[k - 1]; int best = 0; for (int j = 0; j < n; ++j) { if (j != k - 1) swap(a[k - 1], a[j]); int wins = 0; int winner = a[0]; bool over = false; for (int i = 1; i < n; ++i) { int opponent = a[i]; if (winner == r) { if (r > opponent) ++wins; else { over = true; break; } } else if (opponent == r) { if (r > winner) { ++wins; winner = r; } else { over = true; break; } } else { if (opponent > winner) winner = opponent; } } if (wins > best) best = wins; if (j != k - 1) swap(a[k - 1], a[j]); } return best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, k, a); // output cout << result << ""\n""; return 0; }",greedy,hard 380,"A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). Return the number of indices where heights[i] != expected[i]. solution main function ```cpp class Solution { public: int solve(vector& heights) { } }; ``` Example 1: Input: heights = [1,1,4,2,1,3] Output: 3 Example 2: Input: heights = [5,1,2,3,4] Output: 5 Constraints: 1 <= heights.length <= @data 1 <= heights[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& heights) { vector expected = heights; sort(expected.begin(), expected.end()); int cnt = 0; for (int i = 0; i < heights.size(); ++i) { if (heights[i] != expected[i]) { cnt++; } } return cnt; } int solve2(vector& heights) { int n = (int)heights.size(); long long last = LLONG_MIN; int idx = 0; int cnt = 0; while (idx < n) { int candidate = INT_MAX; for (int i = 0; i < n; ++i) { int h = heights[i]; if ((long long)h > last && h < candidate) { candidate = h; } } int times = 0; for (int i = 0; i < n; ++i) { if (heights[i] == candidate) { times++; } } for (int k = 0; k < times; ++k) { if (heights[idx] != candidate) { cnt++; } idx++; } last = candidate; } return cnt; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector num; for(int i=1;i<=n;i++) { int x; cin>>x; num.push_back(x); } // solve Solution solution; auto result = solution.solve(num); // output cout << result << ""\n""; // for(auto it:result) cout<& arr, int k) { } }; ``` Example 1: Input: arr = [2,1,3,5,4,6,7], k = 2 Output: 5 Example 2: Input: arr = [3,2,1], k = 10 Output: 3 Constraints: 2 <= arr.length <= @data 1 <= arr[i] <= 10^6 arr contains distinct integers. 1 <= k <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& arr, int k) { int maxElement = arr[0]; for (int i = 1; i < arr.size(); i++) { maxElement = max(maxElement, arr[i]); } int curr = arr[0]; int winstreak = 0; for (int i = 1; i < arr.size(); i++) { int opponent = arr[i]; if (curr > opponent) { winstreak++; } else { curr = opponent; winstreak = 1; } if (winstreak == k || curr == maxElement) { return curr; } } return -1; } int solve2(vector& arr, int k) { int maxElement = arr[0]; for (int i = 1; i < (int)arr.size(); ++i) { if (arr[i] > maxElement) maxElement = arr[i]; } int winstreak = 0; while (true) { if (arr[0] == maxElement) return arr[0]; int a = arr[0]; int b = arr[1]; if (a > b) { ++winstreak; int x = arr[1]; arr.erase(arr.begin() + 1); arr.push_back(x); } else { arr.erase(arr.begin()); arr.push_back(a); winstreak = 1; } if (winstreak >= k) return arr[0]; } } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,k); // output cout << result << ""\n""; return 0; }",greedy,hard 382,"# Problem Statement Alice and Bob are playing a game. They have an array $a_1, a_2,\ldots,a_n$. The game consists of two steps: - First, Alice will remove **at most** $k$ elements from the array. - Second, Bob will multiply **at most** $x$ elements of the array by $-1$. Alice wants to maximize the sum of elements of the array while Bob wants to minimize it. Find the sum of elements of the array after the game if both players play optimally. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &k, int &x, vector &a) { // write your code here } }; ``` where: - `n` is the number of elements in the array, `k` is the maximum number of elements Alice can remove, and `x` is the maximum number of elements Bob can multiply by $-1$. - `a` is the array of elements. - The return value is the sum of elements of the array after the game. # Example 1: - Input: n = 4, k = 1, x = 1 a = [3, 1, 2, 4] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq x,k \leq n$ - $1 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &k, int &x, vector &a) { sort(a.begin(), a.end()); int ans = -1e9; for (int i = 1; i < n; i++) a[i] += a[i - 1]; for (int i = 0; i <= k; i++) { int res = -((n - i) == 0 ? 0 : a[n - i - 1]) + 2 * ((n - i - x) > 0 ? a[n - i - x - 1] : 0); ans = max(ans, res); } return ans; } int solve2(int &n, int &k, int &x, vector &a) { sort(a.begin(), a.end()); long long total = 0; for (int i = 0; i < (int)a.size(); i++) total += a[i]; long long removed = 0; long long best = LLONG_MIN; for (int i = 0; i <= k; i++) { int rem_len = n - i; long long sumR = total - removed; int flip = x < rem_len ? x : rem_len; long long sumTop = 0; if (flip > 0) { int start = rem_len - flip; for (int j = start; j < rem_len; j++) sumTop += a[j]; } long long res = sumR - 2LL * sumTop; if (res > best) best = res; if (i < k && n - 1 - i >= 0) removed += a[n - 1 - i]; } if (best < INT_MIN) return INT_MIN; if (best > INT_MAX) return INT_MAX; return (int)best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k, x; cin >> n >> k >> x; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, k, x, a); // output cout << result << ""\n""; return 0; }","math,sort",medium 383,"# Problem Statement Stalin Sort is a humorous sorting algorithm designed to eliminate elements which are out of place instead of bothering to sort them properly, lending itself to an $\mathcal{O}(n)$ time complexity. It goes as follows: starting from the second element in the array, if it is strictly smaller than the previous element (ignoring those which have already been deleted), then delete it. Continue iterating through the array until it is sorted in non-decreasing order. For example, the array $[1, 4, 2, 3, 6, 5, 5, 7, 7]$ becomes $[1, 4, 6, 7, 7]$ after a Stalin Sort. We define an array as vulnerable if you can sort it in **non-increasing** order by repeatedly applying a Stalin Sort to **any of its subarrays$^{\text{∗}}$**, as many times as is needed. Given an array $a$ of $n$ integers, determine the minimum number of integers which must be removed from the array to make it vulnerable. $^{\text{∗}}$An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - the return value is the minimum number of integers to be removed to make the array vulnerable # Example 1: - Input: n = 7 a = [3, 6, 4, 9, 2, 5, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int ans = n; for (int i = 0; i < n; i++) { int res = 0; for (int j = 0; j < n; j++) { if (j < i || a[j] > a[i]) res++; } ans = min(ans, res); } return ans; } int solve2(int &n, vector &a) { int ans = n; for (int i = 0; i < n; i++) { int res = i; int ai = a[i]; if (res >= ans) continue; for (int j = i + 1; j < n; j++) { if (a[j] > ai) { res++; if (res >= ans) break; } } if (res < ans) ans = res; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",greedy,medium 384,"# Problem Statement There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li. You are given lengths of the claws. You need to find the total number of alive people after the bell rings. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the total number of alive people after the bell rings. # Example 1: - Input: n = 4 L = [0, 1, 0, 10] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $0 \leq L[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &L) { for (int i = n - 1; i > 0; i--) L[i - 1] = max(L[i - 1], L[i] - 1); int ans = 1 + count(L.begin() + 1, L.end(), 0); return ans; } int solve2(int &n, vector &L) { int survivors = 0; for (int j = 0; j < n; ++j) { bool killed = false; for (int i = j + 1; i < n; ++i) { long long reach_start = (long long)i - (long long)L[i]; if ((long long)j >= reach_start) { killed = true; break; } } if (!killed) ++survivors; } return survivors; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,implementation",medium 385,"# Problem Statement You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have $26$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct. You are given a sequence of hits, the $i$-th hit deals $a_i$ units of damage to the opponent's character. To perform the $i$-th hit you have to press the button $s_i$ on your gamepad. Hits are numbered from $1$ to $n$. You know that if you press some button **more than** $k$ times **in a row** then it'll break. You cherish your gamepad and don't want to break any of its buttons. To perform a brutality you have to land some of the hits of the given sequence. **You are allowed to skip any of them, however changing the initial order of the sequence is prohibited**. The total damage dealt is the sum of $a_i$ over all $i$ for the hits which weren't skipped. **Note that if you skip the hit then the counter of consecutive presses the button won't reset**. Your task is to skip some hits to deal the **maximum** possible total damage to the opponent's character and not break your gamepad buttons. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, int &k, vector &a, string &s) { // write your code here } }; ``` where: - return: he maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons. # Example 1: - Input: n = 7, k = 3 a = [1, 5, 16, 18, 7, 2, 10] s = ""baaaaca"" - Output: 54 # Constraints: - $1 \leq k \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - $s[i]$ is a lowercase Latin letter - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &k, vector &a, string &s) { long long ans = 0; int start = 0; for (int i = 1; i <= n; i++) { if (i == n || s[i] != s[i - 1]) { if (i - start > k) sort(a.begin() + start, a.begin() + i); for (int j = 0; j < k && i - j - 1 >= start; j++) ans += a[i - j - 1]; start = i; } } return ans; } long long solve2(int &n, int &k, vector &a, string &s) { long long ans = 0; int start = 0; for (int i = 1; i <= n; i++) { if (i == n || s[i] != s[i - 1]) { int len = i - start; int picks = k < len ? k : len; for (int t = 0; t < picks; t++) { int best_idx = -1; int best_val = -1; for (int idx = start; idx < i; idx++) { int val = a[idx]; if (val > best_val) { best_val = val; best_idx = idx; } } ans += (long long)best_val; a[best_idx] = -1; } start = i; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, k, a, s); // output cout << result << ""\n""; return 0; }","greedy,sort,two_pointers",hard 386,"# Problem Statement There are $M$ rows and $N$ columns of seats in a classroom. The seat in row $i$ and column $j$ is denoted by $(i, j)$. Some pairs of students may talk to each other during class. Each such pair occupies two adjacent seats. A passage placed between two adjacent rows or between two adjacent columns separates the corresponding seats, so students on the two sides of that passage will not talk to each other. You need to place $K$ horizontal passages between adjacent rows and $L$ vertical passages between adjacent columns so that the number of talking pairs that remain unseparated is minimized. The input guarantees that the optimal scheme is unique. The main function of the solution is defined as: ```cpp class Solution { public: pair, vector> solve(int M, int N, int K, int L, int D, vector> &seats) { // write your code here } }; ``` where: - $M$ and $N$ are the numbers of rows and columns. - $K$ is the number of horizontal passages to place. - $L$ is the number of vertical passages to place. - $D$ is the number of talking pairs. - `seats[i] = [X_i, Y_i, P_i, Q_i]` means the students at $(X_i, Y_i)$ and $(P_i, Q_i)$ may talk to each other. - return: two arrays. The first array contains the $K$ row indices after which horizontal passages are placed. The second array contains the $L$ column indices after which vertical passages are placed. Both arrays should be in increasing order. # Example 1: - Input: M = 4, N = 5, K = 1, L = 2, D = 3 seats = [[4, 2, 4, 3], [2, 3, 3, 3], [2, 5, 2, 4]] - Output: [[2], [2, 4]] # Constraints: - $2 \leq M, N \leq @data$ - $2 \leq D \leq 3 * @data$ - $0 \leq K \leq M$ - $0 \leq L \leq N$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 100, 1000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { struct A { int n, p; }; static bool cmp(A x, A y) { if (x.n != y.n) return x.n > y.n; return x.p < y.p; } static bool cmp1(A x, A y) { return x.p < y.p; } public: pair, vector> solve(int M, int N, int K, int L, int D, vector>& seats) { vector row(M + 1), col(N + 1); vector row_divisions, col_divisions; for (const auto& edge : seats) { int x1 = edge[0], y1 = edge[1], x2 = edge[2], y2 = edge[3]; if (x1 == x2) { int idx = min(y1, y2); col[idx].p = idx; col[idx].n++; } else { int idx = min(x1, x2); row[idx].p = idx; row[idx].n++; } } sort(row.begin() + 1, row.begin() + M + 1, cmp); sort(col.begin() + 1, col.begin() + N + 1, cmp); sort(row.begin() + 1, row.begin() + K + 1, cmp1); sort(col.begin() + 1, col.begin() + L + 1, cmp1); for (int i = 1; i <= K; i++) row_divisions.push_back(row[i].p); for (int i = 1; i <= L; i++) col_divisions.push_back(col[i].p); return {row_divisions, col_divisions}; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int m,n,k,l,d; cin>>m>>n>>k>>l>>d; vector > seats; for(int i=1;i<=d;i++) { vector temp; for(int j=1,x;j<=4;j++) { cin>>x; temp.push_back(x); } seats.push_back(temp); } // solve Solution solution; pair,vector > result = solution.solve(m,n,k,l,d,seats); // output for(int i=0;i using namespace std; #include using namespace std; class Solution { public: double solve1(int n) { return n == 1 ? 1.0 : 0.5; } double solve2(int n) { if (n <= 1) return 1.0; double S = 1.0, p = 0.0; for (int k = 2; k <= n; ++k) { p = 1.0 / k + (S - 1.0) / k; S += p; } return p; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output printf(""%.3lf"",result); // for(auto it:result) cout<& derived) { } }; ``` Example 1: Input: derived = [1,1,0] Output: 1 Example 2: Input: derived = [1,1] Output: 1 Constraints: n == derived.length 2 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve1(vector& derived) { int sum = accumulate(derived.begin(), derived.end(), 0); return sum % 2 == 0; } bool solve2(vector& derived) { int n = (int)derived.size(); for (int x0 = 0; x0 <= 1; ++x0) { int curr = x0; for (int i = 0; i < n - 1; ++i) { curr ^= derived[i]; } if ((curr ^ x0) == derived[n - 1]) return true; } return false; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector< int > num; for(int i=1,x;i<=n;i++) { cin>>x; num.push_back(x); } // solve Solution solution; int result = solution.solve(num); // output cout << result << ""\n""; return 0; }",bit_manipulation,medium 389,"# Problem Statement There is a shop with $n$ objects numbered from $1$ to $n$, and only one copy of each object. According to you, the objects have values $v_1, v_2, \dots, v_n$ (values can be negative). Alice and Bob have their own preference orders (permutations $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$). In particular, Alice's favourite object is $a_1$, then $a_2$, etc.; Bob's favourite object is $b_1$, then $b_2$, etc. For $n$ turns, one of them goes to the shop and buys his or her most favourite object still in the shop. At the end, Alice and Bob have their own sets of objects. Now the shop is empty, and you wonder whether Alice's preferences are similar to yours. Over all sets of objects that Alice could have bought, what is the maximum possible sum of values according to you? The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &v, vector &a, vector &b) { // write your code here } }; ``` where: - `n`: number of objects - `v`: values of the objects (can be negative) - `a`: Alice's preference permutation - `b`: Bob's preference permutation - return: the maximum possible total value of the set that Alice could have bought # Example: - Input: ``` n = 3 v = [1, -1, 1] a = [3, 1, 2] b = [2, 3, 1] ``` - Output: ``` 2 ``` # Constraints: - $1 \le n \le @data$ - $-10^9 \le v[i] \le 10^9$ - $1 \le a[i], b[i] \le n$ (both are permutations) - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 400, 80], [6400, 3200, 640]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve(int &n, vector &v, vector &a, vector &b) { for (int i = 0; i < n; i++) { a[i]--; } auto c = b; for (int i = 0; i < n; i++) { c[i]--; b[c[i]] = i; } map f; long long ans = 0; for (int x = 0; x < n; x++) { int val = v[a[x]]; int y = b[a[x]]; ans += val; val *= -1; auto it = f.lower_bound(y); while (val < 0 && it != f.end()) { if (it->second + val > 0) { it->second += val; val = 0; break; } val += it->second; it = f.erase(it); } if (val > 0) { f[y] += val; } } for (auto [x, y] : f) { ans += y; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector v(n); for (int i = 0; i < n; i++) cin >> v[i]; vector a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; // solve Solution solution; auto result = solution.solve(n, v, a, b); // output cout << result << ""\n""; return 0; }","greedy,data_structures",hard 390,"# Problem Statement An array $b$ of length $m$ is good if for all $i$ the $i$-th element is greater than or equal to $i$. In other words, $b$ is good if and only if $b_i \geq i$ for all $i$ ($1 \leq i \leq m$). You are given an array $a$ consisting of $n$ positive integers. Find the number of pairs of indices $(l, r)$, where $1 \le l \le r \le n$, such that the array $[a_l, a_{l+1}, \ldots, a_r]$ is good. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the number of suitable pairs of indices, please use `long long` type. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { long long result = 0; int l = 0; for (int r = 0; r < n; ++r) { while (l <= r && a[r] < (r - l + 1)) l++; result += (r - l + 1); } return result; } long long solve2(int &n, vector &a) { long long result = 0; for (int l = 0; l < n; ++l) { int req = 1; for (int r = l; r < n; ++r) { if (a[r] >= req) { result++; req++; } else { break; } } } return result; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","two_pointers,binary",medium 391,"Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Choosing any x with 0 < x < n and n % x == 0. Replacing the number n on the chalkboard with n - x. Also, if a player cannot make a move, they lose the game. Return true if and only if Alice wins the game, assuming both players play optimally. In examples, the returned boolean is shown as `1` for true and `0` for false. solution main function ```cpp class Solution { public: bool solve(int n) { } }; ``` Example 1: Input: n = 2 Output: 1 Example 2: Input: n = 3 Output: 0 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: bool solve1(int n) { return n%2==0; } bool solve2(int n) { bool alice = true; while (n > 1) { n -= 1; alice = !alice; } return !alice; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: bool isVowel(char c) { return c == 'a' || c == 'e' || c == 'o'|| c == 'u'|| c == 'i' || c == 'A' || c == 'E' || c == 'O'|| c == 'U'|| c == 'I'; } string solve1(string s) { unordered_map count; for (char c : s) { if (isVowel(c)) { count[c]++; } } string sortedVowel = ""AEIOUaeiou""; string ans; int j = 0; for (int i = 0; i < s.size(); i++) { if (!isVowel(s[i])) { ans += s[i]; } else { while (count[sortedVowel[j]] == 0) { j++; } ans += sortedVowel[j]; count[sortedVowel[j]]--; } } return ans; } string solve2(string s) { int total[10] = {0}; auto idx = [](char c)->int{ switch(c){ case 'A': return 0; case 'E': return 1; case 'I': return 2; case 'O': return 3; case 'U': return 4; case 'a': return 5; case 'e': return 6; case 'i': return 7; case 'o': return 8; case 'u': return 9; default: return -1; } }; for (char c : s) { int k = idx(c); if (k != -1) total[k]++; } int used[10] = {0}; int j = 0; string ans; ans.reserve(s.size()); for (int i = 0; i < (int)s.size(); ++i) { if (!isVowel(s[i])) { ans += s[i]; } else { while (j < 10 && used[j] >= total[j]) j++; char ch = 'u'; if (j == 0) ch = 'A'; else if (j == 1) ch = 'E'; else if (j == 2) ch = 'I'; else if (j == 3) ch = 'O'; else if (j == 4) ch = 'U'; else if (j == 5) ch = 'a'; else if (j == 6) ch = 'e'; else if (j == 7) ch = 'i'; else if (j == 8) ch = 'o'; else if (j == 9) ch = 'u'; ans += ch; if (j < 10) used[j]++; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output cout< &a) { // write your code here } }; ``` where: - return: the maximum sum of the subarray # Example 1: - Input: n = 5 a = [1, 2, 3, 4, 5] - Output: 15 # Constraints: - $1 \leq n \leq @data$ - $-10^3 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int ans = -1E9; int suf = -1E9; for (int i = 0; i < n; i++) { if (i && (a[i] - a[i - 1]) % 2 == 0) { suf = 0; } suf = max(suf, 0) + a[i]; ans = max(ans, suf); } return ans; } int solve2(int &n, vector &a) { long long ans = LLONG_MIN; for (int i = 0; i < n; ++i) { long long sum = a[i]; if (sum > ans) ans = sum; for (int j = i + 1; j < n; ++j) { if ((a[j] - a[j - 1]) % 2 == 0) break; sum += a[j]; if (sum > ans) ans = sum; } } if (ans > INT_MAX) return (int)ans; if (ans < INT_MIN) return (int)ans; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,two_pointers,dp",hard 394,"Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold. solution main function ```cpp class Solution { public: int solve(vector& arr, int k, int threshold) { } }; ``` Example 1: Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 Output: 3 Example 2: Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5 Output: 6 Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= 10^4 1 <= k <= arr.length 0 <= threshold <= 10^4 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& arr, int k, int threshold) { int n = arr.size() , count=0 ,prefixsum =0 ; int l=0, r=0; while(r= threshold) { count++; } prefixsum-=arr[l]; l++; } r++; } return count; } int solve2(vector& arr, int k, int threshold) { int n = (int)arr.size(); if (k <= 0 || k > n) return 0; long long need = (long long)threshold * (long long)k; int count = 0; for (int i = 0; i + k <= n; ++i) { long long s = 0; for (int j = 0; j < k; ++j) { s += (long long)arr[i + j]; } if (s >= need) ++count; } return count; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k,sum; cin>>n>>k>>sum; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,k,sum); // output // for(auto it:result) cout< using namespace std; class Solution { public: int solve1(int &n, int &k, string &s) { const int MOD = 998244353; auto mod_pow = [&](long long a, long long e) { long long r = 1 % MOD; a %= MOD; while (e) { if (e & 1) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return (int)r; }; vector fact(n + 1), ifact(n + 1); fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = 1ll * fact[i - 1] * i % MOD; ifact[n] = mod_pow(fact[n], MOD - 2); for (int i = n; i >= 1; i--) ifact[i - 1] = 1ll * ifact[i] * i % MOD; auto C = [&](int a, int b) -> int { if (b < 0 || b > a) return 0; return 1ll * fact[a] * ifact[b] % MOD * ifact[a - b] % MOD; }; auto calc = [&](const string &str) -> int { long long ans = 0; int m = k - 1; int v1 = n + 1; for (int i = 0; i < n; i++) { if (str[i] == '1') { v1 = i; break; } } int p0 = 0, p1 = 0; for (int i = n - k + 1; i < n; i++) { if (i >= 0 && i < n) { if (str[i] == '0') p0++; else if (str[i] == '1') p1++; } } if (v1 > n - k) { for (int c1 = m / 2; c1 <= m; c1++) { if (c1 >= p0 && m - c1 >= p1) { ans = (ans + C(m - p0 - p1, c1 - p0)) % MOD; } } } vector ps(m, 0); for (int i = n - k + 1; i < n; i++) { if (i >= 0 && i < n) { if (str[i] == '0') ps[i % m] |= 1; else if (str[i] == '1') ps[i % m] |= 2; } } p0 = p1 = 0; for (int r = 0; r < m; r++) { if (ps[r] == 1) p0++; else if (ps[r] == 2) p1++; } for (int i = n - k - 1; i >= 0; i--) { int cls = (i + 1) % m; if (ps[cls] == 0) { if (str[i + 1] == '0') { ps[cls] |= 1; p0++; } else if (str[i + 1] == '1') { ps[cls] |= 2; p1++; } } else { if (str[i + 1] == '0') ps[cls] |= 1; else if (str[i + 1] == '1') ps[cls] |= 2; if (ps[cls] == 3) break; } if (v1 > i && ps[cls] != 1) { int free_classes = m - p0 - p1; if (ps[cls] == 0) { ans = (ans + C(free_classes - 1, m / 2 - p0)) % MOD; } else { ans = (ans + C(free_classes, m / 2 - p0)) % MOD; } } } return (int)(ans % MOD); }; string t = s; int ans = calc(t); for (char &ch : t) { if (ch == '0') ch = '1'; else if (ch == '1') ch = '0'; } ans += calc(t); if (ans >= MOD) ans -= MOD; return ans; } int solve2(int &n, int &k, string &s) { const int MOD = 998244353; int q = 0; for (int i = 0; i < n; ++i) if (s[i] == '?') ++q; int need = k / 2 + 1; auto check_fixed = [&](void) -> int { for (int i = 0; i + k <= n; ++i) { char L = s[i]; if (L != '0' && L != '1') return 0; int cnt = 0; for (int j = i; j < i + k; ++j) { char c = s[j]; if (c == L) ++cnt; } if (cnt < need) return 0; } return 1; }; if (q == 0) { return check_fixed(); } using u128 = unsigned __int128; auto charAt = [&](int pos, u128 m1, u128 m2, u128 m3, int q1, int q2, int q3) -> char { char ch = s[pos]; if (ch != '?') return ch; int idx = 0; for (int t = 0; t < pos; ++t) if (s[t] == '?') ++idx; if (idx < q1) { u128 bit = (m1 >> idx) & (u128)1; return bit ? '1' : '0'; } else if (idx < q1 + q2) { int jdx = idx - q1; u128 bit = (m2 >> jdx) & (u128)1; return bit ? '1' : '0'; } else { int jdx = idx - q1 - q2; u128 bit = (m3 >> jdx) & (u128)1; return bit ? '1' : '0'; } }; auto good = [&](u128 m1, u128 m2, u128 m3, int q1, int q2, int q3) -> bool { for (int i = 0; i + k <= n; ++i) { char L = charAt(i, m1, m2, m3, q1, q2, q3); int cnt = 0; for (int j = i; j < i + k; ++j) { if (charAt(j, m1, m2, m3, q1, q2, q3) == L) ++cnt; } if (cnt < need) return false; } return true; }; int q1 = min(q, 127); int q2 = min(q - q1, 127); int q3 = q - q1 - q2; if (q3 > 127) { return 0; } u128 T1 = (u128)1; if (q1 > 0) T1 <<= q1; u128 T2 = (u128)1; if (q2 > 0) T2 <<= q2; u128 T3 = (u128)1; if (q3 > 0) T3 <<= q3; long long ans = 0; for (u128 m3 = 0; m3 < T3; ++m3) { for (u128 m2 = 0; m2 < T2; ++m2) { for (u128 m1 = 0; m1 < T1; ++m1) { if (good(m1, m2, m3, q1, q2, q3)) { ans += 1; if (ans >= MOD) ans -= MOD; } } } } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, k, s); // output cout << result << ""\n""; return 0; }","string,math",hard 396,"# Problem Statement ErnKor is ready to do anything for Julen, even to swim through crocodile-infested swamps. We decided to test this love. ErnKor will have to swim across a river with a width of $1$ meter and a length of $n$ meters. The river is very cold. Therefore, **in total** (that is, throughout the entire swim from $0$ to $n+1$) ErnKor can swim in the water for no more than $k$ meters. For the sake of humanity, we have added not only crocodiles to the river, but also logs on which he can jump. Our test is as follows: Initially, ErnKor is on the left bank and needs to reach the right bank. They are located at the $0$ and $n+1$ meters respectively. The river can be represented as $n$ segments, each with a length of $1$ meter. Each segment contains either a log 'L', a crocodile 'C', or just water 'W'. ErnKor can move as follows: - If he is on the surface (i.e., on the bank or on a log), he can jump forward for no more than $m$ ($1 \le m \le 10$) meters (he can jump on the bank, on a log, or in the water). - If he is in the water, he can only swim to the next river segment (or to the bank if he is at the $n$-th meter). - ErnKor cannot land in a segment with a crocodile in any way. Determine if ErnKor can reach the right bank. The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, int &m, int &k, string &a) { // write your code here } }; ``` where: - return ""YES"" if ErnKor can pass the test, and return ""NO"" otherwise. # Example 1: - Input: n = 6, m = 2, k = 0 a = ""LWLLLW"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - $0 \leq k \leq @data$ - $1 \leq m \leq 10$ - $a[i] \in \{ 'L', 'W', 'C' \}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, int &m, int &k, string &a) { int x = -1; for (int i = 0; i <= n; i++) { if (x >= 0 && a[x] == 'W') { x = i; k--; } else if (i == n || a[i] == 'L' || i - x == m) x = i; if (x >= 0 && x < n && a[x] == 'C') { return ""NO""; } } return k >= 0 ? ""YES"" : ""NO""; } string solve2(int &n, int &m, int &k, string &a) { int pos = 0; while (pos < n + 1) { int bound = pos + m; if (bound >= n + 1) return ""YES""; if (bound > n) bound = n; int nextL = -1; for (int t = bound; t >= pos + 1; --t) { if (a[t - 1] == 'L') { nextL = t; break; } } if (nextL != -1) { pos = nextL; continue; } int p = bound; if (a[p - 1] == 'C') { bool found = false; for (int t = p - 1; t >= pos + 1; --t) { if (a[t - 1] != 'C') { p = t; found = true; break; } } if (!found) return ""NO""; } int w = p - 1; while (true) { if (w == n - 1) { k--; if (k < 0) return ""NO""; pos = n + 1; break; } if (a[w + 1] == 'C') return ""NO""; k--; if (k < 0) return ""NO""; w++; if (a[w] == 'L') { pos = w + 1; break; } } } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m, k; cin >> n >> m >> k; string a; cin >> a; // solve Solution solution; auto result = solution.solve(n, m, k, a); // output cout << result << ""\n""; return 0; }","dp,greedy",hard 397,"# Problem Statement You received an $n\times m$ grid from a mysterious source. The source also gave you a magic positive integer constant $k$. The source told you to color the grid with some colors, satisfying the following condition: - If $(x_1,y_1)$, $(x_2,y_2)$ are two distinct cells with the same color, then $\max(|x_1-x_2|,|y_1-y_2|)\ge k$. You don't like using too many colors. Please find the minimum number of colors needed to color the grid. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &m, int &k) { // write your code here } }; ``` where: - return: the minimum number of colors needed to color the grid. # Example 1: - Input: n = 3, m = 3, k = 2 - Output: 4 # Constraints: - $1 \leq n, m \leq @data$ - $1 \leq k \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &m, int &k) { return min(n, k) * min(m, k); } int solve2(int &n, int &m, int &k) { int rows = n < k ? n : k; int cols = m < k ? m : k; int total = 0; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { total += 1; } } return total; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m, k; cin >> n >> m >> k; // solve Solution solution; auto result = solution.solve(n, m, k); // output cout << result << ""\n""; return 0; }",constructive_algorithms,easy 398,"A happy string is a string that: consists only of letters of the set ['a', 'b', 'c']. s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). For example, strings ""abc"", ""ac"", ""b"" and ""abcbabcbcb"" are all happy strings and strings ""aa"", ""baa"" and ""ababbc"" are not happy strings. Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n. solution main function ```cpp class Solution { public: string solve(int n, int k) { } }; ``` Example 1: Input: n = 1, k = 3 Output: ""c"" Example 2: Input: n = 1, k = 4 Output: """" Constraints: 1 <= n <= @data 1 <= k <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: string solve(int n, int &k, int p = 0, char last_ch = 0) { if (p == n) --k; else for (char ch = 'a'; ch <= 'c'; ++ch) { if (ch != last_ch) { auto res = solve(n, k, p + 1, ch); if (k == 0) return string(1, ch) + res; } } return """"; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; // solve Solution solution; auto result = solution.solve(n,k); // output // for(auto it:result) cout< &a, vector &b) { // write your code here } }; ``` where: - `n` is the number of videos - `t` is the lunch time - `a` is the duration of the videos - `b` is the entertainment value of the videos # Example 1: - Input: n = 5 t = 9 a = [1, 5, 7, 6, 6] b = [3, 4, 7, 1, 9] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i], b[i], t \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &t, vector &a, vector &b) { int x = -2; for (int i = 0; i < n; i++) { if (a[i] + i <= t) { if (x == -2 || b[x] < b[i]) x = i; } } return x + 1; } int solve2(int &n, int &t, vector &a, vector &b) { int bestIndex = -1; int bestEntertainment = -1; for (int i = 0; i < n; ++i) { long long total = (long long)a[i] + i; if (total <= t) { if (bestIndex == -1 || b[i] > bestEntertainment) { bestIndex = i; bestEntertainment = b[i]; } } } if (bestIndex == -1) return -1; return bestIndex + 1; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, t; cin >> n >> t; vector a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; // solve Solution solution; auto result = solution.solve(n, t, a, b); // output cout << result << ""\n""; return 0; }",greedy,easy 400,"We define the conversion array conver of an array arr as follows: conver[i] = arr[i] + max(arr[0..i]) where max(arr[0..i]) is the maximum value of arr[j] over 0 <= j <= i. We also define the score of an array arr as the sum of the values of the conversion array of arr. Given a 0-indexed integer array nums of length n, return an array ans of length n where ans[i] is the score of the prefix nums[0..i]. solution main function ```cpp class Solution { public: vector solve(vector& nums) { } }; ``` Example 1: Input: nums = [2,3,7,5,10] Output: [4,10,24,36,56] Example 2: Input: nums = [1,1,2,4,8,16] Output: [2,4,8,16,32,64] Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve1(vector& nums) { vector result(nums.size()); int max_num = nums[0]; result[0] = nums[0] * 2; for(int i = 1; i < nums.size(); i++) { max_num = max(max_num, nums[i]); result[i] = nums[i] + max_num + result[i-1]; } return result; } vector solve2(vector& nums) { int n = (int)nums.size(); vector result(n); for (int i = 0; i < n; ++i) { long long score = 0; int max_num = INT_MIN; for (int j = 0; j <= i; ++j) { if (nums[j] > max_num) max_num = nums[j]; score += (long long)nums[j] + (long long)max_num; } result[i] = score; } return result; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output for(auto it:result) cout< using namespace std; class Solution { public: int solve1(int &n, string &s) { int l = 0, r = n - 1; while (s[l] == 'W') { l++; } while (s[r] == 'W') { r--; } int ans = r - l + 1; return ans; } int solve2(int &n, string &s) { bool allW = true; for (int i = 0; i < n; i++) { if (s[i] == 'B') { allW = false; break; } } if (allW) return 0; int best = n; for (int i = 0; i < n; i++) { bool preOk = true; for (int k = 0; k < i; k++) { if (s[k] == 'B') { preOk = false; break; } } if (!preOk) continue; for (int j = i; j < n; j++) { bool sufOk = true; for (int k = j + 1; k < n; k++) { if (s[k] == 'B') { sufOk = false; break; } } if (sufOk) { int len = j - i + 1; if (len < best) best = len; if (best == 1) return 1; } } } return best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s;cin>>s; // solve Solution solution; auto result = solution.solve(n,s); // output cout << result << ""\n""; return 0; }","greedy,string",easy 402,"There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. solution main function ```cpp class Solution { public: vector solve(int n, vector>& edges) { } }; ``` Example 1: Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] Output: [8,12,6,10,10,10] Example 2: Input: n = 1, edges = [] Output: [0] Constraints: 1 <= n <= @data edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { int res=0; int dfs(int cur,int par, vector>& adj,vector& cnt,int lvl){ int sum=0; res+=lvl; for(auto child:adj[cur]){ if(child!=par){ sum+=dfs(child,cur,adj,cnt,lvl+1); } } cnt[cur]=sum+1; return sum+1; } inline int baseId(int v, int n) { if (v < 0) return -(v + 1); if (v >= n) return v - n; return v; } inline int stateOf(int v, int n) { if (v < 0) return 1; if (v >= n) return 2; return 0; } inline void markNodeOld(int id, vector>& edges, int n) { int neg = -(id + 1); for (auto &e : edges) { if (e[0] == id) e[0] = neg; if (e[1] == id) e[1] = neg; } } inline void markNodeNew(int id, vector>& edges, int n) { int nv = n + id; for (auto &e : edges) { if (e[0] == id) e[0] = nv; if (e[1] == id) e[1] = nv; } } inline void promoteNewToOld(vector>& edges, int n) { for (auto &e : edges) { if (e[0] >= n) e[0] = -((e[0] - n) + 1); if (e[1] >= n) e[1] = -((e[1] - n) + 1); } } inline void normalizeAll(vector>& edges, int n) { for (auto &e : edges) { if (e[0] < 0) e[0] = -(e[0] + 1); else if (e[0] >= n) e[0] = e[0] - n; if (e[1] < 0) e[1] = -(e[1] + 1); else if (e[1] >= n) e[1] = e[1] - n; } } public: vector solve1(int n, vector>& edges) { vector> adj(n); for(int i=0; i cnt(n,0); int total=dfs(0,-1,adj,cnt,0); vector par(n,0); par[0]=res; queue q; q.push(0); while(!q.empty()){ int cur=q.front(); q.pop(); for(auto child:adj[cur]){ if(par[child]==0){ par[child]=par[cur]-cnt[child]+(total-cnt[child]); q.push(child); } } } return par; } vector solve2(int n, vector>& edges) { vector ans(n, 0); if (n <= 1) { if (n == 1) ans[0] = 0; return ans; } for (int root = 0; root < n; ++root) { normalizeAll(edges, n); markNodeOld(root, edges, n); long long sum = 0; int dist = 1; while (true) { long long cntNew = 0; for (size_t i = 0; i < edges.size(); ++i) { int a = edges[i][0], b = edges[i][1]; int sa = stateOf(a, n), sb = stateOf(b, n); if (sa == 1 && sb == 0) { int idb = baseId(b, n); markNodeNew(idb, edges, n); ++cntNew; } else if (sb == 1 && sa == 0) { int ida = baseId(a, n); markNodeNew(ida, edges, n); ++cntNew; } } if (cntNew == 0) break; sum += cntNew * (long long)dist; promoteNewToOld(edges, n); ++dist; } ans[root] = (int)sum; } normalizeAll(edges, n); return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector> e; for(int i=1;i>x>>y; vector temp; temp.push_back(x); temp.push_back(y); e.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,e); // output for(auto it:result) cout<& nums) { } }; ``` Example 1: Input: nums = [5,4,0,3,1,6,2] Output: 4 Example 2: Input: nums = [0,1,2] Output: 1 Constraints: 1 <= nums.length <= @data 0 <= nums[i] < nums.length All the values of nums are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { int ans = 0; for (int x : nums) { if (x == -1) continue; int cnt = 0; while (nums[x] != -1) { cnt += 1; int prev = x; x = nums[x]; nums[prev] = -1; } ans = max(ans, cnt); } return ans; } int solve2(vector& nums) { int n = (int)nums.size(); int ans = 0; for (int i = 0; i < n; ++i) { int x = nums[i]; if (x == -1) continue; int cnt = 0; while (x != -1 && nums[x] != -1) { ++cnt; int prev = x; x = nums[prev]; nums[prev] = -1; } if (cnt > ans) ans = cnt; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }",search,easy 404,"# Problem Statement To train young Kevin's arithmetic skills, his mother devised the following problem. Given $n$ integers $a_1, a_2, \ldots, a_n$ and a sum $s$ initialized to $0$, Kevin performs the following operation for $i = 1, 2, \ldots, n$ in order: - Add $a_i$ to $s$. If the resulting $s$ is even, Kevin earns a point and repeatedly divides $s$ by $2$ until it becomes odd. Note that Kevin can earn at most one point per operation, regardless of how many divisions he does. Since these divisions are considered more beneficial for Kevin's development, his mother wants to rearrange $a$ so that the number of Kevin's total points is maximized. Determine the maximum number of points. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - returns the maximum number of points. # Example 1: - Input: n = 2, a = [1, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { int odd = 0; for (int i = 0; i < n; i++) { odd += a[i] % 2; } return min(n - 1, odd) + min(1, n - odd); } int solve2(int &n, vector &a) { if (n <= 1) { unsigned __int128 s = 0; int points = 0; for (int i = 0; i < n; ++i) { s += (unsigned long long)a[i]; if ((s & 1) == 0) { ++points; while ((s & 1) == 0) s >>= 1; } } return points; } while (next_permutation(a.begin(), a.end())) ; int best = 0; do { unsigned __int128 s = 0; int points = 0; for (int i = 0; i < n; ++i) { s += (unsigned long long)a[i]; if ((s & 1) == 0) { ++points; while ((s & 1) == 0) s >>= 1; } } if (points > best) best = points; } while (next_permutation(a.begin(), a.end())); return best; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",math,easy 405,"Given an integer array nums and an integer k, modify the array in the following way: choose an index i and replace nums[i] with -nums[i]. You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way. solution main function ```cpp class Solution { public: int solve(vector& nums, int k) { } }; ``` Example 1: Input: nums = [4,2,3], k = 1 Output: 5 Example 2: Input: nums = [3,-1,0,2], k = 3 Output: 6 Constraints: 1 <= nums.length <= @data -100 <= nums[i] <= 100 1 <= k <= 10^4 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums, int k) { sort(nums.begin(),nums.end()); int n=nums.size(),mini=INT_MAX,sum=0; for(int i=0;i0 && k){ sum-=2*mini; } if(mini<0 && k){ sum+=-2*mini; } return sum; } int solve2(vector& nums, int k) { long long sum = 0; int n = (int)nums.size(); for (int i = 0; i < n; ++i) sum += nums[i]; for (int t = 0; t < k; ++t) { int idx = 0; int minVal = nums[0]; for (int i = 1; i < n; ++i) { if (nums[i] < minVal) { minVal = nums[i]; idx = i; } } if (minVal < 0) { sum += -2LL * minVal; nums[idx] = -nums[idx]; } else if (minVal == 0) { break; } else { sum -= 2LL * minVal; nums[idx] = -nums[idx]; } } return (int)sum; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,k; cin>>n>>k; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s,k); // output // for(auto it:result) cout<& nums) { } }; ``` Example 1: Input: nums = [1,2,2,3,1,4] Output: 4 Example 2: Input: nums = [1,2,3,4,5] Output: 5 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve1(vector& nums) { unordered_map frequencies; int maxFrequency = 0; int totalFrequencies = 0; for (int num : nums) { frequencies[num]++; int frequency = frequencies[num]; if (frequency > maxFrequency) { maxFrequency = frequency; totalFrequencies = frequency; } else if (frequency == maxFrequency) { totalFrequencies += frequency; } } return totalFrequencies; } int solve2(vector& nums) { int n = (int)nums.size(); int maxFrequency = 0; for (int i = 0; i < n; ++i) { int count = 0; for (int j = 0; j < n; ++j) { if (nums[j] == nums[i]) ++count; } if (count > maxFrequency) maxFrequency = count; } int totalFrequencies = 0; for (int i = 0; i < n; ++i) { bool first = true; for (int k = 0; k < i; ++k) { if (nums[k] == nums[i]) { first = false; break; } } if (!first) continue; int count = 0; for (int j = 0; j < n; ++j) { if (nums[j] == nums[i]) ++count; } if (count == maxFrequency) totalFrequencies += count; } return totalFrequencies; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector a; for(int i=1;i<=n;i++) { int x; cin>>x; a.push_back(x); } // solve Solution solution; auto result = solution.solve(a); // output cout << result << ""\n""; // for(auto it:result) cout< using namespace std; class Solution { public: int solve1(string &s) { const int n = s.length(); int ans = n + 1; int cnt[3] = {}; for (int i = 0, j = 0; i < n; ++i) { while ((!cnt[0] || !cnt[1] || !cnt[2]) && j <= n) { if (j < n) ++cnt[s[j] - '1']; ++j; } if (j > n) break; ans = min(ans, j - i); --cnt[s[i] - '1']; } if (ans > n) { return 0; } else { return ans; } } int solve2(string &s) { const int n = (int)s.length(); int ans = n + 1; for (int i = 0; i < n; ++i) { int c1 = 0, c2 = 0, c3 = 0; for (int j = i; j < n; ++j) { char ch = s[j]; if (ch == '1') ++c1; else if (ch == '2') ++c2; else if (ch == '3') ++c3; if (c1 && c2 && c3) { int len = j - i + 1; if (len < ans) ans = len; break; } } } if (ans > n) { return 0; } else { return ans; } } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string s; cin >> s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }","binary,dp,two_pointers",easy 408,"# Problem Statement You have an array of **zeros** $a_1, a_2, \ldots, a_n$ of length $n$. You can perform two types of operations on it: 1. Choose an index $i$ such that $1 \le i \le n$ and $a_i = 0$, and assign $1$ to $a_i$; 2. Choose a pair of indices $l$ and $r$ such that $1 \le l \le r \le n$, $a_l = 1$, $a_r = 1$, $a_l + \ldots + a_r \ge \lceil\frac{r - l + 1}{2}\rceil$, and assign $1$ to $a_i$ for all $l \le i \le r$. What is the minimum number of operations of the **first type** needed to make all elements of the array equal to one? The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n) { // write your code here } }; ``` where: - return:the minimum number of needed operations of first type. # Example 1: - Input: n = 1 - Output: 1 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n) { int ans = 1; int k = 1; while (k < n) { k = (k + 1) * 2; ans++; } return ans; } int solve2(int &n) { if (n <= 1) return 1; int ans = 1; while (true) { long long cap = 0; for (int i = 1; i <= ans; ++i) { if (i == 1) { cap = 1; } else { if (cap > (LLONG_MAX - 2) / 2) { cap = LLONG_MAX; } else { cap = 2 * (cap + 1); } } if (cap >= n) break; } if (cap >= n) break; ans++; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; // solve Solution solution; auto result = solution.solve(n); // output cout << result << ""\n""; return 0; }","constructive_algorithms,math",easy 409,"Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: perm[i] is divisible by i. i is divisible by perm[i]. Given an integer n, return the number of the beautiful arrangements that you can construct. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 2 Output: 2 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[5, 10, 15]",1000,"[[200, 64, 64], [1600, 160, 64], [12800, 1280, 128]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { bool check[16]={}; int ans=0; public: int solve1(int n) { dfs(1,n); return ans; } void dfs(int pos,int n) { if(pos==n+1) { ans++; return; } for(int i=1;i<=n;i++) { if(!check[i]&&(pos%i==0||i%pos==0)) { check[i]=true; dfs(pos+1,n); check[i]=false; } } } int solve2(int n) { if(n<=0) return 0; bool used[16]={0}; int cur[16]={0}; long long ans=0; int pos=1; cur[1]=0; while(true){ if(pos==0) break; if(pos==n+1){ ans++; pos--; if(pos>=1){ used[cur[pos]]=false; } continue; } int i=cur[pos]+1; while(i<=n){ if(!used[i] && ((pos%i==0) || (i%pos==0))) break; i++; } if(i<=n){ used[i]=true; cur[pos]=i; pos++; if(pos<=n) cur[pos]=0; }else{ if(pos==1 && cur[pos]==0){ pos=0; }else{ pos--; if(pos>=1){ used[cur[pos]]=false; } } } } return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< max(heights[i+1], heights[i+2], ..., heights[j-1]). Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue. solution main function ```cpp class Solution { public: vector solve(vector& heights) { } }; ``` Example 1: Input: heights = [10,6,8,5,11,9] Output: [3,1,2,1,1,0] Example 2: Input: heights = [5,1,2,3,10] Output: [4,1,1,1,0] Constraints: n == heights.length 1 <= n <= @data 1 <= heights[i] <= @data All the values of heights are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[1250, 625, 312], [10000, 5000, 2500], [80000, 40000, 20000]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector solve(vector& A) { int n = A.size(); vector res(n), stack; for (int i = 0; i < n; ++i) { while (!stack.empty() && A[stack.back()] <= A[i]) res[stack.back()]++, stack.pop_back(); if (!stack.empty()) res[stack.back()]++; stack.push_back(i); } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; vector s; for(int i=1;i<=n;i++) { int x; cin>>x; s.push_back(x); } // solve Solution solution; auto result = solution.solve(s); // output for(auto it:result) cout< &a) { // write your code here } }; ``` where: - return the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, return −1. # Example 1: - Input: n = 3, x = 3 a = [1,2,3] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq x, a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &x, vector &a) { int u = -1, v = -1; int ans = -1, sum = 0; for (int i = 0; i < n; ++i) { sum = (sum + a[i]) % x; if (sum) ans = max(ans, i + 1); if (u != -1 && sum != u) ans = max(ans, i + 1 - v); if (u == -1 && sum) { u = sum; v = i + 1; } } return ans; } int solve2(int &n, int &x, vector &a) { int ans = -1; for (int l = 0; l < n; ++l) { int rem = 0; for (int r = l; r < n; ++r) { rem += a[r] % x; if (rem >= x) rem -= x; if (rem) { int len = r - l + 1; if (len > ans) ans = len; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, x; cin >> n >> x; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, x, a); // output cout << result << ""\n""; return 0; }","math,two_pointers,data_structures",medium 412,"Given a connected undirected graph $G$ with $n$ nodes and $m$ edges, where all nodes are numbered from 1 to $n$. Find the sum of the edge weights of the minimum spanning tree of $G$. The edges are represented as $edges[i] = [a, b, c]$, indicating that there is an edge between nodes $a$ and $b$ with a weight of $c$. solution main function ```cpp class Solution { public: long long solve(int n, vector>& edges) { } }; ``` Example 1: Input: n = 7, edges = [[1,2,9],[1,5,2],[1,6,3],[2,3,5],[2,6,7],[3,4,6],[3,7,3],[4,5,6],[4,7,2],[5,6,3],[5,7,6],[6,7,1]] Output: 16 Constraints: 2 <= n <= @data edges[i].size ==3 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; typedef long long ll; class Solution { public: int n=0, m=0, fa1=0, fa2=0, k=0; struct node { int u, v, w; bool operator <(const node &a) const { return w < a.w; } }; int find(int x) { if (x == fa[x]) return x; return fa[x] = find(fa[x]); } vector edge; vector fa; long long ans=0; long long solve1(int N, vector>& edges) { n=N; m=edges.size(); fa.resize(n+10,0); for(int i=1;i<=n;i++) fa[i]=i; for (int i = 1; i <= m; i++) edge.push_back({edges[i-1][0],edges[i-1][1],edges[i-1][2]}); sort(edge.begin(), edge.end()); for (int i = 0; i < m; i++) { fa1 = find(edge[i].u); fa2 = find(edge[i].v); if (fa1 == fa2) continue; fa[fa1] = fa2; ans += edge[i].w; k++; if (k == n - 1) break; } return ans; } long long solve2(int n, vector>& edges) { if(n<=1) return 0; sort(edges.begin(), edges.end(), [](const vector& a, const vector& b){ return a[2] < b[2]; }); vector fa(n+1); for(int i=1;i<=n;i++) fa[i]=i; auto findp = [&](int x)->int { while(fa[x]!=x){ fa[x]=fa[fa[x]]; x=fa[x]; } return x; }; long long ans=0; int cnt=0, m=(int)edges.size(); for(int i=0;in||v<1||v>n) continue; int fu=findp(u), fv=findp(v); if(fu==fv) continue; fa[fu]=fv; ans += (long long)edges[i][2]; cnt++; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,m; cin>>n>>m; vector< vector > edge; for(int i=1,x,y,z;i<=m;i++) { scanf(""%d%d%d"",&x,&y,&z); vector temp; temp.push_back(x); temp.push_back(y); temp.push_back(z); edge.push_back(temp); } // solve Solution solution; auto result = solution.solve(n,edge); // output // for(auto it:result) cout< using namespace std; #include using namespace std; class Solution { public: string solve1(string word, char ch) { int left = 0; for (int right = 0; right < word.length(); right++) { if (word[right] == ch) { while (left < right) { swap(word[right], word[left]); left++; right--; } return word; } } return word; } string solve2(string word, char ch) { size_t n = word.size(); size_t pos = n; for (size_t i = 0; i < n; ++i) { if (word[i] == ch) { pos = i; break; } } if (pos == n) return word; size_t l = 0, r = pos; while (l < r) { char t = word[l]; word[l] = word[r]; word[r] = t; ++l; --r; } return word; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s,ch; cin>>ch>>s; // solve Solution solution; auto result = solution.solve(s,ch[0]); // output cout< using namespace std; class Solution { public: int solve1(string &s) { int cnt = 1, cnt2 = 0; for (int i = 1; i < s.size(); i++) if (s[i] == '0' && s[i - 1] == '1') cnt++; else if (s[i] == '1' && s[i - 1] == '0') cnt2++; if (cnt2) cnt2--; return cnt + cnt2; } int solve2(string &s) { long long a = 0, b = 0; for (size_t i = 1; i < s.size(); ++i) { char p = s[i - 1], c = s[i]; if (p == '0' && c == '1') ++a; else if (p == '1' && c == '0') ++b; } long long res = (a == 0) ? (b + 1) : (a + b); if (res > INT_MAX) return INT_MAX; return (int)res; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string s; cin >> s; // solve Solution solution; auto result = solution.solve(s); // output cout << result << ""\n""; return 0; }","dp,sort,string",hard 415,"# Problem Statement You are given two binary strings $a$ and $b$. A binary string is a string consisting of the characters '0' and '1'. Your task is to determine the maximum possible number $k$ such that a prefix of string $a$ of length $k$ is a subsequence of string $b$. A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements. The main function of the solution is defined as: ```cpp class Solution { public: int solve(string &a, string &b) { // write your code here } }; ``` where: - return: the maximum possible number $k$ such that a prefix of string $a$ of length $k$ is a subsequence of string $b$. # Example 1: - Input: a = ""10011"" b = ""1110"" - Output: 2 # Constraints: - $1 \leq a.length, b.length \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(string &a, string &b) { int n = a.size(); int m = b.size(); int ans = 0; for (int i = 0; i < m; i++) { if (ans < n && b[i] == a[ans]) { ans++; } } return ans; } int solve2(string &a, string &b) { int n = (int)a.size(); int m = (int)b.size(); int ans = 0; for (int k = n; k >= 0; k--) { int j = 0; for (int i = 0; i < m && j < k; i++) { if (b[i] == a[j]) { j++; } } if (j == k) { ans = k; break; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input string a, b; cin >> a >> b; // solve Solution solution; auto result = solution.solve(a, b); // output cout << result << ""\n""; return 0; }","two_pointers,string",easy 416,"There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents: the price needed to open the gate at node i, if amount[i] is negative, or, the cash reward obtained on opening the gate at node i, otherwise. The game goes on as follows: Initially, Alice is at node 0 and Bob is at node bob. At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0. For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that: If the gate is already open, no price will be required, nor will there be any cash reward. If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each. If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other. Return the maximum net income Alice can have if she travels towards the optimal leaf node. solution main function ```cpp class Solution { public: int solve(vector>& edges, int bob, vector& amount) { } }; ``` Example 1: Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6] Output: 6 Example 2: Input: edges = [[0,1]], bob = 1, amount = [-7280,2350] Output: -7280 Constraints: 2 <= n <= @data edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree. 1 <= bob < n amount.length == n amount[i] is an even integer in the range [-10^4, 10^4] Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: vector>adj; vectorpar,dis; void dfs(int u,int p = 0,int d = 0){ dis[u] = d; par[u] = p; for(int v:adj[u]){ if(v==p)continue; dfs(v,u,d+1); } } int dfs2(int u,vector&amount,int p= 0){ int ret = amount[u]; int mxc = -INT_MAX; for(int v:adj[u]){ if(v!=p){ mxc= max(mxc,dfs2(v,amount,u)); } } if(mxc==-INT_MAX)return ret; else return ret+mxc; } int solve1(vector>& edges, int bob, vector& amount) { int n = amount.size(); adj.resize(n,vector()); for(auto&e:edges){ adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); } par.resize(n); dis.resize(n); dfs(0); int cur = bob; int bob_dis = 0; while(cur!=0){ if(dis[cur]>bob_dis){ amount[cur] = 0; }else if(dis[cur]==bob_dis){ amount[cur]/=2; } cur = par[cur]; bob_dis++; } return dfs2(0,amount); } int solve2(vector>& edges, int bob, vector& amount) { int n = (int)amount.size(); int m = (int)edges.size(); int cur = 0; while (true) { bool found = false; for (int i = 0; i < m; i++) { int a = edges[i][0], b = edges[i][1]; if (a == cur && b >= 0) { edges[i][1] = -b; cur = b; found = true; break; } else if (b == cur && a >= 0) { edges[i][0] = -a; cur = a; found = true; break; } } if (found) continue; if (cur == 0) break; int parent = 0; for (int i = 0; i < m; i++) { if (edges[i][0] == -cur) { parent = edges[i][1]; break; } else if (edges[i][1] == -cur) { parent = edges[i][0]; break; } } cur = parent; } int depth_bob = 0; int tmp = bob; while (tmp != 0) { int parent = 0; for (int i = 0; i < m; i++) { if (edges[i][0] == -tmp) { parent = edges[i][1]; break; } else if (edges[i][1] == -tmp) { parent = edges[i][0]; break; } } tmp = parent; depth_bob++; } int bob_dis = 0; tmp = bob; while (true) { int depth_cur = depth_bob - bob_dis; if (depth_cur > bob_dis) { amount[tmp] = 0; } else if (depth_cur == bob_dis) { amount[tmp] /= 2; } if (tmp == 0) break; int parent = 0; for (int i = 0; i < m; i++) { if (edges[i][0] == -tmp) { parent = edges[i][1]; break; } else if (edges[i][1] == -tmp) { parent = edges[i][0]; break; } } tmp = parent; bob_dis++; } long long ans = LLONG_MIN; bool rootHasChild = false; for (int i = 0; i < m; i++) { if ((edges[i][0] == 0 && edges[i][1] < 0) || (edges[i][1] == 0 && edges[i][0] < 0)) { rootHasChild = true; break; } } if (!rootHasChild) { ans = max(ans, (long long)amount[0]); } for (int node = 1; node < n; node++) { bool hasChild = false; for (int i = 0; i < m; i++) { if ((edges[i][0] == node && edges[i][1] < 0) || (edges[i][1] == node && edges[i][0] < 0)) { hasChild = true; break; } } if (!hasChild) { long long sum = 0; int x = node; while (true) { sum += (long long)amount[x]; if (x == 0) break; int parent = 0; for (int i = 0; i < m; i++) { if (edges[i][0] == -x) { parent = edges[i][1]; break; } else if (edges[i][1] == -x) { parent = edges[i][0]; break; } } x = parent; } if (sum > ans) ans = sum; } } if (ans == LLONG_MIN) ans = 0; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,bob; cin>>n>>bob; vector > edge; vector< int > val; for(int i=1,x,y,z;i temp; temp.push_back(x); temp.push_back(y); edge.push_back(temp); } for(int i=1,x;i<=n;i++) { scanf(""%d"",&x); val.push_back(x); } // solve Solution solution; auto result = solution.solve(edge,bob,val); // output // for(auto it:result) cout< &v, vector &a) { // write your code here } }; ``` Pass in parameters: - `n`, `d`: the number of stops and kilometers traveled per liter of fuel. - `v`: an array of `n - 1` positive integers, where `v[i]` is the distance between consecutive sites. - `a`: an array of `n` positive integers, where `a[i]` is the fuel price at a station. Return parameters: An integer indicating the minimum money the Bract must spend on fuel from site $1$ to site $n$. Example 1: Input: n = 5, d = 4, v = [10, 10, 10, 10], a = [9, 8, 9, 6, 5] Output: 79 Constraints: 1 <= n <= @data 1 <= d <= 10^5 1 <= a[i], v[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: long long solve1(int n, int d, vector &v, vector &a) { long long ans = 0, s = 0; int mi = INT_MAX; v.insert(v.begin(), 0); a.insert(a.begin(), 0); for (int i = 1; i < n; i++) { s += v[i]; mi = min(mi, a[i]); if (s > 0) { ans += (s + d - 1) / d * mi; s -= (s + d - 1) / d * d; } } return ans; } long long solve2(int n, int d, vector &v, vector &a) { long long cost = 0; long long fuel_km = 0; for (int i = 0; i < n - 1; ++i) { long long distSum = 0; int j = i + 1; while (j < n && a[j] >= a[i]) { distSum += (long long)v[j - 1]; ++j; } long long targetDist = (j == n) ? distSum : (distSum + (long long)v[j - 1]); long long needKm = targetDist - fuel_km; if (needKm > 0) { long long liters = (needKm + (long long)d - 1) / (long long)d; cost += liters * (long long)a[i]; fuel_km += liters * (long long)d; } fuel_km -= (long long)v[i]; } return cost; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n,d; cin>>n>>d; vector dist,val; for(int i=1,x;i>x; dist.push_back(x); } for(int i=1,x;i<=n;i++) { cin>>x; val.push_back(x); } // solve Solution solution; auto result = solution.solve(n,d,dist,val); // output cout << result << ""\n""; return 0; }",dp,hard 418,"# Problem Statement Karina has an array of $n$ integers $a_1, a_2, a_3, \dots, a_n$. She loves multiplying numbers, so she decided that the beauty of a pair of numbers is their product. And the beauty of an array is the maximum beauty of a pair of **adjacent** elements in the array. For example, for $n = 4$, $a=[3, 5, 7, 4]$, the beauty of the array is $\max$($3 \cdot 5$, $5 \cdot 7$, $7 \cdot 4$) = $\max$($15$, $35$, $28$) = $35$. Karina wants her array to be as beautiful as possible. In order to achieve her goal, she can remove some elements (possibly zero) from the array. After Karina removes all elements she wants to, the array must contain at least two elements. Unfortunately, Karina doesn't have enough time to do all her tasks, so she asks you to calculate the maximum beauty of the array that she can get by removing any number of elements (possibly zero). The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - return value is a 64-bit integer representing the maximum beauty of the array # Example 1: - Input: n = 4 a = [5, 0, 2, 1] - Output: 10 # Constraints: - $2 \leq n \leq @data$ - $-10^9 \leq a_i \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { long long ans = -1E18, mn = 1E18, mx = -1E18; for (int i = 0; i < n; i += 1) { long long x = a[i]; if (i) ans = max({ans, x * mx, x * mn}); mn = min(mn, x); mx = max(mx, x); } return ans; } long long solve2(int &n, vector &a) { long long ans = LLONG_MIN; for (int i = 0; i < n; ++i) { long long x = (long long)a[i]; for (int j = i + 1; j < n; ++j) { long long p = x * (long long)a[j]; if (p > ans) ans = p; } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","greedy,math,sort",easy 419,"There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. For example, the correct password is ""345"" and you enter in ""012345"": After typing 0, the most recent 3 digits is ""0"", which is incorrect. After typing 1, the most recent 3 digits is ""01"", which is incorrect. After typing 2, the most recent 3 digits is ""012"", which is incorrect. After typing 3, the most recent 3 digits is ""123"", which is incorrect. After typing 4, the most recent 3 digits is ""234"", which is incorrect. After typing 5, the most recent 3 digits is ""345"", which is correct and the safe unlocks. Return any string of minimum length that will unlock the safe at some point of entering it. Any valid minimum-length string is accepted. The examples show one valid returned string; this runner validates the returned string and prints 1 if it is valid, or 0 otherwise. solution main function ```cpp class Solution { public: string solve(int n, int k) { // write your code here } }; ``` Example 1: Input: n = 1, k = 2 One valid output: ""10"" Example 2: Input: n = 2, k = 2 One valid output: ""01100"" Constraints: 1 <= n <= 4 1 <= k <= @data 1 <= k^n <= 4096 Time limit: @time_limit ms Memory limit: @memory_limit KB","[3, 5, 10]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: string solve(int n, int k) { int nodeNum = pow(k, n - 1); int nedge = pow(k, n); std::vector vecNode(nodeNum, k - 1); std::string strret(nedge + (n - 1), '0'); for (int i = n - 1, idx = 0; i < strret.length(); ++i) { int& curedge = vecNode[idx]; strret[i] = curedge + '0'; idx = (idx * k + curedge) % nodeNum; --curedge; } return strret; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n, k; cin >> n >> k; // solve Solution solution; auto result = solution.solve(n, k); // output long long total = 1; for (int i = 0; i < n; i++) total *= k; bool ok = (long long)result.size() == total + n - 1; unordered_set seen; if (ok) { for (char ch : result) { if (ch < '0' || ch >= char('0' + k)) { ok = false; break; } } } if (ok) { for (size_t i = 0; i + n <= result.size(); i++) { seen.insert(result.substr(i, n)); } ok = (long long)seen.size() == total; } cout << (ok ? 1 : 0) << ""\n""; return 0; } ",graph,hard 420,"You are given a string s. Reorder the string using the following algorithm: Remove the smallest character from s and append it to the result. Remove the smallest character from s that is greater than the last appended character, and append it to the result. Repeat step 2 until no more characters can be removed. Remove the largest character from s and append it to the result. Remove the largest character from s that is smaller than the last appended character, and append it to the result. Repeat step 5 until no more characters can be removed. Repeat steps 1 through 6 until all characters from s have been removed. If the smallest or largest character appears more than once, you may choose any occurrence to append to the result. Return the resulting string after reordering s using this algorithm. solution main function ```cpp class Solution { public: string solve(string s) { } }; ``` Example 1: Input: s = ""aaaabbbbcccc"" Output: ""abccbaabccba"" Example 2: Input: s = ""rat"" Output: ""art"" Constraints: 1 <= s.length <= @data s consists of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",1000,"[[400, 200, 100], [3200, 1600, 800], [25600, 12800, 6400]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: string solve1(string s) { int cnt[26]{}; for (char& c : s) { ++cnt[c - 'a']; } string ans; while (ans.size() < s.size()) { for (int i = 0; i < 26; ++i) { if (cnt[i]) { ans += i + 'a'; --cnt[i]; } } for (int i = 25; i >= 0; --i) { if (cnt[i]) { ans += i + 'a'; --cnt[i]; } } } return ans; } string solve2(string s) { size_t n = s.size(); string ans; ans.reserve(n); while (ans.size() < n) { int idx = -1; char best = 0; for (size_t i = 0; i < n; ++i) { char c = s[i]; if (c == 0) continue; if (idx == -1 || c < best) { idx = (int)i; best = c; } } if (idx != -1) { ans.push_back(best); s[idx] = 0; char prev = best; while (true) { int idx2 = -1; char best2 = 0; for (size_t i = 0; i < n; ++i) { char c = s[i]; if (c == 0) continue; if (c > prev && (idx2 == -1 || c < best2)) { idx2 = (int)i; best2 = c; } } if (idx2 == -1) break; ans.push_back(best2); s[idx2] = 0; prev = best2; } } if (ans.size() >= n) break; idx = -1; best = 0; for (size_t i = 0; i < n; ++i) { char c = s[i]; if (c == 0) continue; if (idx == -1 || c > best) { idx = (int)i; best = c; } } if (idx != -1) { ans.push_back(best); s[idx] = 0; char prev = best; while (true) { int idx2 = -1; char best2 = 0; for (size_t i = 0; i < n; ++i) { char c = s[i]; if (c == 0) continue; if (c < prev && (idx2 == -1 || c > best2)) { idx2 = (int)i; best2 = c; } } if (idx2 == -1) break; ans.push_back(best2); s[idx2] = 0; prev = best2; } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input string s; cin>>s; // solve Solution solution; auto result = solution.solve(s); // output // for(auto it:result) cout< &a) { // write your code here } }; ``` where: - The return value is the maximum total number of petals that can be assembled in the bouquet. Note that the answer may be very large and should be stored in a 64-bit integer type. # Example 1: - Input: n = 5, m = 10 a = [1, 1, 2, 2, 3] - Output: 7 # Constraints: - $1 \leq n \leq @data$ - $1 \leq m \leq 10^18$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, long long &m, vector &a) { sort(a.begin(), a.end()); long long max_sum = 0, current_sum = 0; int l = 0; for (int r = 0; r < n; r++) { current_sum += a[r]; while (l <= r && (a[r] - a[l] > 1 || current_sum > m)) { current_sum -= a[l]; l++; } max_sum = max(max_sum, current_sum); } return max_sum; } long long solve2(int &n, long long &m, vector &a) { long long ans = 0; for (int i = 0; i < n; ++i) { int k = a[i]; bool seen = false; for (int j = 0; j < i; ++j) { if (a[j] == k) { seen = true; break; } } if (seen) continue; long long cnt_k = 0, cnt_k1 = 0; for (int t = 0; t < n; ++t) { if (a[t] == k) ++cnt_k; else if (a[t] == k + 1) ++cnt_k1; } long long cap = m; long long best = 0; for (long long y = 0; y <= cnt_k1; ++y) { long long cost_y = y * (long long)(k + 1); if (cost_y > cap) break; long long rem = cap - cost_y; long long x = k > 0 ? rem / (long long)k : 0; if (x > cnt_k) x = cnt_k; long long sum = cost_y + x * (long long)k; if (sum > best) best = sum; } long long total = cnt_k * (long long)k + cnt_k1 * (long long)(k + 1); if (best > total) best = total; if (best > ans) ans = best; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; long long m; cin >> n >> m; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, m, a); // output cout << result << ""\n""; return 0; }","two_pointers,greedy,sort",medium 422,"# Problem Statement The beauty of an array $b$ of length $m$ ($m \ge 2$) is defined as $$ \max_{1 \le i < j \le m} (b_j - b_i). $$ Note that the beauty can be negative if the array is strictly decreasing. Hao and Alex play a turn-based game on an array $a$ of length $n$. Initially all elements are unlocked. The players move alternately, with Hao going first: - On Hao's turn, he selects one unlocked element from $a$ and removes it. - On Alex's turn, he selects one unlocked element from $a$ and locks it (so it can no longer be removed). The game ends when all elements are either locked or removed. It can be proven that the game lasts exactly $n$ turns and exactly $\lfloor n/2 \rfloor$ elements remain locked in the final array $b$. Hao wants to minimize the beauty of the final array $b$, while Alex wants to maximize it. Assuming both play optimally, determine the beauty of the final locked array. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - `n`: the length of the input array - `a`: the array elements - return: the beauty of the final locked array under optimal play # Example: - Input: n = 5 a = [5, 1, 2, 3, 4] - Output: 1 # Constraints: - $4 \le n \le @data$ - $1 \le a[i] \le 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",1000,"[[100, 64, 64], [800, 400, 160], [6400, 3200, 1280]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { auto check = [&](int g) -> bool { vector b(n, 0); int mn[3] = {INT_MAX, INT_MAX, INT_MAX}; int mn_sz = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < mn_sz; j++) { if (a[i] - mn[j] >= g) b[i]++; } int v = a[i]; for (int j = 0; j < 3; j++) { if (j >= mn_sz || v < mn[j]) { if (mn_sz < 3) mn_sz++; for (int k = mn_sz - 1; k > j; k--) mn[k] = mn[k - 1]; mn[j] = v; break; } } } int mx[3] = {INT_MIN, INT_MIN, INT_MIN}; int mx_sz = 0; for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < mx_sz; j++) { if (mx[j] - a[i] >= g) b[i]++; } int v = a[i]; for (int j = 0; j < 3; j++) { if (j >= mx_sz || v > mx[j]) { if (mx_sz < 3) mx_sz++; for (int k = mx_sz - 1; k > j; k--) mx[k] = mx[k - 1]; mx[j] = v; break; } } } int t = 0; for (int i = 1; i < n; i++) if (b[i] > b[t]) t = i; if (b[t] <= 1) return false; if (b[t] > 2) { for (int i = 0; i < n; i++) { if (i == t) continue; int diff = (a[i] > a[t] ? a[i] - a[t] : a[t] - a[i]); int bi = b[i] - (diff >= g ? 1 : 0); if (bi >= 2) return true; } return false; } int cnt2 = 0; for (int i = 0; i < n; i++) if (b[i] == 2) cnt2++; if (cnt2 > 3) return true; for (int i = 0; i < n; i++) { if (b[i] != 2) continue; bool ok = true; for (int j = 0; j < n && ok; j++) { if (j == i) continue; int diff = (a[j] > a[i] ? a[j] - a[i] : a[i] - a[j]); int bj = b[j] - (diff >= g ? 1 : 0); if (bj >= 2) ok = false; } if (ok) return false; } return true; }; int lo = -1000000005, hi = 1000000005; while (lo < hi) { int mid = lo + (hi - lo + 1) / 2; if (check(mid)) lo = mid; else hi = mid - 1; } return lo; } int solve2(int &n, vector &a) { auto b_at = [&](int idx, int g) -> int { int cnt = 0; int mn[3] = {INT_MAX, INT_MAX, INT_MAX}; int mn_sz = 0; for (int i = 0; i < idx; i++) { int v = a[i]; for (int j = 0; j < 3; j++) { if (j >= mn_sz || v < mn[j]) { if (mn_sz < 3) mn_sz++; for (int k = mn_sz - 1; k > j; k--) mn[k] = mn[k - 1]; mn[j] = v; break; } } } for (int j = 0; j < mn_sz; j++) { if (a[idx] - mn[j] >= g) cnt++; } int mx[3] = {INT_MIN, INT_MIN, INT_MIN}; int mx_sz = 0; for (int i = idx + 1; i < n; i++) { int v = a[i]; for (int j = 0; j < 3; j++) { if (j >= mx_sz || v > mx[j]) { if (mx_sz < 3) mx_sz++; for (int k = mx_sz - 1; k > j; k--) mx[k] = mx[k - 1]; mx[j] = v; break; } } } for (int j = 0; j < mx_sz; j++) { if (mx[j] - a[idx] >= g) cnt++; } return cnt; }; auto check = [&](int g) -> bool { int t = 0; int bt = b_at(0, g); for (int i = 1; i < n; i++) { int bi = b_at(i, g); if (bi > bt) { bt = bi; t = i; } } if (bt <= 1) return false; if (bt > 2) { for (int i = 0; i < n; i++) { if (i == t) continue; int diff = (a[i] > a[t] ? a[i] - a[t] : a[t] - a[i]); int bi = b_at(i, g); int bi_adj = bi - (diff >= g ? 1 : 0); if (bi_adj >= 2) return true; } return false; } int cnt2 = 0; for (int i = 0; i < n; i++) { if (b_at(i, g) == 2) cnt2++; } if (cnt2 > 3) return true; for (int i = 0; i < n; i++) { int bi = b_at(i, g); if (bi != 2) continue; bool ok = true; for (int j = 0; j < n && ok; j++) { if (j == i) continue; int diff = (a[j] > a[i] ? a[j] - a[i] : a[i] - a[j]); int bj = b_at(j, g); int bj_adj = bj - (diff >= g ? 1 : 0); if (bj_adj >= 2) ok = false; } if (ok) return false; } return true; }; int lo = -1000000005, hi = 1000000005; while (lo < hi) { int mid = lo + (hi - lo + 1) / 2; if (check(mid)) lo = mid; else hi = mid - 1; } return lo; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","binary,data_structures",hard 423,"# Problem Statement Dora has a set $s$ containing integers. In the beginning, she will put all integers in $[l, r]$ into the set $s$. That is, an integer $x$ is initially contained in the set if and only if $l \leq x \leq r$. Then she allows you to perform the following operations: - Select three **distinct** integers $a$, $b$, and $c$ from the set $s$, such that $\gcd(a, b) = \gcd(b, c) = \gcd(a, c) = 1^\dagger$. - Then, remove these three integers from the set $s$. What is the maximum number of operations you can perform? $^\dagger$Recall that $\gcd(x, y)$ means the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers $x$ and $y$. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &l, int &r) { // write your code here } }; ``` where: - return: the maximum number of operations you can perform. # Example 1: - Input: l = 1, r = 3 - Output: 1 # Constraints: - $1 \leq l \leq r \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &l, int &r) { int ans = 0; for (int i = l; i + 2 <= r; i++) { if (i % 2 == 0) continue; ans++; i += 2; } return ans; } int solve2(int &l, int &r) { long long L = l, R = r; long long n = R - L + 1; if (n < 3) return 0; long long ans = (n + (L & 1LL)) / 4; return (int)ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int l, r; cin >> l >> r; // solve Solution solution; auto result = solution.solve(l, r); // output cout << result << ""\n""; return 0; }",math,medium 424,"# Problem Statement You have an integer array $a$ of length $n$. There are two kinds of operations you can make. - Remove an integer from $a$. This operation costs $c$. - Insert an arbitrary positive integer $x$ to any position of $a$ (to the front, to the back, or between any two consecutive elements). This operation costs $d$. You want to make the final array a permutation of **any** positive length. Please output the minimum cost of doing that. Note that you can make the array empty during the operations, but the final array must contain at least one integer. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). Note that the answer may be large, so you should use a type. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, int &c, int &d, vector &a) { // write your code here } }; ``` where: - Return 64-bit integer type of the minimum cost # Example 1: - Input: n = 3, c = 3, d = 3 a = [1, 2, 3] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq c, d \leq 10^9$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, int &c, int &d, vector &a) { sort(a.begin(), a.end()); long long ans = 1LL * c * n + d; int t = 0; for (int i = 0; i < n; i++) { if (i == 0 || a[i] != a[i - 1]) t++; ans = min(ans, 1LL * c * n + 1LL * d * a[i] - 1LL * (c + d) * t); } return ans; } long long solve2(int &n, int &c, int &d, vector &a) { sort(a.begin(), a.end()); long long N = n, C = c, D = d; long long ans = C * N + D; long long distinct = 0; int i = 0; while (i < n) { int v = a[i]; distinct++; long long cost = C * N + D * (long long)v - (C + D) * distinct; if (cost < ans) ans = cost; while (i < n && a[i] == v) i++; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, c, d; cin >> n >> c >> d; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, c, d, a); // output cout << result << ""\n""; return 0; }","math,sort",hard 425,"# Problem Statement Dmitry has a string $s$, consisting of lowercase Latin letters. Dmitry decided to remove two **consecutive** characters from the string $s$ and you are wondering how many different strings can be obtained after such an operation. For example, Dmitry has a string ""aaabcc"". You can get the following different strings: ""abcc""(by deleting the first two or second and third characters), ""aacc""(by deleting the third and fourth characters),""aaac""(by deleting the fourth and the fifth character) and ""aaab"" (by deleting the last two). The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, string &s) { // write your code here } }; ``` where: - return: the number of distinct strings that can be obtained by removing two consecutive letters. # Example 1: - Input: n = 6 s = ""aaabcc"" - Output: 4 # Constraints: - $3 \leq n \leq @data$ - $s$ consists of lowercase Latin letters - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, string &s) { int ans = n - 1; for (int i = 0; i + 2 < n; i++) { ans -= (s[i] == s[i + 2]); } return ans; } int solve2(int &n, string &s) { int ans = 0; for (int i = 0; i + 1 < n; ++i) { if (i > 0 && s[i - 1] == s[i + 1]) continue; ++ans; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, s); // output cout << result << ""\n""; return 0; }","string,greedy,data_structures",hard 426,"There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step: Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). Paste: You can paste the characters which are copied last time. Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen. solution main function ```cpp class Solution { public: int solve(int n) { } }; ``` Example 1: Input: n = 3 Output: 3 Example 2: Input: n = 1 Output: 0 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; #include using namespace std; class Solution { public: int solve(int n) { if (n == 1) return 0; int steps = n; for (int d = 2; d <= sqrt(n); ++d) { if (n % d == 0) { steps = min(steps, solve(d) + (n / d)); steps = min(steps, solve(n / d) + d); } } return steps; } }; #endif","#include #include using namespace std; #include ""std.h"" int main(int argc, char *argv[]) { // input int n; cin>>n; // solve Solution solution; auto result = solution.solve(n); // output cout< &a) { // write your code here } }; ``` where: - return:the maximum rating that the last remaining fighter can preserve. # Example 1: - Input: n = 2, a = [2, 1] - Output: -1 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { long long ans = 0; for (int i = 1; i <= n; i++) { if (i <= n - 2) ans = ans + a[i - 1]; else ans = a[i - 1] - ans; } return ans; } long long solve2(int &n, vector &a) { long long last = (long long)a[n - 1]; long long prev = (long long)a[n - 2]; for (int i = 0; i <= n - 3; ++i) { prev -= (long long)a[i]; } return last - prev; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","constructive_algorithms,math",easy 428,"# Problem Statement Alice and Bob are playing a game. They have an array of positive integers $a$ of size $n$. Before starting the game, Alice chooses an integer $k \ge 0$. The game lasts for $k$ stages, the stages are numbered from $1$ to $k$. During the $i$-th stage, Alice must remove an element from the array that is less than or equal to $k - i + 1$. After that, if the array is not empty, Bob must add $k - i + 1$ to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the $k$-th stage ends and Alice hasn't lost yet, she wins. Your task is to determine the maximum value of $k$ such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the maximum value of k such that Alice can win if both players play optimally. # Example 1: - Input: n = 3 a = [1, 1, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[20000, 200000, 2500000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { vector cnt(n); for (int i = 0; i < n; i++) { if (a[i] <= n) { cnt[a[i] - 1]++; } } for (int i = 1; i < n; i++) { cnt[i] += cnt[i - 1]; } int ans = n; for (int i = 0; i < n; i++) { ans = min(ans, max(cnt[i] - i, i)); } return ans; } int solve2(int &n, vector &a) { sort(a.begin(), a.end()); int l = 0, r = n; while (l <= r) { if (l == r) return l; int mid = (l + r + 1) / 2; int x = mid; for (int i = n; i >= mid; i--) { if (a[i - 1] <= x) { x--; } } if (x == 0) l = mid; else r = mid - 1; } } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","binary,data_structures,sort",hard 429,"# Problem Statement You are given an array $a_1, a_2, \dots a_n$. Count the number of pairs of indices $1 \leq i, j \leq n$ such that $a_i < i < a_j < j$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the number of pairs of indices satisfying the condition in the statement. # Example 1: - Input: n = 8 a = [1, 1, 2, 3, 8, 2, 1, 4] - Output: 3 # Constraints: - $2 \leq n \leq @data$ - $0 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { vector sum(n + 1); for (int i = 0; i < n; i++) { sum[i + 1] = sum[i] + (a[i] < i + 1); } long long ans = 0; for (int i = 0; i < n; i++) { if (a[i] < i + 1 && a[i] > 0) { ans += sum[min(n, a[i] - 1)]; } } return ans; } long long solve2(int &n, vector &a) { long long ans = 0; for (int i = 0; i < n; i++) { if (a[i] < i + 1 && a[i] > 0) { for (int j = 0; j < min(n, a[i] - 1); j++) { if (a[j] < j + 1) { ans++; } } } } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }","sort,dp,greedy",hard 430,"# Problem Statement: An integer array $a_1, a_2, \ldots, a_n$ is being transformed into an array of lowercase English letters using the following prodecure: While there is at least one number in the array: - Choose any number $x$ from the array $a$, and any letter of the English alphabet $y$. - Replace all occurrences of number $x$ with the letter $y$. For example, if we initially had an array $a = [2, 3, 2, 4, 1]$, then we could transform it the following way: - Choose the number $2$ and the letter c. After that $a = [c, 3, c, 4, 1]$. - Choose the number $3$ and the letter a. After that $a = [c, a, c, 4, 1]$. - Choose the number $4$ and the letter t. After that $a = [c, a, c, t, 1]$. - Choose the number $1$ and the letter a. After that $a = [c, a, c, t, a]$. After the transformation all letters are united into a string, in our example we get the string ""cacta"". Having the array $a$ and the string $s$ determine if the string $s$ could be got from the array $a$ after the described transformation? The main function of the solution is defined as: ```cpp class Solution { public: string solve(int &n, vector &a, string &s) { // write your code here } }; ``` Where: - `n` is an integer representing the length of the array and string. - `a` is an integer array. - `s` is a string consisting of lowercase English letters. - The return value is ""YES"" if the string $s$ could be got from the array $a$ after the described transformation, otherwise return ""NO"". # Example 1: - Input: n = 5 a = [2, 3, 2, 4, 1] s = ""cacta"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: string solve1(int &n, vector &a, string &s) { vector mp(n + 1, -1); for (int i = 0; i < n; i++) { if (mp[a[i]] == -1) mp[a[i]] = s[i]; else if (mp[a[i]] != s[i]) return ""NO""; } return ""YES""; } string solve2(int &n, vector &a, string &s) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (a[i] == a[j] && s[i] != s[j]) return ""NO""; } } return ""YES""; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; string s; cin >> s; // solve Solution solution; auto result = solution.solve(n, a, s); // output cout << result << ""\n""; return 0; }",greedy,medium 431,"# Problem Statement Given an array $a$ of length $n$, where $2 \leq a[i] \leq n$, you need to find the smallest prime factor of each number and return the XOR sum of all results. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the XOR sum of the smallest prime factor of each number in the array. # Example 1: - Input: n = 4 a = [2, 4, 3, 4] - Output: 1 # Constraints: - $2 \leq n \leq @data$ - $2 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 100000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { vector prime; vector min_prime(n + 1, 0); for (int i = 2; i <= n; i++) { if (min_prime[i] == 0) { prime.push_back(i); min_prime[i] = i; } for (int j = 0; j < prime.size() && i * prime[j] <= n; j++) { min_prime[i * prime[j]] = prime[j]; if (i % prime[j] == 0) break; } } int res = 0; for (int i = 0; i < n; i++) { res ^= min_prime[a[i]]; } return res; } int solve2(int &n, vector &a) { int res = 0; for (int i = 0; i < n; i++) { int min_prime = a[i]; for (int j = 2; j * j <= a[i]; j++) { if (a[i] % j == 0) { min_prime = j; break; } } res ^= min_prime; } return res; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",math,easy 432,"# Problem Statement Given an array $a$ of length $n$. You need to count the number of inversions in the array. An inversion is defined as a pair of elements $a[i]$ and $a[j]$ such that $i < j$ and $a[i] > a[j]$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the number of inversions in the array. # Example 1: - Input: n = 5 a = [3, 1, 2, 5, 4] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { long long ans = 0; vector bit(n + 2); for (int i = n - 1; i >= 0; i--) { for (int j = a[i] - 1; j; j -= j & -j) ans += bit[j]; for (int j = a[i]; j <= n; j += j & -j) bit[j]++; } return ans; } long long solve2(int &n, vector &a) { long long ans = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] > a[j]) ans++; return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",data_structures,easy 433,"# Problem Statement Given an array $a$ of length $n$, where the elements are integers. You need to count the number of subarrays whose sum is 0. The sum of a subarray is defined as the sum of elements from index $l$ to $r$, i.e., $a[l] + a[l+1] + \dots + a[r]$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the number of subarrays whose sum is 0. # Example 1: - Input: n = 5 a = [1, -1, 2, -2, 0] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $-n \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 160, 64], [6400, 1280, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { vector prefix(n + 1); for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + a[i]; unordered_map mp; long long result = 0; mp[0] = 1; for (int i = 1; i <= n; i++) { if (mp.find(prefix[i]) != mp.end()) result += mp[prefix[i]]; mp[prefix[i]]++; } return result; } long long solve2(int &n, vector &a) { long long result = 0; for (int i = 0; i < n; i++) { long long sum = 0; for (int j = i; j < n; j++) { sum += a[j]; if (sum == 0) result++; } } return result; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",data_structures,medium 434,"# Problem Statement A permutation $a$ of length $n$ consists of integers from $1$ to $n$, with each integer appearing exactly once. For each number $a[i]$, define its contribution as the length of the cycle that $a[i]$ belongs to. The cycle is defined by starting from $a[i]$, then visiting the next element $a[a[i]]$, then $a[a[a[i]]]$, and so on, until returning to $a[i]$. Please calculate the sum of the contributions of $a$.Note that the index of $a$ starts from $1$, you may need to convert it to start from $0$. The main function of the solution is defined as: ```cpp class Solution { public: long long solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the sum of the contributions of $a$. # Example 1: - Input: n = 4 a = [2, 1, 3, 4] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - $a[i]$ is distinct - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: long long solve1(int &n, vector &a) { vector vis(n); long long ans = 0; for (int i = 0; i < n; i++) a[i]--; for (int i = 0; i < n; i++) { if (vis[i]) continue; int j = i; int cnt = 0; while (!vis[j]) { vis[j] = 1; cnt++; j = a[j]; } ans += 1ll * cnt * cnt; } return ans; } long long solve2(int &n, vector &a) { long long ans = 0; for (int i = 0; i < n; i++) a[i]--; for (int i = 0; i < n; i++) { int j = i; int cnt = 1; j = a[j]; while (j != i) { cnt++; j = a[j]; } ans += cnt; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",search,hard 435,"# Problem Statement Given an array $a$ of length $n$, where $2 <= a[i] <= n$, determine whether each number in the array is a prime number. For each number, if it is a prime, represent it as 1; otherwise, represent it as 0. Finally, store the result as a binary string of length $n$ in the given string. The main function of the solution is defined as: ```cpp class Solution { public: void solve(int &n, vector &a, string &res) { // write your code here } }; ``` where: - return: a binary string representing whether each number in the array is a prime number. The string is stored in the given string `res`. # Example 1: - Input: n = 2 a = [2, 2] - Output: 11 # Constraints: - $2 <= n <= @data$ - $2 <= a[i] <= n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 120, 64], [6400, 960, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: void solve1(int &n, vector &a, string &res) { vector prime; vector is_prime(n + 1, true); is_prime[0] = is_prime[1] = false; for (int i = 2; i <= n; i++) { if (is_prime[i]) prime.push_back(i); for (int j = 0; j < prime.size() && i * prime[j] <= n; j++) { is_prime[i * prime[j]] = false; if (i % prime[j] == 0) break; } } res = """"; for(int i = 0; i < n; i++) res += is_prime[a[i]] ? ""1"" : ""0""; } void solve2(int &n, vector &a, string &res) { res = """"; for (int i = 0; i < n; i++) { bool is_prime = true; for (int j = 2; j * j <= a[i]; j++) { if (a[i] % j == 0) { is_prime = false; break; } } res+= is_prime ? ""1"" : ""0""; } } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; string result; solution.solve(n, a, result); // output cout << result << ""\n""; return 0; }",math,easy 436,"# Problem Statement Given an array $a$ of length $n$, where $2 <= a[i] <= n$, you need to find the modular inverse of each number modulo 998244353. Return the XOR of all the results. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the XOR of all the results. # Example 1: - Input: n = 2 a = [2, 2] - Output: 0 # Constraints: - $2 <= n <= @data$ - $2 <= a[i] <= n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[20000, 200000, 2000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { vector inv(n + 1); const int mod = 998244353; for (int i = 1; i <= n; i++) inv[i] = i == 1 ? 1 : (long long)(mod - mod / i) * inv[mod % i] % mod; int res = 0; for (int i = 0; i < n; i++) res = res ^ inv[a[i]]; return res; } int solve2(int &n, vector &a) { const int mod = 998244353; int ans = 0; for (int i = 0; i < n; i++) { int res = 1; int b = mod - 2; int v = a[i]; while (b) { if (b & 1) res = (long long)res * v % mod; v = (long long)v * v % mod; b >>= 1; } ans ^= res; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",math,medium 437,"# Problem Statement Given an integer $n$ and an array $a$ of length $n$, where $1 <= a[i] <= n$, you need to calculate the $a[i]$-th term of the Fibonacci sequence, then take the result modulo 998244353, and finally return the XOR sum of all results. The Fibonacci sequence is defined as follows: - $F(0) = 0$ - $F(1) = 1$ - $F(i) = F(i-1) + F(i-2)$ for $i \geq 2$ The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the xor sum of all results. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 100000, 1000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: const int MOD = 998244353; array, 2> mat; array, 2> result; array, 2> temp; void matrix_multiply(const array, 2> &A, const array, 2> &B, array, 2> &C) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { C[i][j] = 0; for (int k = 0; k < 2; k++) { C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD; } } } } void matrix_pow(int power) { result = {{{1, 0}, {0, 1}}}; while (power > 0) { if (power & 1) { matrix_multiply(result, mat, temp); result = temp; } matrix_multiply(mat, mat, temp); mat = temp; power >>= 1; } } int fib(int n) { if (n == 0) return 0; mat = {{{1, 1}, {1, 0}}}; matrix_pow(n - 1); return result[0][0]; } int solve1(int &n, vector &a) { vector fib(n + 1); fib[0] = 0; fib[1] = 1; for (int i = 2; i <= n; i++) { fib[i] = (fib[i - 1] + fib[i - 2]) % MOD; } int xor_sum = 0; for (int num : a) { xor_sum ^= fib[num]; } return xor_sum; } int solve2(int &n, vector &a) { int xor_sum = 0; for (int num : a) { xor_sum ^= fib(num); } return xor_sum; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",math,medium 438,"# Problem Statement Given an array $a$ of length $n$ and an integer $k$. For each element $a[i]$ in the array, where $1 \leq a[i] \leq n$, assume there are $a[i]$ people standing in a circle, numbered from $1$ to $a[i]$. Starting from the person numbered $1$, count up to $k$ and the person at position $k$ is eliminated. Then, start counting again from the next person. This process continues until only one person remains in the circle. You need to calculate the position of the last remaining person for each $a[i]$ and return the XOR sum of all results. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &k, vector &a) { // write your code here } }; ``` where: - return: The XOR sum of all results. # Example 1: - Input: n = 2, k = 2 a = [1, 2] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq k \leq 10^3$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &k, vector &a) { vector dp(n + 1); dp[1] = 0; for (int m = 2; m <= n; m++) { dp[m] = (dp[m - 1] + k) % m; } int xor_sum = 0; for (int num : a) { xor_sum ^= (dp[num] + 1); } return xor_sum; } int solve2(int &n, int &k, vector &a) { int xor_sum = 0; for (int num : a) { int x = 0; for (int i = 1; i <= num; i++) { x = (x + k) % i; } xor_sum ^= (x + 1); } return xor_sum; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, k; cin >> n >> k; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, k, a); // output cout << result << ""\n""; return 0; }",math,medium 439,"# Problem Statement Given an integer $n$, you need to answer $m$ queries. Each query provides a range $[l, r]$, and you are required to count the number of 1s in the binary representation of each number in the range $[l, r]$. Return the XOR sum of all query results. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, int &m, vector> &q) { // write your code here } }; ``` where: - `q`: $m$ queries, each query gives a range $[l, r]$, $q[i][0]$ represents the left endpoint $l$ of query $i$, $q[i][1]$ represents the right endpoint $r$ of query $i$. - Return: return the XOR sum of all query results. # Example 1: - Input: n = 5 m = 1 q = [[1, 3]] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq l \leq r \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, int &m, vector> &q) { vector cnt(n + 1); for(int i=1;i<=n;i++) { cnt[i] = cnt[i-1] + __builtin_popcount(i); } int ans = 0; for(auto &i:q) { ans ^= cnt[i[1]] - cnt[i[0]-1]; } return ans; } int solve2(int n, int m, vector> q) { int ans = 0; for(auto &i:q) { int cnt = 0; for(int j=i[0];j<=i[1];j++) { cnt += __builtin_popcount(j); } ans ^= cnt; } return ans; } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n, m; cin >> n >> m; vector> q(m); for (int i = 0; i < m; i++) { cin >> q[i][0] >> q[i][1]; } // solve Solution solution; auto result = solution.solve(n, m, q); // output cout << result << ""\n""; return 0; }",greedy,medium 440,"# Problem Statement Given an array $a$ of length $n$, return the count of the most frequently occurring element in the array. The main function of the solution is defined as: ```cpp class Solution { public: int solve(int &n, vector &a) { // write your code here } }; ``` where: - return: the count of the most frequently occurring element in the array. # Example 1: - Input: n = 5 a = [1, 2, 2, 3, 3] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[20000, 200000, 2000000]",1000,"[[100, 64, 64], [800, 80, 64], [6400, 640, 64]]","#ifndef STD_H #define STD_H #include using namespace std; class Solution { public: int solve1(int &n, vector &a) { sort(a.begin(), a.end()); int ans = 0; int pre = -1; int cnt = 0; for (int i = 0; i < n; i++) { if (a[i] == pre) cnt++; else { ans = max(ans, cnt); cnt = 1; pre = a[i]; } } ans = max(ans, cnt); return ans; } int solve2(int &n, vector &a) { vector cnt(n + 1, 0); for (int i = 0; i < n; i++) cnt[a[i]]++; return *max_element(cnt.begin(), cnt.end()); } }; #endif","#include using namespace std; #include ""std.h"" int main() { // input int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; // solve Solution solution; auto result = solution.solve(n, a); // output cout << result << ""\n""; return 0; }",sort,hard