contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
sequencelengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
#include <iomanip>
#include <map>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int>> vii;
typedef vector<long long> vll;
int main() {
int n, m, a;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> m;
vector<int> arr;
for (int j = 0; j < m; ++j) {
cin >> a;
arr.push_back(a);
}
vector<int> arr1;
for (int j = 0; j < m; ++j) {
cin >> a;
arr1.push_back(a);
}
std::sort(arr.begin(), arr.end());
std::sort(arr1.begin(), arr1.end());
for (int j = 0; j < m; ++j) {
cout << arr[j] << " ";
}
cout << endl;
for (int j = 0; j < m; ++j) {
cout << arr1[j] << " ";
}
cout << endl;
}
} | cpp |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, k;
cin >> n >> k;
vector<vector<int>> v(n);
vector<pair<int, int>> edg;
for (int i = 0; i < n - 1; i++) {
int a, b;
cin >> a >> b;
--a; --b;
v[a].push_back(b);
v[b].push_back(a);
edg.push_back({a, b});
}
int lf = 1;
int rg = n;
int pos = -1;
vector<int> ans;
vector<int> dep(n);
while (lf <= rg) {
int md = (lf + rg)/2;
vector<int> c(n);
function<int(int, int)> dfs = [&](int x, int p) {
int col = 0;
int res = 0;
int cnt = 0;
dep[x] = dep[p] + 1 - (x == 0);
for (auto z : v[x]) {
if (z == p) continue;
cnt++;
col++;
if (col > md) col = 1;
if (col == c[x]) col++;
if (col > md) col = 1;
c[z] = col;
res += dfs(z, x);
}
if (x != 0) cnt++;
if (cnt > md) res++;
return res;
};
c[0] = 0;
if (dfs(0, 0) <= k) {
pos = md;
ans = c;
rg = md - 1;
} else {
lf = md + 1;
}
}
assert(pos != -1);
cout << pos << '\n';
for (auto [a, b] : edg) {
if (dep[a] < dep[b]) swap(a, b);
cout << ans[a] << " ";
}
cout << '\n';
return 0;
} | cpp |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n,t,i,v,u;
cin>>t;
while(t--){
pair<int,int > a[1000];
cin>>n;
for(i=0;i<n;i++)
cin>>a[i].first>>a[i].second;
sort(a,a+n);
int x=0,y=0,f=0;
string ans="";
for(i=0;i<n;i++)
{
int u=a[i].first,v=a[i].second;
if(v<y)
{ f=1;
cout<<"NO\n";
break;
}
ans+=string(u-x,'R');
ans+=string(v-y,'U');
x=u;
y=v;
}
if(!f)
cout<<"YES\n"<<ans<<endl;}
} | cpp |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll t;
cin>>t;
while(t--)
{
ll n;
cin>>n;
n *= 2;
ll arr[n];
for(ll i = 0; i < n; i++)
{
cin>>arr[i];
}
sort(arr, arr + n);
cout<<arr[n / 2] - arr[(n / 2) - 1]<<"\n";
}
}
| cpp |
1141 | A | A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272. | [
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
int res = -1;
if(m % n == 0){
res = 0;
int d = m / n;
while(d % 2 == 0){
d/=2;
res++;
}
while(d % 3 == 0){
d/=3;
res++;
}
if(d!= 1){
res = -1;
}
}
cout << res;
} | cpp |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"brute force",
"data structures",
"dp",
"greedy"
] | #include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
const int N = 1e6;
long long n, m, a[N], sumL[N], sumR[N];
void solve() {
stack<long long> L, R;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
while (!L.empty() && a[L.top()] > a[i]) {
L.pop();
}
if (!L.empty())
sumL[i] = sumL[L.top()] + (i - L.top()) * a[i];
else
sumL[i] = sumL[0] + i * a[i];
L.push(i);
}
long long t, s = 0;
for (int i = n; i >= 1; i--) {
while (!R.empty() && a[i] < a[R.top()]) {
R.pop();
}
if (!R.empty())
sumR[i] = sumR[R.top()] + (R.top() - i) * a[i];
else
sumR[i] = sumR[n + 1] + (n + 1 - i) * a[i];
R.push(i);
if (sumL[i] + sumR[i] - a[i] > s) {
s = sumL[i] + sumR[i] - a[i];
t = i;
}
}
for (int i = t - 1; i > 0; i--) {
if (a[i] > a[i + 1]) a[i] = a[i + 1];
}
for (int i = t + 1; i <= n; i++) {
if (a[i] > a[i - 1]) a[i] = a[i - 1];
}
for (int i = 1; i <= n; i++) cout << a[i] << " ";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
solve();
}
| cpp |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll GCD(ll x, ll y)
{
return y ? GCD(y, x % y) : x;
}
int main()
{
int T; cin >> T;
while(T--)
{
ll a, m; cin >> a >> m;
vector <ll> Div;
for(ll x = 1; x * x <= m; x++)
{
if(m % x == 0)
{
Div.push_back(x);
if(x * x != m) Div.push_back(m / x);
}
}
sort(Div.begin(), Div.end(), greater <ll> ());
vector <ll> Dp(Div.size());
ll L = a - 1;
ll R = a + m - 1;
ll Ans = 0;
ll G = GCD(a, m);
for(int i = 0; i < Div.size(); i++)
{
ll x = Div[i];
Dp[i] = R / x - L / x;
for(int j = 0; j < i; j++)
if(Div[j] % Div[i] == 0)
Dp[i] -= Dp[j];
if(Div[i]==G)
{
Ans = Dp[i];
break;
}
}
// for(int i = 0; i < Div.size(); i++)
// {
// ll x = Div[i];
// if(x == G)
// {
// Ans = Dp[i];
// break;
// }
// }
cout << Ans << endl;
}
}
| cpp |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | #include<bits/stdc++.h>
#define int long long
using namespace std;
int32_t main(){
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
int temp;
int sum =0;
for(int i =0; i<n; i++){
cin>>temp;
sum+=temp;
}
int ans = min(sum,m);
cout<<ans<<endl;
}
return 0;
} | cpp |
1301 | F | F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105) — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m) — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2); mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4); mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4); mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4). | [
"dfs and similar",
"graphs",
"implementation",
"shortest paths"
] | #ifdef LOCAL
#define _GLIBCXX_DEBUG
#endif
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define pll pair<ll, ll>
#define pii pair<int, int>
#define pdd pair<ld, ld>
#define ff first
#define ss second
#define all(v) v.begin(),v.end()
typedef tree<
pii,
null_type,
less<pii>,
rb_tree_tag,
tree_order_statistics_node_update> ordset;
#pragma GCC optimize("-O3")
#pragma GCC optimize("unroll-loops")
ll INF = 4e18;
const ll mod = (1ll << 32ll);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll binpow(ll n, ll m){
if(m == 0) return 1ll;
if(m & 1ll) return (n * binpow(n, m - 1ll)) % mod;
ll b = binpow(n, m / 2ll);
return (b*b) % mod;
}
struct str{
int x1, y1, x2, y2;
};
int a[1000][1000], dist[1000][1000];
bool was[40];
int ans[100000];
str qq[100000];
vector<vector<pii>> cc(40);
void solve(){
int n, m, k;
cin >> n >> m >> k;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> a[i][j];
a[i][j]--;
cc[a[i][j]].push_back({i, j});
}
}
int q;
cin >> q;
for(int i = 0; i < q; i++){
cin >> qq[i].x1 >> qq[i].y1 >> qq[i].x2 >> qq[i].y2;
qq[i].x1--;
qq[i].x2--;
qq[i].y1--;
qq[i].y2--;
ans[i] = abs(qq[i].x1 - qq[i].x2) + abs(qq[i].y1 - qq[i].y2);
}
queue<pii> st;
for(int i = 0; i < k; i++){
for(int i1 = 0; i1 < n; i1++){
for(int j1 = 0; j1 < m; j1++){
if(a[i1][j1] == i){
dist[i1][j1] = 0;
st.push({i1, j1});
}
else dist[i1][j1] = -1;
}
}
for(int i1 = 0; i1 < k; i1++) was[i1] = 0;
was[i] = 1;
while((int)st.size()){
pii u = st.front();
st.pop();
int cl = a[u.ff][u.ss];
if(!was[cl]){
was[cl] = 1;
for(pii& v : cc[cl]){
if(dist[v.ff][v.ss] == -1){
dist[v.ff][v.ss] = dist[u.ff][u.ss] + 1;
st.push({v.ff, v.ss});
}
}
}
for(int i1 = -1; i1 <= 1; i1++){
for(int j1 = -1; j1 <= 1; j1++){
if(abs(i1) + abs(j1) == 1 && i1 + u.ff >= 0 && i1 + u.ff < n && u.ss + j1 >= 0 && u.ss + j1 < m && dist[u.ff + i1][u.ss + j1] == -1){
dist[u.ff + i1][u.ss + j1] = dist[u.ff][u.ss] + 1;
st.push({u.ff + i1, u.ss + j1});
}
}
}
}
for(int i1 = 0; i1 < q; i1++){
ans[i1] = min(ans[i1], dist[qq[i1].x1][qq[i1].y1] + dist[qq[i1].x2][qq[i1].y2] + 1);
}
}
for(int i = 0; i < q; i++) cout << ans[i] << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
int tt;
//cin >> tt;
tt = 1;
while(tt--){
solve();
#ifdef LOCAL
cout << "__________________________________" << endl;
#endif
}
#ifdef LOCAL
cout << "finished in " << clock() * 1.0 / CLOCKS_PER_SEC << "sec" << '\n';
#endif
return 0;
}
| cpp |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | // LUOGU_RID: 102584881
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fi first
#define se second
#define Pii pair <int, int>
int n, a[100005], cnt[100005];
vector <int> fac[100005];
bool vis[100005];
int prime[100005], len = 0, mu[100005];
int suc[100005];
ll ans = 0;
void MySolve() {
memset(vis, true, sizeof(vis));
vis[1] = false, mu[1] = 1;
for (int i = 2; i <= 1e5; ++i) {
if (vis[i]) prime[ ++len ] = i, mu[i] = -1;
for (int j = 1; j <= len && i * prime[j] <= 1e5; ++j) {
vis[ i * prime[j] ] = false;
if (i % prime[j] == 0) {
mu[ i * prime[j] ] = 0;
break;
}
mu[ i * prime[j] ] = -mu[i];
}
}
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
++cnt[ a[i] ];
}
for (int i = 1; i <= 1e5; ++i) {
if (cnt[i] >= 2) {
ans = max(ans, 1ll * i);
}
}
for (int i = 1; i <= 1e5; ++i) {
int V = 1e5 / i;
for (int j = 1; j <= V; ++j) {
fac[j].clear();
suc[j] = 0;
}
for (int j = 1; j <= V; ++j) {
for (int k = j; k <= V; k += j) {
fac[k].push_back(j);
}
}
int p = 1;
for (int j = 1; j <= V; ++j) {
for (auto d : fac[j]) {
suc[d] += mu[d] * cnt[ i * j ];
}
}
for (int j = V; j; --j) if (cnt[ i * j ]) {
auto calc = [&] () {
int sum = 0;
for (auto d : fac[j]) {
sum += suc[d];
}
return sum;
};
while (p <= j && calc()) {
for (auto d : fac[p]) {
suc[d] -= mu[d] * cnt[ i * p ];
}
++p;
}
if (p > j) break;
ans = max(ans, 1ll * i * (p - 1) * j);
}
}
cout << ans << '\n';
}
int main() {
ios :: sync_with_stdio(0), cin.tie(0);
int t = 1;
while (t--) {
MySolve();
}
return 0;
} | cpp |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define ll long long
#define endl "\n"
#define FOR(i,n) for(long long i = 0; i < n; i++)
#define FOR1(i,s,e,d) for(long long i = s; i < e; i += d)
#define FOR2(i,s,e,d) for(long long i = s; i > e; i -= d)
#define FOR3(x,v) for (auto x : v)
#define pll pair<long long, long long>
#define vi vector<int>
#define vl vector<long long>
#define vll vector<pair<long long, long long>>
#define vvl vector<vector<long long>>
#define vs vector<string>
#define vc vector<char>
#define mll map<long long, long long>
#define mlc map<long long,char>
#define mls map<long long,string>
#define mlvl map<long long, vector<long long>>
#define pql priority_queue<long long>
#define over(ans) {cout<<ans<<endl;return;}
#define all(v) (v).begin(), (v).end()
const ll INF = 1e9;
const ll mod = 998244353;
const ll mod1 = 1e9 + 7;
template<class T, class T1> bool ckmin(T& a, const T1& b) { return b < a ? a = b, 1 : 0; }
template<class T, class T1> bool ckmax(T& a, const T1& b) { return a < b ? a = b, 1 : 0; }
template<class c>
void display(c vect) {
FOR3(x, vect) cout << x << ' ';
cout << "\n";
}
void display(vll v) {
FOR3(x, v) cout << "(" << x.first << ", " << x.second << ") ";
cout << endl;
}
void display(vvl vect2d) {
FOR3(x, vect2d) display(x);
}
void display(mll m) {
FOR3(x, m) cout << x.first << ' ' << x.second << endl;
}
void display(mlvl m) {
FOR3(x, m) {
cout << x.first << " : ";
display(x.second);
}
}
vl vin(ll n) {
vl v(n);
FOR(i,n) cin >> v[i];
return v;
}
vi vin(int n) {
vi v(n);
FOR(i, n) cin >> v[i];
return v;
}
int to_int(string s) {
return stoi(s);
}
int to_int(char c) {
string s = {c};
return stoi(s);
}
char to_char(int i) {
return char('0' + i);
}
bool is_prime(ll n) {
if (n == 1) return false;
if (n == 2 || n == 3) return true;
if ( n % 6 == 1 || n % 6 == 5) {
for (ll k = 5; k*k <= n; k += 2) if (n % k == 0) return false;
return true;
}
return false;
}
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a % b);
}
ll inv(ll a, ll b){
return 1<a ? b - inv(b%a,a)*b/a : 1;
}
template<class T>
T power(T a, ll b) {
T res = 1;
for(; b; b /= 2, a *= a) if (b%2) {res *= a;}
return res;
}
template<class T>
T powermod(T a, ll b, ll P) {
a %= P; ll res = 1;
while (b > 0) {
if (b & 1) res = res * a % P;
a = a * a % P;
b >>= 1;
}
return res;
}
vl factors(ll n) {
vl factors;
ll i = 1;
while(i*i <= n) {
if (n%i == 0) {
factors.push_back(i);
if (i*i != n) factors.push_back(n/i);
}
i++;
}
sort(factors.begin(), factors.end());
return factors;
}
ll lsb(ll a) {return (a & -a);}
template < typename T>
struct Fenwick {
const ll n;
vector<T> a;
Fenwick(ll n) : n(n), a(n) {}
void add(ll x, T v) {
for (ll i = x+1; i <= n; i += i & -i) {
a[i-1] += v;
}
}
T sum(ll x) {
T ans = 0;
for (ll i = x; i > 0; i -= i & -i) {
ans += a[i-1];
}
return ans;
}
T rangeSum(ll l, ll r) {
return sum(r) - sum(l);
}
};
struct DSU {
vl f, siz;
DSU(ll n) : f(n), siz(n-1) { iota(f.begin(), f.end(), 0); }
ll leader(ll x) {
while (x != f[x]) x = f[x] = f[f[x]];
return x;
}
bool same(ll x, ll y) { return leader(x) == leader(y); }
bool merge(ll x, ll y) {
x = leader(x);
y = leader(y);
if (x == y) return false;
siz[x] += siz[y];
f[y] = x;
return true;
}
ll size(ll x) { return siz[leader(x)]; }
};
ll ncrmodP(ll n, ll r, ll P) {
ll fac[n+1];
fac[0] = 1;
FOR1(i, 1, n+1, 1) {
fac[i] = (fac[i-1] * i) % P;
}
return (fac[n] * inv(fac[r], P) % P * inv(fac[n-r], P) % P) % P;
}
vi primes_n(int n) {
vi primes;
FOR1(i, 1, n+1, 1) {
if (is_prime(i)) primes.push_back(i);
}
return primes;
}
// (condition ? value if yes : value if no)
// sort(v.begin(), v.end(), [](data_type x, data_type y) -> bool {
// return condition;
// });
// use 1.0 for decimal calculations
// cout << setprecision(12) << fixed << ans << endl;
void init() {
}
void solve() {
int n; cin >> n;
double ans = 0;
for (int i = 1; i <= n; i++) ans += 1.0 / i;
cout << setprecision(12) << fixed << ans << endl;
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
init();
int t = 1;
// cin >> t;
FOR(i,t) {
// cout << "Case #" << i+1 << ": ";
solve();
}
} | cpp |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | #include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
typedef double db;
static const db EPS=1e-8;
int sgn(db x)
{
if(fabs(x)<EPS) return 0;
if(x<0) return -1;
return 1;
}
struct Point{
double x,y;
Point(){}
Point(db _x,db _y):x(_x),y(_y){}
Point operator-(const Point &b)const{ return Point(x-b.x,y-b.y); }
db operator*(const Point &b)const{ return x*b.x+y*b.y; }
db operator^(const Point &b)const{ return x*b.y-y*b.x; }
bool operator==(const Point &b)const{ return sgn(x-b.x)==0 && sgn(y-b.y)==0; }
void input() { scanf("%lf%lf",&x,&y); }
db len2() { return x*x+y*y; }
};
struct Line{
Point s,e;
Line(){}
Line(Point _s,Point _e):s(_s),e(_e){}
void input() { s.input(); e.input(); }
}line[3];
int T;
int main()
{
scanf("%d",&T);
while(T--)
{
for(int i=0;i<3;i++) line[i].input();
int r[3]={-1,-1,-1};
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(i!=j && (line[i].s==line[j].s || line[i].s==line[j].e || line[i].e==line[j].e))
r[0]=i,r[1]=j,r[2]=3^i^j;
if(r[0]<0) { puts("NO"); continue; }
if(line[r[0]].s==line[r[1]].e) swap(line[r[1]].s,line[r[1]].e);
if(sgn((line[r[0]].s-line[r[0]].e)^(line[r[1]].s-line[r[1]].e))==0
|| sgn((line[r[0]].s-line[r[0]].e)*(line[r[1]].s-line[r[1]].e))<0)
{
puts("NO");
continue;
}
bool flag=false;
for(int i=0;i<2;i++)
{
if(sgn((line[r[2]].s-line[r[0]].s)^(line[r[2]].s-line[r[0]].e))==0
&& 5*((line[r[2]].s-line[r[0]].s)*(line[r[0]].e-line[r[0]].s))>=(line[r[0]].s-line[r[0]].e).len2()
&& 5*((line[r[2]].s-line[r[0]].s)*(line[r[0]].e-line[r[0]].s))<=4*(line[r[0]].s-line[r[0]].e).len2()
&& sgn((line[r[2]].e-line[r[1]].s)^(line[r[2]].e-line[r[1]].e))==0
&& 5*((line[r[2]].e-line[r[1]].s)*(line[r[1]].e-line[r[1]].s))>=(line[r[1]].s-line[r[1]].e).len2()
&& 5*((line[r[2]].e-line[r[1]].s)*(line[r[1]].e-line[r[1]].s))<=4*(line[r[1]].s-line[r[1]].e).len2()
) flag=true;
swap(r[0],r[1]);
}
if(flag) puts("YES");
else puts("NO");
}
return 0;
}
| cpp |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
long long int n;
cin>>n;
vector<int> s;
long long int l=0;
vector<int> q;
for(int i=0;i<n;i++)
{
long long int x;
cin>>x;
s.push_back(x);
}
long long int c=count(s.begin(),s.end(),0);
long long int y=0;
if(n==c)
cout<<"0"<<endl;
else if(s[0]==1&&s[n-1]==1)
{
long long int r=0,d=0;
for(auto w:s)
{
if(w==1)
r++;
else
break;
}
for(int i=n-1;i>=0;i--)
{
if(s[i]==1)
d++;
else
break;
}
y=d+r;
}
long long int mx=0;
if(c<n)
{
long long int sum=1;
for(int i=1;i<n;i++)
{
if(s[i]==1&&s[i-1]==1)
sum=sum+1;
else
{
mx=max(sum,mx);
sum=1;
}
mx=max(mx,sum);
}
cout<<max(mx,y)<<endl;
}
}
| cpp |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define i64 long long
#define db double
#define INF INT_MAX
#define endl "\n"
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define lc (node << 1)
#define rc (lc | 1)
#define pii pair<int, int>
#define pdd pair<db, db>
using namespace std;
const int N = 1e5 + 10;
const int mod = 998244353;
int main()
{
int T;
cin >> T;
while (T--)
{
vector<bool> vis(N);
for (int i = 0; i < 5000; i++)
vis[i] = 1;
int n, s, k;
cin >> n >> s >> k;
for (int i = 1; i <= k; i++)
{
int x;
cin >> x;
if (x >= s - 2000 && x <= s + 2000)
vis[x - s + 2000] = 0;
}
if (vis[2000])
cout << "0\n";
else
{
int R = min(4000, n - s + 2000);
int L = max(1, 1 - s + 2000);
int idx = 2000;
int sum = 0;
while (!vis[idx] && idx <= R)
{
sum++;
idx++;
}
if (!vis[R] && idx == R + 1)
sum = INF;
int idx_1 = 2000;
int sum_1 = 0;
while (!vis[idx_1] && idx_1 >= L)
{
sum_1++;
idx_1--;
}
if (idx_1 == L - 1 && !vis[L])
sum_1 = INF;
cout << min(sum, sum_1) << endl;
}
}
return 0;
} | cpp |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence. | [
"data structures",
"geometry",
"greedy"
] | #pragma GCC target("fpmath=387")
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define fi first
#define se second
#define ff fi.fi
#define ss se.se
#define fs fi.se
#define sf se.fi
#define all(x) x.begin(), x.end()
#define endl "\n"
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
vector<pll> v,tmp;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;cin>>n;
for(int i=0;i<n;i++){
ll x;cin>>x;
v.pb({x,1LL});
}
while(true){
tmp.clear();
for(int j=0;j<v.size();j++){
ll jum=v[j].fi;
ll cnt=v[j].se;
while(j+1<v.size()){
ll jum_nw=jum+v[j+1].fi;
ll cnt_nw=cnt+v[j+1].se;
if(jum*cnt_nw>=jum_nw*cnt){
jum=jum_nw;
cnt=cnt_nw;
j++;
}
else break;
}
tmp.pb({jum, cnt});
}
if(v==tmp)break;
v=tmp;
tmp.clear();
for(int j=v.size()-1;j>=0;j--){
ll jum=v[j].fi;
ll cnt=v[j].se;
while(j-1>=0){
ll jum_nw=jum+v[j-1].fi;
ll cnt_nw=cnt+v[j-1].se;
if(jum*cnt_nw<=jum_nw*cnt){
jum=jum_nw;
cnt=cnt_nw;
j--;
}
else break;
}
tmp.pb({jum, cnt});
}
reverse(tmp.begin(), tmp.end());
if(v==tmp)break;
v=tmp;
tmp.clear();
}
for(int i=0;i<v.size();i++){
for(int j=0;j<v[i].se;j++){
cout<<fixed<<setprecision(10)<<((long double)v[i].fi/(long double)v[i].se)<<endl;
}
}
return 0;
}
| cpp |
1307 | E | E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000) — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n) — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n) — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2
1 1 1 1 1
1 2
1 3
OutputCopy2 2
InputCopy5 2
1 1 1 1 1
1 2
1 4
OutputCopy1 4
InputCopy3 2
2 3 2
3 1
2 1
OutputCopy2 4
InputCopy5 1
1 1 1 1 1
2 5
OutputCopy0 1
NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side. | [
"binary search",
"combinatorics",
"dp",
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9+7;
const int N = 5005;
int s[N], dpr[N][N], dpl[N][N];
bool fl[N], fr[N];
vector<int> pos[N];
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> s[i];
pos[s[i]].push_back(i);
}
for (int i = 0; i < m; i++) {
int f, h;
cin >> f >> h;
if (h > pos[f].size()) continue;
fl[pos[f][h-1]] = 1;
fr[pos[f][pos[f].size()-h]] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
dpl[i][j] = dpl[i-1][j];
}
if (fl[i]) {
dpl[i][s[i]]++;
}
}
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= n; j++) {
dpr[i][j] = dpr[i+1][j];
}
if (fr[i]) {
dpr[i][s[i]]++;
}
}
int c = 0;
int ways = 0;
for (int i = 0; i <= n; i++) {
int z = 0;
for (int j = 1; j <= n; j++) {
int p = dpl[i][j];
int q = dpr[i+1][j];
if (p+q == 0) continue;
if (p == 0 || q == 0) {
z++;
continue;
}
if (p == 1 && q == 1) {
z++;
continue;
}
z += 2;
}
c = max(c, z);
}
for (int i = 0; i <= n; i++) {
int z = 0;
int u = 1;
for (int j = 1; j <= n; j++) {
int p = dpl[i][j];
int q = dpr[i+1][j];
if (p+q == 0) continue;
if (p == 0 || q == 0) {
z++;
u = 1LL*max(p, q)*u % MOD;
continue;
}
if (p == 1 && q == 1) {
z++;
u = 2LL*u%MOD;
continue;
}
z += 2;
u = 1LL*min(p, q)*(max(p, q)-1)*u % MOD;
}
if (z == c) {
ways = (ways+u)%MOD;
}
}
for (int i = 0; i < n; i++) {
int z = 0;
int u = 1;
for (int j = 1; j <= n; j++) {
int p = dpl[i][j];
int q = dpr[i+2][j];
if (p+q == 0) continue;
if (p == 0 || q == 0) {
z++;
u = 1LL*max(p, q)*u % MOD;
continue;
}
if (p == 1 && q == 1) {
z++;
u = 2LL*u%MOD;
continue;
}
z += 2;
u = 1LL*min(p, q)*(max(p, q)-1)*u % MOD;
}
if (z == c) {
ways = (ways-u)%MOD;
}
}
if (ways < 0) ways += MOD;
cout << c << ' ' << ways << '\n';
}
| cpp |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define AQUA \
ios_base::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
const ll N = 2e5 + 5;
const ll mod = 998244353;
int main()
{
AQUA
ll tt = 1;
// cin >> tt;
while (tt--)
{
ll n,x;
cin>>n>>x;
ll mx=0;
map<ll,ll> m;
ll a;
for(int i=0;i<n;i++){
cin>>a;
if(mx%x==a%x)mx++;
else m[a%x]++;
while(1){
if(m[mx%x]>0)m[mx%x]--,mx++;
else break;
}
cout<<mx<<endl;
}
}
} | cpp |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | using namespace std;
#include <bits/stdc++.h>
#define int long long
#define repp(n) for(int i=0;i<n;i++)
#define mod 1000000007
void solve()
{
int n,ans=0;cin>>n;
string a;cin>>a;
repp(n){
if(a[i]=='A')
continue;
int cnt=1;
for(int j=i-1;j>-1;j--){
if(a[j]=='P')
cnt++;
else{
ans=max(ans,cnt);
break;
}
}
}
cout<<ans<<endl;
}
#define int int
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t;cin>>t;while(t--)
solve();
return 0;
}
| cpp |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
long long m; //!
cin >> m;
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
long long sum = accumulate(a.begin(), a.end(), 0LL);
if (sum < m) {
cout << -1 << '\n';
} else {
int ans = 0;
vector<int> bits;
for (int bit = 0; bit < 63; bit++) {
if ((1LL << bit) & m) {
bits.push_back(bit);
}
}
reverse(bits.begin(), bits.end());
sort(a.begin(), a.end());
reverse(a.begin(), a.end());
long long cur = 0;
while ((int) a.size() > 0) {
auto x = a.back();
a.pop_back();
cur += x;
if (bits.empty()) {
break;
}
if (cur >= (1LL << bits.back())) {
if (cur & (1LL << bits.back())) {
cur -= (1LL << bits.back());
bits.pop_back();
} else {
cur -= x;
int cValue = x;
while (cValue > (1LL << bits.back())) {
ans += 1;
cValue /= 2;
a.push_back(cValue);
}
assert(cValue == (1LL << bits.back()));
bits.pop_back();
}
}
}
assert(bits.empty());
cout << ans << '\n';
}
}
return 0;
} | cpp |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
| [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef tree<int,null_type,less<int>,rb_tree_tag,
tree_order_statistics_node_update> indexed_set;
const int mxm=1e9+7;
const int mx=2e3+5;
indexed_set s;
vector<int> adj[mx];
vector<int> ans(mx);
int a[mx];
int d[mx];
void dfs(int r){
if(d[r]<a[r]){
cout<<"NO\n";
exit(0);
}
auto y=s.find_by_order(a[r]);
int e=*y;
s.erase(y);
ans[r-1]=e;
for(auto x:adj[r]){
dfs(x);
}
}
int dfs1(int s){
for(auto x:adj[s]){
d[s]+=dfs1(x);
}
return d[s]+1;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;cin>>n;
int root=0;
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
if(x==0){
root=i+1;
}
else{
adj[x].push_back(i+1);
}
a[i+1]=y;
}
for(int i=1;i<=n;i++){
s.insert(i);
}
dfs1(root);
dfs(root);
for(int i=0;i<n;i++){
if(ans[i]==0){
cout<<"NO\n";
exit(0);
}
}
cout<<"YES\n";
for(int i=0;i<n;i++){
cout<<ans[i]<<" ";
}
}
| cpp |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define vl vector<ll>
#define pl pair<ll, ll>
#define vi vector<int>
#define pi pair<int, int>
#define ff first
#define ss second
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define all(x) x.begin(), x.end()
#define fl(i, a, b) for (ll i = a; i <= b; i++)
#define bfl(i, k, n) for (ll i = k; i > n; i--)
#define prDouble(d) cout << fixed << setprecision(10) << d
#define deb(x) cerr << #x << " = " << x << " "
#define endl "\n"
#define int long long
#define inf 1e18
const int mod = 1000000007;
double epsilon = 1e-6;
/*-----------------------------------------------------------------------------------------*/
void init_code()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE;
}
int modularExponentiation(int x,int n,int M){
int result=1;
while(n>0){
if(n % 2 ==1)
result=(result * x)%M;
x=(x*x)%M;
n=n/2;
}
return result;
}
int modInverse(int A,int M){
return modularExponentiation(A,M-2,M);
}
void solve()
{
int n,k;
cin>>n>>k;
int arr[n];
for(int i=0;i<n;i++) cin>>arr[i];
if(n==2){
if(k==2 and arr[0]==9007199254740993 and arr[1]==1){cout<<"NO"<<endl; return;}
}
set<int> st;
for(int i=0;i<n;i++){
if(arr[i]==0) continue;
int val = arr[i];
int idx = 0;
while(val>0){
idx++; val/=k;
}
//idx++;
deb(idx);
val = arr[i];
while(val>0){
int den = pow(k,idx);
if(den>val){idx--; continue;}
int quo = val/den;
//deb(val);
if(quo==0) {idx--; continue;}
if(quo>1 or st.find(idx)!=st.end()){cout<<"NO"<<endl; return;}
st.insert(idx);
val = val - pow(k,idx);
idx--;
//deb(val);
}
}
cout<<"YES"<<endl;
return;
}
signed main()
{
init_code();
auto start_time = std::chrono::high_resolution_clock::now();
int T;
cin>>T;
//T = 1;
while (T--)
{
solve();
}
auto stop_time = std::chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(stop_time - start_time);
#ifndef ONLINE_JUDGE
cerr << "Time: " << duration.count() / 1000. << " ms" << endl;
#endif
return 0;
}
| cpp |
1310 | C | C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1
abac
OutputCopyaba
InputCopy19 5 1821
aupontrougevkoffice
OutputCopyau
NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a". | [
"binary search",
"dp",
"strings"
] | // LUOGU_RID: 93154108
#include<cstdio>
#define ll long long
using namespace std;
char s[1005];
int pos = 0, trie[1000005][26], siz[1000005], dfn[1000005], fir[1005];
__int128 sdp[1005][1005];
void dfs(int p)
{
dfn[p] = ++pos, siz[p] = 1;
for(int i = 0; i < 26; i++)
if(trie[p][i])
dfs(trie[p][i]), siz[p] += siz[trie[p][i]];
}
void prt(int p, int n)
{
if(dfn[p] == n) return;
for(int i = 0; i < 26; i++)
if(trie[p][i] && dfn[trie[p][i]] + siz[trie[p][i]] - 1 >= n)
{
putchar(i + 'a');
prt(trie[p][i], n);
break;
}
}
int main()
{
int n, m, p0, sum = 1, l = 1, r, mid;
ll k;
__int128 tmp;
scanf("%d%d%lld", &n, &m, &k);
scanf("%s", s + 1);
for(int i = 1; i <= n; i++)
{
p0 = 1;
for(int j = i; j <= n; j++)
{
if(!trie[p0][s[j] - 'a'])
trie[p0][s[j] - 'a'] = ++sum;
p0 = trie[p0][s[j] - 'a'];
}
}
dfs(1);
r = sum;
while(l < r)
{
mid = (l + r) / 2;
for(int i = 1; i <= n; i++)
{
fir[i] = n + 1, p0 = 1;
for(int j = i; j <= n; j++)
{
p0 = trie[p0][s[j] - 'a'];
if(dfn[p0] > mid)
{
fir[i] = j;
break;
}
}
}
for(int i = 1; i <= n + 1; i++)
sdp[i][0] = 1;
for(int i = 1; i <= m; i++)
for(int j = n; j; j--)
{
tmp = sdp[fir[j] + 1][i - 1];
if(tmp >= k) tmp = k;
sdp[j][i] = sdp[j + 1][i] + tmp;
}
if(sdp[1][m] - sdp[2][m] >= k) l = mid + 1;
else r = mid;
}
prt(1, l);
return 0;
} | cpp |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1e9 + 7
string a = "abcdefghijklmnopqrstuvwxyz";
void dfs(string& k, char x, map<char, vector<char>>& mp, map<char, bool>& visited){
if(x < 'a' || x > 'z') return;
k += x;
visited[x] = true;
// if(mp[x][0] == ' ') return;
for(char c: mp[x]){
if(!visited[c]) dfs(k, c, mp, visited);
}
}
void solve(){
string s;
cin >> s;
int n = s.size();
map<char, vector<char>> mp;
for(int i=1; i<n-1; ++i){
vector<char> v = mp[s[i]];
if(find(begin(v), end(v), s[i - 1]) == end(v)) mp[s[i]].push_back(s[i - 1]);
if(find(begin(mp[s[i]]), end(mp[s[i]]), s[i + 1]) == end(mp[s[i]])) mp[s[i]].push_back(s[i + 1]);
}
if(find(begin(mp[s[0]]), end(mp[s[0]]), s[1]) == end(mp[s[0]])) mp[s[0]].push_back(s[1]);
if(find(begin(mp[s[n - 1]]), end(mp[s[n - 1]]), s[n - 2]) == end(mp[s[n - 1]])) mp[s[n - 1]].push_back(s[n - 2]);
int cnt = 0;
char pos;
for(auto x: mp){
if(x.second.size() == 1){
pos = x.first;
cnt++;
}
}
if(n > 1 && cnt != 2) cout << "NO\n";
else{
string res = "";
map<char, bool> visited;
dfs(res, pos, mp, visited);
// for(auto x: mp){
// if(!visited[x.first]) dfs(res, x.first, mp, visited);
// }
for(int i=0; i<26; ++i){
if(mp[a[i]].empty()) res.push_back(a[i]);
}
cout << "YES\n" << res << "\n";
}
// for(auto x: mp){
// cout << x.first << " ";
// for(int k=0; k<x.second.size(); ++k){
// cout << x.second[k] << " ";
// }
// cout << "\n";
// }
// cout << "\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
//#ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
//#endif
ll t = 1;
cin >> t;
while(t--){
solve();
}
return 0;
}
| cpp |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define out(x) cout << #x << '=' << x << endl;
#define lowbit(x) (x & -x);
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t = 1;
//cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
int c = 0;
int aa = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] == 0) {
c = 0;
} else {
aa = max(aa, ++c);
}
}
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
c = 0;
} else {
aa = max(aa, ++c);
}
}
cout << aa << endl;
}
}
| cpp |
1307 | G | G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3
1 2 2
2 3 2
1 3 3
5
0
1
2
3
4
OutputCopy3.0000000000
4.0000000000
4.5000000000
5.0000000000
5.5000000000
| [
"flows",
"graphs",
"shortest paths"
] | #pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
#define INF 1000000007
using namespace __gnu_pbds;
using namespace std;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
int n,m,q;
long long f[60];
vector<pair<pair<int,int>,pair<int,int> > > g[60];
int dist[60],pre[60],edge[60],vis[60];
inline void add_edge(int x,int y,int c,int num)
{
g[x].push_back(make_pair(make_pair(y,c),make_pair(num,g[y].size())));
g[y].push_back(make_pair(make_pair(x,0),make_pair(-num,g[x].size()-1)));
}
inline int min_cost_flow(int f)
{
int res=0;
while(f>0){
for(int i=1;i<=n;i++) dist[i]=INF;
dist[1]=0;
queue<int> q;
q.push(1);vis[1]=1;
while(!q.empty()){
int u=q.front();q.pop();vis[u]=0;
for(int i=0;i<(int)g[u].size();i++){
pair<pair<int,int>,pair<int,int> > e=g[u][i];
if(e.first.second>0&&dist[e.first.first]>dist[u]+e.second.first){
dist[e.first.first]=dist[u]+e.second.first;
pre[e.first.first]=u;
edge[e.first.first]=i;
if(!vis[e.first.first]){
vis[e.first.first]=1;
q.push(e.first.first);
}
}
}
}
if(dist[n]==INF) return -1;
int flow=f;
for(int i=n;i!=1;i=pre[i]){
flow=min(flow,g[pre[i]][edge[i]].first.second);
}
f-=flow;
res+=flow*dist[n];
for(int i=n;i!=1;i=pre[i]){
g[pre[i]][edge[i]].first.second-=flow;
g[i][g[pre[i]][edge[i]].second.second].first.second+=flow;
}
}
return res;
}
signed main()
{
ios::sync_with_stdio(false);cin.tie(0);
cin>>n>>m;
for(int i=1;i<=m;i++){
int x,y,w;cin>>x>>y>>w;
add_edge(x,y,1,w);
}
int pos=n;f[0]=0ll;
for(int i=1;i<=n;i++){
int now=min_cost_flow(1);
if(now==-1){
pos=i-1;break;
}
f[i]=f[i-1]+1ll*now;
}
cin>>q;
for(int i=1;i<=q;i++){
int x;cin>>x;
double ans=(f[1]+1ll*x)*1.0;
for(int j=2;j<=pos;j++) ans=min(ans,(f[j]+1ll*x)*1.0/j);
cout<<fixed<<setprecision(10)<<ans<<'\n';
}
return 0;
}
| cpp |
1316 | F | F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212. | [
"data structures",
"divide and conquer",
"probabilities"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll mod=1e9+7;
int n,m;
int a[300005];
ll fac[300005],inv[300005];
pair<ll,int> val[600005];int cnt;
struct query{
int pos;
int val;
}que[300005];
struct node{
int tot;
ll val,val1,val2;
}tree[2400005];
node operator +(const node &a,const node &b){
node res;
res.tot=a.tot+b.tot;
res.val1=(a.val1+b.val1*fac[a.tot]%mod)%mod;
res.val2=(a.val2+b.val2*inv[a.tot]%mod)%mod;
res.val=(a.val+b.val+a.val1*b.val2%mod*inv[a.tot]%mod)%mod;
return res;
}
void update(int k,int l,int r,int x,int y){
if(l==r){
// printf("k=%d\n",k);
// if(y>0)printf("add %d val=%lld\n",x,val[x].first);
// else printf("del %d\n",x);
if(y>0)tree[k].tot=1,tree[k].val=0,tree[k].val1=val[x].first,tree[k].val2=val[x].first*inv[1]%mod;
else tree[k].tot=tree[k].val=tree[k].val1=tree[k].val2=0;
return;
}
int mid=l+r>>1;
if(x<=mid)update(k*2,l,mid,x,y);
else update(k*2+1,mid+1,r,x,y);
tree[k]=tree[k*2]+tree[k*2+1];
}
ll power(ll a,ll p){
ll res=1;
while(p){
if(p&1)res=res*a%mod;
p>>=1;
a=a*a%mod;
}
return res;
}
int main(){
fac[0]=1;
for(int i=1;i<=300000;i++)fac[i]=fac[i-1]*2%mod;
inv[300000]=power(fac[300000],mod-2);
for(int i=299999;i>=0;i--)inv[i]=inv[i+1]*2%mod;
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]),val[++cnt].first=a[i],val[cnt].second=cnt;
scanf("%d",&m);
for(int i=1;i<=m;i++)scanf("%d%d",&que[i].pos,&que[i].val),val[++cnt].first=que[i].val,val[cnt].second=cnt;
sort(val+1,val+cnt+1);
for(int i=1;i<=n;i++)a[i]=lower_bound(val+1,val+cnt+1,make_pair(1ll*a[i],i))-val;
for(int i=1;i<=m;i++)que[i].val=lower_bound(val+1,val+cnt+1,make_pair(1ll*que[i].val,i+n))-val;
for(int i=1;i<=n;i++)update(1,1,cnt,a[i],1);
printf("%lld\n",tree[1].val);
for(int i=1;i<=m;i++){
update(1,1,cnt,a[que[i].pos],-1);
a[que[i].pos]=que[i].val;
update(1,1,cnt,a[que[i].pos],1);
printf("%lld\n",tree[1].val);
// printf("%lld %lld %lld\n",tree[3].val,tree[6].val1,tree[7].val2);
}
return 0;
} | cpp |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define MOD 1000000007
using namespace std;
using namespace __gnu_pbds;
template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
priority_queue <int, vector<int>, greater<int>> q;
pair <long long, long long> v[105];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
long long ax, ay, bx, by, x, y, t, sol = 0;
cin >> v[1].first >> v[1].second >> ax >> ay >> bx >> by;
cin >> x >> y >> t;
int n = 1;
while(v[n].first < x + t && v[n].second < y + t){
n++;
v[n].first = v[n - 1].first * ax + bx;
v[n].second = v[n - 1].second * ay + by;
}
for(int i = 1; i <= n; i++){
long long xx = x, yy = y, nr = 0, num = 0;
for(int j = i; j <= n; j++){
long long dist = abs(xx - v[j].first) + abs(yy - v[j].second);
nr += dist;
// cout << nr << " ";
if(nr <= t) num++;
else break;
xx = v[j].first;
yy = v[j].second;
}
sol = max(sol, num);
xx = x, yy = y, nr = 0, num = 0;
for(int j = i; j >= 1; j--){
long long dist = abs(xx - v[j].first) + abs(yy - v[j].second);
nr += dist;
// cout << nr << " ";
if(nr <= t) num++;
else break;
xx = v[j].first;
yy = v[j].second;
}
sol = max(sol, num);
}
cout << sol;
return 0;
} | cpp |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44. | [
"brute force",
"data structures",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
//int a[N];
signed main(){
int t;
cin>>t;
while(t--){
int n,m,k;
cin>>n>>m>>k;
m--;
k=min(k,m);
vector<int> a(n);
for(int&x :a) cin>>x;
int op=0;
for(int i=0;i<=k;i++){
int l=k-i;
int minl=1e9;
for(int j=l;j<=m-i;j++){
minl=min(minl,max(a[j],a[n-1-(m-j)]));
}
op=max(op,minl);
}
cout<<op<<"\n";
}
} | cpp |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"brute force",
"data structures",
"dp",
"greedy"
] | #include <bits/stdc++.h>
#define sys ios_base::sync_with_stdio(0);cin.tie(0);
#define mod 1000000007
using namespace std;
//#pragma comment(linker, "/STACK:268435456");
#define count_setbits(n) __builtin_popcount(n)
#define fixed cout<<fixed<<setprecision(16)
#define count_bits(n) ((ll)log2(n))+1
#define no_of_digits(n) ((ll)log10(n))+1
#define str string
#define c(itretor) cout<<itretor
#define cp(itretor) cout<<setprecision(itretor)
#define cys cout<<"YES"<<endl
#define cno cout<<"NO"<<endl
#define endl "\n"
#define imx INT_MAX
#define imn INT_MIN
#define lmx LLONG_MAX
#define lmn LLONG_MIN
#define ll long long
#define f(i,l,r) for(long long i=l;i<r;++i)
#define fr(i,r,l) for(long long i=r-1;i>=l;--i)
#define vi vector<int>
#define vs vector<string>
#define vll vector <long long>
#define mii map<int,int>
#define mll map<long long,long long>
#define pll pair<ll,ll>
#define tsolve long long t;cin>>t; while(t--) solve();
#define inp(x) for(auto &i:x) cin>>i;
#define all(x) x.begin(),x.end()
#define pb push_back
#define ff first
#define ss second
#define ins insert
#define vec vector
#define print(x) for(auto i:x) cout<<i<<" ";
#define pprint(x) for(auto [i,j]:x) cout<<i<<" "<<j
#define dbg1(x) cout << #x << "= " << x << endl;
#define dbg2(x,y) cout << #x << "= " << x << " " << #y << "= " << y <<endl;
#define dbg3(x,y,z) cout << #x << "= " << x << " " << #y << "= " << y << " " << #z << "= " << z << endl;
#define dbg4(x,y,z,w) cout << #x << "= " << x << " " << #y << "= " << y << " " << #z << "= " << z << " " << #w << "= " << w << endl;
//const ll N=2e5;
//vector<bool> isprime(N+1,1);
//inline void sieve(){ isprime[0]=isprime[1]=1; for(int i=2;i<=N;i++) if(isprime[i]) for(int j=i*i;j<=N;j+=i) isprime[j]=false;}
inline vector<ll> get_factors(ll n) { vector<ll> factors; if(n==0) return factors; for(ll i=1;i*i<=n;++i){ if(n%i==0){factors.push_back(i);
if(i!=n/i) factors.push_back(n/i);}} return factors;}
inline ll modpower(ll a, ll b, ll m = mod)
{ ll ans = 1; while (b) { if (b & 1) ans = (ans * a) % m; a = (a * a) % m; b >>= 1; } return ans; }
inline ll mod_inverse(ll x,ll y) { return modpower(x,y-2,y); }
inline ll max_ele(ll * arr ,ll n) { ll max=*max_element(arr,arr+n); return max;}
inline ll max_i(ll * arr,ll n){ return max_element(arr,arr+n)-arr+1; }
inline void solve()
{
ll n; cin>>n;
vll a(n); inp(a);
ll ans=0,p=0;
f(i,0,n){
ll tans=a[i];
ll j=i-1;ll k=a[i],m=a[i];
while(j>=0){
tans+=min(a[j],k),k=min(a[j],k);
--j;
}
j=i+1,k=a[i];
while(j<n){
tans+=min(a[j],k),k=min(a[j],k);
++j;
}
if(tans>ans){
ans=tans;
p=i;
}
}
ll j=p-1,k=a[p];
while(j>=0){
a[j]=min(a[j],k),k=min(a[j],k);
--j;
}
j=p+1,k=a[p];
while(j<n){
a[j]=min(a[j],k),k=min(a[j],k);
++j;
}
print(a);cout<<endl;
}
int main()
{
sys;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
solve();
return 0;
} | cpp |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | #pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define f first
#define s second
#define ii pair<int,int>
#define vi vector<int>
#define vvi vector<vi>
#define vvii vector<vector<ii>>
#define pb push_back
#define vpi vector<ii>
#define forcin for(int i = 0; i<n; ++i) cin>>v[i];
#define pq priority_queue<ii>
#define mp make_pair
#define ld long double
#define vc vector<char>
#define vvc vector<vc>
#define vb vector<bool>
#define vvb vector<vb>
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define For(i, n, x) for (int i = x; i < n; i++)
#define rsz(a,x) assign(a,x)
#define endl "\n"
int n,k;
vvi G;
map<ii,int> ans;
set<int> bad;
bitset<200002> used;
int r;
void dfs(int u, int c){
used[u] = 1;
int act = 0;
for(int v : G[u]){
if(used[v]) continue;
act++;
if(act == c) act++;
if(act > r) act = 1;
ans[{u,v}] = ans[{v,u}] = act;
dfs(v,act);
}
}
bool check(int m){
int c = 0;
For(i,n,0){
c+=(G[i+1].size() > m);
}
return c<=k;
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>k;
G.rsz(n+1,vi());
vpi edges;
For(i,n,1){
int u,v; cin>>u>>v;
G[u].pb(v); G[v].pb(u);
edges.pb({u,v});
}
int l = 0; r = n;
while(r > l+1){
int m = (l+r)/2;
if(check(m)) r = m;
else l = m;
}
cout<<r<<endl;
//pillar construccio valida
For(i,n+1,1){
if(G[i].size() > r) bad.insert(i);
}
//filling notbad and refilling bad
dfs(1,0);
for(auto x : edges) cout<<ans[x]<<" ";
}
| cpp |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | /*
* Author - Sumitp007
* Don't Copy ,Just Watch
*/
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define mk make_pair
#define F first
#define S second
#define mod 1000000007
#define maxi INT_MAX
#define mini INT_MIN
#define vi vector<int>
#define vvll vector<vector<long long int>>
#define vb vector<bool>
#define vs vector<string>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vll vector<long long int>
#define vpii vector<pair<int,int>>
#define vvi vector<vector<int>>
#define mii map<int,int>
#define umii unordered_map<int,int>
#define mci map<char,int>
#define pii pair<int,int>
#define readarr(arr,n) for(int i=1;i<=n;i++){cin>>arr[i];}
#define readvi(a,n) for(int i=0;i<n;i++){cin>>a[i];}
void Traverse( vi v ) {
for ( auto it : v ) {
cout << it << " ";
}
cout << endl;
}
bool Asc_Pair_Sort(pii a,pii b) {
//* Sorting is done with second element of pairs to be Smaller
if ( a.second < b.second ) return true;
return false;
}
ll Fast_Power(ll x,ll y) {
ll res = 1;
while ( y != 0 ) {
if ( y&1 ) res *= x;
x*=x;
y>>=1;
}
return res;
}
void solve() {
ll n;
cin >> n;
ll a = -1, b = -1 , c = -1 , dupn = n;
for ( int i = 2 ; i * i <= n ; i++ ) {
if ( n % i == 0 ) {
if ( a == -1 ) a = i;
else if ( b == -1 ) b = i;
if ( a != -1 && b != -1 ) break;
n /= i;
}
}
c = ( dupn / ( a * b ) );
if ( a != b && b != c && a != c && dupn == ( a * b * c ) && a >=2 && b >= 2 && c >=2 ) {
cout << "YES\n";
cout << a << " " << b << " " << c << "\n";
}
else cout << "NO" << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t=1;
cin >> t;
while ( t -- > 0 ) {
solve();
}
return 0;
} | cpp |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7. | [
"brute force",
"combinatorics",
"math",
"number theory"
] | #include "bits/stdc++.h"
using namespace std;
#define int long long
//#define endl "\n"
#define inf (int)1e18
#define BeethovenBeedrilla true
#define TheEndOfPutin true
const int MOD =1000000000+7;
int binPow(int x, int p, int mod) {
int res = 1;
while (p > 0) {
if (p % 2)
res = (res * x) % mod;
x = (x * x) % mod;
p /= 2;
}
return res;
}
inline int modDiv(int a, int b, int mod = MOD) {
int p = binPow(b, mod - 2, mod);
return (a * p) % mod;
}
vector<int> facts;
int fact(int x, int mod = MOD) {
if (facts.size() <= x) {
facts.push_back(x <= 0 ? 1 : (fact(x - 1, mod) * x) % mod);
}
return facts[x];
}
inline int binom(int n, int k, int mod = MOD) {
return modDiv(fact(n), fact(n - k) * fact(k) % mod);
}
int logPow(int n, int p, int mod = MOD) {
int ans = 1;
int c = n % mod;
while (p > 0) {
if (p % 2) {
ans = (ans * c) % mod;
}
p /= 2;
c%=mod;
c = (c * c) % mod;
}
return ans;
}
//int fact(int n){
// int ans = 1;
// while(n>= 2){
// ans *=n;
// n--;
// }
// return ans;
//}
int sp_mult(int l,int r){
int ans = 1;
for(int i = l+1 ; i <=r ; i ++){
ans *= i;
}
return ans ;
}
signed main() {
cin.tie(nullptr), cout.tie(nullptr);
ios_base::sync_with_stdio(false);
cout << setprecision(15) << fixed;
int n,m;
cin>>n>>m;
int num[n];
int x=1;
for(int j=0;j<n;j++)
{
cin>>num[j];
for(int i=0;i<j&&x!=0;i++)
x=x*abs(num[i]-num[j])%m;
}
cout<<x%m;
}
| cpp |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | //श्रमं विना न किमपि साध्यम्
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define all(a) (a).begin(),(a).end()
#define rev(p) reverse(p.begin(),p.end());
#define v vector
#define sortt(a) sort(all(a))
#define pll pair<ll,ll>
#define sz(c) (int)c.size()
#define fr first
#define sc second
#define pb push_back
#define pf push_front
#define eb emplace_back
#define mp make_pair
#define rep(i,a,n) for(int i=a ; i<n ; i++)
#define pi (2*acos(0.0))
#define F(a,b,i) for(int i=a;i<b;i++)
#define FN(a,b,i) for(int i=a-1;i>=b;i--)
#define endl "\n"
//*****DEBUG FUNCTIONS********//
#ifndef ONLINE_JUDGE
template<typename T>void __p(std::vector<T> v);
template<typename T>void __p(T a){cout<<a;}
template<typename T, typename F>void __p(pair<T, F> a){cout<<"{";__p(a.first);cout<<",";__p(a.second);cout<<"}";}
template<typename T>void __p(std::vector<T> a) {cout<<"{";for(auto it=a.begin(); it<a.end(); it++)__p(*it),cout<<",}"[it+1==a.end()];}
template<typename T>void __p(std::set<T> a){cout<<"{";for(auto it=a.begin(); it!=a.end();){__p(*it); cout<<",}"[++it==a.end()];}}
template<typename T>void __p(std::multiset<T> a){cout<<"{";for(auto it=a.begin(); it!=a.end();){__p(*it); cout<<",}"[++it==a.end()];}}
template<typename T, typename F>void __p(std::map<T,F> a){cout<<"{\n";for(auto it=a.begin(); it!=a.end();++it){__p(it->first);cout << ": ";__p(it->second);cout<<"\n";}cout << "}\n";}
template<typename T, typename ...Arg>void __p(T a1, Arg ...a){__p(a1);__p(a...);}
template<typename Arg1>void __f(const char *name, Arg1 &&arg1){cout<<name<<" : ";__p(arg1);cout<<endl;}
template<typename Arg1, typename ... Args>void __f(const char *names, Arg1 &&arg1, Args &&... args) {int bracket=0,i=0;for(;; i++)if(names[i]==','&&bracket==0)break;else if(names[i]=='(')bracket++;else if(names[i]==')')bracket--;const char *comma=names+i;cout.write(names,comma-names)<<" : ";__p(arg1);cout<<" | ";__f(comma+1,args...);}
#define trace(...) cout<<"Line:"<<__LINE__<<" ", __f(#__VA_ARGS__, __VA_ARGS__)
#else
#define trace(...)
#define error(...)
#endif
//*****DEBUG FUNCTIONS********//
ll inf =1e18;
ll mod1 = 1e9 + 7;
ll mod2=998244353;
ll log2n(ll n) // floor of(log2 n) , log2 (13)=3
{
//FAILS FOR N=0
if(n==0)return 0;
return (63-__builtin_clzll(n));
}
bool is_prime( ll n)
{
if(n==1)return false;
ll i=2;
for(i=2;i*i<=n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
ll power(ll x, ll y, ll p)
{
x = x % p;
if(x==0)return 0;
ll res = 1;
while (y > 0)
{
if (y & 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
ll pwr(ll x, ll y){if(x==0)return 0;ll res = 1;x = x ;while (y > 0){if (y & 1)res = (res * x);y = y >> 1;x = (x * x) ;}return res;}
ll modInverse(ll n, ll p){return power(n, p - 2, p);}
ll ncr(ll n, ll r , ll modd){if(r>n){return 0;}
if(r>n-r){r = n-r;}ll ans = 1;
for(ll i = 1; i<=r ; i++){
ans *= (n-i+1);ans%= modd;ans *= modInverse(i, modd);ans %= modd;}
return ans;}
ll _gcd(ll a, ll b){ if (b == 0) return a; return _gcd(b, a % b);}
//********CLOCK********
ll begtime = clock();
#define time() cerr << "\n\nTime elapsed: " << (clock() - begtime)*1000/CLOCKS_PER_SEC << " ms\n\n";
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//********CLOCK********
ll testctr;
const int N=2e6+5;
void solve()
{
ll i, j , t1 , t2 , t3 ,t4 , flag;
//ARE YOU REALLY SURE()?
//chckdstc?
//MXMN?BSPZL
//order_1e18?overflow!!!
ll n,s,k; cin>>n>>s>>k;
set<ll>s1;
for(i=0;i<k;i++)
{
cin>>t1;
s1.insert(t1);
}
for(i=0;;i++)
{
t1=s+i;t2=s-i;
if( (t1>=1 && t1<=n && s1.count(t1)==0) || (t2>=1 && t2<=n && s1.count(t2)==0))
{
cout<<i<<endl;return;
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input1.txt", "r", stdin);
freopen("output1.txt", "w", stdout);
#endif
cout<<fixed<<setprecision(20);
ll TESTS;
cin>>TESTS;
//TESTS=1;
for(int i=1;i<=TESTS;i++)
{
testctr=i;
// cout<<"Case #"<<i<<":"<<" ";
solve();
}
time();
return 0;
} | cpp |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | #include <bits/stdc++.h>
// يارب أطلع سبسوب
#define BeboDBale ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define e "\n"
#define sin(a) sin((a)*PI/180)
#define cos(a) cos((a)*PI/180)
#define tan(a) tan((a)*PI/180)
#define inf 1e18
#define pp push_back
#define pf push_front
#define ll long long
#define ld long double
#define vll vector<ll>
#define pll pair<ll,ll>
#define vint vector<int>
#define vvll vector<vll>
#define vpll vector<pll>
#define vbool vector<bool>
#define ull unsigned long long
#define sz(x) (int)(x).size()
#define mkp make_pair
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define ins insert
#define forn(i, n) for(long long i = 0; i<(n); i++)
#define no cout << "NO\n"
#define yes cout << "YES\n"
int dx[] = {+0, +0, -1, +1, +1, +1, -1, -1};
int dy[] = {-1, +1, +0, +0, +1, -1, +1, -1};
using namespace std;
unsigned long long power(int n, int pow) {
unsigned long long ans = 1;
for (int i = 0; i < pow; ++i) {
ans *= n;
}
return ans;
}
set<long long> lucky_numbers;
void generate_lucky_number() {
for (int i = 0; i <= 10; i++) {
for (int j = 0; j < (1 << i); ++j) {
string s;
int cnt1 = 0, cnt2 = 0;
for (int k = 0; k < i; ++k) {
if ((1 << k) & j) {
s += "7";
cnt1++;
} else {
s += "4";
cnt2++;
}
}
if (!s.empty())lucky_numbers.insert(stoll(s));
}
}
}
// v.begin = 0 - v.end = n
const int BASE = 1000000007;
const long double PI = 3.14159265358979323846;
const int N = 1e5 + 5;
void solvingPeopleProblemsIgnoringMine() {
int n;cin >> n;
set<int>s;
for (int i = 2; i <= sqrt(n); ++i) {
if(n%i==0) {
s.insert(i);
s.insert(n/i);
}
}
for(auto it:s){
for (int i = 2; i <= sqrt(it); ++i) {
set<int>a;
a.insert(n/it);
if(it%i==0){
a.insert(i);
a.insert(it/i);
}
if(a.size()==3){
yes;
for(auto x:a){cout<<x<<' ';}
cout << e;
return;
}
}
}
no;
}
int main() {
BeboDBale
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
int t = 1;
cin >> t;
while (t--) {
solvingPeopleProblemsIgnoringMine();
}
} | cpp |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] | #include "bits/stdc++.h"
using namespace std;
signed main() {
int n,m;
scanf("%d%d",&n,&m);
vector< vector< int >> a(n+3,vector<int>(m+3));
for(int i = 1; i <=n ;i++)
for(int j = 1 ; j <=m;j++)
cin >> a[i][j];
int ans = 0;
for(int i = 1; i <=m;i++){
vector<int>cnt(n+3);
for(int j = 1; j <=n;j++){
if(a[j][i] < i or (a[j][i] - i) %m) continue;
int row = (a[j][i] -i) / m + 1;
if(row > n) continue;
int offset = j - row;
cnt[(offset + n)%n]++;
}
int cur = n;
for(int j = 0 ; j < n; j++) cur = min(cur, j + n - cnt[j]);
ans += cur;
}
printf("%d\n",ans);
}
| cpp |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | /*______________________________________________________________________
||--------------------------------------------------------------------||
|| ||
|| "I bear witness that there is no god but Allah and I bear witness ||
|| that Muhammad (peace be upon him) is the Messenger of Allah" ||
|| ||
|| *** In the name of Allah, the Most Gracious, the Most Merciful.*** ||
|| ||
========================================================================
========================================================================
|| ||
|| --> Author : Abu Bakar Siddique Arman (#arman_bhaai) ||
|| --> Email : [email protected] ||
|| --> Portfolio : arman-bhaai.github.io ||
|| --> LinkedIn : linkedin.com/in/abubakar-arman ||
|| --> GitHub : github.com/arman-bhaai ||
|| --> FaceBook : fb.me/arman.bhaai ||
|| --> YouTube : youtube.com/@arman-bhaai ||
|| --> StopStalk : stopstalk.com/user/profile/arman_bhaai ||
|| --> Clist : clist.by/coder/arman_bhaai ||
|| --> CodeForces : codeforces.com/profile/arman_bhaai ||
|| --> CodeChef : codechef.com/users/arman_bhaai ||
|| --> AtCoder : atcoder.jp/users/arman_bhaai ||
|| --> HackerRank : hackerrank.com/arman_bhaai ||
|| --> LeetCode : leetcode.com/arman_bhaai ||
||____________________________________________________________________||
----------------------------------------------------------------------*/
// I believe in OpenSource. So, any of my code snippets are Copyright-Free.
// <3 Happy Coding <3
// Contest ID :: 1295
// Problem Name :: A. Display The Number
// Problem URL :: https://codeforces.com/contest/1295/problem/A
// Submission ::
/*******************************************************************************
////////////////////////////////////////////////////////////////////////////////
*******************************************************************************/
#include <bits/stdc++.h>
using namespace std;
// typedefs
typedef long long ll;
typedef string str; // salute Python! proud to be a Pythonista too!!
typedef long double db;
typedef vector<int> vi;
typedef vector<ll> vii;
typedef vector<vector<ll>> vvi;
// typedef map<ll,ll> mi;
typedef pair<ll,ll> pi;
// shortcuts
#define en '\n'
#define pb push_back
#define ins insert
#define ft front
#define bk back
#define mp make_pair
#define F first
#define S second
#define LB lower_bound
#define UB upper_bound
#define getv(_) for(auto &__:_) cin>>__;
#define all(_) (_).begin(),(_).end()
#define rall(_) (_).rbegin(),(_).rend()
#define forn(_,__) for(int _=0;_<(__);_++)
#define fornr(_,__) for(int _=(__);_>0;_--)
#define forab(_,__,___) for(int _=(__);_<(___);_++)
#define forba(_,___,__) for(int _=(___);_>(__);_--)
#define sz(_) (_).size()
#define rsz(__) (__).resize()
#define each(__, _) for (auto&__:_)
// constants
const db PI = acos(-1.0);
const int MX = (int)2e5 + 5;
const ll INF = (ll)1e18; // not too close to LLONG_MAX
const int MOD = (int)1e9 + 7;
// debugging
template<class ff,class ss>ostream&operator<<(ostream&os,const pair<ff,ss>&p){return os<<"("<<p.F<<", "<<p.S<<")";}
template<class T>ostream&operator<<(ostream&os,const vector<T>&v){os<<"[";for(auto it=v.begin();it!=v.end();++it){if(it!=v.begin())os<<", ";os<<*it;}return os<<"]";}
template<class T>ostream&operator<<(ostream&os,const set<T>&v){os<<"{";for(auto it=v.begin();it!=v.end();++it){if(it!=v.begin())os<<", ";os<<*it;}return os<<"}";}
template<class T>ostream&operator<<(ostream&os,const multiset<T>&v) {os<<"{";for(auto it=v.begin();it!=v.end();++it){if(it!=v.begin())os<<", ";os<<*it;}return os<<"}";}
template<class ff,class ss>ostream&operator<<(ostream&os,const map<ff,ss>&v){os<<"[";for(auto it=v.begin();it!=v.end();++it){if(it!=v.begin())os<<", ";os<<"("<<it->F<<", "<<it->S<<")";}return os<<"]";}
#define couts(___) cout<<(___)<<" ";
#define coutn(___) cout<<(___)<<'\n';
#define dbg(args...) do {cerr << #args << " ==> "; boss(args); } while(0);
void boss(){cerr << endl;}
template<class T>void boss(T a[],int n){for(int i=0;i<n;++i)cerr<<a[i]<<' ';cerr<<endl;}
template<class T,class...k>void boss(T arg,const k&...j){cerr<<arg<<", ";boss(j...);}
/*=====================//===========\\=====================*/
/*====================// Code Begins \\====================*/
/*====================\\=============//====================*/
// void solve();
void solve(){
int n; cin>>n;
str s="";
if(n&1){
s="7";
forn(i,(n-3)/2) s.pb('1');
} else {
forn(i,n/2) s.pb('1');
}
cout<<s;
}
int main(){
// fastIO
ios::sync_with_stdio(0); cin.tie(0);
// handle TC
int ___=1, __=___;
cin>>__;
for(int _=___; _<=__; _++){
// cout<<"Case "<<_<<": ";
solve(); cout<<en;
}
return 0;
}
/* Alternative Approaches
void solve(){
int n; cin>>n;
str s(n/2, '1');
if(n&1) s[0]='7';
cout<<s;
}
void solve(){
int n; cin>>n;
cout<<(n&1 ? '7'+str((n-3)/2,'1') : str(n/2,'1'));
}
void solve(){
int n; cin>>n;
if(n&1){
cout<<7;
n-=3;
}
while(n){
cout<<1;
n-=2;
}
}
*/ | cpp |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | /// IN THE NAME OF ALLAH
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t; cin >> t;
int a, b, c, n;
while(t--)
{
cin >> a >> b >> c >> n;
int mx = max (a, max(b, c));
int tr = mx - a;
a += tr;
n -= tr;
tr = mx - b;
b += tr;
n -= tr;
tr = mx - c;
c += tr;
n -= tr;
if ((a == b && b == c) && (n%3 == 0 && n >= 0)) cout<< "YES" << endl;
else cout << "NO" << endl;
}
} | cpp |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define int long long int
#define vi vector<int>
int gcd(int a,int b) {if (b==0) return a; return gcd(b, a%b);}
int lcm(int a,int b) { return a/gcd(a,b)*b; }
bool prime(int a) { if (a==1) return 0; for (int i=2;i<=round(sqrt(a));i++) if (a%i==0) return 0; return 1; }
void yes() { cout<<"YES\n"; }
void no() { cout<<"NO\n"; }
int ModExp(int x,int y){if(y==0) return 1;int p=ModExp(x,y/2);if(y&1)return (x*(p*p)%MOD)%MOD; return (p*p)%MOD;}
// *******************SOLVE START**************
void solve(){
int n;
cin>>n;
vi arr(n);
vi pref(n+1,0);
int maxpref=0,minpref=0;
for(int i=0;i<n;i++){
cin>>arr[i];
pref[i+1]=pref[i]+arr[i];
}
for(int i=1;i<=n;i++){
if(pref[i]>pref[maxpref]){
maxpref=i;
}
if(pref[i]<=pref[minpref]){
minpref=i;
}
}
if((maxpref==n&&minpref==0)||(pref[n]>pref[maxpref]-pref[minpref])) yes();
else no();
}
// *******************SOLVE END****************
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.out","w",stdout);
#endif
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t=1;
cin>>t;
while(t--){
solve();
}
return 0;
} | cpp |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7. | [
"brute force",
"combinatorics",
"math",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define vll vector<long long>
#define vpll vector<pair<long long, long long>>
#define mll map<long long, long long>
#define umll unordered_map<long long>
#define mmll multimap<long long, long long>
#define sll set<long long>
#define msll multiset<long long>
#define usll unordered_set<long long> //faster than set
#define vvll vector<vector<ll>>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define yes cout << "YES\n"
#define no cout << "NO\n"
#define endl cout << "\n"
#define modv 1000000007
#define md 998244353
#define invll(x, n) \
vll x(n); \
rep(i, 0, n) cin >> x[i];
#define makegraph(graph, edges) \
for (ll i = 0; i < edges; i++) \
{ \
ll a, b; \
cin >> a >> b; \
graph[a].pb(b); \
graph[b].pb(a); \
}
#define inll(...) \
ll __VA_ARGS__; \
read(__VA_ARGS__);
#define inint(...) \
int __VA_ARGS__; \
read(__VA_ARGS__);
#define instring(s) \
string s; \
cin>>s;
#define inchar(ch) \
char ch; \
cin>>ch;
#define printvec(v) for(ll i=0; i<v.size(); i++){cout<<v[i]<<" ";} cout<<endl;
#define printarr(arr, n) for(ll i=0; i<n; i++) {cout<<arr[i]<<" ";} cout<<endl;
#define printset(s) for(auto it : s) {cout<<it<<" ";} cout<<endl;
#define all(n) n.begin(), n.end()
#define allrev(n) n.rbegin(),n.rend()
#define lb lower_bound
#define ub upper_bound
#define rep(i, k, n) for (ll i = k; i < n; i++)
#define repr(i, k, n) for (ll i = k; i >= n; i--)
#define setval(arr, size, val) rep(i, 0, size) arr[i] = val;
#define setbits(x) __builtin_popcount(x)
#define setbitsll(x) __builtin_popcountll(x)
template <typename... T>
void read(T &...args){
((cin >> args), ...);
}
template <typename... T>
void print(T... args){
((cout << args << " "), ...);
cout << "\n";
}
#define fast \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}
ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;}
bool comp(pair<ll, ll> &a, pair<ll, ll> &b){
return (a.se < b.se);
}
ll lcm(ll a, ll b) { return a / __gcd(a, b) * b; }
ll digit(ll n) { return floor(log10(n))+1;}
string decToBinary(ll n){
string s;
ll f=0;
repr(i,31,0){
ll k = n >> i;
if (k & 1){
s = s + '1';
f=1;
}
else if(f==1) s = s + '0';
}
return s;
}
bool ispowtwo(ll n){
if(n && (!(n&(n-1)))) return true;
else return false;
}
ll mod(ll a, ll b){
ll res=((a%b)+b)%b;
return res;
}
ll binpow(ll a, ll b){
ll res = 1;
while (b > 0){
if (b & 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
//SEGMENT TREE
void update(ll Tree[], ll idx, ll s, ll e, ll pos, ll X){
if (s == e) Tree[idx] += X;
else{
ll m = (s + e) / 2;
if (pos <= m) update(Tree, 2 * idx, s, m, pos, X);
else update(Tree, 2 * idx + 1, m + 1, e, pos, X);
Tree[idx] = Tree[2 * idx] + Tree[2 * idx + 1];
}
}
ll sum(ll Tree[], ll idx, ll s, ll e, ll ql, ll qr){
if (ql == s && qr == e) return Tree[idx];
if (ql > qr) return 0;
ll m = (s + e) / 2;
return sum(Tree, 2 * idx, s, m, ql, min(m, qr)) + sum(Tree, 2 * idx + 1, m + 1, e, max(ql, m + 1), qr);
}
//getElement(Tree, ind - 1, n);
ll getElement(ll Tree[], ll X, ll N){
return sum(Tree, 1, 0, N - 1, 0, X);
}
//range_Update(Tree, l - 1, r - 1, 1, n);
void range_Update(ll Tree[], ll L, ll R, ll X, ll N){
update(Tree, 1, 0, N - 1, L, X);
if (R + 1 < N) update(Tree, 1, 0, N - 1, R + 1, -X);
}
//END
bool isPrime(ll n){
if (n <= 1) return false;
for (ll i = 2; i * i <= n; i++){
if (n % i == 0) return false;
}
return true;
}
bool isSorted(vector <ll> &v){
ll n = v.size();
vll v1;
v1=v;
sort(all(v1));
rep(i,0,n){
if(v[i]!=v1[i]) return false;
}
return true;
}
//SIEVE
vector<ll> primes;
void SieveOfEratosthenes(ll n)
{
bool prime[n + 1];
memset(prime, true, sizeof(prime));
for (ll p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int p = 2; p <= n; p++)
if (prime[p])
primes.push_back(p);
}
vll primefac(ll n){
vll fac;
for(ll i=0;i<primes.size();i++){
if(primes[i]>n) break;
while(n%primes[i]==0){
n/=primes[i];
fac.pb(primes[i]);
}
}
if(n>0){
fac.pb(n);
}
return fac;
}
ll getfactors(ll n){
ll ct=0;
for(ll i=1; i<=sqrt(n); i++){
if (n%i == 0){
if (n/i == i) ct++;
else ct+=2;
}
}
return ct;
}
//gcd(a,b) == gcd(b,a-b) == gcd(b, a%b)
//Array is faster than vector
ll modpower(ll x, ll y){
ll res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
void solve(){
inll(n,m);
invll(v,n);
ll ans=0;
if(n<=m){
ans++;
rep(i,0,n-1){
rep(j,i+1,n){
ans = ans * (abs(v[i]-v[j]));
ans = ans%m;
}
}
}
print(ans%m);
}
int main(){
fast;
ll tt=1;
//cin>>tt;
while (tt){
tt--;
solve();
}
} | cpp |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | #include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<unordered_map>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstdlib>
#include<stack>
#include<ctime>
#define forin(i,a,n) for(int i=a;i<=n;i++)
#define forni(i,n,a) for(int i=n;i>=a;i--)
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=3e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
int T;
int n,m,k;
int w[N];
void solve() {
n=read();
for(int i=1;i<=n;i++) w[i]=read();
int idx=0;
int i=1;
while(i<=n&&w[i]>=idx) idx++,i++;
if(w[i]==w[i-1]&&idx-1==n-i) {
printf("No\n");
return ;
}
idx=n-i;
while(i<=n&&w[i]>=idx) idx--,i++;
if(i>n) printf("Yes\n");
else printf("No\n");
}
int main() {
// init();
// stin();
scanf("%d",&T);
// T=1;
while(T--) solve();
return 0;
}
| cpp |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
vector<int> a(3);
cin >> a[0] >> a[1] >> a[2];
sort(a.rbegin(), a.rend());
int ans = 0;
if (a[0] > 0)
ans++, a[0]--;
if (a[1] > 0)
ans++, a[1]--;
if (a[2] > 0)
ans++, a[2]--;
if (a[0] > 0 and a[1] > 0)
ans++, a[0]--, a[1]--;
if (a[0] > 0 and a[2] > 0)
ans++, a[0]--, a[2]--;
if (a[1] > 0 and a[2] > 0)
ans++, a[1]--, a[2]--;
if (a[0] > 0 and a[1] > 0 and a[2] > 0)
ans++, a[0]--, a[1]--, a[2]--;
cout << ans << "\n";
}
}
| cpp |
1322 | D | D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
OutputCopy6
InputCopy2 2
1 2
0 0
2 1 -100 -100
OutputCopy2
InputCopy5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
OutputCopy62
NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11. | [
"bitmasks",
"dp"
] | #include<bits/stdc++.h>
using namespace std;
const int N = 5010;
int n, m, l[N], s[N], c[N], f[N][N/2];
int main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
m += n;
memset(f, 0xcf, sizeof(f));
for(int i = n; i; i--) cin >> l[i];
for(int i = n; i; i--) cin >> s[i];
for(int i = 1; i <= m; i++) cin >> c[i];
for(int i = 0; i <= m; i++) f[i][0] = 0;
for(int i = 1; i <= n; i++){
for(int j = n; j; j--){
f[l[i]][j] = max(f[l[i]][j], f[l[i]][j - 1] + c[l[i]] - s[i]);
}
for(int j = l[i];j <= m; j++){
for(int k = 0; k <= (n>>(j-l[i])); k++)
f[j + 1][k/2] = max(f[j + 1][k/2], f[j][k] + k/2*c[j + 1]);
}
}
cout << f[m][0];
return 0;
}
| cpp |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample: | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | #include <bits/stdc++.h>
#define sys ios_base::sync_with_stdio(0);cin.tie(0);
#define mod 1000000007
using namespace std;
//#pragma comment(linker, "/STACK:268435456");
#define count_setbits(n) __builtin_popcount(n)
#define count_bits(n) ((ll)log2(n))+1
#define no_of_digits(n) ((ll)log10(n))+1
#define str string
#define c(itretor) cout<<itretor
#define cp(itretor) cout<<setprecision(itretor)
#define cys cout<<"YES"<<endl
#define cno cout<<"NO"<<endl
#define endl "\n"
#define imx INT_MAX
#define imn INT_MIN
#define lmx LLONG_MAX
#define lmn LLONG_MIN
#define ll long long
#define f(i,l,r) for(long long i=l;i<r;++i)
#define fr(i,r,l) for(long long i=r-1;i>=l;--i)
#define vi vector<int>
#define vs vector<string>
#define vll vector <long long>
#define mii map<int,int>
#define pll pair<ll,ll>
#define mll map<long long,long long>
#define tsolve long long t;cin>>t; while(t--) solve();
#define inp(x) for(auto &i:x) cin>>i;
#define all(x) x.begin(),x.end()
#define print(x) for(auto i:x) cout<<i<<" ";
#define pprint(x) for(auto [i,j]:x) cout<<i<<" "<<j
ll modpower(ll a, ll b, ll m = mod)
{ ll ans = 1; while (b) { if (b & 1) ans = (ans * a) % m; a = (a * a) % m; b >>= 1; } return ans; }
ll mod_inverse(ll x,ll y) { return modpower(x,y-2,y); }
ll max_ele(ll * arr ,ll n) { ll max=*max_element(arr,arr+n); return max;}
ll max_i(ll * arr,ll n){ return max_element(arr,arr+n)-arr+1; }
void solve(){
ll n; cin>>n;
unordered_set<ll> s[n+1];
vector<pll> v(n-1);
map<pll,ll> weight;
f(i,0,n-1){
cin>>v[i].first>>v[i].second;
s[v[i].first].insert(v[i].second);
s[v[i].second].insert(v[i].first);
}
ll l=1;
f(i,0,n){
if(s[i].size()>2){
for(auto x:s[i]){
weight[{x,i}]=weight[{i,x}]=l++;
}
break;
}
}
f(i,0,n-1){
if(!weight[v[i]]){
c(l-1)<<endl;
++l;
}else{
c(weight[v[i]] -1)<<endl;
}
}
}
int main()
{
sys;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
solve();
return 0;
} | cpp |
1312 | G | G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier. | [
"data structures",
"dfs and similar",
"dp"
] | #include<bits/stdc++.h>
#define pii pair<int,int>
#define fi first
#define se second
#define eb emplace_back
#define ll long long
using namespace std;
const int M=1e6+9;
int n,m,sz;
int id[M],c[M][26],b[M],t[M],dp[M],L[M],R[M],val[M];
bool vis[M],bo[M];
int Min(int x,int y){
return id[x]<id[y]?x:y;
}
int Max(int x,int y){
return id[x]>id[y]?x:y;
}
void dfs(int u){
id[u]=++sz;
L[u]=n+1,R[u]=0;
if(vis[u]){
L[u]=u;
R[u]=u;
}
for(int i=0;i<26;++i){
if(c[u][i]){
dfs(c[u][i]);
if(R[c[u][i]]){
if(R[u]){
L[u]=Min(L[u],L[c[u][i]]);
R[u]=Max(R[u],R[c[u][i]]);
}
else L[u]=L[c[u][i]],R[u]=R[c[u][i]];
}
}
}
}
struct Segment_tree{
int vis[M<<2],sum[M<<2];
void pd(int now,int l,int r){
int &v=vis[now];
if(v){
int ls=now<<1,rs=now<<1|1;
vis[ls]=min(vis[ls],v);
vis[rs]=min(vis[rs],v);
sum[ls]=min(sum[ls],v);
sum[rs]=min(sum[rs],v);
v=0;
}
}
void pu(int now){
sum[now]=min(sum[now<<1],sum[now<<1|1]);
}
void update(int now,int l,int r,int x,int y,int v){
if(x>y)return;
if(x<=l&&r<=y){
vis[now]=min(vis[now],v);
sum[now]=min(sum[now],v);
return;
}
pd(now,l,r);
int mid=(l+r)>>1;
if(x<=mid)update(now<<1,l,mid,x,y,v);
if(y>mid)update(now<<1|1,mid+1,r,x,y,v);
pu(now);
}
int query(int now,int l,int r,int x,int y){
if(x>y)return 0;
if(x<=l&&r<=y){
return sum[now];
}
pd(now,l,r);
int mid=(l+r)>>1;
int rex=0;
if(x<=mid)rex=min(rex,query(now<<1,l,mid,x,y));
if(y>mid)rex=min(rex,query(now<<1|1,mid+1,r,x,y));
return rex;
}
}T;
void solve(int u){
if(vis[u])dp[u]=min(dp[u],T.query(1,1,m,val[u],val[u])+val[u]);
if(R[u])T.update(1,1,m,val[L[u]],val[R[u]],dp[u]+1-val[L[u]]);
for(int i=0;i<26;++i){
if(c[u][i]){
dp[c[u][i]]=dp[u]+1;
solve(c[u][i]);
}
}
}
int main(){
cin>>n;
for(int i=1;i<=n;++i){
int p;
char s[5];
cin>>p>>s;
c[p][s[0]-'a']=i;
}
cin>>m;
for(int i=1;i<=m;++i){
cin>>b[i];
t[i]=i;
vis[b[i]]=1;
}
dfs(0);
sort(t+1,t+m+1,[&](const int&l,const int&r){return id[b[l]]<id[b[r]];});
for(int i=1;i<=m;++i){
val[b[t[i]]]=i;
}
solve(0);
for(int i=1;i<=m;++i){
cout<<dp[b[i]]<<" \n"[i==m];
}
return 0;
}
/*
1 2 2 4 3 6
*/ | cpp |
1290 | E | E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th question.ExamplesInputCopy5
2 4 1 5 3
OutputCopy1
3
6
8
11
InputCopy6
1 2 4 5 6 3
OutputCopy1
3
6
8
12
17
NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11. | [
"data structures"
] | # include <bits/stdc++.h>
# define int long long
static const int N = 150005;
int n, a[N], pos[N], ans[N];
FILE *fin, *fout, *ferr;
class SGT {
# define ls (x << 1)
# define rs (x << 1 | 1)
private:
class TreeNode {
public:
int sum, l, cnt, mx1, mx2;
TreeNode(int sum = 0, int l = 0, int cnt = 0, int mx1 = 0, int mx2 = 0):
sum(sum), l(l), cnt(cnt), mx1(mx1), mx2(mx2) {}
TreeNode operator + (TreeNode &a) {
TreeNode o = TreeNode(0, 0, 0, 0, 0);
o.sum = sum + a.sum;
o.l = l + a.l;
if (mx1 > a.mx1)
{
o.mx1 = mx1;
o.mx2 = std::max(mx2, a.mx1);
o.cnt = cnt;
}
if (mx1 < a.mx1)
{
o.mx1 = a.mx1;
o.mx2 = std::max(mx1, a.mx2);
o.cnt = a.cnt;
}
if (mx1 == a.mx1)
{
o.mx1 = mx1;
o.mx2 = std::max(mx2, a.mx2);
o.cnt = cnt + a.cnt;
}
return o;
}
} tr[N << 2];
int tag[N << 2], cov[N << 2];
public:
void reset(int x) {
tr[x] = TreeNode(0, 0, 0, 0, -1);
tag[x] = 0;
cov[x] = -1;
return void();
}
void pushtag(int x, int v) {
if (tr[x].l == 0)
return void();
tr[x].sum += tr[x].l * v;
tr[x].mx1 += v;
if (tr[x].mx2 != -1)
tr[x].mx2 += v;
tag[x] += v;
if (cov[x] != -1)
cov[x] += v;
return void();
}
void pushtag2(int x, int v) {
if (tr[x].l == 0)
return void();
if (v > tr[x].mx1)
return void();
tr[x].sum -= (tr[x].mx1 - v) * tr[x].cnt;
tr[x].mx1 = v;
cov[x] = v;
return void();
}
void pushup(int x) {
return tr[x] = tr[ls] + tr[rs], void();
}
void pushdown(int x) {
if (tr[x].l == 0)
return void();
if (tag[x])
{
pushtag(ls, tag[x]);
pushtag(rs, tag[x]);
tag[x] = 0;
}
if (cov[x] != -1)
{
pushtag2(ls, cov[x]);
pushtag2(rs, cov[x]);
cov[x] = -1;
}
return void();
}
void build(int x, int l, int r) {
reset(x);
if (l == r)
return void();
int mid = (l + r) >> 1;
build(ls, l, mid);
build(rs, mid + 1, r);
return void();
}
void getmin(int x, int l, int r, int ql, int qr, int v) {
if (ql <= l && r <= qr)
if (tr[x].mx2 < v) {
pushtag2(x, v);
return void();
}
int mid = (l + r) >> 1;
pushdown(x);
if (ql <= mid)
getmin(ls, l, mid, ql, qr, v);
if (qr > mid)
getmin(rs, mid + 1, r, ql, qr, v);
return pushup(x);
}
void update(int x, int l, int r, int ql, int qr, int v) {
if (ql <= l && r <= qr)
return pushtag(x, v);
int mid = (l + r) >> 1;
pushdown(x);
if (ql <= mid)
update(ls, l, mid, ql, qr, v);
if (qr > mid)
update(rs, mid + 1, r, ql, qr, v);
return pushup(x);
}
void insert(int x, int l, int r, int p, int v) {
if (l == r) {
tr[x] = TreeNode(v, 1, 1, v, -1);
return void();
}
int mid = (l + r) >> 1;
pushdown(x);
p <= mid ? insert(ls, l, mid, p, v) : insert(rs, mid + 1, r, p, v);
return pushup(x);
}
int query(int x, int l, int r, int ql, int qr) {
if (ql <= l && r <= qr)
return tr[x].l;
int mid = (l + r) >> 1, ans = 0;
pushdown(x);
if (ql <= mid)
ans += query(ls, l, mid, ql, qr);
if (qr > mid)
ans += query(rs, mid + 1, r, ql, qr);
return ans;
}
int query() {
return tr[1].sum;
}
} t;
void solve() {
for (int i = 1; i <= n; ++i) pos[a[i]] = i;
t.build(1, 1, n);
for (int i = 1; i <= n; ++i) {
int p = pos[i];
if (p < n) t.update(1, 1, n, p + 1, n, 1);
if (p > 1) {
int x = t.query(1, 1, n, 1, p - 1) + 1;
t.getmin(1, 1, n, 1, p - 1, x);
}
t.insert(1, 1, n, p, i + 1);
ans[i] += t.query();
}
return void();
}
signed main() {
fin = stdin;
fout = stdout;
ferr = stderr;
// fin = fopen("Input.txt", "r");
// fout = fopen("Output.txt", "w+");
// ferr = fopen("Debug.txt", "w+");
fscanf(fin, "%lld", &n);
for (int i = 1; i <= n; ++i) fscanf(fin, "%lld", a + i);
solve();
std::reverse(a + 1, a + n + 1);
solve();
for (int i = 1; i <= n; ++i) fprintf(fout, "%lld\n", ans[i] - i * (i + 2));
return 0;
}
| cpp |
1295 | F | F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212. | [
"combinatorics",
"dp",
"probabilities"
] | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=50+5;
const int Mod=998244353;
int n,m,ans,a[N],b[N],c[N<<1],f[N],g[N];
int qpow(int x,int k)
{ int res=1;
while(k)
{ if(k&1)res=1ll*res*x%Mod;
x=1ll*x*x%Mod,k>>=1;
}
return res;
}
int main()
{ scanf("%d",&n);
for(int i=1;i<=n;i++)
{ scanf("%d%d",&a[i],&b[i]);
c[++m]=a[i],c[++m]=++b[i];
}
sort(c+1,c+1+m);
m=unique(c+1,c+1+m)-c-1;
for(int i=1;i<=n;i++)
{ a[i]=lower_bound(c+1,c+1+m,a[i])-c;
b[i]=lower_bound(c+1,c+1+m,b[i])-c;
}
f[0]=1;
for(int j=m-1;j>=1;j--)
{ int l=c[j+1]-c[j];
g[0]=1;
for(int i=1;i<=n;i++)g[i]=1ll*g[i-1]*(l+i-1)%Mod*qpow(i,Mod-2)%Mod;
for(int i=n;i>=1;i--)
if(a[i]<=j&&j<b[i])for(int o=1,k=i-1;k>=0;k--,o++)
{ f[i]=(f[i]+1ll*g[o]*f[k]%Mod)%Mod;
if(a[k]>j||j>=b[k])break;
}
}
ans=f[n];
for(int i=1;i<=n;i++)ans=1ll*ans*qpow(c[b[i]]-c[a[i]],Mod-2)%Mod;
printf("%d\n",ans);
return 0;
} | cpp |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#ifdef DEBUG
#include "debug.h"
#else
#define debug(x) void(37)
#endif
#define lsb(x) ((x)&(-x))
#define all(x) x.begin(),x.end()
#define setprec(n) cout << fixed << showpoint;cout << setprecision(n);
typedef long long ll;
typedef long double ld;
const ld eps = 1e-10;
const ll MOD1 = 1e9+7;//1000000007
const ll MOD2 = 998244353ll;
const ll LINF = (ll)1e18;
const int IINF = (int)1e9;
#define int ll
void solve(){
int n, m;
cin >> n >> m;
vector<int> arr(n);
for(int i = 0;i < n;i++)
cin >> arr[i];
int sm = 0;
for(auto it:arr)
sm += it;
cout << min(sm, m) << "\n";
}
signed main(){
ios_base::sync_with_stdio(false); cin.tie(NULL);
mt19937 mt(time(NULL));
//setprec(10);
//freopen("sleepy.in", "r", stdin);
//freopen("in.txt", "w", stdout);
int t = 1;
cin >> t;
for(int i = 1;i <= t;i++)
solve();
return 0;
} | cpp |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define vi vector<int>
#define vll vector<long long int>
#define vp vector<pair<int,int>>
#define vvi vector<vector<int>>
#define mp make_pair
#define ss second
#define ff first
#define all(v) v.begin(),v.end()
#define umi unordered_map<int, int>
#define umc unordered_map<char, int>
#define usi unordered_set<int>
#define si set<int>
#define sc set<char>
#define usc unordered_set<char>
#define sorts(s) sort(s.begin(), s.end())
#define dsort(s) sort(s.begin(), s.end(), greater<ll>())
// #define reverse(s) reverse(s.rbegin(),s.rend())
#define input(s,n) for(int i=0;i<n;i++) cin>>s[i];
#define NUM 100000+10
#define mod 1000000007
#define MAX LONG_MAX
template<typename T1, typename T2>
istream& operator>>(istream& ins,
pair<T1, T2>& v) {
ins >> v.first >> v.second;
return ins;
}
template<typename T, size_t N>
istream& operator>>(istream& ins,
array<T, N>& v) {
for (int i = 0; i < int(N); i++) cin >> v[i];
return ins;
}
template<typename T>
istream& operator>>(istream& ins,
vector<T>& v) {
for (int i = 0; i < int(v.size()); i++) ins >> v[i];
return ins;
}
template<typename T>
ostream& operator<<(ostream& outs,
vector<T>& v) {
for (int i = 0; i < v.size(); i++) outs << v[i] << " ";
return outs;
}
template<typename T, size_t N>
ostream& operator<<(ostream& outs,
array<T, N>& v) {
for (int i = 0; i < int(N); i++) outs << v[i] << " ";
return outs;
}
void solve(){
int a[3], res = 0;
cin >> a[0] >> a[1] >> a[2];
sort(a, a + 3);
for(int i=0; i<3; ++i){
if(a[i]){
++res;
a[i]--;
}
}
if(a[2] && a[1]){
a[2]--, a[1]--;
++res;
}
if(a[2] && a[0]){
a[2]--, a[0]--;
++res;
}
if(a[1] && a[0]){
a[1]--, a[0]--;
++res;
}
if(a[2] && a[1] && a[0]){
++res;
}
cout<<res<<endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// precompute();
ll t; cin>>t;
while(t--) {
solve();
}
// solve();
return 0;
} | cpp |
1284 | F | F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4
1 2
2 3
4 3
1 3
2 4
1 4
OutputCopy3
3 2 4 2
2 1 1 3
4 3 1 4
InputCopy5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
OutputCopy4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
InputCopy9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
OutputCopy8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
| [
"data structures",
"graph matchings",
"graphs",
"math",
"trees"
] | #include<cstdio>
#include<vector>
std::vector<int> v[300010],g[300010];
int f[300010][20],d[300010],n,q[300010];
int find(int x){while(x!=q[x])x=q[x]=q[q[x]];return x;}
void dfs1(int x){
d[x]=d[f[x][0]]+1,q[x]=x;
for(int i=1;i<19;i++)f[x][i]=f[f[x][i-1]][i-1];
for(auto u:v[x])if(u!=f[x][0])f[u][0]=x,dfs1(u);
}
void link(int x,int y){
x=find(x),y=find(y);
for(int i=18;~i;i--) if(d[find(f[x][i])]>d[y]) x=find(f[x][i]);
if(find(f[x][0])==y) x=find(x);
else x=find(y);
printf("%d %d ",x,q[x]=f[x][0]);
}
void dfs2(int x,int fa){
for(auto u:g[x])if(u!=fa) dfs2(u,x),link(x,u),printf("%d %d\n",x,u);
}
int main(){
scanf("%d",&n);
for(int i=1,x,y;i<n;i++)scanf("%d%d",&x,&y),v[x].push_back(y),v[y].push_back(x);
for(int i=1,x,y;i<n;i++)scanf("%d%d",&x,&y),g[x].push_back(y),g[y].push_back(x);
printf("%d\n",n-1);
dfs1(1),dfs2(1,0);
return 0;
} | cpp |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define int long long int
#define endl "\n"
bool debugg = false;
#define dbg if(debugg)
#define ff first
#define ss second
template <typename T>
using order_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;
int n,a,b;
bool f(int mid)
{
int req = (n+1)/2;
int cycle = (mid)/(a+b);
int rem = (mid)%(a+b);
int good = cycle*a + min(a,rem);
return (good>=req && mid>=n);
}
void solve()
{
cin>>n>>a>>b;
int ans , lo = 0 , hi = 1e18;
while(lo <= hi){
int mid = (lo+hi)/2;
if(f(mid)){
ans = mid;
hi = mid-1;
}
else lo = mid+1;
}
cout<<ans<<"\n";
}
int32_t main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
cin>>t;
while(t--){
solve();
}
return 0;
} | cpp |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int t,a,b,x,y;
int main(){for(cin>>t;t--;cout<<max(a*y,max(a*(b-y-1),max(b*x,b*(a-x-1))))<<'\n')cin>>a>>b>>x>>y;} | cpp |
1292 | E | E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1
4
2 1 2
1 2
0
1OutputCopy
? C
? CH
? CCHO
! CCHH
InputCopy2
5
0
2 2 3
1
8
1 5
1 5
1 3
2 1 2
1OutputCopy
? O
? HHH
! CHHHH
? COO
? COOH
? HCCOO
? HH
! HHHCCOOH
NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well. | [
"constructive algorithms",
"greedy",
"interactive",
"math"
] | // LUOGU_RID: 96893101
/*
* @Author: cmk666
* @Created time: 2022-12-09 15:40:13
* @Last Modified time: 2022-12-09 16:50:11
*/
#pragma GCC optimize("Ofast", "unroll-loops")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i, j, k) for ( int i = j ; i <= k ; i++ )
#define Fol(i, j, k) for ( int i = j ; i >= k ; i-- )
inline void read(auto &x)
{
char c = getchar(); for ( ; c < '0' || c > '9' ; c = getchar() );
for ( x = 0 ; c >= '0' && c <= '9' ; c = getchar() ) x = x * 10 + c - '0';
}
int n; char s[509]; vector < int > p; bool flag;
inline void ask(const char *s, const auto &f)
{
printf("? %s\n", s), fflush(stdout);
int l, x; read(l); if ( !~l ) exit(0);
For(i, 1, l) read(x), f(x);
}
inline void ans(const char *s)
{
printf("! %s\n", s), fflush(stdout);
int r; read(r); if ( !r ) exit(0);
}
inline void work()
{
read(n), memset(s, 0, sizeof(s)), flag = false;
if ( n > 4 )
{
ask("CC", [](int x) { s[x] = s[x + 1] = 'C'; });
ask("CH", [](int x) { s[x] = 'C'; });
ask("CO", [](int x) { s[x] = 'C', s[x + 1] = 'O'; });
ask("HO", [](int x) { s[x + 1] = 'O'; });
ask("OO", [](int x) { s[x] = s[x + 1] = 'O'; });
For(i, 2, n - 1) if ( !s[i] ) s[i] = 'H';
if ( s[1] && s[n] ) { ans(s + 1); return; }
if ( s[1] )
{
flag = false, s[n] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[n] = 'H', ans(s + 1); return;
}
if ( s[n] )
{
flag = false, s[1] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[1] = 'H', ans(s + 1); return;
}
flag = false, s[1] = 'O', s[n] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'H', s[n] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'O', s[n] = 'H', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[1] = s[n] = 'H', ans(s + 1); return;
}
ask("CC", [](int x) { s[x] = s[x + 1] = 'C', flag = true; });
ask("CO", [](int x) { s[x] = 'C', s[x + 1] = 'O', flag = true; });
ask("CH", [](int x) { s[x] = 'C', s[x + 1] = 'H', flag = true; });
ask("HO", [](int x) { s[x] = 'H', s[x + 1] = 'O', flag = true; });
if ( flag )
{
if ( s[1] && s[2] && s[3] && s[4] ) { ans(s + 1); return; }
if ( s[1] && s[2] && s[3] )
{
flag = false, s[4] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[4] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[4] = 'H', ans(s + 1); return;
}
if ( s[1] && s[2] && s[4] )
{
flag = false, s[3] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[3] = 'H', ans(s + 1); return;
}
if ( s[1] && s[3] && s[4] )
{
flag = false, s[2] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[2] = 'H', ans(s + 1); return;
}
if ( s[2] && s[3] && s[4] )
{
flag = false, s[1] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[1] = 'H', ans(s + 1); return;
}
if ( s[1] && s[2] )
{
flag = false, s[3] = 'O', s[4] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[3] = s[4] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[3] = 'O', s[4] = 'H', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[3] = 'H', s[4] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[3] = 'H', s[4] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[3] = s[4] = 'H', ans(s + 1); return;
}
if ( s[1] && s[3] )
{
flag = false, s[2] = 'O', s[4] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[2] = s[4] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[2] = 'O', s[4] = 'H', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[2] = 'H', s[4] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[2] = 'H', s[4] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[2] = s[4] = 'H', ans(s + 1); return;
}
if ( s[1] && s[4] )
{
flag = false, s[2] = s[3] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[2] = 'O', s[3] = 'H', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[2] = 'H', s[3] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[2] = s[3] = 'H', ans(s + 1); return;
}
if ( s[2] && s[3] )
{
flag = false, s[1] = 'O', s[4] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = s[4] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'O', s[4] = 'H', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'H', s[4] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'H', s[4] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[1] = s[4] = 'H', ans(s + 1); return;
}
if ( s[2] && s[4] )
{
flag = false, s[1] = s[3] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'O', s[3] = 'H', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'H', s[3] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[1] = s[3] = 'H', ans(s + 1); return;
}
if ( s[3] && s[4] )
{
flag = false, s[1] = s[2] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'O', s[2] = 'H', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
flag = false, s[1] = 'H', s[2] = 'O', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[1] = s[2] = 'H', ans(s + 1); return;
}
assert(false);
}
ask("OO", [](int x) { s[x] = s[x + 1] = 'O', flag = true; });
if ( flag )
{
if ( !s[3] ) s[3] = 'H';
if ( s[4] ) { ans(s + 1); return; }
flag = false, s[4] = 'C', ask(s + 1, [](int x) { flag = true; });
if ( flag ) { ans(s + 1); return; }
s[4] = 'H', ans(s + 1); return;
}
s[2] = s[3] = 'H';
ask("HHH", [](int x) { s[x] = s[x + 1] = s[x + 2] = 'H'; });
if ( !s[1] ) s[1] = 'O';
if ( !s[4] ) s[4] = 'C';
ans(s + 1);
}
int main() { int t; read(t); For(tt, 1, t) work(); return 0; } | cpp |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | /*
*
* \OoO/
*
*/
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <iomanip>
#include <map>
#include <algorithm>
#include <set>
#include <queue>
#include <climits>
#include <cstdlib>
#include <chrono>
// #include <ext/pd_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
using namespace std;
// #define ordered_set tree<ll, null_tyoe, less<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define iamtefu ios_base::sync_with_stdio(false); cin.tie(0);
#define ll long long
#define ld long double
#define fl(i,a,n) for (ll i(a); i<n; i++)
#define rfl(i,a,n) for (ll i(n-1); i>=a; i--)
#define print(a) for (auto x:a){cout<<x<<" ";} cout<<"\n";
#define tt int tt; cin>>tt; for(;tt--;)
template <typename T1, typename T2>
decltype(auto) max(T1 a, T2 b){return (a>b?a:b);}
template <typename T1, typename T2>
decltype(auto) min(T1 a, T2 b){return (a<b?a:b);}
ll gcd(ll a, ll b){
if (b==0){
return a;
}
return gcd(b, a%b);
}
ll pw(ll a, ll b, ll m){
ll res=1;
a%=m;
while (b){
if (b&1){
res=(res*a)%m;
}
a=(a*a)%m;
b>>=1;
}
return res;
}
void scn(){
ll x0, y0, ax, ay, bx, by; cin>>x0>>y0>>ax>>ay>>bx>>by;
vector <vector <ll>> huh={{x0, y0}};
while ((ld)(ax-1)*1.0*huh.back()[0]+bx+(ld)(ay-1)*1.0*huh.back()[1]+by<=1e17){
huh.push_back({ax*huh.back()[0]+bx, ay*huh.back()[1]+by});
//print(huh.back());
}
ll xs, ys, t; cin>>xs>>ys>>t;
//cerr<<"huh\n";
ll ans=0;
fl(i,0,huh.size()){
ll co=(abs(xs-huh[i][0])+abs(ys-huh[i][1]));
if (co>t){
continue;
}
ll dj=1;
fl(j,i+1,huh.size()){
if (co>t)break;
else{
co+=(abs(huh[j-1][0]-huh[j][0])+abs(huh[j-1][1]-huh[j][1]));
if (co>t)break;
dj++;
}
}
ll co1=(abs(xs-huh[i][0])+abs(ys-huh[i][1]));
ll dj1=1;
rfl(j,1,i+1){
if (co1>t)break;
else{
co1+=(abs(huh[j-1][0]-huh[j][0])+abs(huh[j-1][1]-huh[j][1]));
if (co1>t)break;
dj1++;
}
}
dj=max(dj, dj1);
ans=max(dj, ans);
/*if (dj==ans){
cout<<i<<"\n";
}*/
}
cout<<ans<<"\n";
}
int main(){
iamtefu;
#if defined(airths)
auto t1=chrono::high_resolution_clock::now();
freopen("in", "r", stdin);
//freopen("out", "w", stdout);
#endif
//tt
{
scn();
}
#if defined(airths)
auto t2=chrono::high_resolution_clock::now();
ld ti=chrono::duration_cast<chrono::nanoseconds>(t2-t1).count();
ti*=1e-6;
cerr<<"Time: "<<setprecision(12)<<ti;
cerr<<"ms\n";
#endif
return 0;
} | cpp |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
#define sz(a) ((int) (a).size())
#define L(i, j, k) for(int i = (j); i <= (k); ++i)
#define R(i, j, k) for(int i = (j); i >= (k); --i)
#define endl '\n'
#define pb push_back
#define all(x) (x).begin(),(x).end()
typedef long long ll;
const int N=2e5;
ll gcd (ll a, ll b) {
if (b == 0)
return a;
else
return gcd (b, a % b);
}
void solve(){
double n,d;
cin>>n>>d;
for (int i=0;i<=sqrt(d);i++){
ll ans = ceil(d/(i+1))+i;
if(ans<=n){
cout<<"YES\n";
return;
}
}
cout<<"NO\n";
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t;
cin>>t;
while(t--){
solve();
}
}
| cpp |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pi;
typedef vector<pi> vpi;
typedef vector<int> vi;
#define PB push_back
#define MP make_pair
// Common memset settings
//memset(memo, -1, sizeof memo); // dp memoization with -1
//memset(arr, 0, sizeof arr); //clear array of integers
struct unionFind {
vector<int> parrent;
vector<int> size;
void init(int n) {
parrent.assign(n, 0);
size.assign(n, 0);
for(int i = 0;i<n;i++) {
parrent[i] = i;
size[i] = 1;
}
}
int get(int a) {
if(parrent[a] != a) {
parrent[a] = get(parrent[a]);
}
return parrent[a];
}
void unionFun(int a, int b) {
a = get(a);
b = get(b);
if(a == b) {
return;
}
if(size[a] > size[b]) {
swap(a,b);
}
parrent[a] = b;
size[b] += size[a];
}
};
struct segtree {
vector<long long> tree;
int size;
void init(int n) {
size = 1;
while(size < n) {
size *= 2;
}
tree.assign(size*2 - 1, 0);
}
void build(vector<int> &a, int x, int lx, int rx) {
if(rx - lx == 1) {
if(lx < a.size())
tree[x] = a[lx];
} else {
int m = (lx + rx)/2;
build(a, 2*x + 1, lx, m);
build(a, 2*x + 2, m, rx);
tree[x] = tree[2*x + 1] + tree[2*x + 2];
}
}
void build(vector<int> &a) {
init(a.size());
build(a,0, 0, size);
}
void set(int i, int v, int x, int lx, int rx) {
if(rx - lx == 1) {
tree[x] = v;
return;
}
int m = (lx + rx)/2;
if(i < m) {
set(i, v, 2*x + 1, lx, m);
} else {
set(i, v, 2*x + 2, m, rx);
}
tree[x] = tree[2*x + 1] + tree[2*x + 2];
}
void set(int i, int v) {
set(i, v, 0, 0, size);
}
long long sum(int l, int r, int x, int lx, int rx) {
if(l >= rx || lx >= r) {
return 0;
}
if(lx >= l && rx <= r) {
return tree[x];
}
int m = (lx + rx)/2;
long long s1 = sum(l, r, 2*x + 1, lx, m);
long long s2 = sum(l, r, 2*x + 2, m, rx);
return s1 + s2;
}
long long sum(int l, int r){
return sum(l, r, 0, 0, size);
}
};
struct P {
int x, y;
bool operator<(const P &p) {
if (x != p.x) return x < p.x;
else return y < p.y;
}
};
void subsetGenerate(int n){
for (int b = 0; b < (1<<n); b++) {
vector<int> subset;
for (int i = 0; i < n; i++) {
if (b&(1<<i)) subset.push_back(i);
}
}
}
void permutationGenerate(int n){
vector<int> permutation;
for (int i = 0; i < n; i++) {
permutation.push_back(i);
}
do {
// process permutation
} while (next_permutation(permutation.begin(),permutation.end()));
}
bool customSort(int a, int b) {
return a < b;
}
//#pragma GCC optimize("Ofast")
//#pragma GCC target("avx,avx2,fma")
//#pragma GCC optimization("unroll-loops")
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
//string s
//getline(cin, s);
//printf("%.9f\n", x);
int t;
cin >> t;
while(t--){
int n;
cin >> n;
string s;
cin >> s;
vector<int> odds;
for(int i=0;i<n;i++){
if((s[i] - '0')%2) {
odds.push_back(s[i] - '0');
}
}
if(odds.size() < 2){
cout << -1 << endl;
} else {
cout << odds[0] << odds[1] << endl;
}
}
return 0;
} | cpp |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
while (t--) {
int n; cin >> n;
string s; cin >> s;
int odd = 0;
for (char c : s) if ((c - '0') & 1) odd++;
if (odd <= 1) { cout << "-1\n"; continue; }
int cnt = 0;
for (char c : s) {
if ((c - '0') & 1) { cout << c; cnt++; }
if (cnt == 2) break;
}
cout << '\n';
}
return 0;
} | cpp |
1310 | D | D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
OutputCopy2
InputCopy3 2
0 1 1
2 0 1
2 2 0
OutputCopy3
| [
"dp",
"graphs",
"probabilities"
] | // LUOGU_RID: 99819798
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define inf INT_MAX
#define N 85
#define K 15
ll n,m,k,ans=0,x,y,l,r,s,z;
ll f[K][N];
ll col[N];
ll e[N][N];
ll cnt=0;
template<typename T>inline void read(T &n){
T w=1; n=0; char ch=getchar();
while (!isdigit(ch) && ch!=EOF){ if (ch=='-') w=-1; ch=getchar(); }
while (isdigit(ch) && ch!=EOF){ n=(n<<3)+(n<<1)+(ch&15); ch=getchar(); }
n*=w;
}
template<typename T>inline void write(T x){
if (x==0){ putchar('0'); return ; }
T tmp;
if (x>0) tmp=x;
else tmp=-x;
if (x<0) putchar('-');
char F[105];
long long cnt=0;
while (tmp){
F[++cnt]=tmp%10+48;
tmp/=10;
}
while (cnt) putchar(F[cnt--]);
}
struct Suiji{
#define R ((ll)rand())
Suiji(){
srand((unsigned)time(NULL));
return ;
}
ll rrr(){
return R*R*R*R+R*R*R+R*R+R;
}
ll M(ll l,ll r){
ll ans,mod;
ans=rrr();
mod=r-l+1;
ans=(ans%mod+mod)%mod;
return ans+l;
}
}suiji;
#define M(l,r) (suiji.M(l,r))
int main(){
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
ll i,j,p;
read(n); read(k);
for (i=1; i<=n; i++){
for (j=1; j<=n; j++){
read(e[i][j]);
}
}
cnt=5000;
ans=inf;
while (cnt--){
for (i=1; i<=n; i++) col[i]=M(0,1);
memset(f,0x3f,sizeof(f));
f[0][1]=0;
for (i=1; i<=k; i++){
for (j=1; j<=n; j++){
for (p=1; p<=n; p++){
if (col[j]==col[p]) continue;
f[i][j]=min(f[i][j],f[i-1][p]+e[p][j]);
}
}
}
s=f[k][1];
ans=min(ans,s);
}
write(ans);
return 0;
} | cpp |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | /*
وَاتَّقُوا فِتْنَةً لَّا تُصِيبَنَّ الَّذِينَ ظَلَمُوا مِنكُمْ خَاصَّةً ۖ وَاعْلَمُوا أَنَّ اللَّهَ شَدِيدُ الْعِقَابِ
0xTesla
*/
#include <bits/stdc++.h>
using namespace std ;
#define Tesla ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
#define sp " "
#define el '\n'
#define dpp(arr,val) memset(arr,val,sizeof(arr))
#define ll long long
#define ull unsigned long long
#define dd double
#define ld long double
#define PQ priority_queue
#define pii pair<int,int>
#define pll pair<ll,ll>
#define S second
#define F first
#define MP make_pair
#define PI 3.14159265
using namespace std;
const long long N = 2e5 + 7, Mod = 1e9, INF = 2e18;
# define test int t ; cin >> t ; while(t--)
void solve()
{
int n ;
cin >> n ;
vector<int>v(n) ;
for(int i = 0 ; i < n ; i ++)
{
cin >> v[i] ;
}
list<int>v1(2*n) ;
iota(v1.begin(),v1.end(),1) ;
for(auto i : v)
{
remove(v1.begin(),v1.end(),i) ;
}
v1.resize(n) ;
vector<int>v2;bool flag = 0 ;
// for(auto i : v) cout << i << sp ;
// cout << el ;
// for(auto i : v1) cout << i << sp ;
// cout << el ;
for(auto i : v)
{
auto it = upper_bound(v1.begin(),v1.end(),i) ;
if( it != v1.end())
{
v2.push_back(i) ;
v2.push_back(*it) ;
v1.erase(it) ;
}
else flag = 1 ;
}
if(flag) cout << "-1" ;
else for(auto i : v2) cout << i << sp ;
cout << el ;
}
int main()
{
Tesla
test
solve();
return 0;
}
| cpp |
1284 | G | G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1). For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1) For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
O
OOO
NO
YES
OOOOO X
O O
X O O X
O
OOO X O
O O O
O OOOOO
YES
OOOOOOOOOOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
| [
"graphs"
] | #include <bits/stdc++.h>
using namespace std;
const int N=10005;
const int M=105;
int head[N],nxt[N],edgenum=1,vet[N],num[N],val[N],dir[N],fa[N],flag[N],vis[N],n,m;
char ans[M][M],c[M][M];
const int dx[4]={1,-1,0,0};
const int dy[4]={0,0,1,-1};
void Add(int u,int v,int w) { vet[++edgenum]=v; nxt[edgenum]=head[u]; head[u]=edgenum; val[edgenum]=w; }
int find(int x) { if (x!=fa[x]) fa[x]=find(fa[x]); return fa[x]; }
bool dfs(int x) {
if (vis[x]) return 0;
vis[x]=1;
for (int e=head[x]; e; e=nxt[e]) {
int v=vet[e];
if (!vis[v] && (!num[v] || dfs(num[v]))) {
num[v]=x;
dir[v]=val[e]^1;
return 1;
}
}
return 0;
}
void dfs2(int x,int f) {
for (int e=head[x]; e; e=nxt[e]) {
int v=vet[e]; if (v==f) continue;
if (find(x)!=find(v)) {
fa[find(x)]=find(v);
ans[(x-1)/m*2+1+dx[val[e]]][(x-1)%m*2+1+dy[val[e]]]='O';
if (v!=1) dfs2(num[v],v);
}
}
}
int main() {
// freopen("sample1.in","r",stdin);
// freopen("1.out","w",stdout);
int deb=0;
int T; scanf("%d",&T);
if (deb) cout<<T<<endl;
while (T--) {
memset(fa,0,sizeof(fa)); memset(head,0,sizeof(head));
memset(dir,0,sizeof(dir));
edgenum=1; for (int i=0; i<M; i++) for (int j=0; j<M; j++) ans[i][j]=' ';
scanf("%d%d",&n,&m);
for (int i=1; i<=n*m; i++) num[i]=flag[i]=0,fa[i]=i;
for (int i=1; i<=n; i++) scanf("%s",c[i]+1);
if (deb) {
cout<<n<<' '<<m<<endl;
for (int i=1; i<=n; i++,puts("")) for (int j=1; j<=m; j++) printf("%c",c[i][j]);
}
for (int x=1; x<=n; x++)
for (int y=(x&1)+1; y<=m; y+=2)
if (c[x][y]=='O') {
for (int k=0; k<4; k++) {
int nx=x+dx[k],ny=y+dy[k];
if (nx<1 || ny<1 || nx>n || ny>m || (nx==1 && ny==1) || c[nx][ny]!='O') continue;
Add((x-1)*m+y,(nx-1)*m+ny,k);
}
}
for (int i=1; i<=n; i++)
for (int j=(i&1)+1; j<=m; j+=2)
if (c[i][j]=='O') {
for (int k=1; k<=n*m; k++) vis[k]=0;
flag[(i-1)*m+j]=dfs((i-1)*m+j);
}
for (int i=1; i<=n; i++)
for (int j=-(i&1)+2; j<=m; j+=2)
if (i+j>2 && c[i][j]=='O') {
if (!num[(i-1)*m+j]) { puts("NO"); goto out; }
fa[find((i-1)*m+j)]=find(num[(i-1)*m+j]);
ans[(i<<1)-1+dx[dir[(i-1)*m+j]]][(j<<1)-1+dy[dir[(i-1)*m+j]]]='O';
}
if (c[2][1]=='O') Add(m+1,1,1);
if (c[1][2]=='O') Add(2,1,3);
for (int i=1; i<=n; i++)
for (int j=(i&1)+1; j<=m; j+=2)
if (c[i][j]=='O' && !flag[(i-1)*m+j]) dfs2((i-1)*m+j,-1);
for (int i=1,rt=find(1); i<=n; i++)
for (int j=1; j<=m; j++) {
if (c[i][j]=='O' && find((i-1)*m+j)!=rt) { puts("NO"); goto out; }
ans[(i<<1)-1][(j<<1)-1]=c[i][j];
}
if (deb) { for (int i=1; i<(n<<1); i++) for (int j=1; j<(m<<1); j++) if (ans[i][j]==' ') ans[i][j]='K'; }
puts("YES");
for (int i=1; i<(n<<1); i++,puts(""))
for (int j=1; j<(m<<1); j++) printf("%c",ans[i][j]);
out:;
}
return 0;
}
| cpp |
1290 | E | E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th question.ExamplesInputCopy5
2 4 1 5 3
OutputCopy1
3
6
8
11
InputCopy6
1 2 4 5 6 3
OutputCopy1
3
6
8
12
17
NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11. | [
"data structures"
] | #include <bits/stdc++.h>
#define st first
#define nd second
#define db double
#define re register
#define pb push_back
#define mk make_pair
#define int long long
#define ldb long double
#define pii pair<int, int>
#define ull unsigned long long
#define mst(a, b) memset(a, b, sizeof(a))
using namespace std;
const int N = 2e5 + 10;
inline int read()
{
int s = 0, w = 1;
char ch = getchar();
while(ch < '0' || ch > '9') { if(ch == '-') w *= -1; ch = getchar(); }
while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s * w;
}
int n, a[N], p[N], ans[N];
#define ls k << 1
#define rs k << 1 | 1
#define mid ((l + r) >> 1)
struct SegmentTree{
int c[N << 2], v[N << 2], s[N << 2], tr[N << 2];
int len[N << 2], lens[N << 2], tag[N << 2], tags[N << 2];
inline void pushup(int k){
c[k] = c[ls] + c[rs], len[k] = len[ls] + len[rs], tr[k] = tr[ls] + tr[rs];
if(v[ls] > v[rs]){
v[k] = v[ls], s[k] = max(s[ls], v[rs]);
len[k] = len[ls], lens[k] = lens[ls] + len[rs] + lens[rs];
} else if(v[ls] < v[rs]){
v[k] = v[rs], s[k] = max(v[ls], s[rs]);
len[k] = len[rs], lens[k] = lens[rs] + len[ls] + lens[ls];
} else{
v[k] = v[ls], s[k] = max(s[ls], s[rs]);
len[k] = len[ls] + len[rs], lens[k] = lens[rs] + lens[ls];
}
}
inline void build(int k, int l, int r){
c[k] = v[k] = s[k] = tr[k] = len[k] = lens[k] = tag[k] = tags[k] = 0;
if(l == r) return;
build(ls, l, mid), build(rs, mid + 1, r);
}
inline void Addtag(int k, int x, int y, int op){
if(!op) x = y;
v[k] += x, tag[k] += x, s[k] += y, tags[k] += y, tr[k] += x * len[k] + y * lens[k];
}
inline void pushdown(int k){
if(!tag[k] && !tags[k]) return;
int tem = v[rs] >= v[ls];
Addtag(ls, tag[k], tags[k], v[ls] >= v[rs]), Addtag(rs, tag[k], tags[k], tem);
tag[k] = tags[k] = 0;
}
inline int query(int k, int l, int r, int x, int y){
if(y < l || x > r) return 0;
if(l >= x && r <= y) { Addtag(k, 1, 1, 1); return c[k]; }
pushdown(k);
int res = query(ls, l, mid, x, y) + query(rs, mid + 1, r, x, y);
pushup(k);
return res;
}
inline void modify(int k, int l, int r, int x, int t) {
if(l == r && l == x) { tr[k] = v[k] = t, len[k] = c[k] = 1; return; }
pushdown(k);
if(x <= mid) modify(ls, l, mid, x, t);
else modify(rs, mid + 1, r, x, t);
pushup(k);
}
inline void update(int k, int l, int r, int x, int y, int t) {
if(y < l || x > r || t >= v[k]) return;
if(l >= x && r <= y && t > s[k]) { Addtag(k, min(t - v[k], 0ll), 0, 1); return; }
pushdown(k), update(ls, l, mid, x, y, t), update(rs, mid + 1, r, x, y, t), pushup(k);
// cout << "k: " << tr[k] << "\n";
}
}T;
signed main()
{
n = read();
for(re int i = 1; i <= n; i++) a[i] = read(), p[a[i]] = i;
for(re int t = 1; t <= 2; t++){
// cout << "Begin: " << t << "\n";
T.build(1, 1, n);
for(re int i = 1, x; i <= n; i++){
x = T.query(1, 1, n, p[i] + 1, n), T.modify(1, 1, n, p[i], i + 1);
//cout << "pos: " << x << "\n";
T.update(1, 1, n, 1, p[i] - 1, i - x), ans[i] += T.tr[1];
}
for(re int i = 1; i <= n; i++) p[i] = n - p[i] + 1;
}
// puts("");
for(re int i = 1; i <= n; i++) printf("%lld\n", ans[i] - i * (i + 2));
return 0;
}
| cpp |
1290 | D | D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"constructive algorithms",
"graphs",
"interactive"
] | // LUOGU_RID: 91499649
#include<bits/stdc++.h>
using namespace std;
int const M=1233;char ch;bool a[M];
int i,j,n,k,bound,Ans,l[M],r[M];
void clr(){cout<<"R"<<endl;}
bool ask(int x){
cout<<"? "<<x<<endl;
cin>>ch;return ch=='Y';
}
void solve(int x){
for (int i=l[x];i<=r[x];i++)
if (a[i]&&ask(i)) a[i]=0;
}
int main(){
cin>>n>>k;bound=n/k;for (i=1;i<=n;i++) a[i]=1;
for (i=1;i<=bound;i++) l[i]=r[i-1]+1,r[i]=i*k;
for (i=1;i<=bound;clr(),i++)
for (j=1;j<=bound;j++)
if (j&1) solve((i-j/2+bound-1)%bound+1);
else solve((i+j/2-1)%bound+1);
for (i=1;i<=n;i++) Ans+=a[i];
return cout<<"! "<<Ans<<endl,0;
} | cpp |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define Sz(x) int((x).size())
#define all(x) x.begin(), x.end()
#define fi first
#define se second
#define cl clear
const int maxn = 1e6 + 10;
const int maxa = 2e9 + 5;
const int mod = 1e9 + 7;
const ll inf = 2e18;
const double eps = 1e-9;
int main(){
ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int n, ans = 0;
string s;
cin >> n >> s;
while (true){
int j = -1;
for (int i = 0; i < Sz(s); i ++){
if((i && s[i - 1] == s[i] - 1) || (i != Sz(s) - 1 && s[i + 1] == s[i] - 1)){
if(j == -1) j = i;
else if(s[i] > s[j]) j = i;
}
}
if(j == -1) break;
string t;
for (int i = 0; i < Sz(s); i ++) if(i != j) t += s[i];
s = t;
ans ++;
}
cout << ans << endl;
return 0;
} | cpp |
1311 | E | E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example: | [
"brute force",
"constructive algorithms",
"trees"
] | #pragma GCC optimize("O2")
#pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ll long long
#define test int _TEST; cin>>_TEST; while(_TEST--)
#define ff first
#define ss second
#define pb push_back
#define ppb pop_back
#define pf push_front
#define ppf pop_front
template <typename T> using Ordered_Set_Tree =
tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T> using Ordered_Multiset_Tree =
tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename A, typename B> ostream& operator<<(ostream& s, const pair<A, B>& self) {s << self.first << ' ' << self.second << ' '; return s; }
template <typename T> ostream& operator<<(ostream& s, const vector<T>& self) { for (auto e : self) { s << e << '\n'; } return s; }
template <typename T> ostream& operator<<(ostream& s, tuple<T, T, T>& self) { s << get<0>(self) << ' ' << get<1>(self) << ' ' << get<2>(self); return s; }
template <typename A, typename B> istream& operator>>(istream& s, pair<A, B>& self) { s >> self.first >> self.second; return s; }
template <typename T> istream& operator>>(istream& s, tuple<T, T, T>& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self); return s; }
template <typename T> istream& operator>>(istream& s, tuple<T, T, T, T>& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self) >> get<3>(self); return s; }
template <typename T> istream& operator>>(istream& s, vector<T>& self) { for (size_t i = 0; i < self.size(); ++i) { s >> self[i]; } return s; }
///DEBUG
void _Print(int t) {cerr << t;}
void _Print(string t) {cerr << t;}
void _Print(char t) {cerr << t;}
void _Print(long long t) {cerr << t;}
void _Print(double t) {cerr << t;}
void _Print(unsigned long long t) {cerr << t;}
template <class T, class V> void _Print(pair <T, V> &p);
template <class T> void _Print(list <T> &v);
template <class T> void _Print(vector <T> &v);
template <class T> void _Print(deque <T> &v);
template <class T, class V> void _Print(T *v, V sz);
template <class T, class V, class P> void _Print(T *v, V sz, P sm);
template <class T> void _Print(set <T> &v);
template <class T, class V> void _Print(map <T, V> &v);
template <class T> void _Print(multiset <T> &v);
template <class T, class V> void _Print(pair <T, V> &p) {cerr << "{"; _Print(p.ff); cerr << ","; _Print(p.ss); cerr << "}\n\n";}
template <class T> void _Print(list <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}
template <class T> void _Print(vector <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}
template <class T> void _Print(deque <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}
template <class T, class V> void _Print(T *v, V sz) {cerr << "[ "; for(int i=0; i<sz; i++) {_Print(v[i]); cerr << " ";} cerr << "]\n\n";}
template <class T, class V, class P> void _Print(T *v, V sz, P sm) {cerr << "[\n"; for(int i=0; i<sz; i++) { for(int j=0; j<sm; j++) {_Print(v[i][j]); cerr << " ";} cerr << "\n";} cerr << "]\n\n";}
template <class T> void _Print(set <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}
template <class T> void _Print(multiset <T>& v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}
template <class T, class V> void _Print(map <T, V> &v) {cerr << "[ "; for (auto i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";}
#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)
vector<string> vec_splitter(string s)
{
s += ',';
vector<string> res;
while(!s.empty())
{
res.push_back(s.substr(0, s.find(',')));
s = s.substr(s.find(',') + 1);
}
return res;
}
void debug_out(vector<string> __attribute__ ((unused)) args, __attribute__ ((unused)) int idx, __attribute__ ((unused)) int LINE_NUM) { cerr << endl; }
template <typename Head, typename... Tail> void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T)
{
if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") ";
stringstream ss; ss << H;
cerr << args[idx] << " = " << ss.str();
debug_out(args, idx + 1, LINE_NUM, T...);
}
///DEBUG
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
test
{
int n, d;
cin>>n>>d;
int mmax = (n*(n-1))/2;
int mmin = 0;
int x = n-1, dd=1, mul=2;
while(x > mul)
{
mmin += mul * dd;
dd++;
x -= mul;
mul *= 2;
}
mmin += x * dd;
if(d>mmax || d<mmin)
{
cout<<"NO\n";
continue;
}
ll int val = mmax;
vector<int> par(n);
vector<set<int>> canTake(n);
vector<int> child(n, 0);
for(int i=0; i<n; i++)
{
canTake[i].insert(i);
par[i] = i-1;
child[i] = 1;
}
child[n-1] = 0;
for(int u=n-1; u>0 && val>d; u--)
{
int dig = u-1;
while(dig && val>d && canTake[dig-1].size()>0)
{
val--;
dig--;
}
child[par[u]]--;
par[u] = *canTake[dig].begin();
child[*canTake[dig].begin()]++;
if(child[*canTake[dig].begin()] == 2)
canTake[dig].erase(canTake[dig].begin());
canTake[dig+1].insert(u);
}
cout<<"YES\n";
for(int i=1; i<n; i++)
cout<<par[i]+1<<" ";
cout<<"\n";
}
}
| cpp |
1313 | D | D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third. | [
"bitmasks",
"dp",
"implementation"
] | /* Code by Reflective-FG */
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define forr(i, a, b) for (int i = a; i <= b; i++)
#define rep(i, n) for (int i = 0; i < n; i++)
#define repp(i, n) for (int i = 1; i <= n; i++)
#define pb push_back
#define mp make_pair
#define init(a, i) memset(a, i, sizeof(a))
#define fi first
#define se second
#define MAXN 0x3f3f3f3f
#define ls node * 2 + 1
#define rs node * 2 + 2
int T_ = 1, case_;
const int N = 200005;
int n, m, k, l, r;
vector<pair<int, int>>p;
int dp[N][1 << 8];
vector<int>cur, tmp;
void solve() {
cin >> n >> m >> k;
repp(i, n) {
cin >> l >> r;
p.pb(mp(l, i)), p.pb(mp(r + 1, -i));
}
sort(p.begin(), p.end());
init(dp, 128);
dp[0][0] = dp[0][1] = 0;
cur.pb(p[0].se);
repp(i, 2 * n - 1) {
int x = p[i].fi, f = p[i].se;
int sz = cur.size();
if (f > 0) {
rep(msk, 1 << sz) {
int add = (x - p[i - 1].fi) * (__builtin_popcount(msk) % 2);
dp[i][msk] = max(dp[i][msk], dp[i - 1][msk] + add);
dp[i][msk + (1 << sz)] = max(dp[i][msk + (1 << sz)], dp[i - 1][msk] + add);
}
cur.pb(f);
}
else {
f *= -1;
rep(msk, 1 << sz) {
int add = (x - p[i - 1].fi) * (__builtin_popcount(msk) % 2);
int nxt = 0, cnt = 0;
rep(j, sz) {
if (cur[j] == f)continue;
if (msk & (1 << j))nxt += (1 << cnt);
cnt++;
}
dp[i][nxt] = max(dp[i][nxt], dp[i - 1][msk] + add);
}
tmp.clear();
rep(j, sz) if (cur[j] != f)tmp.pb(cur[j]);
cur = tmp;
}
}
int ans = 0;
rep(i, 256)ans = max(ans, dp[2 * n - 1][i]);
cout << ans;
}
int main() {
// ios::sync_with_stdio(0);
// cin.tie(0), cout.tie(0);
// cin >> T_;
for (case_ = 1; case_ <= T_; case_++)solve();
return 0;
} | cpp |
1301 | B | B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33. | [
"binary search",
"greedy",
"ternary search"
] | #include <bits/stdc++.h>
#define ll long long int
#define fr(i, x, n) for (int i = x; i < n; i++)
#define fra(x, v) for (auto x : v)
using namespace std;
ll power(int a, int b)
{
if (b == 0)
return 1;
ll temp = power(a, b / 2);
if (b % 2 == 0)
return temp * temp;
else
return temp * temp * a;
}
ll fact(ll a){
ll ans = 1;
while (a > 0)
{
ans *= a;
a--;
}
return ans;
}
ll ones(ll a){
ll ans = 0;
while (a > 0)
{
ans += a%2;
a /= 2;
}
return ans;
}
ll gcd(ll a, ll b)
{
return b == 0 ? a : gcd(b, a % b);
}
int dig(ll a)
{
int ans = 0;
while (a > 0)
{
a /= 10;
ans++;
}
return ans;
}
ll sumdig(ll a)
{
ll sum = 0;
while (a > 0)
{
sum += a % 10;
a /= 10;
}
return sum;
}
ll const N = 1000;
ll a[N][N], b[N][N];
// ll ans[10][10];
// void mulM(ll a[10][10] , ll b[10][10] , ll n){
// fr(i , 0 , n){
// fr(j , 0 , n){
// fr(k , 0 , n){
// ans[i][j] += a[i][k]*b[k][j];
// }
// }
// }
// }
// const double pi = 3.1415926536;
// const int maxo = 2e5 + 5;
// bool check[maxo];
//map<char, ll> mp2;
map<char, ll> mp3;
bool isValid(ll xx, ll yy, ll n, ll m)
{
return (xx > 0 && xx <= n && yy > 0 && yy <= m);
}
bool sortbyCond(const pair<double, int> &a,
const pair<double, int> &b)
{
if (a.second != b.second)
return (a.second < b.second);
else
return (a.first < b.first);
}
// const int N = 1000006;
vector<vector<ll>> v(N);
bool vist[N];
// void dfs(ll x)
// {
// for(int i =0 ; i< v[x].size() ; i++ ){
// }
// }
void debug(){
cout << "test" << endl;
return ;
}
ll facto[15];
vector<pair<ll,ll>> comb;
void solve(ll ind , ll s , ll x){
if(ind == 15)return;
s += facto[ind];
x++;
comb.push_back({s , x});
solve(ind + 1 , 0 , 0);
solve(ind + 1 , s , x);
return;
}
map<ll, ll> mpf;
map<ll , ll> mpe;
int main()
{
ios_base::sync_with_stdio(0);
ll tt;cin >> tt;
while(tt--){
ll n ;cin >> n;
ll a[n + 5];
ll mino = 1e9 + 103 , maxo = 0;
bool g = 0;
fr(i , 0 , n ){
cin >> a[i];
if(a[i] == -1){
g = 1;
if(i > 0 && a[i - 1] > -1){
mino = min(a[i - 1] , mino);
maxo = max(a[i - 1] , maxo);
}
}else {
if(g){
mino = min(a[i] , mino);
maxo = max(a[i] , maxo);
}
g = 0;
}
}
// cout << mino << " " << maxo << endl;
ll ans = (maxo + mino)/2;
ll m = 0;
fr(i , 0 ,n - 1){
if(a[i] == -1)a[i] = ans;
if(a[i + 1] == -1)a[i + 1] = ans;
m = max(m , abs(a[i] - a[i + 1]));
}
cout << m << " " << ans << endl;
}
return 0;
} | cpp |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | #include<iostream>
#include<iterator>
#include<ranges>
void solve_test_case();
int main()
{
unsigned t{ 1 };
do
solve_test_case();
while (--t);
}
void solve_test_case()
{
unsigned number_of_hours;
std::cin >> number_of_hours;
unsigned ones_at_beginning{};
for (unsigned type;
std::cin >> type,
type;
++ones_at_beginning);
unsigned
length_of_ones_segment{},
answer{};
for (number_of_hours -= ones_at_beginning;
--number_of_hours;) {
unsigned type;
std::cin >> type;
if (type)
++length_of_ones_segment;
else {
answer += (length_of_ones_segment > answer) * (length_of_ones_segment - answer);
length_of_ones_segment = 0;
}
}
length_of_ones_segment += ones_at_beginning;
std::cout
<< (answer += (length_of_ones_segment > answer) * (length_of_ones_segment - answer))
<< std::endl;
} | cpp |
1301 | F | F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105) — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m) — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2); mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4); mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4); mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4). | [
"dfs and similar",
"graphs",
"implementation",
"shortest paths"
] | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define debug(x) cerr << #x << " " << x << "\n"
#define debugs(x) cerr << #x << " " << x << " "
using namespace std;
typedef long long ll;
typedef pair <short, short> pii;
const ll NMAX = 1002;
const ll VMAX = 41;
const ll INF = (1LL << 59);
const ll MOD = 1000000009;
const ll BLOCK = 318;
const ll base = 31;
const ll nrbits = 21;
short dist[NMAX][NMAX][41];
short mat[NMAX][NMAX];
vector <pii> v[41];
struct ura {
short pf, ps;
int cost;
};
vector <ura> muchii;
bool viz[41];
short dx[] = {0, 1, -1, 0};
short dy[] = {1, 0, 0, -1};
short n, m;
bool OK(short i, short j) {
if(i > 0 && i <= n && j > 0 && j <= m)
return 1;
return 0;
}
int main() {
#ifdef HOME
ifstream cin(".in");
ofstream cout(".out");
#endif // HOME
short k, i, j;
cin >> n >> m >> k;
for(i = 1; i <= n; i++) {
for(j = 1; j <= m; j++) {
cin >> mat[i][j];
v[mat[i][j]].push_back({i, j});
}
}
for(int col = 1; col <= k; col++) {
for(i = 1; i <= n + 1; i++) {
for(j = 1; j <= max(m, k); j++) {
dist[i][j][col] = 32767;
}
}
for(i = 1; i <= k; i++) viz[i] = 0; /// BRUH Cum sa uit...
queue <pii> q;
for(auto x : v[col]) {
dist[x.first][x.second][col] = 0;
q.push({x.first, x.second});
}
while(q.size()) {
pii x = q.front();
q.pop();
for(int d = 0; d < 4; d++) {
pii care = {x.first + dx[d], x.second + dy[d]};
if(!OK(care.first, care.second)) continue;
if(dist[care.first][care.second][col] == 32767) { /// Hmm...
dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1;
q.push({care.first, care.second});
}
}
if(!viz[mat[x.first][x.second]]) {
viz[mat[x.first][x.second]] = 1;
for(auto y : v[mat[x.first][x.second]]) {
pii care = y;
if(dist[care.first][care.second][col] == 32767) { /// Hmm...
dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1;
q.push({care.first, care.second});
}
}
}
}
}
int q;
cin >> q;
while(q--) {
int a, b, c, d;
cin >> a >> b >> c >> d;
int minim = abs(c - a) + abs(d - b);
for(int col = 1; col <= k; col++) {
minim = min(minim, (int)dist[a][b][col] + (int)dist[c][d][col] + 1);
}
cout << minim << "\n";
}
return 0;
} | cpp |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | /// endless ?
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
#define ll long long
#define F first
#define S second
#define pii pair<int, int>
#define all(x) x.begin(), x.end()
#define vi vector<int>
#define vii vector<pii>
#define pb push_back
#define pf push_front
#define wall cout <<'\n'<< "-------------------------------------" <<'\n';
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define int ll
const ll MAXN = 3e5 + 43;
const ll MOD = 1e9 + 7; ///998244353;
const ll INF = 1e18 + 19763;
const ll LG = 19;
ll pw(ll a, ll b){return b == 0 ? 1LL : (pw(a * a%MOD , b / 2)%MOD * (b % 2 == 0 ? 1LL : a))%MOD;}
int a[MAXN][10], n, m, bt[MAXN], mrk[MAXN];
pii ans = {-1, -1};
bool check(int x)
{
ans = {-1, -1};
fill(mrk, mrk + 600, 0);
for (int i = 0; i < n; i++)
{
int num = 0;
for (int j = 0; j < m; j++)
{
if (a[i][j] >= x)
num += (1 << j);
}
//cout << num << '\n';
mrk[num] = i + 1;
}
for (int i = 0; i < 300; i++)
{
///cout << i << ' ' << mrk[i] << '\n';
for (int j = 0; j < 300; j++)
{
int ord = i|j;
if (ord == ((1 << m) - 1) && mrk[i] != 0 && mrk[j] != 0){ans = {mrk[i], mrk[j]}; return 1;}
}
}
return 0;
}
void solve()
{
fast
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int l = 0, r = 1e9 + 3;
while (r - l > 1)
{
int mid = (l + r)/2;
///cout << mid << ' ' << check(mid) << ' ' << ans.F << ' ' << ans.S << '\n';
if (check(mid))l = mid;
else r = mid;
}
bool bl = check(l);
int mid = 2;
//cout << mid << ' ' << check(mid) << ' ' << ans.F << ' ' << ans.S << '\n';
cout << ans.F << ' ' << ans.S << '\n';
}
int32_t main ()
{
fast
int t = 1;// cin >> t;
while (t --)
{
solve();
}
}
/// Thanks GOD :)
| cpp |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T>
using o_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T>
using o_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
// member functions :
// 1. order_of_key(k) : number of elements strictly lesser than k
// 2. find_by_order(k) : k-th element in the set
template <class key, class value, class cmp = std::less<key>>
using o_map = __gnu_pbds::tree<key, value, cmp, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>;
using i64 = long long;
const i64 Mod = 1000000007;
const i64 MOD = 998244353;
const i64 Inf = 1E18;
const int dx[] = {0, 0, 1, -1, -1, -1, 1, 1};
const int dy[] = {1, -1, 0, 0, -1, 1, -1, 1};
//FOR unordered_map<int,int,custom_hash> TO AVOID FALTU TLE'S COZ OF ANTIHASHES.
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
template <typename T>
T roundup(T a, T b) {
return(a / b + ((a ^ b) > 0 && a % b));
}
template <typename T>
T choose(T n, T r) {
if(n < r) return 0LL;
T res = 1;
for(T e = 0 ; e < r ; e ++) {
res = res * (n - e);
res = res / (e + 1);
}
return res;
}
template <typename T>
bool expotwo(T n) {
T val = (n & (n - 1));
if(val == 0LL) return true;
return false;
}
template <typename T>
T modexpo(T b, T e, T mod) {
T ans = 1;
while(e) {
if(e & 1) ans = ((ans % mod) * (b % mod)) % mod;
b = ((b % mod) * (b % mod)) % mod;
e >>= 1;
}
return ans;
}
template <typename T>
T expo(T b, T e) {
T ans = 1;
while(e) {
if(e & 1) ans = ans * b;
b = b * b;
e >>= 1;
}
return ans;
}
template <typename T>
bool eprime(T n) {
if(n < 2) return false;
for(T e = 2; e * e <= n; e ++) {
if(n % e == 0) return false;
}
return true;
}
template <typename T>
bool eparity(T x, T y) {
return !((x & 1) ^ (y & 1));
};
template <typename T>
void amax(T& a, T b) {
a = max(a, b);
}
template <typename T>
void amin(T& a, T b) {
a = min(a, b);
}
template <typename T>
void add(T& a, T b, T M) {
a = ((a % M) + (b % M)) % M;
}
template <typename T>
void mul(T& a, T b, T M) {
a = ((a % M) * (b % M)) % M;
}
template <typename T>
void sub(T& a, T b, T M) {
a = (a - b + M) % M;
}
/* ------------------------------------------ lessgo -------------------------------------------------*/
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
vector <vector<int>> divisor(30000);
void compute() {
for(int i = 1; i < 30000; i ++) {
for(i64 j = 1; j * j <= i; j ++) {
if(i % j == 0) {
int cur = j;
divisor[i].push_back(cur);
if(j * j != i) divisor[i].push_back(i / cur);
}
}
}
}
void Solution()
{
int a, b, c; cin >> a >> b >> c;
vector <pair<int, int>> operations(30000,{INT_MAX, INT_MAX});
int ans = INT_MAX;
array <int, 3> res = {0, 0, 0};
for(int i = 1; i < 30000; i ++) {
operations[i].first = abs(b - i);
int add = abs(i - a), prev = i;
for(auto &x : divisor[i]) {
if(add > abs(x - a)) {
add = abs(x - a);
prev = x;
}
}
operations[i].first += add;
operations[i].second = prev;
}
for(int i = 1; i < 30000; i ++) {
for(auto &x : divisor[i]) {
// cout << i << ' ' << x << ' ' << operations[x].first << '\n';
if(operations[x].first < INT_MAX) {
int k = abs(i - c) + operations[x].first;
if(k < ans) {
ans = k;
res = {operations[x].second, x, i};
}
}
}
}
cout << ans << '\n';
cout << res[0] << ' ' << res[1] << ' ' << res[2] << '\n';
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int Test_case = 1; cin >> Test_case;
compute();
while(Test_case --) Solution();
}
| cpp |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair<ll, ll> ii;
#define eps 1e-9
#define MOD 1000000007
#define pi 3.141592653589793
#define fast ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define yo cout << "I reached here" << endl;
const int INF = 1e9 + 5;
int main()
{
int n;
cin >> n;
vector<ll> A(n);
for(int i = 0; i < n; i++) cin >> A[i];
vector<vector<ll>> dp(n+1, vector<ll>(n+1, -1));
for(int len = 1; len <= n; len++){
for(int i = 0; i < n; i++){
int j = i + len - 1;
if(j >= n) continue;
if(i == j){
dp[i][j] = A[i];
// cout << "i = " << i << " j = " << j << " value = " << dp[i][j] << " " << endl;
continue;
}
int cnt = 0;
bool possible = false;
int answer = -1;
for(int k = i; k < j; k++){
if(dp[i][k] == dp[k+1][j] && dp[i][k] != -1){
possible = true;
answer = dp[i][k];
}
}
if(possible) dp[i][j] = answer + 1;
}
}
// for(int len = 1; len <= n; len++){
// for(int i = 0; i < n; i++){
// cout << "len = " << len << endl;
// int j = i + len - 1;
// if(j >= n) continue;
// cout << "i = " << i << " j = " << j << " value = " << dp[i][j] << " " << endl;
// }
// }
// for(int i = 0; i < n; i++){
// for(int j = i; j < n; j++){
// cout << "i = " << i << " j = " << j << " value = " << dp[i][j] << " " << endl;
// }
// cout << endl;
// }
vector<ll> sp(n + 1, INF);
sp[0] = 0;
for(int i = -1; i < n; i++){
for(int j = i + 1; j < n; j++){
// cout << "i = " << i << " j = " << j << endl;
if(dp[i+1][j] > 0){
// cout << "----------------i = " << i << " j = " << j << endl;
sp[j + 1] = min(sp[j + 1], sp[i + 1] + 1);
}
}
}
// for(int i = 0; i <= n; i++){
// cout << sp[i] << " ";
// }
// cout << endl;
cout << sp[n] << endl;
return 0;
}
| cpp |
1316 | F | F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212. | [
"data structures",
"divide and conquer",
"probabilities"
] | #line 1 "/home/maspy/compro/library/my_template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) \
vector<vector<vector<type>>> name( \
h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name( \
a, vector<vector<vector<type>>>( \
b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
#define FOR_(n) for (ll _ = 0; (_) < (ll)(n); ++(_))
#define FOR(i, n) for (ll i = 0; (i) < (ll)(n); ++(i))
#define FOR3(i, m, n) for (ll i = (m); (i) < (ll)(n); ++(i))
#define FOR_R(i, n) for (ll i = (ll)(n)-1; (i) >= 0; --(i))
#define FOR3_R(i, m, n) for (ll i = (ll)(n)-1; (i) >= (ll)(m); --(i))
#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define stoi stoll
template <typename T>
T SUM(vector<T> &A) {
T sum = T(0);
for (auto &&a: A) sum += a;
return sum;
}
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int lowbit(u32 x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int lowbit(ll x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
int lowbit(u64 x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
template <typename T, typename U>
T ceil(T x, U y) {
return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U>
T floor(T x, U y) {
return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
T q = floor(x, y);
return {q, x - q * y};
}
ll binary_search(function<bool(ll)> check, ll ok, ll ng) {
assert(check(ok));
while (abs(ok - ng) > 1) {
auto x = (ng + ok) / 2;
if (check(x))
ok = x;
else
ng = x;
}
return ok;
}
template <class T, class S>
inline bool chmax(T &a, const S &b) {
return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
return (a > b ? a = b, 1 : 0);
}
vi s_to_vi(string S, char first_char = 'a') {
vi A(S.size());
FOR(i, S.size()) { A[i] = S[i] - first_char; }
return A;
}
template <typename T>
vector<T> cumsum(vector<T> &A, int off = 1) {
int N = A.size();
vector<T> B(N + 1);
FOR(i, N) { B[i + 1] = B[i] + A[i]; }
if (off == 0) B.erase(B.begin());
return B;
}
template <typename T, typename CNT = int>
vc<CNT> bincount(vc<T> &A, int size) {
vc<CNT> C(size);
for (auto &&x: A) { ++C[x]; }
return C;
}
template <typename T>
vector<int> argsort(vector<T> &A) {
// stable
vector<int> ids(A.size());
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
return ids;
}
#line 1 "/home/maspy/compro/library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace detail {
template <typename T, decltype(&T::is_modint) = &T::is_modint>
std::true_type check_value(int);
template <typename T>
std::false_type check_value(long);
} // namespace detail
template <typename T>
struct is_modint : decltype(detail::check_value<T>(0)) {};
template <typename T>
using is_modint_t = enable_if_t<is_modint<T>::value>;
template <typename T>
using is_not_modint_t = enable_if_t<!is_modint<T>::value>;
struct Scanner {
FILE* fp;
char line[(1 << 15) + 1];
size_t st = 0, ed = 0;
void reread() {
memmove(line, line + st, ed - st);
ed -= st;
st = 0;
ed += fread(line + ed, 1, (1 << 15) - ed, fp);
line[ed] = '\0';
}
bool succ() {
while (true) {
if (st == ed) {
reread();
if (st == ed) return false;
}
while (st != ed && isspace(line[st])) st++;
if (st != ed) break;
}
if (ed - st <= 50) {
bool sep = false;
for (size_t i = st; i < ed; i++) {
if (isspace(line[i])) {
sep = true;
break;
}
}
if (!sep) reread();
}
return true;
}
template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
while (true) {
size_t sz = 0;
while (st + sz < ed && !isspace(line[st + sz])) sz++;
ref.append(line + st, sz);
st += sz;
if (!sz || st != ed) break;
reread();
}
return true;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
bool neg = false;
if (line[st] == '-') {
neg = true;
st++;
}
ref = T(0);
while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
if (neg) ref = -ref;
return true;
}
template <class T, is_modint_t<T> * = nullptr>
bool read_single(T &ref) {
long long val = 0;
bool f = read_single(val);
ref = T(val);
return f;
}
bool read_single(double &ref) {
string s;
if (!read_single(s)) return false;
ref = std::stod(s);
return true;
}
template <class T>
bool read_single(vector<T> &ref) {
for (auto &d: ref) {
if (!read_single(d)) return false;
}
return true;
}
template <class T, class U>
bool read_single(pair<T, U> &p) {
return (read_single(p.first) && read_single(p.second));
}
template <class A, class B, class C>
bool read_single(tuple<A, B, C> &p) {
return (read_single(get<0>(p)) && read_single(get<1>(p))
&& read_single(get<2>(p)));
}
template <class A, class B, class C, class D>
bool read_single(tuple<A, B, C, D> &p) {
return (read_single(get<0>(p)) && read_single(get<1>(p))
&& read_single(get<2>(p)) && read_single(get<3>(p)));
}
void read() {}
template <class H, class... T>
void read(H &h, T &... t) {
bool f = read_single(h);
assert(f);
read(t...);
}
Scanner(FILE *fp) : fp(fp) {}
};
struct Printer {
Printer(FILE *_fp) : fp(_fp) {}
~Printer() { flush(); }
static constexpr size_t SIZE = 1 << 15;
FILE *fp;
char line[SIZE], small[50];
size_t pos = 0;
void flush() {
fwrite(line, 1, pos, fp);
pos = 0;
}
void write(const char &val) {
if (pos == SIZE) flush();
line[pos++] = val;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
void write(T val) {
if (pos > (1 << 15) - 50) flush();
if (val == 0) {
write('0');
return;
}
if (val < 0) {
write('-');
val = -val; // todo min
}
size_t len = 0;
while (val) {
small[len++] = char(0x30 | (val % 10));
val /= 10;
}
for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
pos += len;
}
void write(const string &s) {
for (char c: s) write(c);
}
void write(const char *s) {
size_t len = strlen(s);
for (size_t i = 0; i < len; i++) write(s[i]);
}
void write(const double &x) {
ostringstream oss;
oss << setprecision(12) << x;
string s = oss.str();
write(s);
}
template <class T, is_modint_t<T> * = nullptr>
void write(T &ref) {
write(ref.val);
}
template <class T>
void write(const vector<T> &val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
template <class T, class U>
void write(const pair<T, U> &val) {
write(val.first);
write(' ');
write(val.second);
}
};
Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);
void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
printer.write(head);
if (sizeof...(Tail)) printer.write(' ');
print(forward<Tail>(tail)...);
}
void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
scanner.read(head);
read(tail...);
}
#define INT(...) \
int __VA_ARGS__; \
read(__VA_ARGS__)
#define LL(...) \
ll __VA_ARGS__; \
read(__VA_ARGS__)
#define STR(...) \
string __VA_ARGS__; \
read(__VA_ARGS__)
#define DBL(...) \
double __VA_ARGS__; \
read(__VA_ARGS__)
#define VEC(type, name, size) \
vector<type> name(size); \
read(name)
#define VV(type, name, h, w) \
vector<vector<type>> name(h, vector<type>(w)); \
read(name)
void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 2 "/home/maspy/compro/library/mod/modint.hpp"
template <int mod>
struct modint {
static constexpr bool is_modint = true;
int val;
constexpr modint(const ll val = 0) noexcept
: val(val >= 0 ? val % mod : (mod - (-val) % mod) % mod) {}
bool operator<(const modint &other) const {
return val < other.val;
} // To use std::map
modint &operator+=(const modint &p) {
if ((val += p.val) >= mod) val -= mod;
return *this;
}
modint &operator-=(const modint &p) {
if ((val += mod - p.val) >= mod) val -= mod;
return *this;
}
modint &operator*=(const modint &p) {
val = (int)(1LL * val * p.val % mod);
return *this;
}
modint &operator/=(const modint &p) {
*this *= p.inverse();
return *this;
}
modint operator-() const { return modint(-val); }
modint operator+(const modint &p) const { return modint(*this) += p; }
modint operator-(const modint &p) const { return modint(*this) -= p; }
modint operator*(const modint &p) const { return modint(*this) *= p; }
modint operator/(const modint &p) const { return modint(*this) /= p; }
bool operator==(const modint &p) const { return val == p.val; }
bool operator!=(const modint &p) const { return val != p.val; }
modint inverse() const {
int a = val, b = mod, u = 1, v = 0, t;
while (b > 0) {
t = a / b;
swap(a -= t * b, b), swap(u -= t * v, v);
}
return modint(u);
}
modint pow(int64_t n) const {
modint ret(1), mul(val);
while (n > 0) {
if (n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
static constexpr int get_mod() { return mod; }
};
struct ArbitraryModInt {
static constexpr bool is_modint = true;
int val;
ArbitraryModInt() : val(0) {}
ArbitraryModInt(int64_t y)
: val(y >= 0 ? y % get_mod()
: (get_mod() - (-y) % get_mod()) % get_mod()) {}
bool operator<(const ArbitraryModInt &other) const {
return val < other.val;
} // To use std::map<ArbitraryModInt, T>
static int &get_mod() {
static int mod = 0;
return mod;
}
static void set_mod(int md) { get_mod() = md; }
ArbitraryModInt &operator+=(const ArbitraryModInt &p) {
if ((val += p.val) >= get_mod()) val -= get_mod();
return *this;
}
ArbitraryModInt &operator-=(const ArbitraryModInt &p) {
if ((val += get_mod() - p.val) >= get_mod()) val -= get_mod();
return *this;
}
ArbitraryModInt &operator*=(const ArbitraryModInt &p) {
unsigned long long a = (unsigned long long)val * p.val;
unsigned xh = (unsigned)(a >> 32), xl = (unsigned)a, d, m;
asm("divl %4; \n\t" : "=a"(d), "=d"(m) : "d"(xh), "a"(xl), "r"(get_mod()));
val = m;
return *this;
}
ArbitraryModInt &operator/=(const ArbitraryModInt &p) {
*this *= p.inverse();
return *this;
}
ArbitraryModInt operator-() const { return ArbitraryModInt(-val); }
ArbitraryModInt operator+(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) += p;
}
ArbitraryModInt operator-(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) -= p;
}
ArbitraryModInt operator*(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) *= p;
}
ArbitraryModInt operator/(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) /= p;
}
bool operator==(const ArbitraryModInt &p) const { return val == p.val; }
bool operator!=(const ArbitraryModInt &p) const { return val != p.val; }
ArbitraryModInt inverse() const {
int a = val, b = get_mod(), u = 1, v = 0, t;
while (b > 0) {
t = a / b;
swap(a -= t * b, b), swap(u -= t * v, v);
}
return ArbitraryModInt(u);
}
ArbitraryModInt pow(int64_t n) const {
ArbitraryModInt ret(1), mul(val);
while (n > 0) {
if (n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
};
template<typename mint>
tuple<mint, mint, mint> get_factorial_data(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
static vector<mint> fact = {1, 1};
static vector<mint> fact_inv = {1, 1};
static vector<mint> inv = {0, 1};
while(len(fact) <= n){
int k = len(fact);
fact.eb(fact[k - 1] * mint(k));
auto q = ceil(mod, k);
int r = k * q - mod;
inv.eb(inv[r] * mint(q));
fact_inv.eb(fact_inv[k - 1] * inv[k]);
}
return {fact[n], fact_inv[n], inv[n]};
}
template<typename mint>
mint fact(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n);
if(n >= mod) return 0;
return get<0>(get_factorial_data<mint>(n));
}
template<typename mint>
mint fact_inv(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
return get<1>(get_factorial_data<mint>(n));
}
template<typename mint>
mint inv(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
return get<2>(get_factorial_data<mint>(n));
}
template<typename mint>
mint C(ll n, ll k, bool large = false) {
assert(n >= 0);
if (k < 0 || n < k) return 0;
if (!large) return fact<mint>(n) * fact_inv<mint>(k) * fact_inv<mint>(n - k);
k = min(k, n - k);
mint x(1);
FOR(i, k) {
x *= mint(n - i);
}
x *= fact_inv<mint>(k);
return x;
}
using modint107 = modint<1000000007>;
using modint998 = modint<998244353>;
using amint = ArbitraryModInt;
#line 2 "/home/maspy/compro/library/ds/segtree.hpp"
template <class Monoid>
struct SegTree {
using X = typename Monoid::value_type;
using value_type = X;
vc<X> dat;
int n, log, size;
SegTree() : SegTree(0) {}
SegTree(int n) : SegTree(vc<X>(n, Monoid::unit)) {}
SegTree(vc<X> v) : n(len(v)) {
log = 1;
while ((1 << log) < n) ++log;
size = 1 << log;
dat.assign(size << 1, Monoid::unit);
FOR(i, n) dat[size + i] = v[i];
FOR3_R(i, 1, size) update(i);
}
X operator[](int i) { return dat[size + i]; }
void update(int i) { dat[i] = Monoid::op(dat[2 * i], dat[2 * i + 1]); }
void set(int i, X x) {
assert(i < n);
dat[i += size] = x;
while (i >>= 1) update(i);
}
X prod(int L, int R) {
assert(L <= R);
assert(R <= n);
X vl = Monoid::unit, vr = Monoid::unit;
L += size, R += size;
while (L < R) {
if (L & 1) vl = Monoid::op(vl, dat[L++]);
if (R & 1) vr = Monoid::op(dat[--R], vr);
L >>= 1, R >>= 1;
}
return Monoid::op(vl, vr);
}
X prod_all() { return dat[1];}
template <class F>
int max_right(F &check, int L) {
assert(0 <= L && L <= n && check(Monoid::unit));
if (L == n) return n;
L += size;
X sm = Monoid::unit;
do {
while (L % 2 == 0) L >>= 1;
if (!check(Monoid::op(sm, dat[L]))) {
while (L < size) {
L = 2 * L;
if (check(Monoid::op(sm, dat[L]))) {
sm = Monoid::op(sm, dat[L]);
L++;
}
}
return L - size;
}
sm = Monoid::op(sm, dat[L]);
L++;
} while ((L & -L) != L);
return n;
}
template <class F>
int min_left(F &check, int R) {
assert(0 <= R && R <= n && check(Monoid::unit));
if (R == 0) return 0;
R += size;
X sm = Monoid::unit;
do {
--R;
while (R > 1 && (R % 2)) R >>= 1;
if (!check(Monoid::op(dat[R], sm))) {
while (R < size) {
R = 2 * R + 1;
if (check(Monoid::op(dat[R], sm))) {
sm = Monoid::op(dat[R], sm);
R--;
}
}
return R + 1 - size;
}
sm = Monoid::op(dat[R], sm);
} while ((R & -R) != R);
return 0;
}
void debug() { print("segtree", dat); }
};
#line 2 "/home/maspy/compro/library/nt/primetable.hpp"
vc<ll>& primetable(int LIM) {
++LIM;
const int S = 32768;
static int done = 2;
static vc<ll> primes = {2}, sieve(S + 1);
if(done >= LIM) return primes;
done = LIM;
primes = {2}, sieve.assign(S + 1, 0);
const int R = LIM / 2;
primes.reserve(int(LIM / log(LIM) * 1.1));
vc<pi> cp;
for (int i = 3; i <= S; i += 2) {
if (!sieve[i]) {
cp.eb(i, i * i / 2);
for (int j = i * i; j <= S; j += 2 * i) sieve[j] = 1;
}
}
for (int L = 1; L <= R; L += S) {
array<bool, S> block{};
for (auto& [p, idx]: cp)
for (int i = idx; i < S + L; idx = (i += p)) block[i - L] = 1;
FOR(i, min(S, R - L)) if (!block[i]) primes.eb((L + i) * 2 + 1);
}
return primes;
}
#line 3 "/home/maspy/compro/library/mod/powertable.hpp"
template<typename mint>
vc<mint> powertable_1(mint a, ll N) {
// table of a^i
vc<mint> f(N, 1);
FOR(i, N - 1) f[i + 1] = a * f[i];
return f;
}
template<typename mint>
vc<mint> powertable_2(ll e, ll N) {
// table of i^e. N 以下の素数テーブルを利用する.
auto& primes = primetable(N);
vc<mint> f(N, 1);
f[0] = mint(0).pow(e);
for(auto&& p : primes){
if(p > N) break;
mint xp = mint(p).pow(e);
ll pp = p;
while(pp < N){
ll i = pp;
while(i < N){
f[i] *= xp;
i += pp;
}
pp *= p;
}
}
return f;
}
#line 6 "main.cpp"
using mint = modint107;
struct T {
mint cnt, ans, min_sum, max_sum;
};
struct Mono {
using value_type = T;
using X = value_type;
static X op(X x, X y) {
if (x.cnt == mint(0)) return y;
if (y.cnt == mint(0)) return x;
T z;
z.cnt = x.cnt * y.cnt;
z.ans = x.ans * y.cnt + y.ans * x.cnt + x.max_sum * y.min_sum;
z.max_sum = y.max_sum * x.cnt + x.max_sum;
z.min_sum = x.min_sum * y.cnt + y.min_sum;
return z;
}
static constexpr X unit = X{0, 0, 0, 0};
static constexpr bool commute = false;
};
void solve() {
LL(N);
VEC(ll, A, N);
LL(Q);
VEC(pi, query, Q);
vc<pi> X;
FOR(i, N) X.eb(A[i], i);
FOR(i, Q) X.eb(query[i].se, i + N);
UNIQUE(X);
vi last_time(N, -1);
iota(all(last_time), 0);
vc<T> seg_raw(N + Q, Mono::unit);
FOR(i, N) {
auto idx = LB(X, mp(A[i], i));
seg_raw[idx] = {2, 0, A[i], A[i]};
}
SegTree<Mono> seg(seg_raw);
mint coef = mint(2).pow(N).inverse();
auto upd = [&](ll time, ll i, ll x) -> void {
if (last_time[i] != -1) {
ll idx = LB(X, mp(A[i], last_time[i]));
seg.set(idx, {0, 0, 0, 0});
}
A[i] = x;
last_time[i] = time;
ll idx = LB(X, mp(x, time));
seg.set(idx, {2, 0, x, x});
};
auto out = [&]() -> void {
auto e = seg.prod_all();
// print(e.cnt, e.ans, e.max_sum, e.min_sum);
print(e.ans * coef);
};
// FOR(i, N) upd(i, i, A[i]);
out();
FOR(q, Q) {
auto [i, x] = query[q];
--i;
upd(N + q, i, x);
out();
}
}
signed main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << setprecision(15);
ll T = 1;
// LL(T);
FOR(_, T) solve();
return 0;
}
| cpp |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | #include<bits/stdc++.h>
#define FAST ios_base::sync_with_stdio(false),cin.tie(NULL);
using namespace std;
void ONLINE();
void clion();
bool cmp (pair<int,int> &a , pair<int,int> &b)
{
return a.first < b.first;
}
#define FIXED 100001
int main(){
//ONLINE();
//clion();
FAST;
//vector<pair<int,int>>v{{0,6},{1,2},{2,5},{3,5},{4,4},{5,5},{6,6},{7,3},{8,7},{9,6}};
//sort(v.begin(),v.end(),cmp);
int t;cin >> t;
while(t--)
{
int n;cin >> n;
if(n == 2)
{
cout << 1 << "\n";
}else if(n == 3)
{
cout << "7\n";
}else
{
if(n % 2 == 1)
{
cout << "7";
n -= 3;
}
for(int i = 1; i <= n ;i+=2)
{
cout << 1;
}
cout << "\n";
}
}
return 0;
}
void clion() {
freopen("Input.txt", "r", stdin);
freopen("Output.txt", "w", stdout);
}
void ONLINE(string name = "cowsignal") {
if ((name.size())) {
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
} | cpp |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n) — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111. | [
"dfs and similar",
"dsu",
"graphs"
] | #pragma GCC target ("avx2")
#pragma GCC optimize ("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize ("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
#define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define endl '\n'
typedef long long ll;
#define mod1 (ll)1000000007
#define mod2 (ll)998244353
#define pll pair<ll,ll>
typedef long double lb;
typedef tree<
pair<ll, ll>,
null_type,
less<pair<ll, ll>>,
rb_tree_tag,
tree_order_statistics_node_update> ordered_set;
#define eps (lb)(1e-9)
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
// Operator overloads
template<typename T1, typename T2> // cin >> pair<T1, T2>
istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.first >> p.second); }
template<typename T> // cin >> vector<T>
istream& operator>>(istream &istream, vector<T> &v)
{
for (auto &it : v)
cin >> it;
return istream;
}
template<typename T1, typename T2> // cout << pair<T1, T2>
ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.first << " " << p.second); }
template<typename T> // cout << vector<T>
ostream& operator<<(ostream &ostream, const vector<T> &c) { for (auto &it : c) cout << it << " "; return ostream; }
// Utility functions
template <typename T>
void print(T &&t) { cout << t << "\n"; }
template <typename T, typename... Args>
void print(T &&t, Args &&... args)
{
cout << t << " ";
print(forward<Args>(args)...);
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll random(ll p){ // gives random number in [0,p]
return uniform_int_distribution<ll>(0, p)(rng);
}
ll inf=1<<20;
ll n,k;
vector<ll>v;
vector<ll>con[1<<19]; // con[i]-> nodes that contain i
vector<ll>okg[1<<19];// okg[i]-> values that node i contain
set<pll>adj[1<<19]; // {node,set}
ll complement(ll x,ll n=k){
if(x<n){return x+n;}
else{return x-n;}
}
class DisjSet {
vector<int>sz,parent; int n;
public:
int connected;
// Constructor to create and
// initialize sets of n items
DisjSet(int n)
{
sz = vector<int>(n,1);
parent = sz;
this->n = n;
this->connected=n;
makeSet();
}
// Creates n single item sets
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
// Finds set of given item x
int find(int x)
{
// Finds the representative of the set
// that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself
// Then x is not the representative of
// his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return parent[x];
}
int size(int x)
{
return sz[find(x)];
}
// Do union of two sets represented
// by x and y.
void Union(int x, int y)
{
// Find current sets of x and y
int xset = find(x);
int yset = find(y);
// If they are already in same set
if (xset == yset){
return;
}
connected--;
// Put smaller ranked item under
// bigger ranked item if ranks are
// different
if (sz[xset] <= sz[yset]) {
parent[xset] = yset;
sz[yset] += sz[xset];
}
else {
parent[yset] = xset;
sz[xset] += sz[yset];
}
}
};
class Bipartite_DisjSet {
// could be slow (i.e logn per query at most) because i am assuring if x is
// a parent so is x+n, path
public:
vector<ll>sz,parent; ll n;
// i and (i+n) are different colors
// int connected;
// Constructor to create and
// initialize sets of n items
Bipartite_DisjSet(ll n)
{
sz = vector<ll>(2*n,1);
for(ll i(n);i<2*n;++i){sz[i]=0;}
parent = sz;
this->n = n;
// this->connected=n;
makeSet();
}
// Creates n single item sets
void makeSet()
{
for (int i = 0; i < 2*n; i++) {
parent[i] = i;
}
}
// Finds set of given item x
ll find(ll x)
{
// Finds the representative of the set
// that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself
// Then x is not the representative of
// his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return parent[x];
}
ll size(ll x)
{
return sz[find(x)];
}
// Do union of two sets represented
// by x and y.
void Union(ll x, ll y,ll edge=0) // parity of edge
{
if(x>y){
return Union(y,x,edge);
}
// x<y
if(y>=n){cout<<"Fuck"<<endl; exit(0);}
// x and y are both <n
// Find current sets of x and y
ll xset = find(x);
ll yset = find(y);
// If they are already in same set
if (xset == yset){
assert(edge==0);
return;
}
else if(xset%n==yset%n){
assert(edge==1);
return;
}
// connected--;
// Put smaller ranked item under
// bigger ranked item if ranks are
// different
if(edge==0){
// merge xset, yset
// merge xset^c,yset^c
parent[yset]=xset;
parent[complement(yset,n)]=complement(xset,n);
sz[xset]+=sz[yset];
sz[complement(xset,n)]+=sz[complement(yset,n)];
}
else{
// merge xset,yset^c
// merge xset^c,yset
parent[yset]=complement(xset,n);
parent[complement(yset,n)]=xset;
sz[xset]+=sz[complement(yset,n)];
sz[complement(xset,n)]+=sz[yset];
}
}
};
void solve();
int main() {
io;
ll t=1,n=1;
// cin>>t;
while (t--){
solve();
}
return 0;
}
void solve(){
cin>>n>>k;
for(ll i(0);i<n;++i){
char pp; cin>>pp;
auto p=pp-'0';
p^=1;
v.push_back(p);
}
for(ll i(0);i<k;++i){
ll sz; cin>>sz;
for(ll j(0);j<sz;++j){
ll tt; cin>>tt;
tt--;
con[tt].push_back(i);
okg[i].push_back(tt);
}
sort(begin(okg[i]),end(okg[i]));
}
// for(ll i(0);i<n;++i){
// if(con[i].size()==2){
// adj[con[i][0]].insert({con[i][1],v[i]});
// adj[con[i][1]].insert({con[i][0],v[i]});
// }
// }
Bipartite_DisjSet dsu(k);
vector<ll>ans(n,0);
ll prev=0;
for(ll i(0);i<n;++i){
if(con[i].empty()){
ans[i]=prev;
}
else if(con[i].size()==2){
// add an edge
ll kk=prev; // just storing previous answer
{
// adj[con[i][0]].insert({con[i][1],v[i]});
// adj[con[i][1]].insert({con[i][0],v[i]});
// dsu.Union(con[i][0],con[i][1],v[i]);
if(dsu.find(con[i][0])%k==dsu.find(con[i][1])%k){
// nothing new happens
ans[i]=prev;
}
else if(min(okg[con[i][0]][0],okg[con[i][1]][0])==i){
// adding 2 nodes
dsu.Union(con[i][0],con[i][1],v[i]);
ll pr=dsu.find(con[i][0]);
ll q=complement(pr);
ans[i]=prev+min(dsu.size(q),dsu.size(pr));
}
else if(okg[con[i][0]][0]==i){
// adding 1 new node
ll val=min(dsu.size(con[i][1]),dsu.size(complement(con[i][1])));
ans[i]=prev-val;
dsu.Union(con[i][0],con[i][1],v[i]);
ans[i]+=min(dsu.size(con[i][1]),dsu.size(complement(con[i][1])));
}
else if(okg[con[i][1]][0]==i){
swap(con[i][1],con[i][0]);
// same as before now
ll val=min(dsu.size(con[i][1]),dsu.size(complement(con[i][1])));
ans[i]=prev-val;
dsu.Union(con[i][0],con[i][1],v[i]);
ans[i]+=min(dsu.size(con[i][1]),dsu.size(complement(con[i][1])));
}
else{
// new connection
ll val1=min(dsu.size(con[i][1]),dsu.size(complement(con[i][1])));
ll val2=min(dsu.size(con[i][0]),dsu.size(complement(con[i][0])));
ans[i]=prev-val1-val2;
dsu.Union(con[i][0],con[i][1],v[i]);
ans[i]+=min(dsu.size(con[i][1]),dsu.size(complement(con[i][1])));
}
}
}
else{
// fix a size
ll t=con[i][0];
{
ans[i]=prev-min(dsu.size(t),dsu.size(complement(t)));
// if(i==6){cout<<ans[i]<<"&&&";}
if(v[i]==0){ // always choose an even number of times
// choose complement
dsu.sz[dsu.find(t)]=inf;
}
else{
// choose t
dsu.sz[dsu.find(complement(t))]=inf;
}
ans[i]+=min(dsu.size(t),dsu.size(complement(t)));
}
}
prev=ans[i];
}
for(auto i:ans){
cout<<i<<endl;
}
}
// Do not get stuck on a single approach for long, think of multiple ways | cpp |
1313 | D | D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third. | [
"bitmasks",
"dp",
"implementation"
] | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define debug(x) cerr << #x << " " << x << "\n"
#define debugs(x) cerr << #x << " " << x << " "
using namespace std;
typedef pair <int, int> pii;
typedef long long ll;
const int NMAX = 100001;
const int VMAX = 41;
const int INF = 1e9;
const int MOD = 1000000009;
const int BLOCK = 318;
const int base = 31;
const int nrbits = 21;
int dp[2][(1 << 8)];
int best[2][(1 << 8)];
vector <int> intervals[NMAX * 2];
pii v[NMAX];
int valoare[NMAX * 2];
pii capete[NMAX * 2];
int cnt = 0;
vector <pii> nrm;
void maxSelf(int &x, int val){
x = max(x, val);
}
int main() {
#ifdef HOME
ifstream cin(".in");
ofstream cout(".out");
#endif // HOME
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m, k, i;
cin >> n >> m >> k;
for(i = 1; i <= n; i++){
cin >> v[i].first >> v[i].second;
nrm.push_back({v[i].first, 0});
nrm.push_back({v[i].second, 1});
}
sort(nrm.begin(), nrm.end());
for(int i = 1; i < nrm.size(); i++){
if(nrm[i] != nrm[i - 1]){
cnt++;
capete[cnt] = {nrm[i - 1].first + (nrm[i - 1].second == 1), nrm[i].first - (nrm[i].second == 0)};
valoare[cnt] = capete[cnt].second - capete[cnt].first + 1;
if(valoare[cnt] <= 0)
cnt--;
}
}
for(i = 1; i <= n; i++){
int r = 0, pas = (1 << nrbits);
while(pas){
if(r + pas <= cnt && capete[r + pas].first < v[i].first)
r += pas;
pas /= 2;
}
r++;
while(r <= cnt && capete[r].second <= v[i].second){
intervals[r].push_back(i);
r++;
}
}
int maxim = 0;
for(i = 1; i <= cnt; i++){
int acum = i%2;
int last = 1 - acum;
int cate = intervals[i].size();
if(cate == 0){
dp[acum][0] = maxim;
continue;
}
for(int j = 0; j < (1 << cate); j++){
dp[acum][j] = -INF;
best[acum][j] = -INF;
}
vector <int> corespunde(cate, -1), comun(intervals[i - 1].size(), -1);
if(i > 1){
for(int j = 0; j < intervals[i].size(); j++){
for(int k = 0; k < intervals[i - 1].size(); k++){
if(intervals[i][j] == intervals[i - 1][k]){
corespunde[j] = k;
comun[k] = j;
}
}
}
}
for(int j = (1 << intervals[i - 1].size()) - 1; j >= 0; j--){
for(int bit = 0; bit < intervals[i - 1].size(); bit++){
if((j & (1 << bit)) || (comun[bit] != -1)) continue;
maxSelf(dp[last][j], dp[last][j | (1 << bit)]);
}
}
for(int j = 0; j < (1 << intervals[i - 1].size()) - 1; j++){
for(int bit = 0; bit < intervals[i - 1].size(); bit++){
if(!(j & (1 << bit)) || (comun[bit] != -1)) continue;
maxSelf(dp[last][j], dp[last][j ^ (1 << bit)]);
}
}
for(int j = 0; j < (1 << cate); j++){
int oblig = 0;
for(int bit = 0; bit < cate; bit++){
if((j & (1 << bit)) && corespunde[bit] != -1){
oblig |= (1 << corespunde[bit]);
}
}
dp[acum][j] = ((__builtin_popcount(j)) % 2 == 1) * valoare[i] + dp[last][oblig];
maxSelf(maxim, dp[acum][j]);
}
}
cout << maxim;
return 0;
}
| cpp |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
| [
"data structures",
"dp"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
signed main()
{
int n;
string s;
cin >> n >> s;
int lo = 1, hi = 27;
int md = 0;
vector<int> col(n + 3);
vector<char> seg(29);
while (lo <= hi)
{
int mid = (lo + hi) / 2;
for (int i = 0; i <= mid; i++)
seg[i] = 'a';
bool flag = 1;
for (int i = 0; i < n; i++)
{
int u = -1;
for (int j = 1; j <= mid; j++)
{
if (s[i] < seg[j])
continue;
if (u == -1 or seg[j] > seg[u])
u = j;
}
if (u == -1)
{
flag = 0;
break;
}
col[i] = u;
seg[u] = s[i];
}
if (flag)
{
hi = mid - 1;
md = mid;
}
else
lo = mid + 1;
}
cout << md << endl;
for (int i = 0; i < s.size(); i++)
cout << col[i] << ' ';
} | cpp |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
long int t,n,k,i,l;
cin>>t;
while(t--)
{ vector< int> arr;
cin>>n;
for ( i = 0; i < 2*n; i++)
{
cin>>l;
arr.push_back(l);
}
sort(arr.begin(),arr.end());
k= arr[n]-arr[n-1];
cout<<k<<'\n';
}
return 0;
} | cpp |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | #include <bits/stdc++.h>
#pragma GCC optimize ("unroll-loops")
#pragma GCC optimize ("O3")
#define ll long long
#define st string
#define ull unsigned ll
#define pii pair <int, int>
#define pll pair <ll, ll>
#define pb push_back
#define ins insert
#define F first
#define S second
#define int ll
using namespace std;
int32_t main () {
//freopen ("points.in", "r", stdin);
//freopen ("points.out", "w", stdout);
ios_base::sync_with_stdio();
cin.tie(0);
cout.tie(0);
int t=1;
cin >> t;
while (t --) {
int n, kol = 0, sum = 0;
cin >> n;
vector <int> v;
for (int i = 0; i < n; i ++) {
int a;
cin >> a;
v.pb(a);
if (!a) kol ++;
sum += a;
}
sum += kol;
if (sum && !kol) {
cout << "0\n";
}
else {
if (!sum && kol) {
cout << kol + 1 << "\n";
}
else if (!sum) {
cout << "1\n";
}
else if (kol) {
cout << kol << "\n";
}
}
}
return 0;
}
| cpp |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | # include<iostream>
using namespace std;
int main(){
int t;
cin >> t;
for(int i=0;i<t;i++){
int n;
cin >> n;
int k;
if (n%2==0){
k=n/2;
}
else{
k=(n-3)/2;
}
if (n%2==0){
for(int g=0;g<k;g++){
cout<<"1";
}
}
else
{
cout<<"7";
for(int y=0;y<k;y++){
cout<<"1";
}
}
cout<<endl;
}
} | cpp |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>
#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int binexp(int a,int b,int m=1e9+7)
{
if(b==0) return 1;
int x=binexp(a,b/2,m)%m;
if(b%2) x=((a%m)*(x*1LL*x)%m)%m;
else x=(x*1LL*x)%m;
return x%m;
}
void ram()
{
int n;
cin>>n;
string s,t;
cin>>s>>t;
vector<pair<char,int>> a,b;
vector<int> x,y;
for(int i=0;i<n;i++)
{
if(s[i]=='?') x.push_back(i);
else a.push_back({s[i],i});
}
for(int i=0;i<n;i++)
{
if(t[i]=='?') y.push_back(i);
else b.push_back({t[i],i});
}
sort(a.begin(),a.end());
sort(b.begin(),b.end());
vector<pair<int,int>> ans;
int i=0,j=0;
while(i<a.size() && j<b.size())
{
if(a[i].first==b[j].first)
{
ans.push_back({a[i].second,b[j].second});
i++;
j++;
}
else if(a[i].first>b[j].first)
{
if(x.size()>0){
ans.push_back({x.back(),b[j].second});
x.pop_back();
}
j++;
}
else if(a[i].first<b[j].first)
{
if(y.size()>0){
ans.push_back({a[i].second,y.back()});
y.pop_back();
}
i++;
}
}
while(i<a.size()){
if(y.size()>0){
ans.push_back({a[i].second,y.back()});
y.pop_back();
}
i++;
}
while(j<b.size())
{
if(x.size()>0){
ans.push_back({x.back(),b[j].second});
x.pop_back();
}
j++;
}
while(x.size()>0 and y.size()>0)
{
ans.push_back({x.back(),y.back()});
x.pop_back();
y.pop_back();
}
cout<<ans.size()<<endl;
for(auto it:ans) cout<<it.first+1<<" "<<it.second+1<<endl;
}
int main()
{
int t=1;
//cin>>t;
while (t--) ram();
} | cpp |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,x = 0;
cin >> n;
int j = n - 2;
for(int i = 2;i < n;i++)
{
int y = n;
while(y > 0)
{
x += y % i,y /= i;
}
}
for(int i = 2;i * i < x;i++) while(j % i == 0&&x % i == 0) j /= i,x /= i;
cout << x << "/" << j;
return 0;
}
| cpp |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
long long get(vector<long long> &f, int pos) {
long long res = 0;
for (; pos >= 0; pos = (pos & (pos + 1)) - 1)
res += f[pos];
return res;
}
void upd(vector<long long> &f, int pos, int val) {
for (; pos < int(f.size()); pos |= pos + 1) {
f[pos] += val;
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<pair<int, int>> p(n);
for (auto &pnt : p) cin >> pnt.first;
for (auto &pnt : p) cin >> pnt.second;
sort(p.begin(), p.end());
vector<int> vs;
for (auto &pnt : p) vs.push_back(pnt.second);
sort(vs.begin(), vs.end());
vs.resize(unique(vs.begin(), vs.end()) - vs.begin());
long long ans = 0;
vector<long long> cnt(vs.size()), xs(vs.size());
for (auto &pnt : p) {
int pos = lower_bound(vs.begin(), vs.end(), pnt.second) - vs.begin();
ans += get(cnt, pos) * 1ll * pnt.first - get(xs, pos);
upd(cnt, pos, 1);
upd(xs, pos, pnt.first);
}
cout << ans << endl;
return 0;
} | cpp |
1291 | F | F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"graphs",
"interactive"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 1100
ll n,k;
inline bool gt(ll x){
cout<<"? "<<x<<'\n';
char tem;
cout.flush();cin>>tem;
if(tem=='N')return 0;
return 1;
}
inline void clear(){
cout<<'R'<<'\n';
return ;
}
ll an[N];
int main()
{
// freopen("test1.in","r",stdin);
//freopen(".in","r",stdin);
//freopen("test1.out","w",stdout);
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>n>>k;
if(k==1){
ll ans=n;
for(int i=2;i<=n;i++){
for(int j=1;j<i;j++){
gt(j);ll o=gt(i);an[i]|=o;
}
if(an[i])ans--;
}cout<<"! "<<ans;
return 0;
}
ll ji=k/2,g=n/ji,ans=n;
for(int i=1;i<=g;i++){
ll l=(i-1)*ji+1,r=i*ji;
for(int j=1;j<i;j++){
for(int q=(j-1)*ji+1;q<=j*ji;q++)gt(q);
for(int q=l;q<=r;q++)an[q]|=gt(q);
clear();
}
for(int j=l;j<=r;j++)an[j]|=gt(j);
for(int j=l;j<=r;j++)if(an[j])ans--;
clear();
}cout<<"! "<<ans;
return 0;
}
| cpp |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 4e5 + 10;
int a[N], b[N];
int n, m, k;
int slove(int x)
{
int cnt1 = 0, cnt = 0;
for (int i = 1; i <= n; i++) {
if (a[i]) cnt1++;
else cnt1 = 0;
if (cnt1 >= x) cnt++;
}
int cnt2 = 0, y = k / x;
int res = 0;
for (int i = 1; i <= m; i++) {
if (b[i]) cnt2++;
else cnt2 = 0;
if (cnt2 >= y) res += cnt;
}
return res;
}
int main()
{
ios::sync_with_stdio(0);
cout.tie(0), cin.tie(0);
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) cin >> b[i];
long long ans = 0;
for (int i = 1; i <= sqrt(k); i++) {
if (k % i == 0) {
ans += slove(i);
if (k / i != i) {
ans += slove(k / i);
}
}
}
cout << ans << endl;
return 0;
}
| cpp |
1307 | F | F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n) — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105) — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi) — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below. | [
"dfs and similar",
"dsu",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
const int N = 4e5+5;
const int K = 19;
const int INF = 1e9;
vector<int> G[N];
int par[N][K], dep[N], dist_from_rest[N], nearest_rest[N];
int fa[N];
int root(int x) {
return (fa[x] == x ? x : fa[x] = root(fa[x]));
}
void join(int x, int y) {
int a = root(x);
int b = root(y);
if (a == b) return;
fa[a] = b;
}
void dfs(int v, int p) {
par[v][0] = p;
dep[v] = dep[p]+1;
for (int i = 1; i < K; i++) {
par[v][i] = par[par[v][i-1]][i-1];
}
for (int u: G[v]) {
if (u == p) continue;
dfs(u, v);
}
}
int lca(int u, int v) {
if (dep[u] > dep[v]) swap(u, v);
for (int i = K-1; i >= 0; i--) {
if (((dep[v]-dep[u])>>i)&1) {
v = par[v][i];
}
}
if (u == v) return u;
for (int i = K-1; i >= 0; i--) {
if (par[u][i] != par[v][i]) {
u = par[u][i];
v = par[v][i];
}
}
return par[u][0];
}
int kth_ancestor(int v, int k) {
for (int i = K-1; i >= 0; i--) {
if ((k>>i)&1) {
v = par[v][i];
}
}
return v;
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int n, k, r;
cin >> n >> k >> r;
for (int i = 0; i < n-1; i++) {
int u, v;
cin >> u >> v;
G[u].push_back(n+1+i);
G[v].push_back(n+1+i);
G[n+1+i].push_back(u);
G[n+1+i].push_back(v);
}
dfs(1, 0);
fill(dist_from_rest, dist_from_rest+N, INF);
vector<int> que;
for (int i = 0; i < r; i++) {
int v;
cin >> v;
que.push_back(v);
dist_from_rest[v] = 0;
nearest_rest[v] = v;
}
iota(fa, fa+N, 0);
for (int i = 0; i < (int)que.size(); i++) {
int v = que[i];
if (dist_from_rest[v] == k) break;
for (int u: G[v]) {
if (nearest_rest[u]) {
join(nearest_rest[u], nearest_rest[v]);
continue;
}
nearest_rest[u] = nearest_rest[v];
dist_from_rest[u] = dist_from_rest[v]+1;
que.push_back(u);
}
}
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
int w = lca(u, v);
int d = dep[u]+dep[v]-2*dep[w];
if (d <= 2*k) {
cout << "YES\n";
continue;
}
int u0 = (dep[u]-dep[w] >= k ? kth_ancestor(u, k) : kth_ancestor(v, d-k));
int v0 = (dep[v]-dep[w] >= k ? kth_ancestor(v, k) : kth_ancestor(u, d-k));
cout << (nearest_rest[u0] && root(nearest_rest[u0]) == root(nearest_rest[v0]) ? "YES" : "NO") << '\n';
}
}
| cpp |
1320 | F | F. Blocks and Sensorstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size 1×1×11×1×1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1×1×11×1×1; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates (x,y,z)(x,y,z) (the cell with these coordinates is a cube with opposite corners in (x,y,z)(x,y,z) and (x+1,y+1,z+1)(x+1,y+1,z+1)) and its contents ax,y,zax,y,z; if the cell is empty, then ax,y,z=0ax,y,z=0, otherwise ax,y,zax,y,z is equal to the type of the block placed in it (the types are integers from 11 to 2⋅1052⋅105).Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size n×m×kn×m×k, containing all cells (x,y,z)(x,y,z) such that x∈[1,n]x∈[1,n], y∈[1,m]y∈[1,m], and z∈[1,k]z∈[1,k]. After that, Polycarp has installed 2nm+2nk+2mk2nm+2nk+2mk sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into 66 types: there are mkmk sensors of the first type; each such sensor is installed in (0,y,z)(0,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the same direction; there are mkmk sensors of the second type; each such sensor is installed in (n+1,y,z)(n+1,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the opposite direction; there are nknk sensors of the third type; each such sensor is installed in (x,0,z)(x,0,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the same direction; there are nknk sensors of the fourth type; each such sensor is installed in (x,m+1,z)(x,m+1,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the opposite direction; there are nmnm sensors of the fifth type; each such sensor is installed in (x,y,0)(x,y,0), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the same direction; finally, there are nmnm sensors of the sixth type; each such sensor is installed in (x,y,k+1)(x,y,k+1), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the opposite direction. Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?InputThe first line contains three integers nn, mm and kk (1≤n,m,k≤2⋅1051≤n,m,k≤2⋅105, nmk≤2⋅105nmk≤2⋅105) — the dimensions of the parallelepiped.Then the sensor data follows. For each sensor, its data is either 00, if the ray emitted from it reaches the opposite sensor (there are no blocks in between), or an integer from 11 to 2⋅1052⋅105 denoting the type of the first block hit by the ray. The data is divided into 66 sections (one for each type of sensors), each consecutive pair of sections is separated by a blank line, and the first section is separated by a blank line from the first line of the input.The first section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (0,i,j)(0,i,j).The second section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (n+1,i,j)(n+1,i,j).The third section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,0,j)(i,0,j).The fourth section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,m+1,j)(i,m+1,j).The fifth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,0)(i,j,0).Finally, the sixth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,k+1)(i,j,k+1).OutputIf the information from the input is inconsistent, print one integer −1−1.Otherwise, print the figure inside the parallelepiped as follows. The output should consist of nmknmk integers: a1,1,1a1,1,1, a1,1,2a1,1,2, ..., a1,1,ka1,1,k, a1,2,1a1,2,1, ..., a1,2,ka1,2,k, ..., a1,m,ka1,m,k, a2,1,1a2,1,1, ..., an,m,kan,m,k, where ai,j,kai,j,k is the type of the block in (i,j,k)(i,j,k), or 00 if there is no block there. If there are multiple figures consistent with sensor data, describe any of them.For your convenience, the sample output is formatted as follows: there are nn separate sections for blocks having x=1x=1, x=2x=2, ..., x=nx=n; each section consists of mm lines containing kk integers each. Note that this type of output is acceptable, but you may print the integers with any other formatting instead (even all integers on the same line), only their order matters.ExamplesInputCopy4 3 2
1 4
3 2
6 5
1 4
3 2
6 7
1 4
1 4
0 0
0 7
6 5
6 5
0 0
0 7
1 3 6
1 3 6
0 0 0
0 0 7
4 3 5
4 2 5
0 0 0
0 0 7
OutputCopy1 4
3 0
6 5
1 4
3 2
6 5
0 0
0 0
0 0
0 0
0 0
0 7
InputCopy1 1 1
0
0
0
0
0
0
OutputCopy0
InputCopy1 1 1
0
0
1337
0
0
0
OutputCopy-1
InputCopy1 1 1
1337
1337
1337
1337
1337
1337
OutputCopy1337
| [
"brute force"
] | #include<bits/stdc++.h>
#define fx for(int y=1;y<=m;++y)for(int z=1;z<=k;++z)
#define fy for(int x=1;x<=n;++x)for(int z=1;z<=k;++z)
#define fz for(int x=1;x<=n;++x)for(int y=1;y<=m;++y)
using namespace std;
const int N=2e5+7;
int n,m,k,a[N],f[6][N];
vector<pair<int,int> >tg[N];
const int dx[6]={1,-1,0,0,0,0};
const int dy[6]={0,0,1,-1,0,0};
const int dz[6]={0,0,0,0,1,-1};
bool chk(int x,int y,int z){
if(x<1||x>n)
return 0;
if(y<1||y>m)
return 0;
if(z<1||z>k)
return 0;
return 1;
}
int id(int x,int y,int z){
return m*k*(x-1)+k*(y-1)+z;
}
int idx(int y,int z){
return k*(y-1)+z;
}
int idy(int x,int z){
return k*(x-1)+z;
}
int idz(int x,int y){
return m*(x-1)+y;
}
void clr(int x,int y,int z,int d){
while(1){
x+=dx[d];
y+=dy[d];
z+=dz[d];
if(!chk(x,y,z))
break;
a[id(x,y,z)]=0;
}
}
void upd(int x,int y,int z,int d,int c){
while(1){
x+=dx[d];
y+=dy[d];
z+=dz[d];
if(!chk(x,y,z))
break;
if(!a[id(x,y,z)])
continue;
if(tg[id(x,y,z)].empty()||tg[id(x,y,z)][0].first==c){
tg[id(x,y,z)].emplace_back(c,d);
break;
}
a[id(x,y,z)]=0;
for(auto u:tg[id(x,y,z)])
upd(x,y,z,u.second,u.first);
tg[id(x,y,z)].clear();
}
}
void col(int x,int y,int z,int d,int c){
while(1){
x+=dx[d];
y+=dy[d];
z+=dz[d];
if(!chk(x,y,z)){
puts("-1");
exit(0);
}
if(!a[id(x,y,z)])
continue;
a[id(x,y,z)]=tg[id(x,y,z)][0].first;
if(a[id(x,y,z)]^c){
puts("-1");
exit(0);
}
break;
}
}
int main(){
scanf("%d%d%d",&n,&m,&k);
memset(a,-1,sizeof(a));
fx scanf("%d",f[0]+idx(y,z));
fx scanf("%d",f[1]+idx(y,z));
fy scanf("%d",f[2]+idy(x,z));
fy scanf("%d",f[3]+idy(x,z));
fz scanf("%d",f[4]+idz(x,y));
fz scanf("%d",f[5]+idz(x,y));
fx if(!f[0][idx(y,z)]) clr(0,y,z,0);
fx if(!f[1][idx(y,z)]) clr(n+1,y,z,1);
fy if(!f[2][idy(x,z)]) clr(x,0,z,2);
fy if(!f[3][idy(x,z)]) clr(x,m+1,z,3);
fz if(!f[4][idz(x,y)]) clr(x,y,0,4);
fz if(!f[5][idz(x,y)]) clr(x,y,k+1,5);
fx if(f[0][idx(y,z)]) upd(0,y,z,0,f[0][idx(y,z)]);
fx if(f[1][idx(y,z)]) upd(n+1,y,z,1,f[1][idx(y,z)]);
fy if(f[2][idy(x,z)]) upd(x,0,z,2,f[2][idy(x,z)]);
fy if(f[3][idy(x,z)]) upd(x,m+1,z,3,f[3][idy(x,z)]);
fz if(f[4][idz(x,y)]) upd(x,y,0,4,f[4][idz(x,y)]);
fz if(f[5][idz(x,y)]) upd(x,y,k+1,5,f[5][idz(x,y)]);
fx if(f[0][idx(y,z)]) col(0,y,z,0,f[0][idx(y,z)]);
fx if(f[1][idx(y,z)]) col(n+1,y,z,1,f[1][idx(y,z)]);
fy if(f[2][idy(x,z)]) col(x,0,z,2,f[2][idy(x,z)]);
fy if(f[3][idy(x,z)]) col(x,m+1,z,3,f[3][idy(x,z)]);
fz if(f[4][idz(x,y)]) col(x,y,0,4,f[4][idz(x,y)]);
fz if(f[5][idz(x,y)]) col(x,y,k+1,5,f[5][idz(x,y)]);
for(int x=1;x<=n;++x,puts(""))
for(int y=1;y<=m;++y)
for(int z=1;z<=k;++z){
if(!~a[id(x,y,z)])
a[id(x,y,z)]=18260;
printf("%d%c",a[id(x,y,z)]," \n"[z==k]);
}
return 0;
} | cpp |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100;
int t[MAX_N], lo[MAX_N], hi[MAX_N];
int main()
{
int tc;
cin >> tc;
while (tc--)
{
int n, m, i;
cin >> n >> m;
for (i = 0; i < n; i++)
cin >> t[i] >> lo[i] >> hi[i];
int prev = 0;
int mn = m, mx = m;
bool flag = true;
for (i = 0; i < n; i++)
{
mx += t[i] - prev;
mn -= t[i] - prev;
if (mx < lo[i] || mn > hi[i])
{
flag = false;
break;
}
mx = min(mx, hi[i]);
mn = max(mn, lo[i]);
prev = t[i];
}
if (flag)
cout << "YES\n";
else
cout << "NO\n";
}
} | cpp |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ub upper_bound
#define lb lower_bound
#define ll long long
#define ld long double
#define pii pair<ll, ll>
typedef __int128 lll;
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef vector<pii> vpi;
typedef set<ll> si;
typedef map<ll, ll> mii;
#define all(value) value.begin(), value.end()
const int M = 1e9+7;
//..................................................................
void solve(){
ll n,d;
cin>>n>>d;
if(d<=n)
{
cout<<"YES"<<endl;return;
}
for (int i = 1 ;i <= n; i++)
{
ll curr=i+d/(i+1);
if(d%(i+1)!=0) curr++;
if(curr<=n)
{
cout<<"YES"<<endl;
return;
}
}
cout<<"NO"<<endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ll t=1;
cin>>t;
while(t--)
{
solve();
}
} | cpp |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS. | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] | #include<bits/stdc++.h>
#pragma GCC target ("sse4.2")
using namespace std;
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
// #define int long long int
#define ld long double
#define fon(i,n) for(int i=0;i<n;i++)
#define fo(i,n) for(int i=1;i<=n;i++)
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define ff first
#define ss second
#define pii pair<int,int>
#define vii vector<int>
#define bs binary_search
#define lb lower_bound
#define ub upper_bound
#define setbits(x) __builtin_popcountll(x)
#define M (1000*1000*1000+7)
#define sz(x) ((int)(x).size())
#define endl "\n"
#define test int T; cin>>T; while(T--)
#define all(z) z.begin() , z.end()
#define allr(z) z.rbegin() , z.rend()
#define sp(x,y) fixed << setprecision(x) << y
#define memo(oo , zz) memset(oo , zz , sizeof(oo))
//template<typename T>
//using ordered_set = tree<T , null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;
// DEBUG START=======================================================================================
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
// DEBUG END =====================================================================================
bool sortbyme(pii a , pii b)
{
return a.ss > b.ss;
}
const long long inf = 1e18;
const int N = 1e5;
vii minimum_lis_sequence(string s , int n) {
vii res;
int i = 0;
int val = n+1;
while(i < n) {
size_t pos = s.find('<' , i);
if(pos == string::npos) {
pos = n;
}
int j = pos;
vii v2;
while(j < n && s[j] == '<') {
v2.eb(val--);
j++;
}
vii v1;
while(i < pos && pos != string::npos) {
v1.eb(val--);
i++;
}
if(res.empty()) {
v1.eb(val--);
}
reverse(all(v2));
res.insert(res.end() , all(v1));
res.insert(res.end() , all(v2));
i = j;
}
return res;
}
void solve()
{
int n;
string s;
cin >> n >> s;
// first let's find the sequence for the smallest length of lis
vii min_lis = minimum_lis_sequence(s , n-1);
reverse(all(s));
for(char &c : s) {
if(c == '<') {
c = '>';
}
else {
c = '<';
}
}
vii max_lis = minimum_lis_sequence(s , n-1);
reverse(all(max_lis));
for(int i = 0 ; i < n ; i++) {
cout << min_lis[i] << " ";
}
cout << endl;
for(int i = 0 ; i < n ; i++) {
cout << max_lis[i] << " ";
}
cout << endl;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
test
{
solve();
}
} | cpp |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample: | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | #include<bits/stdc++.h>
using namespace std;
#define X ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int long long
void solve() {
int n;
cin >> n;
int ans[n + 1];
vector<int> g[n];
for (int e = 1; e <= n; e++)ans[e] = -1;
for (int i = 1; i < n; i++) {
int v, u;
cin >> u >> v;
v--;
u--;
g[v].push_back(i);
g[u].push_back(i);
}
int k = 0;
for (int v = 0; v < n; v++) {
if ((int) g[v].size() <= 2) continue;
for (int id: g[v])
if (ans[id] == -1)
ans[id] = k++;
}
for (int i = 1; i < n; i++)
if (ans[i] == -1)
ans[i] = k++;
for (int i = 1; i < n; i++)
cout << ans[i] << " ";
}
int32_t main() {
X;
int t;
t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
} | cpp |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | #include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// order_of_key(a) -> gives index of the element(number of elements smaller than a)
// find_by_order(a) -> gives the element at index a
#define accelerate ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define int long long int
#define ld long double
#define mod1 998244353
#define endl "\n"
#define ff first
#define ss second
#define all(x) (x).begin(),(x).end()
#define ra(arr,n) vector<int> arr(n);for(int in = 0; in < n; in++) {cin >> arr[in];}
const int mod = 1e9 + 7;
const int inf = 1e18;
int MOD(int x) {int a1 = (x % mod); if (a1 < 0) {a1 += mod;} return a1;}
int power( int a, int b) {
int p = 1; while (b > 0) {if (b & 1)p = (p * a); a = (a * a) ; b >>= 1;}
return p;
}
int go(int ind, vector<int>&arr, vector<vector<int>>&dp, int x)
{
if (ind == arr.size())return 0;
if (dp[ind][x] != -1)return dp[ind][x];
if (x == arr.size())
{
return dp[ind][x] = max(arr[ind] + go(ind + 1, arr, dp, ind), go(ind + 1, arr, dp, x));
}
if (arr[ind] - arr[x] == ind - x)
{
return dp[ind][x] = max(arr[ind] + go(ind + 1, arr, dp, ind), go(ind + 1, arr, dp, x));
}
return dp[ind][x] = go(ind + 1, arr, dp, x);
}
void lessgoo()
{
int n;
cin >> n;
ra(arr, n);
int ans = 0;
map<int, int>mp;
for (int i = 0; i < n; i++)
{
mp[arr[i] - i] += arr[i];
ans = max(ans, mp[arr[i] - i]);
}
cout << ans << endl;
}
signed main()
{
accelerate;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int test = 1;
// cin >> test;
for (int tcase = 1; tcase <= test; tcase++)
{
// cout << "Case #" << tcase << ": ";
lessgoo();
}
return 0;
}
| cpp |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes. | [
"brute force",
"strings"
] | #include<bits/stdc++.h>
#define int long long
#define pb push_back
#define _ ios::sync_with_stdio(false); cin.tie(NULL);
#define endl "\n"
using namespace std;
int32_t main()
{
_
int t = 1;
cin>>t;
while(t--)
{
int n;
cin>>n;
int ara[n];
for(int i = 0;i<n;i++)
cin >> ara[i];
int flag = 0,pos = 0;;
int rex = 0;
map<int,int>mp;
for (int i = 0; i < n; ++i)
{
mp[ara[i]]++;
}
int f = 0;
for(auto y : mp)
{
if(y.second >= 3){
f = 1;break;
// cout << "YES" << endl;
}
}
for(int i = 0;i<n;i++)
{
int a = ara[i];
for(int j = i+1;j<n;j++)
{
if(ara[j] != a) {
pos = j;
flag++;
break;
}
}
for(int k = pos+1;k<n;k++)
if(ara[k] == a)
{
flag++;
break;
}
if(flag ==2 )
break;
else flag = 0;
}
if(flag == 2 or f == 1)cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
| cpp |
1284 | E | E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213 | [
"combinatorics",
"geometry",
"math",
"sortings"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/priority_queue.hpp>
using namespace __gnu_pbds;
using namespace __gnu_cxx;
using namespace std;
typedef tree<int, null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> TREE;
//tree.find_by_order() / tree.order_of_key();
#define N 2505
using pi = pair<int, int>;
int castle[N][2];
long long int c[N][10];
long long int cmpin(pair<int, int> a, pair<int, int> b){
long long int ady = a.first, adx = a.second, bdy = b.first, bdx = b.second;
ady*=bdx;
bdy*=adx;
return bdy-ady;
}
bool cmp(pair<int, int> a, pair<int, int> b){
bool bh1 = a < pi(0, 0);
bool bh2 = b < pi(0, 0);
if(bh1 != bh2) return bh1 < bh2;
return cmpin(a, b) > 0;
}
long long int comb(int n, int m){
if(m>n){
return 0;
}
if(n==m){
return 1;
}
if(m==1){
return n;
}
if(c[n][m]>0){
return c[n][m];
}
c[n][m] = comb(n-1, m)+comb(n-1, m-1);
return c[n][m];
}
int main(){
ios::sync_with_stdio(0); cin.tie(0);
int n;
cin >> n;
for(int i=0; i<n; ++i){
cin >> castle[i][0] >> castle[i][1];
}
long long int ans = comb(n, 5)*5;
for(int i=0; i<n; ++i){
vector<pair<int, int>> ang;
for(int j=0; j<n; ++j){
if(i==j){
continue;
}
int dx = castle[i][0]-castle[j][0], dy = castle[i][1]-castle[j][1];
ang.push_back(make_pair(dy, dx));//j to i
}
//ang[i].push_back(make_pair(-1, -9));
sort(ang.begin(), ang.end(), cmp);
/*for(int j=0; j<ang[i].size(); ++j){
cout << "ang[" << i << "][" << j << "] = " << ang[i][j].first << ", " << ang[i][j].second << "\n";
}*/
int j = 0;
for(int k=0; k<ang.size(); k++){
while(j < k + ang.size() && cmpin(ang[k], ang[j % ang.size()]) >= 0) j++;
ans -= comb(j - k - 1, 3);
}
}
cout << ans << '\n';
return 0;
}
| cpp |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | [
"math"
] | //submission by ffaith
/*
** author: ffaith
** created: i dont remember
** [solved by] : also ffaith
*/
#include <bits/stdc++.h>
#define ld long double
#define ins insert
#define rll 10000000000000000
#define ull unsigned long long
#define pb push_back
#define endl "\n"
#define ll long long
#define lp(a,b) for(int i = a; i<b; i++)
#define deflp(a,b) for(i = a; i<b; i++)
#define pl(a,b) for(int i = a; i>=b; i--)
#define pj(a,b) for(int j = a; j>=b; j--)
#define jp(a,b) for(int j = a; j<b; j++)
#define kp(a,b) for(int k = a; k<b; k++)
#define funcget(a,b); for(int i = 0;i<b;i++){ cin>>a[i];}
#define sumfuncget(a,b,c); for(int i = 0;i<b;i++){ cin>>a[i];c+=a[i];}
#define fsort(a) sort(a.begin(), a.end())
#define fsort2(a) sort(a.begin(), a.end(), greater <int>())
#define fcnt(a,b) count(a.begin(), a.end(), b)
#define setget(s,n) lp(0,n){ll tmp; cin >> tmp;s.ins(tmp);}
#define findmax(a) Max(a) - a.begin()
#define findmin(a) Min(a) - a.begin()
#define vectup(); ll n; cin >> n;vector <ll> fn(n);funcget(fn,n);
#define sumvectup(); ll n,sum = 0; cin >> n;vector <ll> fn(n);sumfuncget(fn,n,sum);
#define alphab() "abcdefghijklmnopqrstuvwxyz"
#define f_it vector<ll>::iterator
#define pq(fn) priority_queue <ll> fn;
#define pq1(fn) priority_queue <ll, vector<ll>, greater<ll> > fn;
#define fprint(a); for(ll i:a){cout<<i<<' ';}cout<<endl;
using namespace std;
/*
to solve{
1786C
1560C
489C
1490A
1373A
1422B
550A
1611B
75A
}
*/
const ll MODULO = 1e9 + 7;
ll comb(ll n){
return n*(n-1)/2;
}
void yesno(bool flag){
if(flag){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
ll fsumv(vector<ll> a){
ll cnt = 0;
lp(0,a.size()){
cnt+=a[i];
}
return cnt;
}
ll digsum(ll a){
ll sum = 0;
while(a!=0){
sum+=a%10;a/=10;
}
return sum;
}
bool powerof2(ll n){
if (n == 0)
return 0;
while (n != 1) {
if (n % 2 != 0)
return 0;
n = n / 2;
}
return 1;
}
ll gcd(ll m, ll n) {
ll r = 0, a, b;
a = (m > n) ? m : n;
b = (m < n) ? m : n;
r = b;
while (a % b != 0) {
r = a % b;
a = b;
b = r;
}
return r;
}
ll lcm(ll m, ll n) {
ll a;
a = (m > n) ? m: n;
while (true) {
if (a % m == 0 && a % n == 0)
return a;
a++;
}
}
bool isPrime(int n){
if (n <= 1)
return false;
else if (n==2){
return true;
}
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
vector <ll> divisors(ll n){
vector <ll> fn;
lp(1,n){
if(n%i==0){
fn.pb(i);
}
}
return fn;
}
vector <ll> SieveOfEratosthenes(ll n){
bool prime[n + 1];
memset(prime, true, sizeof(prime));
vector <ll> primes;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int p = 2; p <= n; p++)
if (prime[p])
primes.pb(p);
return primes;
}
string ftolow(string a){
lp(0,a.size()){
a[i] = towlower(a[i]);
}
return a;
}
string ftoup(string a){
lp(0,a.size()){
a[i] = towupper(a[i]);
}
return a;
}
string casefold(string s){
lp(0,s.size()){
if (s[i] == toupper(s[i])){
s[i] = tolower(s[i]);
}
else{
s[i] = toupper(s[i]);
}
}
string d = s;
return d;
}
ll fib(ll n){
vector <ll> dp(n+1);
dp[0] = 0;dp[1] = 1;
lp(2,n+1){
dp[i] = dp[i-2] + dp[i-1];
}
return dp[n];
}
ll fibsum(ll n){
vector <ll> dp(n+1);ll sum = 0;
dp[0] = 0;dp[1] = 1;
lp(2,n+1){
dp[i] = dp[i-2] + dp[i-1];
}
lp(0,n){
sum+=dp[i];
}
return sum;
}
bool isInteger(double N)
{
ll X = N;
double fuuuuc = N - X;
if (fuuuuc > 0) {
return false;
}
return true;
}
bool nozeroes(string s){
if(count(s.begin(), s.end(), '0') == 0){
return true;
}
return false;
}
bool no1s(string s){
if(count(s.begin(), s.end(), '1') == 0){
return true;
}
return false;
}
string removal(string s){
lp(1,s.size()){
if((s[i] == '0' && s[i-1] == '1') || (s[i] == '1' && s[i-1] == '0')){
s.erase(s.begin()+i);s.erase(s.begin()+(i-1));
}
}
return s;
}
vector <ll> merge(vector <ll> &a, vector <ll> &b){
ll x = 0,y = 0,k = 0;vector <ll> c(a.size() + b.size());
while(x<a.size() || y<b.size()){
if((y == b.size() )|| (x < a.size() && (a[x] < b[y]))){
c[k++] = a[x++];
}
else{
c[k++] = b[y++];
}
}
return c;
}
ll findget(vector <ll> v, ll isk){
auto it = find(v.begin(), v.end(), isk);
if(it!=v.end()){
return it - v.begin();
}
else{
return -1;
}
}
ll power(ll n, ll p){
ll z = n;
lp(0,p-1){
n = n * z;
}
return n;
}
ll distinctness(vector <ll> &a){
set <ll> s;
lp(0,a.size()){
s.ins(a[i]);
}
return s.size();
}
bool isdistinct(vector <ll> &a){
set <ll> s;
lp(0,a.size()){
s.ins(a[i]);
}
if(s.size() == a.size()){
return true;
}
else{
return false;
}
}
vector <ll> permutation(ll n){
vector <ll> a(n);
lp(0,n){
a[i] = i+1;
}
return a;
}
ll evenoddsum(vector <ll>&a,string z){
ll cnt0 = 0,cnt1 = 0;
lp(0,a.size()){
if(a[i]%2){
cnt1++;
}
else{
cnt0++;
}
}
if(ftolow(z) == "even"){
return cnt0;
}
else{
return cnt1;
}
}
ll factorial(ll n){
ll z = 1;
lp(1,n+1){z = (z*i) % MODULO;}
return z;
}
pair <ll, ll> maxsegment(vector <ll>&fn,ll n){
ll mx = -200,mxend = 0,start = 0, end = 0, s = 0;
lp(0,n){
mxend+=fn[i];
if(mxend > mx){
mx = mxend;
start = s; end = i;
}
if(mxend < 0){
mxend = 0;s = i + 1;
}
}
pair <ll, ll> z;
z.first = start;z.second = end;
return z;
}
ll secondmin(vector <ll>&a){
fsort(a);return a[1];
}
ll secondmax (vector<ll>&a){
fsort2(a);return a[1];
}
// fn[n-1] is faster than *max_element(fn.begin(), fn.end())
bool intdistinct(ll a){
vector <ll> aa;
while(a!=0){
aa.pb(a%10);a/=10;
}
if(isdistinct(aa)){
return true;
}
return false;
}
vector<ll> findPrefixSums(vector<ll>& a) {
ll n = a.size();
vector<ll> prefixSums(n + 1, 0);
for (ll i = 0; i < n; i++) {
prefixSums[i + 1] = prefixSums[i] + a[i];
}
return prefixSums;
}
// 6 8 2 8 h = 2
ll ugliness(vector <ll>&a){
fsort(a);return abs(a[0] - a[a.size() - 1]);
}
bool palindrome(string s){
string prev = s;
reverse(s.begin(), s.end());
if(prev == s){
return true;
}return false;
}
ll Max(vector <ll>&a){
vector <ll> v = a;
fsort2(v);return v[0];
}
ll Min(vector <ll>&a){
vector <ll> v = a;
fsort(v);return v[0];
}
ll doublefactorial(ll n){
for(ll i = 1;i<n;i+=2){
n*=i;n%=MODULO;
}
return n%MODULO;
}
/*
1 2
3 4
5 6
00 00
01 10
02 20
03 30
04 40
05 50
10 01
11 11
12 21
13 31
14 41
15 51
20 02
21 12
22 22
23 32
*/
vector <string> strsegments(string s){
vector <string> f;
map <string ,bool> used;
ll n = s.size();
lp(0,n){
jp(1,n+1){
string temp = s.substr(i,j);
if(!used[temp]){
f.pb(temp);used[temp] = true;
}
}
}
return f;
}
ll vectorxor(vector <ll>&a){
ll z = 0;
lp(0,a.size()){
z = z^a[i];
}
return z;
}
bool square(ll n){
ll z = sqrt(n);
if(z*z == n){
return true;
}return false;
}
bool equal(vector <ll> a){
set <ll> s;
lp(0,a.size()){
s.ins(a[i]);
}
if(s.size() == 1){
return true;
}return false;
}
ll dignum(ll a){
ll cnt = 0;
while(a!=0){
a/=10;cnt++;
}
return cnt;
}
ll power10(ll a){
return pow(10,a);
}
ll allneg(vector <ll> a){
bool flag = true;
lp(0,a.size()){
if(a[i] > 0){
flag = false;break;
}
}
if(flag){
return true;
}
return false;
}
ll takes(ll a, ll m){
ll cnt = 0;
while(a>0){
a-=m;cnt++;
}
return cnt;
}
string strlcm(string x,string y){
string z = x,d = y;
while(z.size()!=d.size()){
if(z.size() < d.size()){
z+=x;
}
else{
d+=y;
}
}
if(z == d){
return z;
}
return "-1";
}
vector <ll> sieve2(ll z){
vector <ll> a(z+1,0);
for(ll i=2; i<=z; i++)
{
if(a[i]==0)
{
for(ll j=2; i*j<=z; j++)
{
a[i*j]=1;
}
}
}
return a;
}
bool isin(vector <ll> a,ll n){
bool z = false;ll l = 0,r = a.size()-1, mid;
while(r>=l){
mid = (l+r)/2;if(a[mid]==n){z = true;break;}
else{
if(a[mid]<n){
l = mid+1;
}
else{
r = mid-1;
}
}
}
if(z){
return true;
}
return false;
}
/*
5 2 5
*/
string binary(ll n)
{
string s = "";
for (ll i = n-1; i >= 0; i--) {
ll k = n >> i;
if (k & 1)
s+="1";
else
s+="0";
}
ll z = 0;
lp(0,s.size()){
if(s[i] == '1'){
z = i;break;
}
}
string f = "";
lp(z,s.size()){
f+=s[i];
}
return f;
}
bool substr(string s,string c){
ll i = -1;
for(char&z : s){
i = s.find(z, i+1);
if(i == string::npos){
return false;
}
}return true;
}
bool nondeg(ll a, ll b, ll c){
if(a >= b+c || b >= a+c || c >= b+a){
return false;
}return true;
}
// 3 4 5 6 7 4
void solve(){
ll x,y,a,b;cin >> x >> y >> a >> b;
if(abs(x-y)%(a+b)){
cout<<-1<<endl;return;
}
cout<<abs(x-y) / (a+b)<<endl;
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);ll t;cin >> t;
while(t--){
solve();
}
return 0;
} | cpp |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | #ifdef LOCAL
#define _GLIBCXX_DEBUG 1
#endif
#include <bits/stdc++.h>
using namespace std;
#define sz(a) (int)((a).size())
template <class T, class V> ostream & operator << (ostream & os, pair<T, V> const& p) { return os << "{" << p.first << "," << p.second << "}"; }
template <class T, class V, class Container> basic_ostream <T, V> & operator << (basic_ostream <T, V> & os, Container const& x) { os << "\n[ "; for (auto& y : x) os << y << " "; return os << "]"; }
template <typename T> bool chmin(T &a, T b) { return (b < a) ? a = b, 1 : 0; }
template <typename T> bool chmax(T &a, T b) { return (b > a) ? a = b, 1 : 0; }
#ifdef LOCAL
void deb_out() { cerr << endl; }
template <typename Head, typename... Tail> void deb_out(Head H, Tail... T) { cerr << " " << H; deb_out(T...); }
#define deb(...) cerr << "(" << #__VA_ARGS__ << "):", deb_out(__VA_ARGS__)
#else
#define deb(...) 1
#endif
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
typedef long double ld;
void solve_test() {
int n;
cin >> n;
vector<int> a(n);
vector<int> b(n);
for (auto &x : a) {
cin >> x;
if (x)
b[x - 1]++;
}
int cntEven = 0, cntOdd = 0;
for (int i = 0; i < n; ++i) {
if (!b[i]) {
if (i & 1)
cntEven++;
else
cntOdd++;
}
}
const int INF = 2e8;
vector<vector<array<int, 2>>> dp(n + 1, vector<array<int, 2>>(cntEven + 1));
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= cntEven; ++j)
dp[i][j][0] = dp[i][j][1] = INF;
}
if (a[0]) {
dp[1][0][a[0] & 1] = 0;
} else {
if (cntEven)
dp[1][1][0] = 0;
if (cntOdd)
dp[1][0][1] = 0;
}
int left = cntEven + cntOdd;
if (!a[0])
left--;
for (int i = 2; i <= n; ++i) {
if (!a[i - 1])
left--;
for (int j = 0; j <= min(cntEven, i); ++j) {
if (a[i - 1]) {
dp[i][j][a[i - 1] & 1] = dp[i - 1][j][0] + ((a[i - 1] & 1) == 1);
chmin(dp[i][j][a[i - 1] & 1], dp[i - 1][j][1] + ((a[i - 1] & 1) == 0));
} else {
if (j) {
dp[i][j][0] = min(dp[i - 1][j - 1][0], dp[i - 1][j - 1][1] + 1);
}
if (left >= cntEven - j) {
dp[i][j][1] = min(dp[i - 1][j][0] + 1, dp[i - 1][j][1]);
}
}
}
}
int res = INF;
for (int i = 0; i <= cntEven; ++i) {
chmin(res, min(dp[n][i][0], dp[n][i][1]));
}
// deb(dp);
cout << res << '\n';
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt = 1;
// cin >> tt;
for (int i = 1; i <= tt; ++i) {
solve_test();
#ifdef LOCAL
cout << "_____________________" << endl;
#endif
}
#ifdef LOCAL
cerr << endl << "Elapsed time: " << 1. * clock() / CLOCKS_PER_SEC << '\n';
#endif
return 0;
}
| cpp |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod = 1e9 + 7;
//const int mod = 998244353;
#define PII pair<long long, long long>
#define x first
#define y second
#define pi 3.14159265359
int qpow(int a, int b)
{
int res = 1;
while (b != 0)
{
if (b & 1)res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
int _qpow(int a, int b)
{
int res = 1;
while (b != 0)
{
if (b & 1)res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
int inv(int a)
{
return qpow(a, mod - 2);
}
int exgcd(int ai, int bi, int& xi, int& yi)
{
if (bi == 0)
{
xi = 1, yi = 0;
return ai;
}
int d = exgcd(bi, ai % bi, yi, xi);
yi -= ai / bi * xi;
return d;
}
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
/*----------------------------------------------------------------------*/
void solve()
{
int n;
cin >> n;
if (n % 2 == 0)
{
for (int i = 0; i < n / 2; i++)cout << "1";
cout << "\n";
return;
}
cout << "7";
for (int i = 0; i < (n - 3) / 2; i++)cout << "1";
cout << "\n";
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tt = 1;
cin >> tt;
while (tt--)solve();
return 0;
} | cpp |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | // LUOGU_RID: 102089595
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define ppb pop_back
#define pf push_front
#define ppf pop_front
#define eb emplace_back
#define ef emplace_front
#define lowbit(x) (x & (-x))
#define ti chrono::system_clock::now().time_since_epoch().count()
#define Fin(x) freopen(x, "r", stdin)
#define Fout(x) freopen(x, "w", stdout)
#define Fio(x) Fin(x".in"), Fout(x".out");
// #define SGT
#define int long long // int main() -> signed
// #define PAIR
#define ll long long
#ifdef PAIR
#define fi first
#define se second
#endif
#ifdef SGT
#define lson (p << 1)
#define rson (p << 1 | 1)
#define mid ((l + r) >> 1)
#endif
const int maxn = 2e5 + 10;
int n, a[maxn], ans;
set<int> st;
mt19937 rnd(ti);
void solve(int x){
for(int i = 2; i * i <= x; i++) if(x % i == 0){
st.insert(i);
while(x % i == 0) x /= i;
}
if(x > 1) st.insert(x);
}
int calc(int x){
int ret = 0;
for(int i = 1; i <= n; i++){
int k = a[i] / x * x;
ret += min(k ? a[i] - k : n, k + x - a[i]);
}
return ret;
}
signed main(){
scanf("%lld", &n), ans = n;
for(int i = 1; i <= n; i++) scanf("%lld", &a[i]);
for(int _ = 1; _ <= 50; _++){
int i = rnd() % n + 1;
solve(a[i]), solve(a[i] + 1), solve(a[i] - 1);
}
for(int i : st) ans = min(ans, calc(i));
printf("%lld\n", ans);
return 0;
} | cpp |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
| [
"brute force",
"math",
"number theory"
] | #include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <cstdio>
#include <numeric>
#define nl "\n"
#define te cin >> t
#define ts to_string
#define pb push_back
#define pob pop_back
#define np next_permutation
#define rv reverse
#define inn insert
#define ff first
#define ss second
#define srt(x,y) sort((x),(x)+(y))
#define cnt(x,y,z) count((x),(x)+(y),z)
#define st for(int z=1;z<=t;z++)
#define ll long long int
#define cnt_bit(x) __builtin_popcount(x)
#define YES cout<<"YES"<<nl;
#define yes cout<<"Yes"<<nl;
#define NO cout<<"NO"<<nl;
#define no cout<<"No"<<nl;
#define forn(x) for(ll i=0;i<(x);i++)
#define pi 2*acos(0.0)
#define mod(x) ((x)%N+N)%N
#define sz(x) x.size()
#define llu long long unsigned int
#define vect(type1,name) vector<type1>name
#define full(x) x.begin(),x.end()
#define cntt(x,y) count((x).begin(),(x).end(),(y))
#define amx *max_element
#define amn *min_element
#define gcd(x,y) (ll)(__gcd(x,y))
#define lcm(x,y) (ll)((x/gcd(x,y))*y)
#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef pair<ll,ll>pr;
typedef vector<char>vc;
typedef vector<ll>vi;
typedef vector<string>vs;
typedef map<ll,ll>mp;
typedef map<char,ll>mpc;
typedef map<string,ll>mps;
typedef set<ll>si;
typedef set<char>sc;
typedef deque<ll>dq;
typedef set<string>ss;
typedef vector<pair<char,ll>>vp;
typedef unordered_set<ll>us;
typedef unordered_set<string>ust;
typedef multiset<ll>mst;
typedef multiset<string>mss;
typedef unordered_map<ll,ll>ump;
typedef unordered_map<string,ll>umps;
int dx[4] = { -1, 0, 1, 0 };
int dy[4] = { 0, 1, 0, -1 };
const ll N = 1e6;
const ll mod = 1e9+7;
//void c(ll n)
//{
// if(n==4){
// //cout <<1<<'\n';
// return;
// }
// c(n+1);
// cout <<n<< '\n';
// c(n+1);
//}
//void B_T_P(string s,ll l,ll r){
//
// if(l==r){
// str.push_back(s);
// }
// else{
// for(ll i=l;i<=r;i++){
// swap(s[l],s[i]);
// bt(s,l+1,r);
// swap(s[l],s[i]);
// }
// }
//}
//ll fact[N];
//void factorial()
//{
// ll ff=1;
// for(ll i=1;i<=N;i++)
// {
// ff*=i;
// ff%=mod;
// fact[i]=ff;
// }
//}
//bool is_prime(ll x)
//{
// for(ll i=2;i*i<=x;i++)
// {
// if(x%i==0)return 0;
// }
// return 1;
//}
//ll spf[N];
//void seive()
//{
// for(ll i=1;i<=N;i++){
// spf[i]=i;
// }
// for(ll i=2;i*i<=N;i++){
// if(spf[i]==i){
// for(ll j=i*i;j<=N;j+=i){
// if(spf[j]==j)spf[j]=i;
// }
// }
// }
//}
//ll ncr(ll c[],ll n,ll r)
//{
// for(ll i=1;i<=n;i++)
// {
// for(ll j=min(i,r);j>0;j--)
// {
// c[j]=(c[j]+c[j-1])%mod;
// }
// }
// return c[r];
//}
//ll B_E_R(ll a,ll b,ll m)
//{
// if(b==0)return 1;
// ll res=B_E_R(a,b/2,m);
// if(b&1)
// return (a*((res*1ll*res)%m)%m);
// else
// return (res*1ll*res)%m;
//}
//ll B_E_I(ll a,ll b,ll m)
//{
// ll ans=1;
// while(b)
// {
// if(b&1)
// ans=(ans*1ll*a)%m;
// a=(a*1ll*a)%m;
// b >>= 1;
// }
// return ans;
//}
void hello()
{
ll n;
cin >> n;
ll a=0,b=0;
for(ll i=1;i*i<n;i++){
if(n%i==0&&i!=n/i&&lcm(i,n/i)==n){
a=i;
b=n/i;
}
}
cout<<max(a,1LL)<<' '<<max(b,1LL)<<nl;
}
int main()
{
FIO
ll t;
//te;st
hello();
return 0;
}
| cpp |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11. | [
"graphs",
"hashing",
"math",
"number theory"
] | // LUOGU_RID: 100364926
#include<bits/stdc++.h>
#define int long long
using namespace std;
int t,n,m;
int a[500005];
int b[500005];
int mod=1e18;
struct node
{
int num,xb;
}c[500005];
bool cmp(node aa,node bb)
{
return aa.num<bb.num;
}
signed main()
{
ios::sync_with_stdio(0);
srand(time(0));
cin>>t;
while(t--)
{
cin>>n>>m;
for(int i=1;i<=n;i++) c[i].num=0;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++) b[i]=(1ll*rand()*rand()*rand()+rand())%mod;
for(int i=1;i<=m;i++)
{
int u,v;
cin>>u>>v;
c[v].num^=b[u];
c[v].xb=v;
}
sort(c+1,c+n+1,cmp);
int now=-1,sum=0;
for(int i=1;i<=n;i++)
{
if(!c[i].num) continue;
if(c[i].num==c[i-1].num) sum+=a[c[i].xb];
else
{
if(now<0) now=sum;
else now=__gcd(now,sum);
sum=a[c[i].xb];
}
}
if(now<0) now=sum;
else now=__gcd(now,sum);
cout<<now<<endl;
}
} | cpp |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
int n,t,a[105];
int main()
{
cin >> t;
while(t--){
cin >> n;
int num0 = 0;
int sum = 0;
for(int i=1; i<=n; ++i){
cin >> a[i];
sum += a[i];
if(a[i] == 0){
++num0;
}
}
int ans = 0;
if(num0 == 0 && sum != 0){
ans = 0;
} else if (num0 == 0 && sum == 0){
ans = 1;
} else if (num0 != 0){
sum += num0;
ans = num0;
num0 = 0;
if(sum == 0){
++sum;
++ans;
}
}
cout << ans << endl;
}
}
| cpp |
1286 | C2 | C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"hashing",
"interactive",
"math"
] | // Problem: C2. Madhouse (Hard version)
// Contest: Codeforces - Codeforces Round #612 (Div. 1)
// URL: https://codeforces.com/contest/1286/problem/C2
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
#define rep(i, a, b) for(int i = (a); i <= (b); i ++)
#define per(i, a, b) for(int i = (a); i >= (b); i --)
#define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt)
using namespace std;
#define eb emplace_back
string solve(int n) {
multiset<string> st;
printf("? %d %d\n", 1, n);
fflush(stdout);
rep(i, 1, n * (n + 1) / 2) {
string s; cin >> s;
sort(s.begin(), s.end());
st.insert(s);
}
if(n == 1) return (* st.begin());
printf("? %d %d\n", 2, n);
fflush(stdout);
rep(i, 1, n * (n - 1) / 2) {
string s; cin >> s;
sort(s.begin(), s.end());
st.erase(st.find(s));
}
string pre[110]; int cnt = 0;
for(string o : st) pre[++ cnt] = o;
sort(pre + 1, pre + cnt + 1, [](string x, string y) {return x.length() < y.length();});
int cnt1[30], cnt2[30];
string ans = pre[1];
rep(i, 1, n - 1) {
rep(j, 0, 25) cnt1[j] = cnt2[j] = 0;
for(auto o : pre[i]) cnt1[o - 'a'] ++;
for(auto o : pre[i + 1]) cnt2[o - 'a'] ++;
rep(j, 0, 25) if(cnt1[j] != cnt2[j]) {
ans += j + 'a';
break;
}
}
return ans;
}
int cnt[110][30];
int main() {
int n; scanf("%lld", &n);
vector<string> all;
printf("? %d %d\n", 1, n);
fflush(stdout);
rep(i, 1, n * (n + 1) / 2) {
string s; cin >> s;
all.eb(s);
}
if(n == 1) {
printf("! "); cout << * all.begin() << endl;
fflush(stdout);
return 0;
}
string ans = solve(n >> 1);
for(string o : all) {
int len = o.length();
for(char c : o) cnt[len][c - 'a'] ++;
}
if(n & 1) {
int len = (n + 1) >> 1;
rep(c, 0, 25) {
int s = cnt[len][c] - cnt[len - 1][c];
if(s) {ans += c + 'a'; break;}
}
}
per(i, n >> 1, 1) {
rep(c, 0, 25) {
int s = (cnt[i][c] - cnt[i - 1][c]);
if(i < (n + 1) / 2) s -= (cnt[i + 1][c] - cnt[i][c]);
if(s - (ans[i - 1] - 'a' == c)) {ans += c + 'a'; break;}
}
}
printf("! "); cout << ans << endl;
fflush(stdout);
return 0;
}
| cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.