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 |
---|---|---|---|---|---|
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;
void solve() {
int n;
cin >> n;
vector<int> edge(n, 0);
vector<pair<int, int> > s;
int ans[n];
for (int i = 1, u, v; i < n; i++) {
cin >> v >> u;
v--;
u--;
s.emplace_back(v, u);
edge[u]++;
edge[v]++;
}
int j = 0;
int k = n - 2;
for (int i = 0; i < n - 1; i++) {
auto [v, u] = s[i];
if (edge[v] == 1 || edge[u] == 1)
ans[i] = j++;
else
ans[i] = k--;
}
for (int i = 0; i < n - 1; i++)
cout << ans[i] << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
} | 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>
using namespace std;
typedef int64_t ll;
struct Vec {
ll x, y;
Vec(ll x = 0, ll y = 0): x(x), y(y) {}
Vec operator - (const Vec& o) const
{ return Vec(x - o.x, y - o.y); }
ll operator ^ (const Vec& o) const
{ return x * o.y - y * o.x; }
bool up() { return y > 0 or (y == 0 and x > 0); }
};
bool cmp(Vec a, Vec b) {
if (a.up() != b.up())
return a.up() > b.up();
return (a ^ b) > 0;
}
ll C(int n, int k) {
if (n < k) return 0;
ll r = 1;
for (int i = 1; i <= k; ++i) {
r *= n + 1 - i;
r /= i;
}
return r;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n;
cin >> n;
vector<Vec> pts(n);
for (auto& [x, y]: pts)
cin >> x >> y;
ll ans = 0;
vector<Vec> a;
for (int i = 0; i < n; ++i) {
a = pts;
swap(a[i], a.back());
a.pop_back();
for (Vec& v: a)
v = v - pts[i];
sort(begin(a), end(a), cmp);
for (int l = 0, r = 1; l < n-1; ++l) {
while (r < l + n-1 and (a[l] ^ a[r - (r >= n-1 ? n-1 : 0)]) >= 0) ++r;
ans += C(r - l - 1, 3);
}
}
cout << 5 * C(n, 5) - ans << '\n';
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"
] | #include "bits/stdc++.h"
using namespace std;
#define all(x) begin(x),end(x)
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = " "; return os; }
#define debug(a) cerr << "(" << #a << ": " << a << ")\n";
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> pi;
const int mxN = 1e5+1;
const ll oo = 2e18;
struct smallmap {
int to[26] = {};
int& operator[](char c) {
return to[c-'a'];
}
};
struct Int {
ll v=0;
Int& operator+=(const Int& o) {
v+=o.v;
v = min(v,oo);
return *this;
}
void unsafeAdd(const Int& o) {
v+=o.v;
}
void unsafeSub(const Int& o) {
v-=o.v;
}
Int operator+(const Int& o) {
Int res = *this;
res+=o;
return res;
}
};
int main() {
int n,m; ll k; cin >> n >> m >> k;
string s; cin >> s;
vector<smallmap> tr = {{}};
string cpar = "$";
vi par = {-1};
auto add = [&](string str) {
int at = 0;
for(auto c : str) {
if(!tr[at][c]) {
tr[at][c]=tr.size();
cpar.push_back(c);
par.push_back(at);
tr.push_back({});
}
at = tr[at][c];
}
};
for(int i=0;i<n;++i) {
add(s.substr(i));
}
vi ord;
auto dfs = [&](auto&& self, int at) -> void {
if(at!=0) ord.push_back(at);
for(int to='a';to<='z';++to) {
if(tr[at][to]) {
self(self,tr[at][to]);
}
}
};
dfs(dfs,0);
auto decode = [&](int at) {
string t;
while(at!=0) {
t.push_back(cpar[at]);
at=par[at];
}
reverse(all(t));
return t;
};
auto ways = [&](int at) {
// decode string
auto t = decode(at);
vi until(n);
for(int i=0;i<n;++i) {
int j = i;
while(j<n and j-i<(int)t.size() and t[j-i]==s[j]) ++j;
if(j-i==(int)t.size()) {
--j;
} else if(j!=n and t[j-i]>s[j]) {
j=n;
}
until[i]=j;
}
vector<Int> bad(n+1);
vector<Int> nbad(n+2);
bad[0].v=1;
for(int rep=0;rep<m;++rep) {
fill(all(nbad),Int{0});
for(int i=0;i<n;++i) {
nbad[until[i]+1]+=bad[i];
}
partial_sum(all(nbad)-1,bad.begin());
}
return bad[n];
};
int lo = 0, hi = ord.size()-1;
while(lo<hi) {
auto mid = (lo+hi+1)/2;
if(ways(ord[mid]).v>=k) {
lo = mid;
} else hi = mid-1;
}
cout << decode(ord[lo]) << '\n';
} | cpp |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111). | [
"implementation",
"strings"
] | //shenoda adel
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include<stack>
#include<queue>
#include <algorithm>
#include<set>
#include<map>
#include<iterator>
#include <vector>
#include <sstream>
#define ll long long
#define endl "\n"
#define fx(x) fixed<<setprecision(x)
#define Test int T;cin>>T;while(T--)
#define str string
#define vc vector
#define pb push_back
#define pr priority_queue
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define sz(s) int(s.size())
#define OO 2'000'000'000
using namespace std;
const double PI= 3.141592653590;
void fast() {
ios_base::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
}
// vc<vc<ll>>v(n,vc<ll>(n-1));
void solve (){
str s ;
cin>>s;
int l=0 , r=0;
for(int i=0;i<sz(s);i++) { if(s[i]=='1') l=i; }
for(int i=sz(s)-1;i>=0;i--) { if(s[i]=='1') r=i; }
cout<<count(s.begin()+r,s.begin()+l,'0')<<endl;
//cout<<l<<" "<<r<<endl;
}
int main()
{
fast();
//freopen("flips.in", "r", stdin);
//freopen("a.in","w" ,stdout);
Test{
solve();
}
return 0;
} | 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 <iostream>
#include <vector>
using namespace std;
int gcd(int a, int b) {
if(b==0){
return a;
}
else{
return gcd(b, a % b);
}
}
int main(){
int a;
int tmp;
int sum;
int n = 0;
cin >> a;
int d = a - 2;
vector<int> base;
vector<int> sums;
for (int i = 2; i < a; i++) {
tmp = a;
sum = 0;
while (tmp > 0) {
base.push_back(tmp % i);
tmp = tmp / i;
}
for (int j = 0; j < base.size(); j++) {
sum += base[j];
}
sums.push_back(sum);
base.clear();
}
for (int k = 0; k < sums.size(); k++) {
n += sums[k];
}
int g = gcd(n,d);
n = n /g;
d = d /g;
cout << n << "/" << d;
return 0;
}
| cpp |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
| [
"constructive algorithms",
"sortings"
] | #include<bits/stdc++.h>
#define ll long long
#define fr(i,a,b) for(int i = a ; i < b ; i++)
#define read(x) int x ; cin>>x
#define yy cout<<"YES"<<endl;
#define nn cout<<"NO"<<endl;
using namespace std;
void init_code(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main(){
init_code();
read(t);
while(t--){
read(n);
int a[n];
fr(i,0,n){
cin>>a[i];
}
sort(a,a+n,greater<int>());
fr(i,0,n){
cout<<a[i]<<" ";
}
cout<<endl;
}
return 0;
}
| cpp |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
int n, u, v;
cin >> n;
vector<vector<int>> tree(n + 1);
int color[n + 1];
int ans[n + 1];
int dp[n + 1];
for (int i = 1; i <= n; ++i) {
cin >> color[i];
if (color[i] == 0) color[i] = -1;
}
for (int i = 0; i < n - 1; ++i) {
cin >> u >> v;
tree[u].push_back(v);
tree[v].push_back(u);
}
function<void(int, int)> dfs = [&](int u, int p) -> void {
dp[u] = color[u];
for (int v : tree[u]) {
if (v != p) {
dfs(v, u);
dp[u] += max(dp[v], 0);
}
}
};
dfs(1, 0);
function<void(int, int)> dfs2 = [&](int u, int p) -> void {
ans[u] = dp[u];
for (int v : tree[u]) {
if (v != p) {
dp[u] -= max(0, dp[v]);
dp[v] += max(0, dp[u]);
dfs2(v, u);
dp[v] -= max(0, dp[u]);
dp[u] += max(0, dp[v]);
}
}
};
dfs2(1, 0);
for (int i = 1; i <= n; ++i) {
cout << ans[i] << ' ';
}
} | cpp |
1322 | E | E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5
1 2 1 2 1
OutputCopy2
1 1 1 1 1
InputCopy6
1 3 2 5 4 6
OutputCopy1
1 2 3 4 5 6
InputCopy6
1 1 2 2 1 1
OutputCopy0
1 1 2 2 1 1
NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00. | [
"data structures"
] | /**
* @file 1322E.cpp
* @author Macesuted ([email protected])
* @date 2023-01-06
*
* @copyright Copyright (c) 2023
*
*/
#include <bits/stdc++.h>
using namespace std;
#ifndef LOCAL
#define endl '\n'
#endif
bool mem1;
#define maxn 500005
typedef pair<int, int> pii;
int n, a[maxn], ans2[maxn];
bool v[maxn];
map<int, vector<int>> rec;
set<int> S, rest;
void update(int x) {
(x > 1 && v[x - 1] != v[x]) ? (S.erase(x), void()) : (S.insert(x), void());
(x < n && v[x] != v[x + 1]) ? (S.erase(x + 1), void()) : (S.insert(x + 1), void());
return;
}
void mark(int l, int r, int v) {
for (auto i = rest.lower_bound(l); i != rest.end() && *i <= r; i = rest.erase(i)) ans2[*i] = v;
return;
}
pii query(int x) { return {*--S.upper_bound(x), *S.upper_bound(x) - 1}; }
void solve(void) {
cin >> n;
S.insert(n + 1);
for (int i = 1; i <= n; i++) cin >> a[i], v[i] = true, rec[a[i]].push_back(i), S.insert(i), rest.insert(i);
int ans1 = 0;
for (auto &i : rec) {
for (auto j : i.second) v[j] = false;
for (auto j : i.second) update(j);
auto calc = [&](int p) {
auto [l, r] = query(p);
ans1 = max(ans1, r - l + 1);
if (!((r - l + 1) & 1))
if (!v[l])
mark(l, (l + r) / 2, i.first);
else
mark((l + r) / 2 + 1, r, i.first);
else if (!v[l])
mark(l, r, i.first);
};
for (auto j : i.second) {
if (j > 1) calc(j - 1);
calc(j);
if (j < n) calc(j + 1);
}
}
cout << (ans1 - 1) / 2 << endl;
for (int i = 1; i <= n; i++) cout << ans2[i] << ' ';
cout << endl;
return;
}
bool mem2;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
#ifdef LOCAL
cerr << "Memory Cost: " << abs(&mem1 - &mem2) / 1024. / 1024. << "MB" << endl;
#endif
int _ = 1;
while (_--) solve();
#ifdef LOCAL
cerr << "Time Cost: " << clock() * 1000. / CLOCKS_PER_SEC << "MS" << endl;
#endif
return 0;
} | cpp |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5. | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | 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;cin>>n;
int a[n+1],ans=0;repp(n)cin>>a[i+1];
vector<int> now(n);repp(n)now[i]=i+1;
vector<vector<int>> vv,temp1,temp2;
vv.push_back(now);
for(int bit=30;bit>-1;bit--){
//cout<<bit<<endl;
int f=(1LL<<bit);
bool flag=false;
for(vector<int> v:vv){
vector<int> x,y;
for(int i:v){
if(a[i]&f)x.push_back(i);
else y.push_back(i);
}
if(x.size()==0 || y.size()==0){
flag=true;
temp1.push_back(v);
}
else{
temp2.push_back(x);
temp2.push_back(y);
}
/*
cout<<"DEBUG"<<endl;
//for(vector<int> v:x){
for(int i:x)cout<<i<<" ";
//cout<<endl;
//}
cout<<endl<<endl;
cout<<"DEBUG"<<endl;
//for(vector<int> v:y){
for(int i:y)cout<<i<<" ";
//cout<<endl;
//}
cout<<endl<<endl;
*/
}
if(flag){
vv=temp1;
}
else{
ans+=f;
vv=temp2;
}
temp1.clear();
temp2.clear();
/*
cout<<"DEBUG"<<endl;
for(vector<int> v:vv){
for(int i:v)cout<<i<<" ";
cout<<endl;
}
cout<<endl<<endl;
*/
}
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 |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000
| [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
char f1, f2;
string s;
cin>>n;
cin>>s;
f1 = 'a';
f2 = 'a';
for(int i=0;i<=n-1;++i)
{
if(s[i]>=f1)
{
f1 = s[i];
s[i] = '0';
}
else if(s[i]>=f2)
{
f2 = s[i];
s[i] = '1';
}
else
{
cout<<"NO";
return 0;
}
}
cout<<"YES"<<"\n";
cout<<s<<"\n";
return 0;
} | cpp |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
#include<iostream>
#include<set>
#include<map>
#include<iterator>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
///Defines.....
#define ll long long
#define lli long long int
#define pb push_back
#define mp make_pair
#define RIP(i,n) for(ll i=0; i<n; i++)
#define F(i,a,b) for(int i=a; i<b; i++)
#define RIP1(i,n) for(int i=(n-1); i>=0; i--)
#define FOR(i,a,b) for(int i=a;i<(b); i++)
#define FOR1(i,a,b) for(int i=a; i>=(b); i--)
#define sc(a) scanf("%lld",&a)
#define SC(a) scanf("%d",&a)
#define cin(a) cin >> a
#define cout(a) cout << a
#define PI acos(-1)
#define pr(a) printf("%lld\n",a)
#define PR(a) printf("%lld ",a)
#define s(a,b) sort(a,b)
#define nl '\n'
using namespace std;
using namespace __gnu_pbds;
//#define ordered_set tree<pair<int,int>, null_type,less<pair<int,int>>, rb_tree_tag,tree_order_statistics_node_update>
typedef tree<ll, null_type, less_equal<ll>, rb_tree_tag,tree_order_statistics_node_update> ordered_set;
///Constants........
const ll mod = 1e9 + 7;
const ll Max = 1e6+5;
const ll inf = 2e18+5;
///Chess moves.........
int dx[] = {+0, +0, -1, +1}; ///Up-down, Left-Right
int dy[] = {+1, -1, +0, +0};
// int dx[] = {+0,+0,+1,-1,-1,+1,-1,+1}; ///King's Move
// int dy[] = {-1,+1,+0,+0,+1,+1,-1,-1};
// int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2}; ///Knight's Move
// int dy[] = {-1, 1, -2, 2, -2, 2, -1, 1};
inline void norm(ll &a) {a%=mod; (a<0) && (a+=mod) ;}
inline ll modAdd(ll a,ll b) {a%=mod, b%=mod; norm(a),norm(b); return (a+b)%mod;}
inline ll modSub(ll a,ll b) {a%=mod, b%=mod; norm(a),norm(b); return (a-b)%mod;}
inline ll modMul(ll a,ll b) {a%=mod, b%=mod; norm(a),norm(b); return (a*b)%mod;}
///Functions..........
ll bigmod(ll a, ll p, ll M)
{
p %= (M-1);
ll result = 1LL;
while(p>0LL){
if(p&1LL) result = result * a % M;
a = a * a % M;
p>>=1LL;
}
return result;
}
ll gcd(ll a, ll b){ while (b){ a %= b; swap(a, b);} return a;}
ll lcm(ll a, ll b){ return (a/gcd(a, b)*b);}
ll inverse(ll a, ll M){
if(gcd(a, M)==1) return bigmod(a, M-2, M) % M;
return 1;
}
ll ncr(ll a, ll b){ ll x = max(a-b, b), ans=1; for(ll K=a, L=1; K>=x+1; K--, L++){ ans = ans * K % mod; ans = ans * inverse(L, mod) % mod;} return ans;}
void Fast_IO()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
///*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* WELCOME TO BATTLEFIELD *=*=*=*=*=**=*=*==*=*=*=*=*==*=*///
///*==============================================================================================*///
int main() {
Fast_IO();
/*#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif*/
int t=1;
cin >> t;
while(t--)
{
ll n,a,b;
cin >> n >> a >> b;
ll p = a+b+1;
ll q = p-n;
ll e = n-q+1;
if(q <= a || q <= b) e--;
cout << max(1ll,n-e) << ' ';
cout << min(a+b-1ll,n) << nl;
}
///...............................................................................///
}
| cpp |
1301 | E | E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105) — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray. | [
"binary search",
"data structures",
"dp",
"implementation"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
const int INF=505;
int n,m,q;
char a[INF][INF];
mt19937 rnd(chrono::system_clock().now().time_since_epoch().count());
int gen(int l,int r) {return rnd()%(r-l+1);}
int vis[INF],p[INF],b[INF][INF],ans[INF][INF];
int f[INF][INF][13][13];
int Get(int x,int y,int xx,int yy) {
// cout<<x<<" "<<y<<" "<<xx<<" "<<yy<<" qweijqwej\n";
return b[xx][yy]-b[x][yy]-b[xx][y]+b[x][y];
}
int solve2(int l,int r,int ll,int rr) {
if (ll-l+1<2) return 0;
if (rr-r+1<2) return 0;
if (l<1 || r<1 || ll>n || rr>m) return 0;
for (int i=0;i<=5;i++) vis[i]=0;
int Mid1=(l+ll)>>1,Mid2=(r+rr)>>1;
int kk=Get(l-1,r-1,Mid1,Mid2);
for (int i=0;i<=0;i++)
if (kk%p[i]==0) {vis[i]++;break;}
kk=Get(Mid1,r-1,ll,Mid2);
for (int i=2;i<=2;i++)
if (kk%p[i]==0) {vis[i]++;break;}
kk=Get(Mid1,Mid2,ll,rr);
for (int i=3;i<=3;i++)
if (kk%p[i]==0) {vis[i]++;break;}
kk=Get(l-1,Mid2,Mid1,rr);
for (int i=1;i<=1;i++)
if (kk%p[i]==0) {vis[i]++;break;}
for (int i=0;i<4;i++)
if (vis[i]!=1) return 0;
return 1;
}
int query(int l,int r,int ll,int rr) {
if (l>ll || r>rr) return -1e9;
int xx=__lg(ll-l+1),yy=__lg(rr-r+1);
return max({f[l][r][xx][yy],f[ll-(1ll<<xx)+1][r][xx][yy],
f[l][rr-(1ll<<yy)+1][xx][yy],f[ll-(1ll<<xx)+1][rr-(1ll<<yy)+1][xx][yy]});
}
signed main()
{
ios::sync_with_stdio(false);
cin>>n>>m>>q;
for (int i=0;i<4;i++) p[i]=rnd();
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++) {
cin>>a[i][j];
if (a[i][j]=='R') b[i][j]=p[0];
else if (a[i][j]=='G') b[i][j]=p[1];
else if (a[i][j]=='Y') b[i][j]=p[2];
else b[i][j]=p[3];
}
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
b[i][j]+=b[i-1][j]+b[i][j-1]-b[i-1][j-1];
for (int i=1;i<=n;i++) {
for (int j=1;j<=m;j++) {
int l=1,r=min(n,m),ans2=0;
while (l<=r) {
int Mid=(l+r)>>1;
if (solve2(i-Mid+1,j-Mid+1,i+Mid,j+Mid)) l=(ans2=Mid)+1;
else r=Mid-1;
}
ans[i][j]=ans2;
f[i][j][0][0]=ans2;
}
}
for (int i=1;i<21;i++) {
if ((1ll<<i)>n) break;
for (int j=1;j+(1ll<<i)-1<=n;j++)
for (int k=1;k<=m;k++)
f[j][k][i][0]=max(f[j][k][i-1][0],f[j+(1ll<<(i-1))][k][i-1][0]);
}
for (int i=1;i<21;i++) {
if ((1ll<<i)>m) break;
for (int j=1;j<=n;j++)
for (int k=1;k+(1ll<<i)-1<=m;k++)
f[j][k][0][i]=max(f[j][k][0][i-1],f[j][k+(1<<(i-1))][0][i-1]);
}
for (int i=1;i<21;i++) {
if ((1ll<<i)>n) break;
for (int p=1;p<21;p++) {
if ((1ll<<p)>m) break;
for (int j=1;j+(1ll<<i)-1<=n;j++) {
for (int k=1;k+(1ll<<p)-1<=m;k++) {
f[j][k][i][p]=max({f[j][k][i-1][p-1],f[j+(1ll<<(i-1))][k][i-1][p-1],
f[j][k+(1ll<<(p-1))][i-1][p-1],f[j+(1ll<<(i-1))][k+(1ll<<(p-1))][i-1][p-1]});
}
}
}
}
for (int i=1;i<=q;i++) {
int x=0,y=0,xx=0,yy=0;
cin>>x>>y>>xx>>yy;
int l=1,r=min(yy-y+1,xx-x+1),ans2=-1;
while (l<=r) {
int Mid=(l+r)>>1;
if (query(x+Mid-1,y+Mid-1,xx-Mid,yy-Mid)>=Mid) l=(ans2=Mid)+1;
else r=Mid-1;
}
if (ans2==-1) cout<<"0\n";
else cout<<ans2*ans2*4<<"\n";
}
return 0;
} | cpp |
13 | C | C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1 | [
"dp",
"sortings"
] | #include<iostream>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<queue>
#include<string>
using namespace std;
#define int long long int
#define MAXN 105
#define nd second
#define st first
#define pb push_back
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL)
typedef vector<int> vi;
typedef vector<vi> vivi;
typedef pair<int, int> pii;
int n,ans,arr[5005],dp[2][5005],ar[5005];
signed main(){
cin >> n;
for(int i=1;i<=n;i++){
cin >> arr[i];
ar[i]=arr[i];
}
sort(ar+1,ar+n+1);
for(int i=1;i<=n;i++){
dp[1][i]=max(arr[1]-ar[i],0ll);
// cout << dp[1][i] << ' ';
}
// cout << endl;
dp[1][0]=1e18;
dp[0][0]=1e18;
for(int i=2;i<=n;i++){
for(int j=1;j<=n;j++){
if(i%2){
dp[1][j]=min(dp[0][j]+abs(arr[i]-ar[j]),dp[1][j-1]);
// cout << dp[1][j] << ' ';
}
else{
dp[0][j]=min(dp[1][j]+abs(arr[i]-ar[j]),dp[0][j-1]);
// cout << dp[0][j] << ' ';
}
}
// cout << endl;
}
cout << dp[n%2][n] << endl;
}
| cpp |
1322 | F | F. Assigning Farestime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMayor of city M. decided to launch several new metro lines during 2020. Since the city has a very limited budget; it was decided not to dig new tunnels but to use the existing underground network.The tunnel system of the city M. consists of nn metro stations. The stations are connected with n−1n−1 bidirectional tunnels. Between every two stations vv and uu there is exactly one simple path. Each metro line the mayor wants to create is a simple path between stations aiai and bibi. Metro lines can intersects freely, that is, they can share common stations or even common tunnels. However, it's not yet decided which of two directions each line will go. More precisely, between the stations aiai and bibi the trains will go either from aiai to bibi, or from bibi to aiai, but not simultaneously.The city MM uses complicated faring rules. Each station is assigned with a positive integer cici — the fare zone of the station. The cost of travel from vv to uu is defined as cu−cvcu−cv roubles. Of course, such travel only allowed in case there is a metro line, the trains on which go from vv to uu. Mayor doesn't want to have any travels with a negative cost, so it was decided to assign directions of metro lines and station fare zones in such a way, that fare zones are strictly increasing during any travel on any metro line.Mayor wants firstly assign each station a fare zone and then choose a lines direction, such that all fare zones are increasing along any line. In connection with the approaching celebration of the day of the city, the mayor wants to assign fare zones so that the maximum cici will be as low as possible. Please help mayor to design a new assignment or determine if it's impossible to do. Please note that you only need to assign the fare zones optimally, you don't need to print lines' directions. This way, you solution will be considered correct if there will be a way to assign directions of every metro line, so that the fare zones will be strictly increasing along any movement of the trains.InputThe first line contains an integers nn, mm (2≤n,≤500000, 1≤m≤5000002≤n,≤500000, 1≤m≤500000) — the number of stations in the city and the number of metro lines.Each of the following n−1n−1 lines describes another metro tunnel. Each tunnel is described with integers vivi, uiui (1≤vi, ui≤n1≤vi, ui≤n, vi≠uivi≠ui). It's guaranteed, that there is exactly one simple path between any two stations.Each of the following mm lines describes another metro line. Each line is described with integers aiai, bibi (1≤ai, bi≤n1≤ai, bi≤n, ai≠biai≠bi).OutputIn the first line print integer kk — the maximum fare zone used.In the next line print integers c1,c2,…,cnc1,c2,…,cn (1≤ci≤k1≤ci≤k) — stations' fare zones. In case there are several possible answers, print any of them. In case it's impossible to assign fare zones, print "-1".ExamplesInputCopy3 1
1 2
2 3
1 3
OutputCopy3
1 2 3
InputCopy4 3
1 2
1 3
1 4
2 3
2 4
3 4
OutputCopy-1
InputCopy7 5
3 4
4 2
2 5
5 1
2 6
4 7
1 3
6 7
3 7
2 1
3 6
OutputCopy-1
NoteIn the first example; line 1→31→3 goes through the stations 1, 2, 3 in this order. In this order the fare zones of the stations are increasing. Since this line has 3 stations, at least three fare zones are needed. So the answer 1, 2, 3 is optimal.In the second example, it's impossible to assign fare zones to be consistent with a metro lines. | [
"dp",
"trees"
] | #include<bits/stdc++.h>
#define R(i,a,b) for(int i=(a),i##E=(b);i<=i##E;i++)
#define L(i,a,b) for(int i=(b),i##E=(a);i>=i##E;i--)
using namespace std;
int n,m;
vector<int>e[555555];
inline void ns()
{
cout<<"-1"<<endl;
exit(0);
}
struct dsu
{
int fa[555555];
bool v[555555];
inline void clear()
{
R(i,1,n) fa[i]=i,v[i]=0;
}
int fnd(int x)
{
if(x==fa[x]) return x;
int f=fa[x];
fa[x]=fnd(fa[x]);
v[x]^=v[f];
return fa[x];
}
inline void mrg(int x,int y,int k)
{
//printf("mrg: x:%d y:%d k:%d\n",x,y,k);
int fx=fnd(x),fy=fnd(y),t=v[x]^v[y]^k;
if(fx==fy)
{
if(t) ns();
}
else fa[fx]=fy,v[fx]=t;
}
}dsu;
struct tree
{
int hson[555555],htop[555555],dfn[555555],pos[555555],tim;
int siz[555555],dep[555555],fa[555555];
int v[555555],vv[555555];
void dfs1(int u,int f)
{
siz[u]=1;
int mx=-1;
for(int v:e[u]) if(v^f)
{
fa[v]=u;dep[v]=dep[u]+1;
dfs1(v,u);
siz[u]+=siz[v];
if(siz[v]>mx) hson[u]=v,mx=siz[v];
}
}
void dfs2(int u,int topf)
{
dfn[u]=++tim;
pos[tim]=u;
htop[u]=topf;
if(!hson[u]) return;
dfs2(hson[u],topf);
//printf("u:%d hson:%d\n",u,hson[u]);
for(int v:e[u]) if(v^fa[u]&&v^hson[u]) dfs2(v,v);
}
inline int LCA(int x,int y)
{
while(htop[x]^htop[y])
{
if(dep[htop[x]]<dep[htop[y]]) swap(x,y);
x=fa[htop[x]];
}
return dep[x]<dep[y]?x:y;
}
int jmp(int x,int y)
{
while(1)
{
if(dep[htop[x]]<=dep[y]) return pos[dfn[y]+1];
if(dep[htop[x]]==dep[y]+1) return htop[x];
x=fa[htop[x]];
}
assert(0);
}
void ins(int x,int y)
{
int l_a=LCA(x,y);
++v[x],++v[y],v[l_a]-=2;
//printf("x:%d y:%d l_a:%d\n",x,y,l_a);
if(x^l_a) ++vv[x],--vv[x=jmp(x,l_a)];
if(y^l_a) ++vv[y],--vv[y=jmp(y,l_a)];
if((x^l_a)&&(y^l_a)) dsu.mrg(x,y,1);
}
void mian()
{
L(i,1,n)
{
int x=pos[i];
v[fa[x]]+=v[x],vv[fa[x]]+=vv[x];
if(vv[x]) dsu.mrg(x,fa[x],0);
}
}
}tr;
int vis[555555],tim;
int dp[555555];
int vl[555555],vr[555555];
int rev[555555],s[555555];
inline int check(int k)
{
deque<int>q;
L(i,1,n)
{
int u=tr.pos[i],f=tr.fa[u];
int l=0,r=0;
++tim;
for(int v:e[u]) if(v^f&&tr.v[v])
{
int fv=dsu.fa[v];
if(vis[fv]!=tim) vis[fv]=tim,vl[fv]=vr[fv]=0,q.emplace_back(fv);
if(!dsu.v[v]) vl[fv]=max(vl[fv],dp[v]);
else vr[fv]=max(vr[fv],dp[v]);
}
int fv=dsu.fa[u];
if(vis[fv]==tim)
{
l=vl[fv],r=vr[fv];
if(dsu.v[u]) swap(l,r);
}
int mn=0,mx=0;
while(q.size())
{
int x=q.front();
q.pop_front();
if(x!=fv)
{
if(vl[x]>vr[x]) swap(vl[x],vr[x]);
mn=max(mn,vl[x]),mx=max(mx,vr[x]);
}
}
if(max(mn,min(l,r))+max(mx,max(l,r))>=k) return 0;
dp[u]=(max(mn,l)+max(mx,r)>=k?max(mx,l):max(mn,l))+1;
}
return 1;
}
void solve(int k)
{
deque<int>q;
R(i,1,n)
{
int u=tr.pos[i],f=tr.fa[u];
++tim;
for(int v:e[u]) if(v^f&&tr.v[v])
{
int fv=dsu.fa[v];
if(vis[fv]!=tim) vis[fv]=tim,vl[fv]=vr[fv]=0,q.emplace_back(fv);
if(!dsu.v[v]) vl[fv]=max(vl[fv],dp[v]);
else vr[fv]=max(vr[fv],dp[v]);
}
while(q.size())
{
int x=q.front();
q.pop_front();
s[x]=rev[u];
if(x!=dsu.fa[u]) s[x]^=((vl[x]>=dp[u])||(vr[x]+dp[u]>k));
else s[x]^=dsu.v[u];
}
for(int v:e[u]) if(v^f&&tr.v[v]) rev[v]=s[dsu.fa[v]]^dsu.v[v];
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cin>>n>>m;
R(i,1,n-1)
{
int x,y;
cin>>x>>y;
e[x].emplace_back(y),e[y].emplace_back(x);
}
dsu.clear();tr.dfs1(1,0);tr.dfs2(1,1);
R(i,1,m)
{
int x,y;
cin>>x>>y;
tr.ins(x,y);
}
tr.mian();
R(i,1,n) dsu.fnd(i);
int l=1,r=n,ans=0;
while(r-l>5)
{
int mid=(l+r)>>1;
if(check(mid)) ans=mid,r=mid-1;
else l=mid+1;
}
R(i,l,r) if(check(i))
{
ans=i;
break;
}
cout<<ans<<endl;
check(ans);
solve(ans);
R(i,1,n) cout<<((!rev[i])?dp[i]:ans+1-dp[i])<<" ";
cout<<endl;
} | 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;
const int maxn=600005;
const int mod=(1e9+7);
int n,m,i,j,t,k,s,ls[maxn],tls,a[maxn],b[maxn];
int pla[maxn],chg[maxn],two[maxn];
int sum[maxn<<2],cnt[maxn<<2],lef[maxn<<2],rig[maxn<<2];
inline int Pow(int x,int y)
{
int ret=1;
while (y)
{
if (y&1) ret=1ll*ret*x%mod;
x=1ll*x*x%mod;y>>=1;
}return ret;
}
inline void re_new(int rt,int v,int c)
{
if (c==0)
{
sum[rt]=lef[rt]=rig[rt]=0;cnt[rt]=1;
}
else
{
sum[rt]=v*1ll*v%mod*(c*1ll*two[c-1]%mod-two[c]+mod+1)%mod;
lef[rt]=rig[rt]=v*1ll*(two[c]-1)%mod;
cnt[rt]=two[c];
}
}
inline void pushup(int rt)
{
sum[rt]=(sum[rt<<1]*1ll*cnt[rt<<1|1]+sum[rt<<1|1]*1ll*cnt[rt<<1]+lef[rt<<1]*1ll*rig[rt<<1|1])%mod;
cnt[rt]=cnt[rt<<1]*1ll*cnt[rt<<1|1]%mod;
lef[rt]=(lef[rt<<1]+lef[rt<<1|1]*1ll*cnt[rt<<1])%mod;
rig[rt]=(rig[rt<<1|1]+rig[rt<<1]*1ll*cnt[rt<<1|1])%mod;
}
void build(int rt,int l,int r)
{
if (l==r)
{
re_new(rt,ls[r],b[r]);
return;
}
int mid=(l+r)>>1;
build(rt<<1,l,mid);build(rt<<1|1,mid+1,r);
pushup(rt);
}
void upd(int rt,int l,int r,int pl)
{
if (l==r){re_new(rt,ls[r],b[r]);return;}
int mid=(l+r)>>1;
if (pl>mid) upd(rt<<1|1,mid+1,r,pl);
else upd(rt<<1,l,mid,pl);
pushup(rt);
}
int main()
{
two[0]=1;
for (i=1;i<maxn;++i) two[i]=2*two[i-1]%mod;
scanf("%d",&n);
for (i=1;i<=n;++i) scanf("%d",&a[i]),ls[i]=a[i];
scanf("%d",&m);
for (i=1;i<=m;++i)
{
scanf("%d%d",&pla[i],&chg[i]);
ls[n+i]=chg[i];
}
sort(ls+1,ls+n+m+1);tls=1;
for (i=2;i<=n+m;++i) if (ls[i]^ls[tls]) ls[++tls]=ls[i];
for (i=1;i<=n;++i)
{
b[a[i]=lower_bound(ls+1,ls+tls+1,a[i])-ls]++;
}
build(1,1,tls);
int mul=Pow(2,mod-1-n);
printf("%lld\n",sum[1]*1ll*mul%mod);
for (i=1;i<=m;++i)
{
chg[i]=lower_bound(ls+1,ls+tls+1,chg[i])-ls;
--b[a[pla[i]]];upd(1,1,tls,a[pla[i]]);
++b[chg[i]];upd(1,1,tls,chg[i]);
a[pla[i]]=chg[i];
printf("%lld\n",sum[1]*1ll*mul%mod);
}
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"
] | // oooo
/*
har chi delet mikhad bebar ~
gitar o ba khodet nabar! ~
;Amoo_Hasan;
*/
/*
link:
*/
#include<bits/stdc++.h>
#pragma GCC optimize("O3,no-stack-protector,unroll-loops,Ofast")
#pragma GCC target("avx2,fma")
using namespace std;
typedef long long ll;
typedef long double ld;
#define Sz(x) int((x).size())
#define All(x) (x).begin(), (x).end()
#define wtf(x) cout<<#x <<" : " <<x <<endl
#define mak make_pair
//constexpr int PRI = 1000696969;
constexpr ll INF = 1e18, N = 5e5 + 10, MOD = 1e9 + 7;
void Clear();
int n, k;
char ns;
int link[N];
bool vis[N];
vector<int> vc[N];
void Add(int x) {
for(auto j : vc[x]) {
if(vis[j]) continue;
cout<<"? " <<j <<endl;
cin >>ns;
if(ns == 'Y') {
vis[j] = true;
}
}
}
void Clear() {
cout<<"R" <<endl;
}
int main() {
ios :: sync_with_stdio(0), cin.tie(0); cout.tie(0);
cin >>n >>k;
if(n == k) {
int ans_t = 0;
for(int i = 1; i <= n; i++) {
cout<<"? " <<i <<endl;
cin >>ns;
if(ns == 'N')
ans_t++;
}
cout<<"! " <<ans_t;
return 0;
}
int tim = 1;
for(int i = 1; i <= n; i += (k / 2) + (k & 1)) {
int tmp = i + (k / 2) + (k & 1);
link[tim] = i;
for(int j = i; j < tmp; j++) {
vc[tim].push_back(j);
}
tim++;
}
--tim;
for(int i = 1; i <= tim / 2; i++) {
Add(i);
int tmp = 0;
while(tmp < tim - 1) {
++tmp;
if((tmp & 1)) {
int cnt = tmp / 2 + 1;
cnt += i;
if(cnt > tim) cnt = cnt - tim;
Add(cnt);
continue;
}
int cnt = tmp / 2;
cnt = i - cnt;
if(cnt <= 0) cnt = tim + cnt;
Add(cnt);
}
Clear();
}
int ans_t = 0;
for(int i = 1; i <= n; i++) {
if(!vis[i]) ans_t++;
}
cout<<"! " <<ans_t;
}
| cpp |
1320 | E | E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1
| [
"data structures",
"dfs and similar",
"dp",
"shortest paths",
"trees"
] | #include<cstdio>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<utility>
#include<queue>
#include<stack>
#include<map>
struct edge{int x,y,d;edge(int x=0,int y=0,int d=0){this->x=x,this->y=y,this->d=d;}};
struct tree
{
std::vector<int> a[200005];
int n,rt,dep[200005],fa[200005],sz[200005],son[200005],top[200005],g[200005],cnt;
static int id[200005];
void add(int x,int y)
{
a[x].push_back(y);
a[y].push_back(x);
}
void dfs1(int v,int d)
{
sz[v]=1;dep[v]=d;son[v]=0;
for (int i=0;i<(int)a[v].size();i++)
{
int u=a[v][i];
if (u==fa[v]) continue;
fa[u]=v;
dfs1(u,d+1);
sz[v]=sz[v]+sz[u];
if (sz[son[v]]<sz[u]) son[v]=u;
}
}
void dfs2(int v,int k)
{
id[v]=++cnt;top[v]=k;
if (son[v]) dfs2(son[v],k);
for (int i=0;i<(int)a[v].size();i++)
{
int u=a[v][i];
if (u==fa[v]||u==son[v]) continue;
dfs2(u,u);
}
}
void pre(int nn,int x=1)
{
rt=x;
n=nn;cnt=0;
fa[rt]=0;
dfs1(rt,1);
dfs2(rt,rt);
}
int lca(int x,int y)
{
while (top[x]!=top[y])
{
if (dep[top[x]]<dep[top[y]]) std::swap(x,y);
x=fa[top[x]];
}
if (dep[x]<dep[y]) std::swap(x,y);
return y;
}
static int cmp(int x,int y)
{
return id[x]<id[y];
}
std::vector<edge> solve(std::vector<int> s)
{
#define rt 1
std::sort(s.begin(),s.end(),cmp);
std::vector<int> p;
std::stack<int> st;
std::vector<edge> e;
st.push(rt);p.push_back(rt);
for (int i=0;i<(int)s.size();i++)
{
int x=s[i],d=lca(st.top(),x);
if (x==rt) continue;
if (st.top()==d){st.push(x),p.push_back(x),g[x]=d;continue;}
while (!st.empty())
{
int k=st.top();st.pop();
if (st.empty()){st.push(k);st.push(x);p.push_back(x);break;}
if (dep[st.top()]<=dep[d])
{
if (st.top()==d){st.push(x),p.push_back(x),g[x]=d;break;}
g[k]=d;
g[d]=st.top(),st.push(d);p.push_back(d);
g[x]=d,st.push(x),p.push_back(x);
break;
}
}
}
for (int i=0;i<(int)p.size();i++) if (p[i]!=rt) e.push_back(edge(p[i],g[p[i]],dep[p[i]]-dep[g[p[i]]]));
for (int i=0;i<(int)p.size();i++) g[p[i]]=0;
return e;
#undef rt
}
};
int tree::id[200005];
struct graph
{
struct edge
{
int to,w;
edge(int to=0,int w=0){this->to=to,this->w=w;}
};
struct node
{
int t,c,d,s;
node(int t=0,int c=0,int d=0,int s=0){this->t=t,this->c=c,this->d=d,this->s=s;}
int operator >(node x)
{
if (t!=x.t) return t>x.t;
if (c!=x.c) return c>x.c;
return s>x.s;
}
int operator <(node x)
{
if (t!=x.t) return t<x.t;
if (c!=x.c) return c<x.c;
return s<x.s;
}
node operator -()
{
node ret=*this;
ret.t=-ret.t;
return ret;
}
node operator +(int w)
{
node ret=*this;
ret.d=ret.d+w;
ret.t=(ret.d-1)/ret.s+1;
return ret;
}
};
int n,vis[200005];
node dis[200005];
std::vector<edge> a[200005];
struct cmp
{
int operator()(std::pair<node,int> x,std::pair<node,int> y){return x.first>y.first;}
};
std::priority_queue< std::pair<node,int>,std::vector< std::pair<node,int> >,cmp > pq;
void add(int x,int y,int s){a[x].push_back(edge(y,s));a[y].push_back(edge(x,s));}
void make(int x,int c,int s){dis[x]=node(0,c,0,s);pq.push(std::make_pair(dis[x],x));}
void dijkstra()
{
while (!pq.empty())
{
int v=pq.top().second;pq.pop();
if (vis[v]) continue;vis[v]=1;
for (int i=0;i<(int)a[v].size();i++)
{
int u=a[v][i].to,w=a[v][i].w;
if (dis[v]+w<dis[u]) dis[u]=dis[v]+w,pq.push(std::make_pair(dis[u],u));
}
}
while (!pq.empty()) pq.pop();
}
void clear(int s)
{
dis[s]=node(1000000000,-1,-1,-1);
vis[s]=0;
a[s].clear();
}
void pre(int n)
{
this->n=n;
for (int i=1;i<=n;i++) dis[i]=node(1000000000,-1,-1,-1);
}
};
graph g;
tree t;
int n,q,pt[200005],p[200005],d[200005];
std::map<int,int> mp;
int main()
{
scanf("%d",&n);
for (int i=1;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
t.add(x,y);
}
t.pre(n);
g.pre(n);
scanf("%d",&q);
while (q--)
{
std::vector<int> vec,used;
int m,s;
scanf("%d%d",&m,&s);
for (int i=1;i<=m;i++)
{
scanf("%d%d",&p[i],&d[i]);
if (!mp[p[i]]) mp[p[i]]=1,vec.push_back(p[i]);
}
for (int i=1;i<=s;i++)
{
scanf("%d",&pt[i]);
if (!mp[pt[i]]) mp[pt[i]]=1,vec.push_back(pt[i]);
}
std::vector<edge> e=t.solve(vec);
used.push_back(1);
for (int i=0;i<(int)e.size();i++)
{
int x=e[i].x,y=e[i].y,d=e[i].d;
used.push_back(x);
used.push_back(y);
g.add(x,y,d);
}
for (int i=1;i<=m;i++) g.make(p[i],i,d[i]);
g.dijkstra();
for (int i=1;i<=s;i++) printf("%d ",g.dis[pt[i]].c);puts("");
for (int i=0;i<(int)used.size();i++) g.clear(used[i]);
for (int i=1;i<=m;i++) p[i]=d[i]=0;
for (int i=1;i<=s;i++) pt[i]=0;
mp.clear();
}
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<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=1e5+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 h[N],e[M],ne[M],idx;
PII vec[N];
void add(int a,int b) {
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void solve() {
n=read();
memset(h,-1,sizeof h);
for(int i=1;i<n;i++) {
int a=read(),b=read();
vec[i]={a,b};
add(a,b),add(b,a);
}
map<int,map<int,int> > st;
int last=1;
bool flag=false;
for(int i=1;i<=n;i++) {
int cnt=0;
for(int j=h[i];j!=-1;j=ne[j]) cnt++;
if(cnt>=3) {
flag=true;
for(int j=h[i];j!=-1;j=ne[j]) {
int k=e[j];
st[i][k]=st[k][i]=last++;
}
break;
}
}
if(!flag) for(int i=0;i<=n-2;i++) printf("%d\n",i);
else {
for(int i=1;i<n;i++) {
if(st[vec[i].fi][vec[i].se]!=0) printf("%d\n",st[vec[i].fi][vec[i].se]-1);
else printf("%d\n",last-1),last++;
}
}
}
int main() {
// init();
// stin();
// scanf("%d",&T);
T=1;
while(T--) solve();
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"
] | // Problem: B. Collecting Packages
// Contest: Codeforces - Codeforces Round #615 (Div. 3)
// URL: https://codeforces.com/problemset/problem/1294/B
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <iostream>
#include <bits/stdc++.h>
#include <numeric>
#define int long long
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define haa cout<<"YES"
#define naa cout<<"NO"
#define po <<"\n";
#define pb emplace_back
#define pof pop_front
#define pob pob_back
#define all(a) a.begin(), a.end()
using namespace std;
signed main(){
fast
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<pair<int,int>> v(n+1);
for(int i=1;i<=n;i++){
cin>>v[i].first>>v[i].second;
}
sort(all(v));
int f=0;
for(int i=2;i<=n;i++){
if(v[i-1].first>v[i].first){
f=1;
}else if(v[i-1].second>v[i].second){
f=1;
}
}
if(f==1){
naa po
continue;
}else{
haa po
}
// for(auto it : v){
// cout<<it.first<<" "<<it.second po
// }
string s="";
for(int i=1;i<=n;i++){
int x=v[i].first-v[i-1].first;
int y=v[i].second-v[i-1].second;
for(int j=0;j<x;j++){
s+='R';
}
for(int k=0;k<y;k++){
s+='U';
}
}
cout<<s po
}
} | cpp |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample: | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
int const M=200200;struct node{int to,next;}node[M<<1];
int i,n,m,u,v,num,B,dep[M],head[M];bool flag[M];vector<int> f,Ans;
int read(){
int x=0;char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
return x;
}
void addedge(int u,int v){node[++num]={v,head[u]};head[u]=num;}
void dfs(int x){
f.push_back(x);dep[x]=f.size();
for (int v,i=head[x];i;i=node[i].next){
if (!dep[v=node[i].to]) dfs(v);
else if (dep[x]-dep[v]+1>=B){
printf("2\n%d\n",dep[x]-dep[v]+1);
for (int i=dep[v]-1;i<dep[x];i++) printf("%d ",f[i]);
exit(0);
}
}
if (!flag[x]){
Ans.push_back(x);
for (int i=head[x];i;i=node[i].next)
flag[node[i].to]=1;
}
f.pop_back();
}
int main(){
n=read();m=read();B=ceil(sqrt(n));
for (i=1;i<=m;i++)
u=read(),v=read(),
addedge(u,v),addedge(v,u); dfs(1);puts("1");
for (i=0;i<B;i++) printf("%d ",Ans[i]);
return 0;
} | cpp |
1320 | E | E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1
| [
"data structures",
"dfs and similar",
"dp",
"shortest paths",
"trees"
] | #include<bits/stdc++.h>
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
typedef pair<int, int> pii;
#define mp make_pair
#define fi first
#define se second
inline int read() {
int x = 0, f = 1; char c = getchar();
while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar();
while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar();
return x * f;
}
const int N = 2e5 + 10;
const int inf = 1e9 + 10;
int n, q;
vector<int> g[N], h[N];
int par[N], dep[N], siz[N], son[N];
void dfs1(int u, int fa) {
dep[u] = dep[par[u] = fa] + (siz[u] = 1);
for(int v : g[u]) if(v != fa) {
dfs1(v, u);
siz[u] += siz[v];
if(!son[u] || siz[v] > siz[son[u]]) son[u] = v;
}
}
int tim, top[N], dfn[N];
void dfs2(int u, int tp) {
top[u] = tp, dfn[u] = ++ tim;
if(son[u]) dfs2(son[u], tp);
for(int v : g[u]) if(v != par[u] && v != son[u]) dfs2(v, v);
}
int getlca(int x, int y) {
while(top[x] != top[y]) {
if(dep[top[x]] < dep[top[y]]) swap(x, y);
x = par[top[x]];
}
return dep[x] < dep[y] ? x : y;
}
int k, s[N], c[N], m, t[N], stk[N], tot;
vector<int> arc;
void add(int u, int v) {
// cerr << "addedge " << u << ' ' << v << endl;
h[u].eb(v), h[v].eb(u);
}
void build() {
sort(arc.begin(), arc.end(), [](int x, int y) {return dfn[x] < dfn[y];});
arc.erase(unique(arc.begin(), arc.end()), arc.end());
vector<int> tmp = arc;
for(int o : tmp) {
if(! tot) {stk[++ tot] = o; continue;}
int cur = getlca(o, stk[tot]);
if(cur != stk[tot]) {
while(tot > 1 && dfn[stk[tot - 1]] >= dfn[cur])
add(stk[tot], stk[tot - 1]), tot --;
if(cur != stk[tot]) add(stk[tot], cur), stk[tot] = cur, arc.eb(cur);
}
stk[++ tot] = o;
}
if(tot) while(-- tot) add(stk[tot], stk[tot + 1]);
}
struct node {
int t, x, d;
bool operator < (const node &a) const {
return (t ^ a.t) ? t > a.t : ((x ^ a.x) ? x > a.x : d > a.d);
}
} dis[N];
bool vis[N];
void solve() {
for(int o : arc) dis[o] = (node) {inf, inf, inf}, vis[o] = false;
priority_queue<pair<node, int>> q;
rep(i, 1, k) {int o = s[i]; dis[o] = (node) {0, i, 0}; q.push(mp(dis[o], o));}
while(! q.empty()) {
int u = q.top().se; q.pop();
if(vis[u]) continue; else vis[u] = true;
// cerr << "dis " << u << ' ' << dis[u].t << ' ' << dis[u].x << ' ' << dis[u].d << endl;
for(int v : h[u]) {
int w = abs(dep[u] - dep[v]);
node nxt;
nxt.t = dis[u].t + (w - dis[u].d + c[dis[u].x] - 1) / c[dis[u].x];
nxt.x = dis[u].x;
nxt.d = (w > dis[u].d) ? (nxt.t - dis[u].t) * c[nxt.x] + dis[u].d - w : dis[u].d - w;
if(dis[v] < nxt) dis[v] = nxt, q.push(mp(dis[v], v));
}
}
rep(i, 1, m) printf("%d%c", dis[t[i]].x, i == m ? '\n' : ' ');
}
int main() {
n = read();
rep(i, 2, n) {int u = read(), v = read(); g[u].eb(v), g[v].eb(u);}
dfs1(1, 0), dfs2(1, 1);
q = read();
while(q --) {
k = read(), m = read();
arc.clear();
rep(i, 1, k) s[i] = read(), c[i] = read(), arc.eb(s[i]);
rep(i, 1, m) t[i] = read(), arc.eb(t[i]);
// cerr << "current " << k << ' ' << m << endl;
build(), solve();
for(int o : arc) h[o].clear();
}
return 0;
}
| cpp |
1320 | E | E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1
| [
"data structures",
"dfs and similar",
"dp",
"shortest paths",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
inline int read(){
int f=1,r=0;char c=getchar();
while(!isdigit(c))f^=c=='-',c=getchar();
while(isdigit(c))r=(r<<1)+(r<<3)+(c^48),c=getchar();
return f?r:-r;
}
#define pii pair<int,int>
#define fi first
#define se second
const int N=2e5+7;
struct Edge{int to,nxt;}e[N<<1];
int s_e,head[N];
inline void add_e(int x,int y){
e[++s_e]=(Edge){y,head[x]},head[x]=s_e;
}
int s_dfn,dfn[N],sz[N],f[N][18],dep[N];
void dfs(int x,int fa){
dfn[x]=++s_dfn,sz[x]=1,dep[x]=dep[fa]+1,f[x][0]=fa;
for(int i=1;i<=17;i++)f[x][i]=f[f[x][i-1]][i-1];
for(int i=head[x];i;i=e[i].nxt)if(e[i].to^fa)dfs(e[i].to,x),sz[x]+=sz[e[i].to];
}
inline int LCA(int x,int y){
if(x==y)return x;if(dfn[x]>dfn[y])swap(x,y);
for(int i=17;~i;i--)
if(dfn[f[y][i]]>dfn[x])y=f[y][i];
return f[y][0];
}
struct D{
int tim,dis,col,id;
bool operator <(const D &q) const {
return tim^q.tim?tim>q.tim:col>q.col;
}
}dis[N];
priority_queue<D>q;
int n,Q,m,k;
int tp,stk[N],a[N],s[N],v[N];
bool vis[N];
vector<int>d;
vector<pii>G[N];
inline void addedge(int x,int y,int w){
G[x].push_back(pii(y,w)),G[y].push_back(pii(x,w));
}
inline void work(){
k=read(),m=read();
for(int i=1;i<=k;i++)s[i]=read(),v[i]=read(),d.push_back(s[i]);
for(int i=1;i<=m;i++)a[i]=read(),d.push_back(a[i]);
for(int i=1;i<=k;i++)q.push(dis[s[i]]=D{0,0,i,s[i]});
sort(d.begin(),d.end(),[](int x,int y){return dfn[x]<dfn[y];});
for(int i=d.size()-2;~i;i--)d.push_back(LCA(d[i],d[i+1]));
sort(d.begin(),d.end(),[](int x,int y){return dfn[x]<dfn[y];});
d.erase(unique(d.begin(),d.end()),d.end()),tp=0;
for(auto x:d){
while(tp && dfn[stk[tp]]+sz[stk[tp]]-1<dfn[x])tp--;
if(tp)addedge(x,stk[tp],dep[x]-dep[stk[tp]]);stk[++tp]=x;
}
for(auto x:d)dis[x]=D{1000000000,1000000000,0,x};
for(int i=1;i<=k;i++)q.push(dis[s[i]]=D{0,0,i,s[i]});
while(!q.empty()){
int x=q.top().id,dist=q.top().dis,c=q.top().col;q.pop();
if(vis[x])continue;vis[x]=1;
for(auto i:G[x]){
int y=i.fi,di=dist+i.se;
D res=D{(di+v[c]-1)/v[c],di,c,y};
if(dis[y]<res){
dis[y]=res;
q.push(res);
}
}
}
for(int i=1;i<=m;i++)printf("%d ",dis[a[i]].col);puts("");
for(auto x:d)G[x].clear(),vis[x]=0;
d.clear();
}
int main(){
n=read();
for(int i=1;i<n;i++){
int x=read(),y=read();
add_e(x,y),add_e(y,x);
}
dfs(1,0),Q=read();
while(Q--)work();
return 0;
}
| cpp |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | [
"implementation",
"strings"
] | #include<bits/stdc++.h>
using namespace std;
const int maxn=25;
int n,m,q;
string s[maxn],t[maxn];
int main()
{
cin>>n>>m;
for(int i=0; i<n; i++)
cin>>s[i];
for(int i=0; i<m; i++)
cin>>t[i];
int q;
cin>>q;
while(q--)
{
int x;
cin>>x;
x--;
cout<<s[x%n]+t[x%m]<<endl;
}
return 0;
} | cpp |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | #pragma GCC optimize("O3,unroll-loops")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define Thank_Queue_Spiderman ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define BITS sizeof(int) * 8
#define TestCase ll T; cin >> T
int arr[1000000];
bool flag = false;
int main() {
Thank_Queue_Spiderman
int n; string s;
cin >> n >> s;
int ansL = count(s.begin(), s.end(),'L');
int ansR = count(s.begin(), s.end(),'R');
cout << ansL+ansR+1 << endl;
}
| cpp |
1322 | F | F. Assigning Farestime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMayor of city M. decided to launch several new metro lines during 2020. Since the city has a very limited budget; it was decided not to dig new tunnels but to use the existing underground network.The tunnel system of the city M. consists of nn metro stations. The stations are connected with n−1n−1 bidirectional tunnels. Between every two stations vv and uu there is exactly one simple path. Each metro line the mayor wants to create is a simple path between stations aiai and bibi. Metro lines can intersects freely, that is, they can share common stations or even common tunnels. However, it's not yet decided which of two directions each line will go. More precisely, between the stations aiai and bibi the trains will go either from aiai to bibi, or from bibi to aiai, but not simultaneously.The city MM uses complicated faring rules. Each station is assigned with a positive integer cici — the fare zone of the station. The cost of travel from vv to uu is defined as cu−cvcu−cv roubles. Of course, such travel only allowed in case there is a metro line, the trains on which go from vv to uu. Mayor doesn't want to have any travels with a negative cost, so it was decided to assign directions of metro lines and station fare zones in such a way, that fare zones are strictly increasing during any travel on any metro line.Mayor wants firstly assign each station a fare zone and then choose a lines direction, such that all fare zones are increasing along any line. In connection with the approaching celebration of the day of the city, the mayor wants to assign fare zones so that the maximum cici will be as low as possible. Please help mayor to design a new assignment or determine if it's impossible to do. Please note that you only need to assign the fare zones optimally, you don't need to print lines' directions. This way, you solution will be considered correct if there will be a way to assign directions of every metro line, so that the fare zones will be strictly increasing along any movement of the trains.InputThe first line contains an integers nn, mm (2≤n,≤500000, 1≤m≤5000002≤n,≤500000, 1≤m≤500000) — the number of stations in the city and the number of metro lines.Each of the following n−1n−1 lines describes another metro tunnel. Each tunnel is described with integers vivi, uiui (1≤vi, ui≤n1≤vi, ui≤n, vi≠uivi≠ui). It's guaranteed, that there is exactly one simple path between any two stations.Each of the following mm lines describes another metro line. Each line is described with integers aiai, bibi (1≤ai, bi≤n1≤ai, bi≤n, ai≠biai≠bi).OutputIn the first line print integer kk — the maximum fare zone used.In the next line print integers c1,c2,…,cnc1,c2,…,cn (1≤ci≤k1≤ci≤k) — stations' fare zones. In case there are several possible answers, print any of them. In case it's impossible to assign fare zones, print "-1".ExamplesInputCopy3 1
1 2
2 3
1 3
OutputCopy3
1 2 3
InputCopy4 3
1 2
1 3
1 4
2 3
2 4
3 4
OutputCopy-1
InputCopy7 5
3 4
4 2
2 5
5 1
2 6
4 7
1 3
6 7
3 7
2 1
3 6
OutputCopy-1
NoteIn the first example; line 1→31→3 goes through the stations 1, 2, 3 in this order. In this order the fare zones of the stations are increasing. Since this line has 3 stations, at least three fare zones are needed. So the answer 1, 2, 3 is optimal.In the second example, it's impossible to assign fare zones to be consistent with a metro lines. | [
"dp",
"trees"
] | #include<bits/stdc++.h>
#define R(i,a,b) for(int i=(a),i##E=(b);i<=i##E;i++)
#define L(i,a,b) for(int i=(b),i##E=(a);i>=i##E;i--)
using namespace std;
int n,m;
vector<int>e[555555];
inline void ns()
{
cout<<"-1"<<endl;
exit(0);
}
struct dsu
{
int fa[555555];
bool v[555555];
inline void clear()
{
R(i,1,n) fa[i]=i,v[i]=0;
}
int fnd(int x)
{
if(x==fa[x]) return x;
int f=fa[x];
fa[x]=fnd(fa[x]);
v[x]^=v[f];
return fa[x];
}
inline void mrg(int x,int y,int k)
{
//printf("mrg: x:%d y:%d k:%d\n",x,y,k);
int fx=fnd(x),fy=fnd(y),t=v[x]^v[y]^k;
if(fx==fy)
{
if(t) ns();
}
else fa[fx]=fy,v[fx]=t;
}
}dsu;
struct tree
{
int hson[555555],htop[555555],dfn[555555],pos[555555],tim;
int siz[555555],dep[555555],fa[555555];
int v[555555],vv[555555];
void dfs1(int u,int f)
{
siz[u]=1;
int mx=-1;
for(int v:e[u]) if(v^f)
{
fa[v]=u;dep[v]=dep[u]+1;
dfs1(v,u);
siz[u]+=siz[v];
if(siz[v]>mx) hson[u]=v,mx=siz[v];
}
}
void dfs2(int u,int topf)
{
dfn[u]=++tim;
pos[tim]=u;
htop[u]=topf;
if(!hson[u]) return;
dfs2(hson[u],topf);
//printf("u:%d hson:%d\n",u,hson[u]);
for(int v:e[u]) if(v^fa[u]&&v^hson[u]) dfs2(v,v);
}
inline int LCA(int x,int y)
{
while(htop[x]^htop[y])
{
if(dep[htop[x]]<dep[htop[y]]) swap(x,y);
x=fa[htop[x]];
}
return dep[x]<dep[y]?x:y;
}
int jmp(int x,int y)
{
while(1)
{
if(dep[htop[x]]<=dep[y]) return pos[dfn[y]+1];
if(dep[htop[x]]==dep[y]+1) return htop[x];
x=fa[htop[x]];
}
assert(0);
}
void ins(int x,int y)
{
int l_a=LCA(x,y);
++v[x],++v[y],v[l_a]-=2;
//printf("x:%d y:%d l_a:%d\n",x,y,l_a);
if(dep[x]^dep[l_a]) ++vv[x],--vv[x=jmp(x,l_a)];
if(dep[y]^dep[l_a]) ++vv[y],--vv[y=jmp(y,l_a)];
if((x^l_a)&&(y^l_a)) dsu.mrg(x,y,1);
}
void mian()
{
L(i,1,n)
{
int x=pos[i];
v[fa[x]]+=v[x],vv[fa[x]]+=vv[x];
if(vv[x]) dsu.mrg(x,fa[x],0);
}
}
}tr;
int vis[555555],tim;
int dp[555555];
int vl[555555],vr[555555];
int rev[555555],s[555555];
inline int check(int k)
{
deque<int>q;
L(i,1,n)
{
int u=tr.pos[i],f=tr.fa[u];
int l=0,r=0;
++tim;
for(int v:e[u]) if(v^f&&tr.v[v])
{
int fv=dsu.fa[v];
if(vis[fv]!=tim) vis[fv]=tim,vl[fv]=vr[fv]=0,q.emplace_back(fv);
if(!dsu.v[v]) vl[fv]=max(vl[fv],dp[v]);
else vr[fv]=max(vr[fv],dp[v]);
}
int fv=dsu.fa[u];
if(vis[fv]==tim)
{
l=vl[fv],r=vr[fv];
if(dsu.v[u]) swap(l,r);
}
int mn=0,mx=0;
while(q.size())
{
int x=q.front();
q.pop_front();
if(x!=fv)
{
if(vl[x]>vr[x]) swap(vl[x],vr[x]);
mn=max(mn,vl[x]),mx=max(mx,vr[x]);
}
}
if(max(mn,min(l,r))+max(mx,max(l,r))>=k) return 0;
dp[u]=(max(mn,l)+max(mx,r)>=k?max(mx,l):max(mn,l))+1;
}
return 1;
}
void solve(int k)
{
deque<int>q;
R(i,1,n)
{
int u=tr.pos[i],f=tr.fa[u];
++tim;
for(int v:e[u]) if(v^f&&tr.v[v])
{
int fv=dsu.fa[v];
if(vis[fv]!=tim) vis[fv]=tim,vl[fv]=vr[fv]=0,q.emplace_back(fv);
if(!dsu.v[v]) vl[fv]=max(vl[fv],dp[v]);
else vr[fv]=max(vr[fv],dp[v]);
}
while(q.size())
{
int x=q.front();
q.pop_front();
s[x]=rev[u];
if(x!=dsu.fa[u]) s[x]^=((vl[x]>=dp[u])||(vr[x]+dp[u]>k));
else s[x]^=dsu.v[u];
}
for(int v:e[u]) if(v^f&&tr.v[v]) rev[v]=s[dsu.fa[v]]^dsu.v[v];
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cin>>n>>m;
R(i,1,n-1)
{
int x,y;
cin>>x>>y;
e[x].emplace_back(y),e[y].emplace_back(x);
}
dsu.clear();tr.dfs1(1,0);tr.dfs2(1,1);
R(i,1,m)
{
int x,y;
cin>>x>>y;
tr.ins(x,y);
}
tr.mian();
R(i,1,n) dsu.fnd(i);
int l=1,r=n,ans=0;
while(r-l>5)
{
int mid=(l+r)>>1;
if(check(mid)) ans=mid,r=mid-1;
else l=mid+1;
}
R(i,l,r) if(check(i))
{
ans=i;
break;
}
cout<<ans<<endl;
check(ans);
solve(ans);
R(i,1,n) cout<<((!rev[i])?dp[i]:ans+1-dp[i])<<" ";
cout<<endl;
} | cpp |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<int> func(vector<vector<int>> &roads, int x)
{
int n = roads.size();
queue<int> q;
vector<int> dist(n, 1e9);
q.push(x);
dist[x] = 0;
while (q.size())
{
int a = q.front(); q.pop();
int d = dist[a];
for (int child : roads[a])
{
if (dist[child] < 1e9) continue;
dist[child] = d + 1;
q.push(child);
}
}
return dist;
}
// long loooooooooooooooong;
void solve(ll kkkk, ll tttt)
{
int n; cin >> n;
int x; cin >> x;
vector<int> arr(n); for (int i = 0; i < n; i++) cin >> arr[i];
sort(arr.rbegin(), arr.rend());
int ans = 1e9 + 70;
for (int i = 0; i < n; i++)
{
if (x % arr[i] == 0)
ans = min(ans, x / arr[i]);
}
int steps = x / arr[0] + 1;
steps = max(steps, 2);
cout << min(steps, ans) << endl;
}
void fast() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); }
int main()
{
fast();
// int t = 0, i = 0;
int t; cin >> t;
for (int i = 1; i <= t; i++)
solve(t, i);
return 0;
}
| cpp |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | /*
奇偶判断由来:
首先,反转次数为 cnt = n-k+1
若奇偶性相同,则 cnt 为奇数,即 s 的前 k 个字符最终是反的
若奇偶性不同,则最终还是正序的
因为一次反转等价于把前 k 个字符 reverse
*/
#include <iostream>
using namespace std;
void solve()
{
int n; cin >> n;
string s; cin >> s;
int ans = 1;
string res = s;
for(int i=2; i<=n; i++) {
string t = s.substr(i-1);
if((i&1) == (n&1)) {
for(int j=i-2; j>=0; j--) t += s[j];
} else {
for(int j=0; j<=i-2; j++) t += s[j];
}
if(t < res) {
ans = i;
res = t;
}
}
cout << res << '\n' << ans << endl;
}
int main()
{
int T;
cin >> T;
while(T--) {
solve();
}
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"
] | #pragma GCC optimize("O3,unroll-loops")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define Thank_Queue_Spiderman ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define BITS sizeof(int) * 8
#define TestCase ll T; cin >> T
int arr[1000000];
bool flag = false;
int main() {
Thank_Queue_Spiderman
TestCase;
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 << endl; continue; }
int cnt = 0;
for (char c : s) {
if ((c - '0') & 1) { cout << c; cnt++; }
if (cnt == 2) break;
}
cout << endl;
}
}
| cpp |
1299 | E | E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter 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 formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2
| [
"interactive",
"math"
] | #include<bits/stdc++.h>
#define vi std::vector<int>
#define N 805
int n;
vi V[N<<2];
int a[N<<2];
inline int qry1(int i,int l,int r,int x,int y){
printf("? %d ",(r-l+1)<<1);
for(int j=l;j<=r;j++) if(j!=i)
printf("%d %d ",V[j][0],V[j][1]);
printf("%d %d\n",x,y),fflush(stdout);
int res;
scanf("%d",&res);
return res;
}
int ans[N];
inline int qry2(int x,int y){
printf("? %d ",n-1-(std::min(x,n-1-x)<<1));
for(int i=1;i<=n;i++) if(i!=y&&(ans[i]==-1||ans[i]==x||ans[i]==n-1-x))
printf("%d ",i);
puts(""),fflush(stdout);
int res;
scanf("%d",&res);
return res;
}
inline void sch(int x){
int u=1,t=x;
while(~a[u])
u=u<<1|(a[u]^(t&1)),t>>=1;
if(V[u].size()==1)
return ans[V[u][0]]=x,void();
for(auto i:V[u]) if(qry2(x,i)){
ans[i]=x;
while(V[u].size()>1){
a[u]=0,u=u<<1|(a[u]^(t&1)),t>>=1;
if(std::find(V[u].begin(),V[u].end(),i)==V[u].end())
a[u>>1]=1,u^=1;
}
break;
}
}
int main(){
scanf("%d",&n);
V[1].resize(n),std::iota(V[1].begin(),V[1].end(),1);
int l=1,r=1;
while(1){
bool flg=0;
for(int i=l;i<=r;i++)
flg|=V[i].size()>2;
if(!flg){
for(int i=l;i<=r;i++) if(V[i].size()==2)
V[i<<1].emplace_back(V[i][0]),V[i<<1|1].emplace_back(V[i][1]);
break;
}
for(int i=l;i<=r;i++){
int x=V[i].back();
vi &A=V[i<<1],&B=V[i<<1|1];
if(V[i].size()==2){
A.emplace_back(V[i][0]),B.emplace_back(V[i][1]);
continue;
}
for(auto y:V[i]) if(y!=x)
(qry1(i,l,r,x,y)?A:B).emplace_back(y);
if(A.size()!=B.size())
(A.size()<B.size()?A:B).emplace_back(x);
else
(qry1(i,l,r,A[0],B[0])?B:A).emplace_back(x);
}
l=l<<1,r=r<<1|1;
}
memset(a,-1,sizeof(a)),memset(ans,-1,sizeof(ans));
for(int i=0;i<n/2;i++)
sch(i),sch(n-1-i);
if(ans[1]>=n/2)
for(int i=1;i<=n;i++)
ans[i]=n-1-ans[i];
printf("! ");
for(int i=1;i<=n;i++)
printf("%d ",ans[i]+1);
puts(""),fflush(stdout);
} | cpp |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111). | [
"implementation",
"strings"
] | /*
author :- sairaj
*/
#pragma GCC optimize("O1")
#include<bits/stdc++.h>
using namespace std;
#define all(a) a.begin(),a.end()
#define sortv(a) sort(all(a))
#define sortvg(a) sort(all(a),greater<>());
#define int long long
#define endl "\n"
#define SPEED {ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);}
template<class T>
void display(T a)
{
for(auto& it:a)
{
cout<<it<<" ";
cout<<endl;
}
}
void jawab()
{
string a;
cin>>a;
int flag = 0;
vector<int> b;
for(int i=0;i<a.length();i++)
{
if(a[i]=='1')
{
b.push_back(i);
}
}
int count = 0;
if(b.size()){for(int i=0;i<b.size()-1;i++)
{
count+=b[i+1]-b[i]-1;
}}
cout<<count<<endl;
}
int32_t main()
{
SPEED;
int t=1;
cin>>t;
while(t--)
{
jawab();
}
return 0;
} | cpp |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | #include <iostream>
#include <string>
using namespace std;
int main()
{
int a;
string b;
cin >> a;
cin >> b;
cout << a + 1;
return 0;
}
| cpp |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string s;
cin >> s;
int len = (int) s.size();
int pref = 0;
int suf = 0;
for (int i = 0; i < len; i++) {
suf += (s[i] == ')');
}
int cut = -1;
for (int i = 0; i <= len; i++) {
if (pref == suf) {
cut = i;
break;
}
if (s[i] == '(') {
++pref;
} else {
--suf;
}
}
vector<int> pos;
for (int i = 0; i < cut; i++) {
if (s[i] == '(') {
pos.push_back(i);
}
}
for (int i = cut; i < len; i++) {
if (s[i] == ')') {
pos.push_back(i);
}
}
if (pos.empty()) {
cout << 0 << '\n';
} else {
cout << 1 << '\n';
cout << pos.size() << '\n';
for (int i = 0; i < (int) pos.size(); i++) {
if (i > 0) cout << " ";
cout << pos[i] + 1;
}
cout << '\n';
}
return 0;
} | 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>
#define ios ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)
#define all(a) a.begin() , a.end()
#define F first
#define S second
using namespace std;
using ll = long long;
const ll N = 305 ,inf = 2e9 + 7;
const ll INF = 1e18 , mod = 1e9+7 , P = 6547;
void solve(){
ll a , b , c , ans = inf;
cin >> a >> b >> c;
ll A = a , B = b , E = c;
for(ll i = 1; i <= 2e4; i++){
ll sum = abs(i-b) , num = inf , C = 0 , D = 0;
for(ll j = i; j <= 4e4; j += i) {
num = min(num , abs(j-c));
if(abs(j-c) == num) C = j;
}
sum += num;
num = inf;
for(ll j = 1; j <= sqrt(i); j++){
if(i % j == 0) {
num = min(num , abs(j-a));
if(abs(j-a) == num) D = j;
num = min(num , abs(i/j-a));
if(abs(i/j-a) == num) D = i/j;
}
}
sum += num;
ans = min(ans , sum);
if(ans == sum){
A = D, B = i , E = C;
}
}
cout << ans <<"\n";
cout << A <<" " << B <<" " << E <<"\n";
}
signed main(){
ios;
ll t;
cin >> t;
while(t--) solve();
return 0;
} | 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 Zeoy std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0)
#define all(x) (x).begin(), (x).end()
#define int long long
#define mp make_pair
#define endl '\n'
using namespace std;
typedef unsigned long long ULL;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-9;
const int N = 1e5 + 10;
int n;
int a[N];
int stk1[N], tt1, stk2[N], tt2;
void solve()
{
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> a[i];
int ans = 0;
int pos = -1;
for (int i = 1; i <= n; ++i)
{
tt1 = tt2 = 0;
int sum = 0;
for (int j = i; j >= 1; --j)
{
if (tt1 && a[j] > stk1[tt1])
{
int t = stk1[tt1];
stk1[++tt1] = t;
sum += stk1[tt1];
}
else if (tt1 && a[j] <= stk1[tt1] || !tt1)
{
stk1[++tt1] = a[j];
sum += stk1[tt1];
}
}
for (int j = i; j <= n; ++j)
{
if (tt2 && a[j] > stk2[tt2])
{
int t = stk2[tt2];
stk2[++tt2] = t;
sum += stk2[tt2];
}
else if (tt2 && a[j] <= stk2[tt2] || !tt2)
{
stk2[++tt2] = a[j];
sum += stk2[tt2];
}
}
sum -= a[i];
if (sum > ans)
{
ans = sum;
pos = i;
}
}
tt1 = tt2 = 0;
for (int j = pos; j >= 1; --j)
{
if (tt1 && a[j] > stk1[tt1])
{
int t = stk1[tt1];
stk1[++tt1] = t;
}
else if (tt1 && a[j] <= stk1[tt1] || !tt1)
stk1[++tt1] = a[j];
}
for (int j = pos; j <= n; ++j)
{
if (tt2 && a[j] > stk2[tt2])
{
int t = stk2[tt2];
stk2[++tt2] = t;
}
else if (tt2 && a[j] <= stk2[tt2] || !tt2)
stk2[++tt2] = a[j];
}
while (tt1)
{
cout << stk1[tt1] << " ";
tt1--;
}
for (int i = 2; i <= tt2; ++i)
cout << stk2[i] << " ";
cout << endl;
}
signed main(void)
{
Zeoy;
int T = 1;
// cin >> T;
while (T--)
{
solve();
}
return 0;
}
| cpp |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | #include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const ll mod = 998244353;
const int mm = 3e5 + 10;
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int n;
cin>>n;
string a;
cin>>a;
int l=0,r=0;
for(auto i:a){
if(i=='L')l++;
else r++;
}
cout<<l+r+1;
}
| cpp |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44. | [
"brute force",
"data structures",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll MOD = 1e9 + 7;
ll ans = 0;
ll dfs(ll x, vector<vector<ll>> &roads, vector<ll> &visited)
{
if (visited[x]) return 0;
visited[x] = true;
ll depth = 0;
for (ll child : roads[x])
depth = max(depth, dfs(child, roads, visited));
ans += ++depth;
ans %= MOD;
return depth;
}
// long loooooooooooooooong;
void solve(ll kkkk, ll tttt)
{
int n, m, k; cin >> n >> m >> k;
vector<int> arr(n); for (int i = 0; i < n; i++) cin >> arr[i];
k = min(k, m - 1);
int rest = m - k - 1;
int ans = -1;
for (int i = 0; i <= k; i++)
{
int newstart = i, newend = n - 1 - (k - i);
int current = 1e9 + 5;
for (int j = 0; j <= rest; j++)
{
int s = newstart + j, e = newend - (rest - j);
int c = max(arr[s], arr[e]);
current = min(current, c);
}
ans = max(ans, current);
}
cout << ans << endl;
}
void fast() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); }
int main()
{
fast();
// int t = 0, i = 0;
int t; cin >> t;
for (int i = 1; i <= t; i++)
solve(t, i);
return 0;
}
| cpp |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
void solve()
{
int n;
cin >> n;
vector<int> a(n + 1);
set<int> st;
for(int i = 1; i <= n; i++) cin >> a[i], st.insert(i), st.insert(n + i);
vector<int> ans(2 * n + 1);
for(int i = 1; i <= n; i++) st.erase(a[i]);
for(int i = 1; i <= n; i++)
{
ans[2 * i - 1] = a[i];
auto pos = st.upper_bound(a[i]);
if(pos == st.end())
{
cout << -1 << '\n';
return ;
}
else ans[2 * i] = *pos, st.erase(pos);
}
for(int i = 1; i <= 2 * n; i++) cout << ans[i] << " ";
cout << '\n';
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while(T--) solve();
return 0;
} | cpp |
1292 | D | D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3
2 1 4
OutputCopy5
InputCopy4
3 1 4 4
OutputCopy6
InputCopy4
3 1 4 1
OutputCopy6
InputCopy5
3 1 4 1 5
OutputCopy11
NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66. | [
"dp",
"graphs",
"greedy",
"math",
"number theory",
"trees"
] | // BEGIN BOILERPLATE CODE
#include <bits/stdc++.h>
using namespace std;
#ifdef KAMIRULEZ
const bool kami_loc = true;
const long long kami_seed = 69420;
#else
const bool kami_loc = false;
const long long kami_seed = chrono::steady_clock::now().time_since_epoch().count();
#endif
const string kami_fi = "kamirulez.inp";
const string kami_fo = "kamirulez.out";
mt19937_64 kami_gen(kami_seed);
long long rand_range(long long rmin, long long rmax) {
uniform_int_distribution<long long> rdist(rmin, rmax);
return rdist(kami_gen);
}
long double rand_real(long double rmin, long double rmax) {
uniform_real_distribution<long double> rdist(rmin, rmax);
return rdist(kami_gen);
}
void file_io(string fi, string fo) {
if (fi != "" && (!kami_loc || fi == kami_fi)) {
freopen(fi.c_str(), "r", stdin);
}
if (fo != "" && (!kami_loc || fo == kami_fo)) {
freopen(fo.c_str(), "w", stdout);
}
}
void set_up() {
if (kami_loc) {
file_io(kami_fi, kami_fo);
}
ios_base::sync_with_stdio(0);
cin.tie(0);
}
void just_do_it();
void just_exec_it() {
if (kami_loc) {
auto pstart = chrono::steady_clock::now();
just_do_it();
auto pend = chrono::steady_clock::now();
long long ptime = chrono::duration_cast<chrono::milliseconds>(pend - pstart).count();
string bar(50, '=');
cout << '\n' << bar << '\n';
cout << "Time: " << ptime << " ms" << '\n';
}
else {
just_do_it();
}
}
int main() {
set_up();
just_exec_it();
return 0;
}
// END BOILERPLATE CODE
// BEGIN MAIN CODE
const int ms = 5e3 + 20;
const long long inf = 1e18L + 20;
vector<array<short, ms>> tr;
map<array<short, ms>, int> f;
vector<pair<int, int>> ch[ms * 2];
int cnt[ms * 2];
long long dp[ms * 2];
int sum[ms * 2];
int cc = ms;
long long res = inf;
bool cmp(array<short, ms> &x, array<short, ms> &y) {
for (int i = ms - 1; i >= 0; i--) {
if (x[i] != y[i]) {
return x[i] < y[i];
}
}
return false;
}
array<short, ms> lca(array<short, ms> &x, array<short, ms> &y) {
array<short, ms> res = {};
for (int i = ms - 1; i >= 0; i--) {
if (x[i] == y[i]) {
res[i] = x[i];
}
else {
res[i] = min(x[i], y[i]);
break;
}
}
return res;
}
bool anc(array<short, ms> &x, array<short, ms> &y) {
for (int i = ms - 1; i >= 0; i--) {
if (x[i] != y[i]) {
if (x[i] > y[i]) {
return false;
}
for (int j = i - 1; j >= 0; j--) {
if (x[j] != 0) {
return false;
}
}
return true;
}
}
return true;
}
int dist(array<short, ms> &x, array<short, ms> &y) {
int res = 0;
for (int i = ms - 1; i >= 0; i--) {
res += y[i] - x[i];
}
return res;
}
int get(array<short, ms> &x) {
auto it = f.find(x);
if (it == f.end()) {
return (f[x] = cc++);
}
else {
return it->second;
}
}
void dfs1(int u) {
sum[u] = cnt[u];
for (auto x: ch[u]) {
int v = x.first;
int w = x.second;
dfs1(v);
sum[u] += sum[v];
dp[u] += dp[v];
dp[u] += 1LL * sum[v] * w;
}
}
void dfs2(int u) {
res = min(res, dp[u]);
for (auto x: ch[u]) {
int v = x.first;
int w = x.second;
sum[u] -= sum[v];
dp[u] -= dp[v];
dp[u] -= 1LL * sum[v] * w;
sum[v] += sum[u];
dp[v] += dp[u];
dp[v] += 1LL * sum[u] * w;
dfs2(v);
dp[v] -= 1LL * sum[u] * w;
dp[v] -= dp[u];
sum[v] -= sum[u];
dp[u] += 1LL * sum[v] * w;
dp[u] += dp[v];
sum[u] += sum[v];
}
}
void just_do_it() {
tr.emplace_back();
for (int i = 2; i < ms; i++) {
tr.push_back(tr.back());
int x = i;
for (int j = 2; j < ms; j++) {
while (x % j == 0) {
tr[i - 1][j]++;
x /= j;
}
}
}
int sz = tr.size();
for (int i = 0; i < sz; i++) {
f[tr[i]] = i + 1;
}
sort(tr.begin(), tr.end(), cmp);
for (int i = 0; i < sz - 1; i++) {
tr.push_back(lca(tr[i], tr[i + 1]));
}
sort(tr.begin(), tr.end(), cmp);
tr.erase(unique(tr.begin(), tr.end()), tr.end());
sz = tr.size();
vector<array<short, ms>> p = {tr[0]};
for (int i = 1; i < sz; i++) {
int v = get(tr[i]);
while (!anc(p.back(), tr[i])) {
p.pop_back();
}
int u = get(p.back());
int w = dist(p.back(), tr[i]);
ch[u].push_back({v, w});
p.push_back(tr[i]);
}
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
if (x == 0) {
x = 1;
}
cnt[x]++;
}
dfs1(1);
dfs2(1);
cout << res;
}
// END MAIN CODE | 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"
] | //______________"In The Name Of GOD"______________
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <ll, ll> pll;
typedef pair <int, int> pii;
const int lg = 20;
const int mod = 1e9 + 7;
const ll inf = 2e18 + 100;
const int maxn = 1e3 + 100;
#define cl clear
#define F first
#define S second
#define pb push_back
#define Sz(x) int((x).size())
#define all(x) (x).begin(), (x).end()
ll lcp[maxn][maxn], ps[maxn][maxn], dp[maxn][maxn], n, m, k;
string s;
vector <pii> vec;
inline bool cmp(pii a, pii b){
ll len = lcp[a.F][b.F];
char c = ' ', d = ' ';
if (a.F + len <= a.S) c = s[a.F + len];
if (b.F + len <= b.S) d = s[b.F + len];
if (c == ' ' && d == ' ') return a.S - a.F < b.S - b.F;
return c < d;
}
inline ll cal(ll l, ll r){
dp[n][0] = 1;
for (int i = 0; i <= n; i ++) ps[i][0] = 1;
for (int i = n; i >= 0; i --){
ll x = -1;
if (lcp[l][i] > r - l) x = i + r - l + 2;
else if (s[l + lcp[l][i]] <= s[i + lcp[l][i]]) x = i + lcp[l][i] + 1;
for (int j = 1; j <= m; j ++){
dp[i][j] = 0;
if (x != -1) dp[i][j] = ps[x][j - 1];
ps[i][j] = dp[i][j] + ps[i + 1][j];
if (ps[i][j] > inf) ps[i][j] = inf;
}
}
return dp[0][m];
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);cout.tie(0);
cin >> n >> m >> k;
cin >> s;
s += ' ';
lcp[n][n] = 0;
for (int i = n; i >= 0; i --){
for (int j = n; j >= 0; j --){
lcp[i][j] = (s[i] == s[j] ? lcp[i + 1][j + 1] + 1 : 0);
}
}
for (int i = 0; i < n; i ++){
for (int j = i; j < n; j ++) vec.pb({i, j});
}
sort(all(vec), cmp);
ll l = -1, r = Sz(vec);
while(r - l > 1){
ll mid = (l + r) / 2;
if (cal(vec[mid].F, vec[mid].S) < k) r = mid;
else l = mid;
}
for (int i = vec[r].F; i <= vec[r].S; i ++) cout << s[i];
cout << '\n';
return 0;
}
/*test case :
*/ | cpp |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | #include <bits/stdc++.h>
const long long mod = 1000001;
#define ll long long int
#define in(k) \
int k; \
cin >> k
#define i(a, b) \
int a, b; \
cin >> a >> b
#define inp(arr, n) \
int arr[n]; \
for (int i = 0; i < n; i++) \
cin >> arr[i]
#define f(i, a, b) for (int i = a; i < b; i++)
#define no cout << "NO"
#define yes cout << "YES"
#define nl cout << "\n"
#define maxi(a, n) *max_element(a, a + n)
#define mini(a, n) *min_element(a, a + n)
#define Sort(a, n) sort(a, a + n, greater<int>())
#define print(a, n) \
for (int i = 0; i < n; i++) \
cout << a[i] << " "
#define vi vector<int>
#define vll vector<ll>
#define ff first
#define ss second
#define pb push_back
#define sum(arr, n) accumulate(arr, arr + n, 0)
#define mii map<int, int>
#define bione __builtin_popcount
#define ppb pop_back
#define mp make_pair
#define ss second
#define ff first
#define pii pair<int, int>
#define all(v) v.begin(), v.end()
#define debug(x) cout << #x << " : " << x << endl;
#define debugarr(a, x) cout << #a << "[" << x << "]" \
<< " : " << a[x] << endl;
#define clock cerr << "Time elapsed: " << 1000 * 1.0 * clock() / CLOCKS_PER_SEC << " ms.\n";
using namespace std;
int gcd(int A, int B)
{
if (B == 0)
return A;
else
return gcd(B, A % B);
}
int SOD(int n)
{
int sum = 0;
while (n > 0)
{
sum = sum + n % 10;
n /= 10;
}
return sum;
}
int lcm(int a, int b) { return (a * b) / gcd(a, b); }
int pow(int a, int b)
{
int res = 1;
while (b > 0)
{
if (b % 2 == 1)
res *= a;
a *= a;
b /= 2;
}
return (int)res;
}
int pow(int x, int y, int p) // Modular Exponentiation
{
int res = 1;
while (y > 0)
{
if (y & 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
string dectobin(int x) // Decimal To Binary
{
string s = "";
while (x > 0)
{
int t = x % 2;
s.pb(t + '0');
x /= 2;
}
reverse(s.begin(), s.end());
if (s.compare("") == 0)
return "0";
else
return s;
}
int bintodec(string s) // Binary To Decimal
{
int ans = 0;
int n = s.size();
for (int i = n - 1; i >= 0; i--)
{
if (s[i] == '1')
ans += pow(2, n - i - 1);
}
return ans;
}
bool isPalindrome(string s)
{
ll low = 0;
ll high = s.length() - 1;
while (low < high)
{
if (s[low] != s[high])
{
return false;
}
low++;
high--;
}
return true;
}
bool isPrime[mod] = {true};
void SieveOfEratosthenes()
{
memset(isPrime, true, sizeof(isPrime));
for (ll p = 2; p * p <= mod; p++)
{
if (isPrime[p] == true)
{
for (ll i = p * 2; i <= mod; i += p)
isPrime[i] = false;
}
}
}
void solve()
{
int n;
cin >> n;
vector<int> a(n);
int odd = 0;
int sum = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
sum += a[i];
}
for (int i = 0; i < n; i++)
{
a[i] = a[i] % 2;
if (a[i] == 1)
{
odd++;
}
}
if (sum % 2 == 1)
{
cout << "YES\n";
}
else
{
if (odd > 0 and odd < n)
cout << "YES\n";
else
cout << "NO\n";
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
in(t);
while (t--)
{
solve();
}
} | cpp |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/detail/standard_policies.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define FIO ios::sync_with_stdio(false); cin.tie(nullptr)
#define TC(t) int t; cin >> t; for(int i = 1; i <= t; i++)
#define ll int
#define ull unsigned long long int
#define lll __int128
#define lld long double
#define loop(i, a, b) for(ll i = a; i <= b; i++)
#define loop2(i, b, a) for(ll i = b; i >= a; i--)
#define ini(x, y) memset(x, y, sizeof(x))
#define all(x) x.begin(), x.end()
#define all2(x) x.rbegin(), x.rend()
#define sz(x) (ll)x.size()
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define M 1000000007
#define endl '\n'
#define bits(x) __builtin_popcountll(x)
#define zrbits(x) __builtin_ctzll(x)
#define vl vector<ll>
#define pll pair<ll,ll>
#define vpll vector<pll>
#define uni(x) x.erase(unique(all(x)), x.end())
#define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define multi_ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define mxheap priority_queue<ll>
#define mnheap priority_queue<ll, vector<ll>, greater<ll>>
#define mxheap2 priority_queue<pair<ll,ll>>
#define mnheap2 priority_queue<pair<ll,ll>, vector<pair<ll,ll>>, greater<pair<ll,ll>>>
const int N = 1e6 + 5;
const int L = 20;
const int MX = 1e9 + 10;
const ll INF = 1e18;
const int dx[] = {0, -1, 0, 1, -1, -1, 1, 1};
const int dy[] = {1, 0, -1, 0, 1, -1, -1, 1};
using namespace std;
using namespace __gnu_pbds;
inline ll uceil(ll a,ll b) {return (a % b ? a / b + 1 : a / b);}
inline ll mod(ll x) {return ( (x % M + M) % M );}
ll ulog(ll val, ll base) {ll cnt = 0; val /= base; while(val) {cnt++; val /= base;} return cnt;}
ll power(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a; a = a * a; b >>= 1;} return res;}
ll modpow(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a % M; a = a * a % M; b >>= 1;} return res;}
#ifdef FARHAN
#define deb(x) cerr << #x << " = " << x << endl;
#define deb2(x, y) cerr << #x << " = " << x << ", " << #y << " = " << y << endl;
#define deb3(x, y, z) cerr << #x << " = " << x << ", " << #y << " = " << y << ", " << #z << " = " << z << endl;
#define deb4() cerr << endl;
#define done cerr << "Line " << __LINE__ << " is done" << endl;
#else
#define deb(x)
#define deb2(x, y)
#define deb3(x, y, z)
#define deb4()
#define done
#endif
template<typename T> ostream& operator<<(ostream& os, const vector<T>& v) {for(auto& x : v) os << x << " "; return os;}
template<typename T> ostream& operator<<(ostream& os, const set<T>& v) {for(auto& x : v) os << x << " "; return os;}
template<typename T, typename S> ostream& operator<<(ostream& os, const pair<T, S>& p) {os << p.first << ' ' << p.second; return os;}
template<typename... T> void in(T&... args) {((cin >> args), ...);}
template<typename... T> void out(T&&... args) {((cout << args << endl), ...);}
template<typename... T> void out2(T&&... args) {((cout << args << " "), ...);}
template<typename... T> void out3(T&&... args) {((cout << args << " "), ...); cout << endl;}
vector<ll> g[N], vis(N);
bool valid(ll i, ll j, ll n) {
return (i >= 0 && i < n && j >= 0 && j < n);
}
ll create(ll i, ll j, ll n) {
return (i * n + j);
}
pll decode(ll node, ll n) {
return {node / n, node % n};
}
char findchar(pll prev, pll cur) {
if(prev.ff == cur.ff) {
if(prev.ss < cur.ss) return 'L';
else return 'R';
} else {
if(prev.ff < cur.ff) return 'U';
else return 'D';
}
}
void fillans(vector<ll>& cycle, vector<vector<char>>& ans) {
int len = cycle.size();
ll n = sz(ans);
for(int i = 1; i < len; i++) {
pll cur = decode(cycle[i], n);
pll prev = decode(cycle[i - 1], n);
char ch = findchar(prev, cur);
ans[cur.ff][cur.ss] = ch;
}
}
vector<ll> cycle;
void dfs(ll node, ll par, ll n, vector<vector<char>>& ans) {
vis[node] = 1;
for(auto child : g[node]) {
if(!vis[child]) {
pll cur = decode(child, n);
pll prev = decode(node, n);
char ch = findchar(prev, cur);
ans[cur.ff][cur.ss] = ch;
dfs(child, node, n, ans);
}
}
}
void dfs2(ll node, vector<vector<char>>& ans, pll tar, vector<vector<pll>>& a) {
vis[node] = 1;
loop(k, 0, 3) {
ll i, j;
tie(i, j) = decode(node, sz(ans));
ll ii = i + dx[k];
ll jj = j + dy[k];
if(valid(ii, jj, sz(ans))) {
ll child = create(ii, jj, sz(ans));
if(!vis[child]) {
pll cur = decode(child, sz(ans));
pll prev = decode(node, sz(ans));
if(a[cur.ff][cur.ss] == tar) {
char ch = findchar(prev, cur);
ans[cur.ff][cur.ss] = ch;
dfs2(child, ans, tar, a);
}
}
}
}
}
void solve() {
ll n;
cin >> n;
vector<vector<pll>> a(n, vector<pll>(n));
for(ll i = 0; i < n; i++) {
for(ll j = 0; j < n; j++) {
cin >> a[i][j].ff >> a[i][j].ss;
}
}
// id ... 1 = cycle, 2 = fix, 3 = general
vector<vector<ll>> info(n, vector<ll>(n));
loop(i, 0, n - 1) {
loop(j, 0, n - 1) {
if(a[i][j].ff == -1) info[i][j] = 1;
else if(a[i][j].ff - 1 == i && a[i][j].ss - 1 == j) info[i][j] = 2;
else info[i][j] = 3;
}
}
// checking for cycle, id = 1
loop(i, 0, n - 1) {
loop(j, 0, n - 1) {
loop(k, 0, 3) {
ll ii = i + dx[k], jj = j + dy[k];
if(valid(ii, jj, n) && info[i][j] == 1 && info[ii][jj] == 1) {
ll u = create(i, j, n);
ll v = create(ii, jj, n);
g[u].pb(v);
g[v].pb(u);
}
}
}
}
vector<vector<char>> ans(n, vector<char>(n, '#'));
loop(p, 0, n - 1) {
loop(q, 0, n - 1) {
ll node = create(p, q, n);
if(!vis[node] && info[p][q] == 1) {
loop(k, 0, 3) {
ll pp = p + dx[k];
ll qq = q + dy[k];
if(valid(pp, qq, n) && info[pp][qq] == 1) {
ll child = create(pp, qq, n);
vis[child] = 1;
vis[node] = 1;
ans[p][q] = findchar({pp, qq}, {p, q});
ans[pp][qq] = findchar({p, q}, {pp, qq});
dfs(node, -1, n, ans);
dfs(child, -1, n, ans);
}
}
}
}
}
loop(i, 0, n - 1) {
loop(j, 0, n - 1) {
if(info[i][j] == 2) {
ans[i][j] = 'X';
ll node = create(i, j, n);
vis[node] = 1;
dfs2(node, ans, {i + 1, j + 1}, a);
}
}
}
loop(i, 0, n - 1) {
loop(j, 0, n - 1) {
if(ans[i][j] == '#') {
cout << "INVALID" << endl;
return;
}
}
}
cout << "VALID" << endl;
loop(i, 0, n - 1) {
loop(j, 0, n - 1) {
cout << ans[i][j];
}
cout << endl;
}
}
signed main () {
#ifdef FARHAN
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
FIO;
// TC(t)
solve();
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"
] | // Problem: C. Fadi and LCM
// Contest: Codeforces - Codeforces Round #613 (Div. 2)
// URL: https://codeforces.com/problemset/problem/1285/C
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
//clear adj and visited vector declared globally after each test case
//check for long long overflow
//Mod wale question mein last mein if dalo ie. Ans<0 then ans+=mod;
//Incase of close mle change language to c++17 or c++14
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define int long long
#define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);cout.precision(dbl::max_digits10);
#define pb push_back
#define mod 1000000007ll //998244353ll
#define lld long double
#define mii map<int, int>
#define pii pair<int, int>
#define ll long long
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define rep(i,x,y) for(int i=x; i<y; i++)
#define fill(a,b) memset(a, b, sizeof(a))
#define vi vector<int>
#define setbits(x) __builtin_popcountll(x)
#define print2d(dp,n,m) for(int i=0;i<=n;i++){for(int j=0;j<=m;j++)cout<<dp[i][j]<<" ";cout<<"\n";}
typedef std::numeric_limits< double > dbl;
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;
//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
const long long N=200005, INF=2000000000000000000;
lld pi=3.1415926535897932;
int lcm(int a, int b)
{
int g=__gcd(a, b);
return a/g*b;
}
int power(int a, int b, int p)
{
if(a==0)
return 0;
int res=1;
a%=p;
while(b>0)
{
if(b&1)
res=(res*a)%p;
b>>=1;
a=(a*a)%p;
}
return res;
}
bool is_prime(int n){
if(n<=1) return false;
for(int i=2;i*i<=n;i++){
if(n%i==0){
return false;
}
}
return true;
}
void test_cases(){
int n;
cin>>n;
if(is_prime(n)){
cout<<1<<" "<<n;
}else{
bool p=true;
set<pii>s;
for(int i=2;i*i<=n;i++){
if(n%i==0){
if(__gcd(i,n/i)==1){
s.insert(make_pair(n/i,i));
p=false;
}
}
}
if(p){
cout<<1<<" "<<n;
}
else{
cout<<(*s.begin()).ss<<" "<<(*s.begin()).ff;
}
}
}
int32_t main()
{
IOS;
int t;
// cin>>t;
t=1;
while(t--){
test_cases();
}
return 0;
} | cpp |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
| [
"math"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
long long int s;
cin>>s;
while(s--)
{
long long int n;
cin>>n;
long long int count=0;
long long int p = n;
while(p>=10)
{
count+=p/10;
p = p/10 + p%10;
}
cout<<n+count<<endl;
}
return 0;
} | cpp |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] | #include<iostream>
#include<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=1e5+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;
char str[N];
PII w[N];
void solve() {
int a=read(),b=read(),p=read();
scanf("%s",str+1);
n=strlen(str+1);
memset(w,0,sizeof(PII)*(n+4));
for(int i=n-1;i>=1;i--) {
if(str[i]==str[i+1]&&i!=n-1) w[i]=w[i+1];
else {
if(str[i]=='A') w[i].first=w[i+1].first+1,w[i].second=w[i+1].second;
else w[i].fi=w[i+1].fi,w[i].se=w[i+1].se+1;
}
}
int i=1;
while(i<n&&(ll)w[i].fi*a+(ll)w[i].se*b>p) i++;
printf("%d\n",i);
}
int main() {
// init();
// stin();
scanf("%d",&T);
// T=1;
while(T--) solve();
return 0;
}
| cpp |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"greedy"
] | #include <bits/stdc++.h>
using LL = long long;
[[maybe_unused]] constexpr int mod = 1e9 + 7, N = 3e5 + 10;
LL a[N], n, sum[N];
void solve() {
std::cin >> n;
for (int i = 1; i <= n; ++i) {
std::cin >> a[i];
sum[i] = sum[i - 1] + a[i];
}
std::map<LL, int> c1;
for (int i = 1; i <= n; ++i) {
for (int j = i; j <= n; ++j) {
c1[sum[j] - sum[i - 1]]++;
}
}
std::vector<std::pair<LL, LL>> ans;
for (auto [x, c] : c1) {
if (c > 1)
ans.emplace_back(c, x);
}
if (ans.empty()) {
std::cout << "1\n1 1\n";
} else {
std::sort(ans.begin(), ans.end());
std::reverse(ans.begin(), ans.end());
int m = 0;
std::vector<std::pair<int, int>> real_ans;
for (auto [c, x] : ans) {
// std::cout << x << ' ' << c << '\n';
std::map<LL, int> mp;
std::vector<std::pair<int, int>> tmp;
mp[0] = 0;
for (int i = 1; i <= n; ++i) {
if (mp.count(sum[i] - x)) {
tmp.emplace_back(mp[sum[i] - x] + 1, i);
mp.clear();
}
mp[sum[i]] = i;
}
if (tmp.size() > real_ans.size())
real_ans.swap(tmp);
// if (m++ == 5 * n) break;
}
std::cout << real_ans.size() << '\n';
for (auto [l , r] : real_ans) {
std::cout << l << ' ' << r << '\n';
}
}
}
int main() {
std::cin.tie(nullptr)->sync_with_stdio(false);
solve();
return 0;
} | cpp |
1304 | B | B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string. | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace __gnu_pbds;
using namespace std;
/***************************************************************************************************************/
template <typename K, typename V, typename Comp = std::less<K>>
using ordered_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = std::less<K>>
using ordered_set = ordered_map<K, null_type, Comp>;
template <typename K, typename V, typename Comp = std::less_equal<K>>
using ordered_multimap = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = std::less_equal<K>>
using ordered_multiset = ordered_multimap<K, null_type, Comp>;
template < typename T = int > istream& operator >> (istream &in, vector < T > &v) {
for (auto &x : v) in >> x;
return in;
}
template < typename T = int > ostream& operator << (ostream &out, const vector < T > &v) {
for (const T &x : v) out << x << ' ';
return out;
}
/***************************************************************************************************************/
#define cin_2d(vec, n, m) for(int ii = 0; ii < n; ii++) for(int jj = 0; jj < m && cin >> vec[ii][jj]; jj++);
#define cout_2d(vec, n, m) for(int i = 0; i < n; i++, cout << "\n") for(int j = 0; j < m && cout << vec[i][j] << " "; j++);
#define cout_map(mp) for(auto& [f,s] :mp) cout<<f<<" "<<s<<"\n";
#define num_of_digit(n) ((int)log10(n)+1)
#define ll long long
#define oo 2000000000
#define sz(s) s.size()
#define Ceil(n, m) (((n) / (m)) + ((n) % (m) ? 1 : 0))
#define f(i,k,n) for (ll i = k; i < n; i++)
#define ln "\n"
#define all(vec) vec.begin(), vec.end()
#define rall(s) s.rbegin(), s.rend()
#define fixed(n) fixed << setprecision(n)
#define Time cerr << "Time Taken: " << (float)clock() / CLOCKS_PER_SEC << " Secs" << "\n";
#define unq(VEC) sort(all(VEC)); VEC.resize(unique(all(VEC)) - VEC.begin());
#define put(s) return void(cout << s << ln);
#define de cout<<"Here"
#define yes cout<<"YES"
#define no cout<<"NO"
using namespace std;
void zyad_elnaghy(){
ios_base::sync_with_stdio(false),cin.tie(nullptr), cout.tie(nullptr);
#ifndef ONLINE_JUDGE
freopen("input.txt","r" , stdin), freopen("output.txt","w",stdout);
#endif
// freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);
}
//__________________________________________________C O D E__________________________________________________//
void solve(){
int n , m ; cin>>n>>m;
map<string , bool > mp;
for(int i = 0 ; i < n ; i++){
string s; cin>>s;
mp[s] = 1;
}
string mid = "", l = "" ,r = "" ;
for(auto it : mp){
string s = it.first;
reverse(all(s));
if( s == it.first ){
mid = s;
}
else if( mp[it.first] && mp.find(s) != mp.end()){
l += it.first ;
r = s + r ;
mp[it.first] = 0;
mp[s] = 0;
}
}
cout<<sz(l)*2 + sz(mid)<<ln;
cout<<l<<mid<<r<<ln;
}
int main()
{ zyad_elnaghy();
int testcases = 1;
// cin >> testcases;
while(testcases--){
solve();
// cout<<ln;
}
Time;
} | 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"
] | // LUOGU_RID: 102062513
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int,int> P;
const int N=3e5+5;
struct edge{
int v,nx;
}e[N<<1],g[N<<1];
int n,ne,cnt,fe[N],fg[N],p[N],sz[N],son[N],deep[N],fa[N],top[N],id[N],rev[N];
vector<P> fv,gv;
void read(edge *eg,int *f,int u,int v)
{ eg[++ne]=(edge){v,f[u]};
f[u]=ne;
}
int find(int x)
{ if(x==p[x])return x;
return p[x]=find(p[x]);
}
void dfs(int u,int ffa)
{ deep[u]=deep[ffa]+1,fa[u]=ffa,sz[u]=1;
for(int i=fe[u];i;i=e[i].nx)
{ int v=e[i].v;
if(v==ffa)continue;
dfs(v,u),sz[u]+=sz[v];
if(sz[v]>sz[son[u]])son[u]=v;
}
}
void dfs2(int u,int tops)
{ top[u]=tops,id[u]=++cnt,rev[cnt]=u;
if(son[u])dfs2(son[u],tops);
for(int i=fe[u];i;i=e[i].nx)
{ int v=e[i].v;
if(v!=fa[u]&&v!=son[u])dfs2(v,v);
}
}
void lca(int u,int v)
{ while(top[u]!=top[v])
{ if(deep[top[u]]<deep[top[v]])gv.push_back(make_pair(id[top[v]],id[v])),v=fa[top[v]];
else fv.push_back(make_pair(id[top[u]],id[u])),u=fa[top[u]];
}
if(deep[u]<deep[v])gv.push_back(make_pair(id[u],id[v]));
else fv.push_back(make_pair(id[v],id[u]));
}
void link(int u,int v)
{ printf("%d %d ",rev[u],rev[v]);
p[find(u)]=find(v);
}
void del(int u,int v)
{ fv.clear(),gv.clear(),lca(u,v),reverse(gv.begin(),gv.end());
int h=0,fl=0,oo=find(id[u]);
for(auto k:fv)
{ int l=k.first,r=k.second;
if(find(r)!=oo)link(r,h),fl=1;
if(!fl&&find(l)!=oo)
{ for(int i=18;i>=0;i--)if(r-(1<<i)>l&&find(r-(1<<i))==oo)r-=(1<<i);
link(r,r-1),fl=1;
}
if(fl){printf("%d %d\n",u,v);return;}
h=l;
}
for(auto k:gv)
{ int l=k.first,r=k.second;
if(find(l)!=oo)link(l,h),fl=1;
if(!fl&&find(r)!=oo)
{ for(int i=18;i>=0;i--)if(l+(1<<i)<r&&find(l+(1<<i))==oo)l+=(1<<i);
link(l,l+1),fl=1;
}
if(fl){printf("%d %d\n",u,v);return;}
h=r;
}
}
void solve(int u,int ffa)
{ for(int i=fg[u];i;i=g[i].nx)
{ int v=g[i].v;
if(v!=ffa)solve(v,u);
}
if(ffa)del(u,ffa);
}
int main()
{ scanf("%d",&n);
for(int i=1,u,v;i<n;i++)
{ scanf("%d%d",&u,&v);
read(e,fe,u,v),read(e,fe,v,u);
}
ne=0;
for(int i=1,u,v;i<n;i++)
{ scanf("%d%d",&u,&v);
read(g,fg,u,v),read(g,fg,v,u);
}
for(int i=1;i<=n;i++)p[i]=i;
dfs(1,0),dfs2(1,1);
printf("%d\n",n-1);
solve(1,0);
return 0;
} | cpp |
1288 | C | C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1]. | [
"combinatorics",
"dp"
] | #include<bits/stdc++.h>
#define eps 1e-9
#define emailam ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define pb push_back
#define all(a) a.begin(),a.end()
#define pf push_front
#define fi first
#define se second
#define pii pair<int,int>
const int INF = INT_MAX;
using namespace std;
const int N = 1e6 + 10;
#define int long long
/*----------------------------------------------------------------*/
int dx[] = {+0, +0, -1, +1, +1, +1, -1, -1};
int dy[] = {-1, +1, +0, +0, +1, -1, +1, -1};
/*----------------------------------------------------------------*/
void READ() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif
}
int mod=1e9+7;
ll power(ll x, ll y) {
ll ret = 1;
while (y > 0) {
if (y % 2 == 0) {
x = x * x;
x %= mod;
y = y / 2;
} else {
ret = ret * x;
ret %= mod;
y = y - 1;
}
}
return ret;
}
int fac[N], inv[N];
void precalc() {
fac[0] = fac[1] = 1;
for (int i = 2; i < N; ++i) {
fac[i] = fac[i - 1] * i;
fac[i] %= mod;
}
inv[0] = 1;
for (int i = 1; i < N; ++i) {
inv[i] = power(fac[i], mod - 2);
}
}
int ncr(int x, int y) {
if (x < y)return 0;
return ((fac[x] * inv[x - y]) % mod * inv[y]) % mod;
}
int mul(int a, int b) {
return (a * b) % mod;
}
int add(int a, int b) {
return ((a) + (b) + 2 * mod) % mod;
}
void solve() {
int n,m;
cin>>n>>m;
precalc();
cout<<ncr(n-1+2*m,n-1)<<endl;
}
signed main() {
emailam
//READ();
int t = 1;
//cin >> t;
while (t--) {
solve();
}
} | 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"
] | /**
* author: magnus_hegdahl
* created: 01.02.2023 00:25
* problem: E2. String Coloring (hard version)
* url: https://codeforces.com/contest/1296/problem/E2
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int n;
string s;
cin >> n >> s;
vector<int> color(n, -1);
map<char, int> active;
for (int i = 0; i < n; ++i) {
auto it = active.upper_bound(s[i]);
if (it == active.begin()) {
color[i] = (int)active.size();
} else {
--it;
color[i] = it->second;
active.erase(it);
}
active.emplace(s[i], color[i]);
}
cout << active.size() << '\n';
for (int c : color) cout << c + 1 << ' ';
cout << '\n';
}
| cpp |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t; cin>>t;
while(t--)
{
int n; cin>>n;
int a[n],b[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n;i++)
{
cin>>b[i];
}
sort(a,a+n);
sort(b,b+n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
for(int i=0;i<n;i++)
{
cout<<b[i]<<" ";
}
cout<<endl;
}
}
| cpp |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
#define endl "\n"
#define int long long
typedef long long LL;
typedef pair<int,int> PII;
void solve(){
int n,x,y;
cin>>n>>x>>y;
int mn=(x+y<n+1)?1:min(n,x+y-n+1);
int mx=min(n,x+y-1);
cout<<mn<<" "<<mx<<endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);cout.tie(nullptr);
int t=1;
cin>>t;
while(t--) {
solve();
}
return 0;
} | cpp |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds. | [
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long int
int32_t main()
{
int n; cin >> n;
string s; cin >> s;
int cur = 0, ans=0, sum=0, k = 0;
for(int i=0; i<n; i++){
if(s[i]==')'){
cur--;
}
else{
cur++;
}
if(cur==0){
if(k!=0)
ans+= (k+1);
cur = 0;
// sum=0;
k = 0;
}
else if(cur<0){
k++;
}
// sum = min(cur, sum);
}
if(cur!=0){
cout << -1 << endl;
return 0;
}
cout << ans << endl;
} | cpp |
1303 | G | G. Sum of Prefix Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define the sum of prefix sums of an array [s1,s2,…,sk][s1,s2,…,sk] as s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk)s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk).You are given a tree consisting of nn vertices. Each vertex ii has an integer aiai written on it. We define the value of the simple path from vertex uu to vertex vv as follows: consider all vertices appearing on the path from uu to vv, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.InputThe first line contains one integer nn (2≤n≤1500002≤n≤150000) — the number of vertices in the tree.Then n−1n−1 lines follow, representing the edges of the tree. Each line contains two integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi), denoting an edge between vertices uiui and vivi. It is guaranteed that these edges form a tree.The last line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤1061≤ai≤106).OutputPrint one integer — the maximum value over all paths in the tree.ExampleInputCopy4
4 2
3 2
4 1
1 3 3 7
OutputCopy36
NoteThe best path in the first example is from vertex 33 to vertex 11. It gives the sequence [3,3,7,1][3,3,7,1], and the sum of prefix sums is 3636. | [
"data structures",
"divide and conquer",
"geometry",
"trees"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(!isdigit(ch))f^=ch=='-',ch=getchar();
while(isdigit(ch))x=x*10+(ch^48),ch=getchar();
return f?x:-x;
}
const int N=150005;
int K[N],B[N],tot,n,a[N],ans;
vector<int> T[N];
int calc(int id,int x){
return K[id]*x+B[id];
}
int newseg(int x,int y){
++tot;
K[tot]=x;
B[tot]=y;
return tot;
}
struct LichaoSegmentTree{
int lc[N<<2],rc[N<<2],pool,val[N<<2],rt;
#define mid (l+r>>1)
void clear(){rt=pool=0;}
int newnode(){
int p=++pool;
lc[p]=rc[p]=val[p]=0;
return p;
}
void modify(int &p,int l,int r,int u){
if(!p)p=newnode();
int &v=val[p];
if(calc(u,mid)>calc(v,mid))swap(u,v);
if(calc(u,l)>calc(v,l))modify(lc[p],l,mid,u);
if(calc(u,r)>calc(v,r))modify(rc[p],mid+1,r,v);
}
int query(int p,int l,int r,int x){
if(!p)return 0;
int ret=calc(val[p],x);
if(l==r)return ret;
if(x<=mid)ret=max(ret,query(lc[p],l,mid,x));
else ret=max(ret,query(rc[p],mid+1,r,x));
return ret;
}
}Tr;
int sum,dep[N],siz[N],root,DP[N],vis[N],pre[N],ppre[N],gre[N],pgre[N];
void findsize(int u,int fa){
siz[u]=1;
for(int v:T[u])if(!vis[v]&&v!=fa){
findsize(v,u);
siz[u]+=siz[v];
}
}
void findroot(int u,int fa){
DP[u]=0;
for(int v:T[u])if(!vis[v]&&v!=fa){
findroot(v,u);
DP[u]=max(DP[u],siz[v]);
}
DP[u]=max(DP[u],sum-siz[u]);
if(DP[u]<DP[root])root=u;
}
void dfs1(int u,int fa){
dep[u]=dep[fa]+1;
gre[u]=gre[fa]+a[u];
pgre[u]=pgre[fa]+gre[u];
ans=max(ans,Tr.query(Tr.rt,0,n,dep[u]-1)+pgre[u]);
ans=max(ans,pgre[u]+dep[u]*a[root]);
for(int v:T[u])if(v!=fa&&!vis[v]){
dfs1(v,u);
}
}
void dfs2(int u,int fa){
pre[u]=pre[fa]+a[u];
ppre[u]=ppre[fa]+dep[u]*a[u];
ans=max(ans,ppre[u]);
Tr.modify(Tr.rt,0,n,newseg(pre[u],ppre[u]));
// Tr.query(Tr.rt,0,n,0);
for(int v:T[u])if(v!=fa&&!vis[v]){
dfs2(v,u);
}
}
void solve(int u){
Tr.clear();
tot=0;
dep[u]=1;
pre[u]=ppre[u]=a[u];
ans=max(ans,ppre[u]);
gre[u]=pgre[u]=0;
for(int v:T[u])if(!vis[v]){
dfs1(v,u);
dfs2(v,u);
}
Tr.clear();
tot=0;
dep[u]=1;
pre[u]=ppre[u]=a[u];
gre[u]=pgre[u]=0;
reverse(T[u].begin(),T[u].end());
for(int v:T[u])if(!vis[v]){
dfs1(v,u);
dfs2(v,u);
}
vis[u]=1;
for(int v:T[u])if(!vis[v]){
findsize(v,u);
sum=siz[v];
root=0;
DP[0]=n;
findroot(v,u);
solve(root);
}
}
void work(){
sum=n;
root=0;
DP[0]=n;
findsize(1,0);
findroot(1,0);
solve(root);
}
signed main(){
n=read();
for(int i=1;i<n;++i){
int x=read(),y=read();
T[x].push_back(y);
T[y].push_back(x);
}
for(int i=1;i<=n;++i){
a[i]=read();
}
work();
printf("%lld\n",ans);
return 0;
} | cpp |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | #include <bits/stdc++.h>
#define Dattebayo() ios::sync_with_stdio(0),cin.tie(nullptr),cout.tie(nullptr)
#define all(v) ((v).begin()), ((v).end())
#define YES cout<<"YES\n"
#define NO cout<<"NO\n"
#define ll long long
#define F first
#define S second
#define endl "\n"
using namespace std;
///Where there's a will there's a way.
///Well, نـورت الكــود يـعـمـنـا
vector <vector<int>> res;
vector <int> ans;
string s;
void solve(){
for(int i=0 ,j=s.size()-1 ; i<j ;i++){
if(s[i]=='('){
for( ; j>i ;j --)
if(s[j]==')'){
ans.push_back(i+1);
ans.push_back(j+1);
s[i]='*',s[j]='*';
break;
}
}
}
sort(all(ans));
res.push_back(ans);
}
bool check(){
bool ex= false;
for(char i : s){
if(i=='(') ex= true;
if(i==')' && ex) return false;
}
return true;
}
int main()
{
Dattebayo();
cin>>s;
while(!check())
solve();
cout<<res.size()<<endl;
if(!res.empty()){
for(const auto& i:res){
cout<<i.size()<<endl;
for(auto j:i)
cout<<j<<" ";
cout<<endl;
}
}
}
| cpp |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102. | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | // LUOGU_RID: 101016299
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 2e5 + 10;
void solve() {
int n;
cin >> n;
vector<int> a(n + 1);
for(int i = 1; i <= n; i++)
cin >> a[i];
int ans = 0;
auto cal = [&](vector<int> &v, int b) {
int cnt = 0;
for(int i = 1; i <= n; i++) {
int l = lower_bound(v.begin() + i + 1, v.end(), (1 << b) - v[i]) - v.begin(), r = upper_bound(v.begin() + i + 1, v.end(), (1 << (b + 1)) - 1 - v[i]) - v.begin() - 1;
cnt ^= (r - l + 1) % 2;
//cout << i << ' ' << l << ' ' << r << '\n';
}
for(int i = 1; i <= n; i++) {
int l = lower_bound(v.begin() + i + 1, v.end(), (1 << b) + (1 << (b + 1)) - v[i]) - v.begin(), r = upper_bound(v.begin() + i + 1, v.end(), (1 << (b + 2)) - 1 - v[i]) - v.begin() - 1;
cnt ^= (r - l + 1) % 2;
//cout << i << ' ' << l << ' ' << r << '\n';
}
if(cnt & 1)
return 1 << b;
else
return 0;
};
for(int i = 0; i < 28; i++) {
vector<int> b(n + 1);
for(int j = 1; j <= n; j++)
b[j] = a[j] % (1 << (i + 1));
sort(b.begin() + 1, b.end());
ans += cal(b, i);
}
cout << ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
while(t--) {
solve();
}
} | cpp |
1284 | D | D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist. | [
"binary search",
"data structures",
"hashing",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define f first
#define s second
#define rep(i,a,b) for (int i=a; i<b; ++i)
#define setpr(x) cout<<setprecision(x)<<fixed
#define sz(v) int(v.size())
#define all(v) v.begin(),v.end()
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template <typename T>
class LazySegTree{
vector<T> t, lazy, len;
public:
int n;
LazySegTree(vector<T> &a){
n = int(a.size());
t.resize(4*n);
lazy.resize(4*n);
len.resize(4*n);
build(a);
}
void build(vector<T> &a){
build(a, 0, n-1, 1);
}
void update(int x, int y, T diff){
update(0, n-1, 1, x, y, diff);
}
T query(int l, int r){
return query(0, n-1, 1, l, r);
}
private:
T merge(T x, T y){
return max(x,y);
}
T default_val() {
return 0;
}
void push(int i){
t[2*i] = max(t[2*i],lazy[i]);
t[2*i+1] = max(t[2*i+1],lazy[i]);
lazy[2*i] = max(lazy[2*i],lazy[i]);
lazy[2*i+1] = max(lazy[2*i+1],lazy[i]);
lazy[i] = 0;
}
void build(vector<T> &a, int l, int r, int i){
if (l==r){
t[i] = a[l];
len[i] = 1;
return;
}
int mid = l+(r-l)/2;
build(a,l,mid,2*i);
build(a,mid+1,r,2*i+1);
t[i] = merge(t[2*i],t[2*i+1]);
len[i] = 1;
}
void update(int l, int r, int i, int x, int y, T diff){
if (x>y) return;
if (x==l && r==y){
t[i] = max(t[i],diff*len[i]);
lazy[i] = max(lazy[i],diff);
return;
}
push(i);
int mid = l+(r-l)/2;
update(l, mid, 2*i, x, min(y,mid), diff);
update(mid+1, r, 2*i+1, max(x,mid+1), y, diff);
t[i] = merge(t[2*i], t[2*i+1]);
}
T query(int l, int r, int i, int x, int y){
if (x>y) return default_val();
if (x<=l && r<=y) {
return t[i];
}
push(i);
int mid = l+(r-l)/2;
return merge(query(l, mid, 2*i, x, min(y,mid)), query(mid+1, r, 2*i+1, max(x,mid+1), y));
}
};
bool solve(vector<vector<int>>& a, int __cnt=1){
int n = sz(a);
if (__cnt>2) return false;
// coords comp
map<int,int> mp;
rep(i,0,n){
rep(j,0,4){
mp[a[i][j]] = 0;
}
}
int __cc = 0;
for (auto it: mp) mp[it.f] = __cc++;
rep(i,0,n){
rep(j,0,4){
a[i][j] = mp[a[i][j]];
}
}
vector<int> tmp(__cc+5);
LazySegTree<int> st(tmp);
rep(i,0,n){
int left_b = a[i][2];
st.update(a[i][0],a[i][1],left_b);
}
rep(i,0,n){
int mx_left = st.query(a[i][0],a[i][1]);
if (mx_left > a[i][3]) {
return true;
}
}
rep(i,0,n){
swap(a[i][0],a[i][2]);
swap(a[i][1],a[i][3]);
}
return solve(a,__cnt+1);
}
int main(int argc, const char * argv[]) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t=1;
// cin>>t;
int n;
cin>>n;
vector<vector<int>> a(n);
rep(i,0,n){
a[i].resize(4);
rep(j,0,4) cin>>a[i][j];
}
for (int i=0;i<t;i++){
cout<<(solve(a) ? "NO":"YES")<<"\n";
}
return 0;
}
| cpp |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] | #pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#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<class key, class cmp = std::less<key>>
using op_set = tree<key, null_type, cmp, rb_tree_tag, tree_order_statistics_node_update>;
#ifdef thunder
#include "bug.h"
#else
#define bug(...)
#endif
#define ll long long
#define lld double
#define all(x) x.begin(), x.end()
#define iceil(n, x) (((n) + (x) - 1) / (x))
#define goog(tno) cout << "Case #" << tno <<": "
const ll INF=2e18;
const ll mod=1000000007;
const ll maxn=2e5+5;
ll n,m;
vector<ll> g[maxn];
vector<ll> rev_g[maxn];
ll k;
vector<ll> a(maxn);
vector<ll> vis(maxn,0);
vector<ll> dis(maxn,INF);
vector<ll> ways(maxn,0);
vector<ll> par(maxn,-1);
void solve(){
cin>>n>>m;
for(ll i=1;i<=m;i++){
ll x,y;
cin>>x>>y;
g[x].push_back(y);
rev_g[y].push_back(x);
}
cin>>k;
for(ll i=1;i<=k;i++) cin>>a[i];
queue<ll> q;
q.push(a[k]);
ways[a[k]]=0;
vis[a[k]]=1;
dis[a[k]]=0;
while(q.size()){
auto node=q.front();
q.pop();
for(auto &to:rev_g[node]){
if(!vis[to]){
q.push(to);
vis[to]=1;
}
if(dis[to]>dis[node]+1){
dis[to]=dis[node]+1;
ways[to]=1;
par[to]=node;
}else if(dis[to]==dis[node]+1){
ways[to]+=ways[node];
}
}
}
bug(dis[a[1]]);
ll mx=0,mn=0;
for(ll i=1;i+1<=k;i++){
if(dis[a[i]]!=dis[a[i+1]]+1){
mn++;
mx++;
continue;
}
if(ways[a[i]]>1){
mx++;
}
}
cout<<mn<<" "<<mx<<'\n';
}
signed main(){
ios_base::sync_with_stdio(false), cin.tie(nullptr);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int t=1;
// cin>>t;
for(int i=1;i<=t;i++){
solve();
}
return 0;
} | cpp |
1286 | F | F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3
1 10 100
OutputCopy3
InputCopy3
5 3 -2
OutputCopy2
InputCopy1
0
OutputCopy0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed. | [
"brute force",
"constructive algorithms",
"dp",
"fft",
"implementation",
"math"
] | /*
わんわん……わんだほーいっ☆
Wonderhoy!
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef double DB;
char buf[1<<21],*p1=buf,*p2=buf;
#define getchar() (p1==p2 && (p2=(p1=buf)+fread(buf,1,1<<18,stdin),p1==p2)?EOF:*p1++)
LL read()
{
LL x=0,f=1;
char c=getchar();
while(c<'0' || c>'9') f=(c=='-'?-1:f),c=getchar();
while(c>='0' && c<='9') x=(x<<1)+(x<<3)+(c^'0'),c=getchar();
return x*f;
}
void write(LL x)
{
if(x>9) write(x/10);
putchar(x%10+'0');
}
LL n,a[20];
LL sum[1<<20],cnt[1<<20];
inline LL Abs(LL x){return x<0?-x:x;}
inline LL lowbit(LL x){return x&(-x);}
bool f[1<<20];
LL g[1<<20];
int main(){
n=read();
for(LL i=0;i<n;++i)
{
a[i]=read();
if(!a[i]) --i,--n;
}
for(LL S=1;S<(1<<n);++S) cnt[S]=cnt[S^lowbit(S)]+1;
for(LL S=0;S<(1<<n);++S)
{
for(LL i=0;i<n;++i)
{
if((S>>i)&1)
{
sum[S]=sum[S^(1<<i)]+a[i];
break;
}
}
}
for(LL S=1;S<(1<<n);++S) if((cnt[S]^sum[S])&1) for(LL T=S&(S-1);T && !f[S];T=S&(T-1)) if(Abs(sum[T]-sum[T^S])<cnt[S]) f[S]=true;
for(LL S=1;S<(1<<n);++S)
{
if(f[S] && !g[S])
{
g[S]=1;
LL U=((1<<n)-1)^S;
for(LL T=U;T;T=U&(T-1)) g[S|T]=max(g[S|T],g[T]+1);
}
}
write(n-g[(1<<n)-1]),puts("");
return 0;
} | cpp |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5
| [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | #include <iostream>
#include <set>
#include <algorithm>
using namespace std;
typedef pair<int, int> pii;
const int N = 2 * 100 * 1000 +10;
pii seg[N];
int dp_last, dp, big, cmp;
void Solve()
{
int n; cin>>n;
for(int i=1; i<=n; i++)
cin>>seg[i].first>>seg[i].second;
sort(seg+1, seg+n+1);
/// Base
set<pii> s;
s.insert({seg[1].second, 1});
cmp = big = 1;
dp = -1;
dp_last = 0;
/// Solve
for(int i=2; i<=n; i++)
{
if(seg[i].second <= seg[big].second)
{
if(i == 2)
dp = 1;
s.erase({seg[big].second, big});
dp_last += (s.empty() || s.rbegin() -> first < seg[i].first);
s.insert({seg[big].second, big});
}
else if(seg[big].second < seg[i].first)
{
dp = max(dp, dp_last) + 1;
dp_last = cmp ++;
big = i;
}
else
{
/// DP LAST
int new_dp_last = cmp;
/// DP
int dp1 = dp, dp2 = dp_last;
s.erase({seg[big].second, big});
dp2 += (s.empty() || s.rbegin() -> first < seg[i].first);
s.insert({seg[big].second, big});
/// UPD
dp_last = new_dp_last;
dp = max(dp1, dp2);
big = i;
}
s.insert({seg[i].second, i});
}
cout<<max(dp, dp_last)<<'\n';
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int t; cin>>t;
while(t --)
Solve();
return 0;
}
| cpp |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
using vi = vector<int>;
using pi = pair<int, int>;
#define FAST_IO \
ios_base::sync_with_stdio(false); \
cin.tie(NULL)
bool is_prime(ll x) {
if (x <= 1) return 0;
for (ll y = 2; y * y <= x; ++y)
if (x % y == 0) return 0;
return 1;
}
using std::gcd; // Computes the greatest common divisor of the integers m and
// n.
using std::lcm; // Computes the least common multiple of the integers m and n.
int popcnt(uint x) { return __builtin_popcount(x); }
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(ull x) { return __builtin_popcountll(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int bsr(uint x) { return 31 - __builtin_clz(x); }
int bsr(ull x) { return 63 - __builtin_clzll(x); }
int ctz(int x) { return __builtin_ctz(x); }
int ctz(ll x) { return __builtin_ctzll(x); }
int ctz(ull x) { return __builtin_ctzll(x); }
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 all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define SUM(v) accumulate(all(v), 0LL)
#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())
ll ceil(ll x, ll y) {
assert(y >= 1);
return (x > 0 ? (x + y - 1) / y : x / y);
}
ll floor(ll x, ll y) {
assert(y >= 1);
return (x > 0 ? x / y : (x - y + 1) / y);
}
ll mod(ll x, ll y) { return x - y * floor(x, y); }
#line 74 "library/ds/unionfind.hpp"
struct UnionFind {
int n;
int n_comp;
std::vector<int> size, par;
UnionFind(int n) : n(n), n_comp(n), size(n, 1), par(n) {
std::iota(par.begin(), par.end(), 0);
}
int find(int x) {
assert(0 <= x && x < n);
while (par[x] != x) {
x = par[x] = par[par[x]];
}
return x;
}
int operator[](int x) { return find(x); }
bool merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
n_comp--;
if (size[x] < size[y]) std::swap(x, y);
size[x] += size[y];
size[y] = 0;
par[y] = x;
return true;
}
std::vector<int> find_all() {
std::vector<int> A(n);
for (int i = 0; i < n; ++i) A[i] = find(i);
return A;
}
void reset() {
n_comp = n;
size.assign(n, 1);
std::iota(par.begin(), par.end(), 0);
}
};
/**************************** debug utils begin *******************************/
#line 121 "debug_utils.cpp"
#ifdef OJ_DEBUG
#define LOG std::cerr << "line: " << __LINE__ << ", "
#else
struct NonFunctioningLogger {
public:
template <typename T>
NonFunctioningLogger& operator<<(const T& obj) {
return *this;
}
};
NonFunctioningLogger LOG;
#endif // OJ_DEBUG
#define DEFINE_CONTAINER_PRINTER(CONTAINER_TYPE) \
template <typename T> \
ostream& operator<<(ostream& ostr, const CONTAINER_TYPE<T>& a) { \
ostr << "{"; \
for (auto it = a.begin(); it != a.end(); it++) { \
if (it != a.begin()) ostr << ", "; \
ostr << *it; \
} \
ostr << "}"; \
return ostr; \
}
DEFINE_CONTAINER_PRINTER(std::vector)
DEFINE_CONTAINER_PRINTER(std::deque)
DEFINE_CONTAINER_PRINTER(std::list)
DEFINE_CONTAINER_PRINTER(std::set)
DEFINE_CONTAINER_PRINTER(std::unordered_set)
template <typename T, typename U>
ostream& operator<<(ostream& os, const pair<T, U>& A) {
os << "(" << A.first << ", " << A.second << ")";
return os;
}
template <typename T, typename Y>
auto operator<<(std::ostream& os, const std::vector<std::pair<T, Y>>& a)
-> std::ostream& {
os << "{";
int i;
for (i = 0; i < a.size() - 1; i++) {
os << "(" << a[i].first << ", " << a[i].second << "), ";
}
if (i < a.size()) {
os << a[i];
}
os << "}";
return os;
}
template <class T, class S>
inline bool chmin(T& a, const S& b) {
return (a > b ? a = b, 1 : 0);
}
/**************************** debug utils end *******************************/
#line 182 "main.cpp"
void solve() {
int n, m;
cin >> n >> m;
vc<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
vc<bool> p(m);
for (int i = 0; i < m; i++) {
int pos;
cin >> pos;
p[pos - 1] = true;
}
// LOG << "a = " << a << "\n";
// LOG << "p = " << p << "\n";
for (int i = 0; i < n; i++) {
if (!p[i]) continue;
int j = i;
while (j < n && p[j]) j++;
sort(a.begin() + i, a.begin() + j + 1);
}
bool ok{true};
for (int i = 0; i < n - 1; i++) {
ok &= a[i] <= a[i + 1];
}
if (ok)
cout << "YES\n";
else
cout << "NO\n";
}
int main() {
FAST_IO;
int t;
cin >> t;
while (t--) solve();
return 0;
}
| cpp |
1325 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14. | [
"constructive algorithms",
"greedy",
"number theory"
] | #include<bits/stdc++.h>
#include<vector>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
long n;
cin>>n;
cout<<n-1<<" "<<1<<endl;
}
return 0;
}
| cpp |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
| [
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define jeno_joyer_khuda_thake int main (void)
#define kaj_shesh return 0
#define sf scanf
#define pf printf
#define ssf sscanf
#define spf sprintf
#define fsf fscanf
#define fpf fprintf
#define fast ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define scase sf ("%d",&tc)
#define whilecase while (tc--)
#define sn sf ("%d",&n)
#define eof while (cin >> n)
#define pcase pf ("Case %d: ",pos)
#define llu unsigned long long
#define lld long long
#define U unsigned int
#define for0(i,n) for (i=0; i<n; i++)
#define for1(i,n) for (i=1; i<=n; i++)
#define forab(i,a,b) for (i=a; i<=b; i++)
#define rof0(i,n) for (i=n-1; i>=0; i--)
#define rof1(i,n) for (i=n; i>=1; i--)
#define rofab(i,a,b) for (i=b; i>=a; i--)
#define c(str) cin >> str
#define g(str) getline (cin,str)
#define vi vector <int>
#define vlld vector <lld>
#define si set <int>
#define slld set <lld>
#define ss set <string>
#define vs vector <string>
#define pii pair <int,int>
#define mii map <int,int>
#define msi map <string,int>
#define pb push_back
#define in insert
#define B begin()
#define E end()
#define rB rbegin()
#define rE rend()
#define F first
#define S second
#define iterate(it,x) for (it=x.B; it!=x.E; it++)
#define riterate(rit,x) for (it=x.rB; it!=x.rE; it++)
#define sort(x) sort (x.B,x.E)
#define sortR(x,a,b) sort (x.B+a,x.B+b+1)
#define rev(x) reverse (x.B,x.E)
#define revR(x,a,b) reverse (x.B+a,x.B+b+1)
#define cl(x) x.clear()
#define end1 "\n"
const int MOD = 1000000007;
const int MAX = 1000005;
const double PI = acos(-1.0);
int SetBit (int n, int X) { return n | (1 << X); }
int ClearBit (int n, int X) { return n & ~(1 << X); }
int ToggleBit (int n, int X) { return n ^ (1 << X); }
bool CheckBit (int n, int X) { return (bool)(n & (1 << X)); }
jeno_joyer_khuda_thake
{
/*
freopen ("input.txt","r",stdin);
freopen ("output.txt","w",stdout);
*/
int tc,n,i,d,ans,p;
sf ("%d",&tc);
while (tc--)
{
sf ("%d",&n);
ans = 0;
while (1)
{
d = (n/10) * 10;
ans += d;
p = n-d;
n = (n/10) + p;
if (n < 10)
{
ans += n;
break;
}
}
pf ("%d\n",ans);
}
kaj_shesh;
} | cpp |
1299 | E | E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter 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 formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2
| [
"interactive",
"math"
] | /*
_/ _/ _/_/_/ _/ _/ _/ _/_/_/_/_/
_/ _/ _/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/
_/_/ _/ _/ _/ _/_/_/_/
_/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/
_/ _/ _/_/_/ _/ _/_/_/_/_/ _/_/_/_/_/
*/
#include <bits/stdc++.h>
#define ll long long
#define lc(x) ((x) << 1)
#define rc(x) ((x) << 1 | 1)
#define ru(i, l, r) for (int i = (l); i <= (r); i++)
#define rd(i, r, l) for (int i = (r); i >= (l); i--)
#define mid ((l + r) >> 1)
#define pii pair<int, int>
#define mp make_pair
#define fi first
#define se second
#define sz(s) (int)s.size()
#define maxn 2005
using namespace std;
inline int read() {
int x = 0, w = 0; char ch = getchar();
while(!isdigit(ch)) {w |= ch == '-'; ch = getchar();}
while(isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}
return w ? -x : x;
}
int n, m, vis[maxn], f[12][maxn], id[maxn], ans[maxn];
vector<int> S[12][maxn];
//int a[maxn];
inline int query(set<int> v) {
printf("? %d ", v.size());
for (auto x: v) printf("%d ", x); printf("\n"); fflush(stdout);
// int sum = 0; for (auto x: v) sum += a[x];
// assert(sum % (v.size() / 2) == 0);
// printf("ans: %d\n", sum % v.size() == 0);
// return sum % v.size() == 0;
return read();
}
inline void work(int x, int v) {
// printf("!!!!!!!!!!!! find that p_%d=%d\n", id[x], v);
ans[id[x]] = v, vis[x] = 1;
ru(i, 0, m - 1) f[i][x & ((1 << i) - 1)] = ((x ^ v) >> i) & 1;
}
inline int chk(int x, int y) {
ru(i, 0, m - 1) {
int tt = f[i][x & ((1 << i) - 1)];
if(tt == -1) continue;
// if(id[x] + y == n + 1 && tt != (((x ^ y) >> i) & 1)) {
// printf("JILEJILE %d %d %d\n", id[x], y, i);
// }
if(tt != (((x ^ y) >> i) & 1)) return 0;
}
return 1;
}
mt19937 Rand(time(NULL));
int main() {
n = read(); //ru(i, 1, n) a[i] = i; shuffle(a + 1, a + n + 1, Rand);
// a[1] = 2, a[2] = 4, a[3] = 1, a[4] = 6, a[5] = 3, a[6] = 5;
// ru(i, 1, n) printf("%d ", n - a[i]); printf("\n");
ru(i, 1, n) S[0][0].push_back(i);
ru(i, 0, 9) {
if((1 << (i + 1)) >= n) {
m = i + 1;
ru(j, 0, (1 << i) - 1) {
// printf("!!! %d %d ", m, j);
// for (auto x: S[i][j]) printf("%d ", x); printf("\n");
f[i][j] = -1;
id[j] = S[i][j][0];
if(S[i][j].size() > 1) id[j + (1 << i)] = S[i][j][1];
else vis[j + (1 << i)] = 1;
}
break;
}
set<int> tmp;
// ru(j, 0, (1 << i) - 1) {
// printf("%d %d ", i, j);
// for (auto x: S[i][j]) printf("%d ", x);
// printf("\n");
// }
// ru(j, 0, (1 << i) - 1) {
// for (auto x: S[i][j]) assert(a[x] % (1 << i) == a[S[i][j][0]] % (1 << i));
// }
ru(j, 0, (1 << i) - 1) f[i][j] = -1, tmp.insert(S[i][j].back()), tmp.insert(S[i][j][S[i][j].size() - 2]);
// printf("it's supposed to be %d\n", (1 << (i + 1)));
int bef = query(tmp);
ru(j, 0, (1 << i) - 1) {
int v = S[i][j].back(); S[i][j].pop_back(); tmp.erase(v);
S[i + 1][j] = {v};
if(S[i][j].size() == 1) {
S[i + 1][j + (1 << i)] = {S[i][j][0]};
tmp.insert(v);
continue;
}
int haha = -1;
for (auto x: S[i][j]) if(x != S[i][j].back()) {
tmp.insert(x);
// printf("bushishenmewanyi\n"); fflush(stdout);
int aft = query(tmp);
if(haha == -1) haha = aft;
S[i + 1][j + ((aft ^ bef) << i)].push_back(x);
tmp.erase(x);
}
// printf("woc:\n");
tmp.insert(v);
tmp.insert(S[i][j][0]);
tmp.erase(S[i][j].back());
int aft = query(tmp);
S[i + 1][j + ((haha ^ aft) << i)].push_back(S[i][j].back());
tmp.erase(S[i][j][0]);
tmp.insert(S[i][j].back());
}
}
// printf("m: %d\n", m); ru(j, 0, (1 << m) - 1) printf("%d ", id[j]); printf("\n");
f[0][0] = 0;
n--;
ru(i, 0, n / 2) {
set<int> t;
ru(j, 0, (1 << m) - 1) if(!vis[j]) t.insert(id[j]);
ru(j, 0, (1 << m) - 1) if(!vis[j] && chk(j, i)) {
// printf("check if p_%d=%d\n", id[j], i);
t.erase(id[j]);
if(query(t)) {work(j, i); t.insert(id[j]); break;}
t.insert(id[j]);
}
ru(j, 0, (1 << m) - 1) if(!vis[j] && chk(j, n - i)) {
// printf("check if p_%d=%d\n", id[j], n - i);
t.erase(id[j]);
if(query(t)) {work(j, n - i); break;}
t.insert(id[j]);
}
}
n++;
// printf("! "); ru(i, 1, n) printf("%d ", ans[i]);
ru(i, 1, n) ans[i] = n - ans[i];
if(ans[1] * 2 > n) {
ru(i, 1, n) ans[i] = n - ans[i] + 1;
}
// ru(i, 1, n) printf("%d ", a[i]); printf("\n");
printf("! "); ru(i, 1, n) printf("%d ", ans[i]);
return 0;
}
| cpp |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = tuple<int, int>;
using vi = vector<ll>;
using vii = vector<ii>;
using vvi = vector<vi>;
using si = set<ll>;
using vsi = vector<si>;
using qii = queue<ii>;
ll n;
vsi g;
si valid;
void dfs(int u, int p) {
valid.erase(u);
for (int v : g[u]) {
if (v == p) continue;
if (!valid.count(v)) continue;
dfs(v, u);
}
g[u].clear();
}
ii nodes(int u) {
qii q;
si s;
q.push({u, 0});
s.insert(u);
int a, k;
while (!q.empty()) {
tie(a, k) = q.front();
q.pop();
for (auto z : g[a]) {
if (s.count(z)) continue;
s.insert(z);
q.push({z, k + 1});
}
}
s.clear();
q.push({a, 0});
s.insert(a);
vi d;
int b;
while (!q.empty()) {
tie(b, k) = q.front();
q.pop();
d.push_back(b);
for (auto z : g[b]) {
if (s.count(z)) continue;
s.insert(z);
q.push({z, k + 1});
}
}
return {a, d[k/2+1]};
}
int find(int u, int v, int p) {
for (int k : g[u]) {
if (k == v) return k;
if (k == p) continue;
int r = find(k, v, u);
if (r != -1) return k;
}
return -1;
}
int main() {
cin.tie(0), ios::sync_with_stdio(0);
ll u, v;
cin >> n;
g = vsi(n);
for (int i = 0; i < n-1; i++) {
cin >> u >> v;
u--, v--;
g[u].insert(v);
g[v].insert(u);
}
valid = si();
for (int i = 0; i < n; i++) valid.insert(i);
while (valid.size() > 1) {
int u = *valid.begin();
int v, w;
tie(u, v) = nodes(u);
cout << "? " << u+1 << " " << v+1 << "\n";
cout.flush();
cin >> w;
w--;
if (w == u) {
v = find(u, v, -1);
dfs(v, u);
g[u].erase(v);
} else if (w == v) {
u = find(v, u, -1);
dfs(u, v);
g[v].erase(u);
} else {
u = find(w, u, -1);
dfs(u, w);
g[w].erase(u);
v = find(w, v, -1);
dfs(v, w);
g[w].erase(v);
}
}
cout << "! " << (*valid.begin())+1 << "\n";
cout.flush();
} | cpp |
13 | C | C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1 | [
"dp",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
const int INF = 1e15;
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int boyut; cin >> boyut;
vector<int> dizi(boyut + 1); set <int> dizi2;
for(int i = 1; i <= boyut; i++)
{
cin >> dizi[i];
dizi2.insert(dizi[i]);
}
vector <int> dizi3; dizi3.push_back(0);
for(auto it = dizi2.begin(); it != dizi2.end(); it++)
dizi3.push_back(*it);
vector <int> dp(dizi2.size() + 1);
dp[0] = INF;
for(int i = 1; i <= boyut; i++)
{
vector <int> dp2(dizi2.size() + 1);
dp2[0] = INF;
for(int j = 1; j <= dizi2.size(); j++)
{
dp2[j] = min(dp2[j -1], dp[j] + abs(dizi[i] - dizi3[j]));
}
/*
for(int i = 1; i <= dizi2.size(); i++)
cout << dp2[i] << " ";
*/
swap(dp, dp2);
//cout << "\n";
}
cout << dp[dizi2.size()];
return 0;
} | 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"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define N 300001
int parent[N], Size[N], val[N];
int c[2][N];
vector<int> Comp[N];
int st[N];
int tot = 0;
void init_dsu(int n){
for (int i = 1; i <= n; i++){
parent[i] = i;
Comp[i].push_back(i);
Size[i] = 1;
val[i] = 0;
c[0][i] = 1;
c[1][i] = 0;
st[i] = -1;
}
}
bool union_sets(int a, int b, int w){
int pa = parent[a], pb = parent[b];
if (pa == pb){
return !(val[a] ^ val[b] ^ w);
}
int offset = val[a] ^ val[b] ^ w;
if (Size[pa] > Size[pb]){
swap(pa, pb);
}
if (st[pa] == -1) tot -= min(c[0][pa], c[1][pa]);
else tot -= c[st[pa]][pa];
if (st[pb] == -1) tot -= min(c[0][pb], c[1][pb]);
else tot -= c[st[pb]][pb];
for (int v : Comp[pa]){
Comp[pb].push_back(v);
parent[v] = pb;
val[v] ^= offset;
}
Comp[pa].clear();
c[0][pb] += c[0 ^ offset][pa];
c[1][pb] += c[1 ^ offset][pa];
Size[pb] += Size[pa];
if (st[pa] != -1) st[pa] ^= offset;
st[pb] = max(st[pa], st[pb]);
if (st[pb] == -1) tot += min(c[0][pb], c[1][pb]);
else tot += c[st[pb]][pb];
return true;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, k; cin >> n >> k;
char s[n + 1];
for (int i = 1; i <= n; i++) cin >> s[i];
init_dsu(k);
vector<int> adj[n + 1];
for (int i = 0; i < k; i++){
int c; cin >> c;
for (int j = 0; j < c; j++){
int idx; cin >> idx;
adj[idx].push_back(i + 1);
}
}
for (int i = 1; i <= n; i++){
if (adj[i].empty());
else if (adj[i].size() == 1){
int v = adj[i][0];
int pv = parent[v];
if (st[pv] == -1){
tot -= min(c[0][pv], c[1][pv]);
st[pv] = (s[i] != '0') ^ val[v];
tot += c[st[pv]][pv];
}
}
else{
int a = adj[i][0], b = adj[i][1];
union_sets(a, b, s[i] == '0');
}
cout << tot << endl;
}
// cout << endl;
// for (int i = 1; i <= k; i++) cout << parent[i] << ' ';
// cout << endl;
// for (int i = 1; i <= k; i++) cout << st[i] << ' ';
// cout << endl;
// for (int i = 1; i <= k; i++) cout << val[i] << ' ';
// cout << endl;
} | cpp |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single 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 string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb. | [
"implementation",
"strings"
] | #include <bits/stdc++.h>
// #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<int>, rb_tree_tag, tree_order_statistics_node_update>
using namespace std;
typedef long long ll;
typedef long double ldb;
typedef vector<int> vi;
typedef vector<long long> vl;
typedef vector<double> vdb;
typedef vector<vector<int>> vvi;
typedef vector<vector<ll>> vvl;
typedef vector<string> vs;
typedef set<int> si;
typedef set<long long> sl;
typedef set<double> sdb;
typedef set<string> ss;
typedef set<char> sc;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define ftb(i, a, b) for (int i = a, _b = b; i <= _b; i++)
#define ft(i, a, b) for (int i = a, _b = b; i < _b; i++)
#define fgb(i, a, b) for (int i = a, _b = b; i >= _b; i--)
#define fg(i, a, b) for (int i = a, _b = b; i > _b; i--)
#define endl "\n"
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while (t--) {
string a, b, c;
cin >> a >> b >> c;
bool ok = true;
ft(i, 0, a.size()) {
if (a[i] != c[i] && b[i] != c[i]) {
ok = false;
break;
}
}
if (!ok) {
cout << "NO" << endl;
}
else cout << "YES" << endl;
}
return 0;
}
| cpp |
1313 | E | E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5]; | [
"data structures",
"hashing",
"strings",
"two pointers"
] | //Then
#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define faster ios_base::sync_with_stdio(0); cin.tie(0);
#define int long long
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair <int, int>;
mt19937_64 Rand(chrono::steady_clock::now().time_since_epoch().count());
const int maxN = 1e6 + 10;
//const int Mod = 1e9 + 7;
//const int inf =
int n, m;
template <class T> vector <int> ZFunc(const T &s){
int _n = s.length();
vector <int> z(_n);
for (int i = 1, l = 0, r = 0; i < _n; ++i){
if (i <= r){
z[i] = min(z[i - l], r - i + 1);
}
while (i + z[i] < _n && s[z[i]] == s[z[i] + i]) ++z[i];
if (i + z[i] - 1 > r){
r = i + z[i] - 1; l = i;
}
}
return z;
}
struct TBit{
ll bit[maxN];
void update(int x, int v){
for (; x <= m + 10; x += x & -x){
bit[x] += v;
}
}
ll get(int x){
ll res = 0;
for (; x > 0; x -= x & -x){
res += bit[x];
}
return res;
}
};
TBit B[2];
string a, b, s;
void Init(){
cin >> n >> m >> a >> b >> s;
vector <int> fa = ZFunc(s + "#" + a);
reverse(s.begin(), s.end());
reverse(b.begin(), b.end());
vector <int> fb = ZFunc(s + "#" + b);
fa.erase(fa.begin(), fa.begin() + s.length() + 1);
fb.erase(fb.begin(), fb.begin() + s.length() + 1);
for (int &i: fa) i = min(i, m - 1);
for (int &i: fb) i = min(i, m - 1);
reverse(fb.begin(), fb.end());
int j = 0;
while (j < min(n, m - 1)){
B[0].update(m + 1 - fb[j], 1);
B[1].update(m + 1 - fb[j], fb[j] - m + 1);
//add 2
++j;
}
ll ans = 0;
for (int i = 0; i < n; ++i){
cerr << fa[i] + 1;
ans += fa[i] * B[0].get(fa[i] + 1) + B[1].get(fa[i] + 1);
B[0].update(m + 1 - fb[i], -1);
B[1].update(m + 1 - fb[i], m - 1 - fb[i]);
if (j < n){
B[0].update(m + 1 - fb[j], 1);
B[1].update(m + 1 - fb[j], fb[j] - m + 1);
++j;
}
}
cout << ans;
}
#define debug
#define taskname "test"
signed main(){
faster
if (fopen(taskname".inp", "r")){
freopen(taskname".inp", "r", stdin);
freopen(taskname".out", "w", stdout);
}
int tt = 1;
//cin >> tt;
while (tt--){
Init();
}
if (fopen("timeout.txt", "r")){
ofstream timeout("timeout.txt");
timeout << signed(double(clock()) / CLOCKS_PER_SEC * 1000);
timeout.close();
#ifndef debug
cerr << "Time elapsed: " << signed(double(clock()) / CLOCKS_PER_SEC * 1000) << "ms\n";
#endif // debug
}
}
| 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 main(){
int n;
cin >> n;
pair<int, int> sc, dp;
vector<int> areas(4,0);
for(int i=0; i<n; i++){
cin >> sc.first >> sc.second >> dp.first >> dp.second;
areas[0] = (dp.first * sc.second);
areas[1] = (sc.first * (sc.second - dp.second - 1));
areas[2] = (dp.second * sc.first);
areas[3] = ((sc.first - dp.first - 1) * sc.second);
int max = areas[0];
for(int j =1; j<4; j++){
if(max < areas[j]) max = areas[j];
}
cout << max << endl;
}
}
| cpp |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vb = vector<bool>;
using vll = vector<ll>;
using vs = vector<string>;
#define ALL(v) v.begin(), v.end()
#define SORT(v) sort(ALL(v))
#define SZ(v) int(v.size())
#ifdef DLOCAL
#include <local.h>
#else
#define deb(...);
#endif
void solve() {
ll n, a, b, k; cin >> n >> a >> b >> k;
vll monsters(n);
for (int i = 0; i < n; ++i) {
cin >> monsters[i];
}
deb(monsters);
ll c = (a + b);
vll skips(n);
for (int i = 0; i < n; ++i) {
ll total = (monsters[i] + c - 1) / c;
ll health = max(0ll, monsters[i] - total * c + b);
ll skips_needed = (health + a - 1) / a;
skips[i] = skips_needed;
}
SORT(skips);
int ans = 0;
for (int i = 0; i < n; ++i) {
if (skips[i] > k) break;
ans++;
k -= skips[i];
}
cout << ans;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
//ifstream cin ("puzzle_name.in");
//ofstream cout ("puzzle_name.out");
solve();
return 0;
}
| cpp |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds. | [
"greedy"
] | #include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define fi first
#define se second
#define ull unsigned long long
#define ld long double
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define in freopen ("input.txt", "r", stdin);
#define out freopen("output.txt", "w", stdout);
using namespace std;
const ll INF = 1e18;
const ll inf = -1e18;
const ll mod = 1e9 + 33;
const ld eps = 1e-14;
const ld pi = acos(-1);
ll test = 1;
ll mx = inf, mn = INF, sum, res, pos, save;
string s;
ll r;
void solve()
{
ll n;
cin >> n;
cin >> s;
pos = -1;
for(int i = 0;i < s.size();i ++)
{
if(s[i] == '(') r++;
if(s[i] == ')') r--;
if(r < 0 && pos == -1)
pos = i;
else if(r >= 0)
{
if(pos != -1)
{
res += i - pos + 1;
pos = -1;
r = 0;
}
}
}
if(r != 0)
{
cout << -1;
}
else
{
cout << res;
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
srand(time(0));
//cin >> test;
while(test --)
{
solve();
cout << '\n';
}
}
| cpp |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | #include<iostream>
#include<cstring>
#include<random>
#include<cmath>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
const int maxn = 2e5 + 5;
static const ULL mod = (1ull << 61) - 1;
ULL power[maxn];
mt19937_64 rnd(random_device{}());
uniform_int_distribution<ULL> dist(100, mod - 1);
const ULL base = dist(rnd);
const ULL v[2] = {dist(rnd), dist(rnd)};
static inline ULL add(ULL a, ULL b){
a += b;
if (a >= mod) a -= mod;
return a;
}
static inline ULL mul(ULL a, ULL b){
__uint128_t c = __uint128_t(a) * b;
return add(c >> 61, c & mod);
}
ULL merge(ULL h1, ULL h2, int len2){
return add(mul(h1, power[len2]), h2);
}
void init(int n){
power[0] = 1;
for(int i = 1; i <= n; i++)
power[i] = mul(power[i - 1], base);
}
int s[maxn], pre[maxn];
ULL query(const vector<ULL> &s, int l, int r){
return add(s[r], mod - mul(s[l], power[pre[r] - pre[l]]));
}
int main(){
#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
int n;
cin >> n;
for(int i = 1; i <= n; i++){
char c;
cin >> c;
s[i] = c - '0';
pre[i] = pre[i - 1] + (s[i] == 0);
}
init(n);
vector<ULL> hsh[2];
hsh[0].assign(n + 1, 0);
hsh[1].assign(n + 1, 0);
for(int i = 1; i <= n; i++){
if (s[i]){
hsh[0][i] = hsh[0][i - 1];
hsh[1][i] = hsh[1][i - 1];
}
else{
hsh[0][i] = add(mul(hsh[0][i - 1], base), v[i & 1]);
hsh[1][i] = add(mul(hsh[1][i - 1], base), v[(i & 1) ^ 1]);
}
}
int m;
cin >> m;
while(m--){
int l1, l2, len;
cin >> l1 >> l2 >> len;
int r1 = l1 + len - 1, r2 = l2 + len - 1;
if (query(hsh[l1 & 1], l1 - 1, r1) == query(hsh[l2 & 1], l2 - 1, r2)) cout << "Yes" << '\n';
else cout << "No" << '\n';
}
} | cpp |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | #include <stdio.h>
#include <random>
#include <time.h>
#include <set>
#define int long long
std::mt19937 random_pool(time(NULL));
std::set<int> PrimeFactor;
int n, a[200001], m = 1e18;
inline void Decompose(int x)
{
if(x <= 0)
return;
for(register int i = 2; i * i <= x; ++ i)
if(!(x % i))
{
PrimeFactor.insert(i);
while(!(x % i))
x /= i;
}
if(x != 1)
PrimeFactor.insert(x);
}
signed main()
{
scanf("%lld", &n);
for(register int i = 1; i <= n; ++ i)
scanf("%lld", a + i);
for(register int i = 1; i <= 50; ++ i)
{
int item = a[random_pool() % n + 1];
Decompose(item - 1);
Decompose(item);
Decompose(item + 1);
}
for(auto i : PrimeFactor)
{
int sum = 0;
for(register int j = 1; j <= n; ++ j)
sum += a[j] > i ? std::min(a[j] % i, i - a[j] % i) : i - a[j];
m = std::min(m, sum);
}
printf("%lld", m);
}
| 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>
#define ll long long int
#define debug(x) cout<<"x = "<<x<<endl;
using namespace std;
int fx[]= {1,-1,0,0,1,-1,1,-1};
int fy[]= {0,0,1,-1,1,-1,-1,1};
const ll MOD = 1e9+7;
void solve(int tt)
{
int n;
cin>>n;
string s;
cin>>s;
vector<int>a[26];
for(int i=0; i<n; i++)a[s[i]-'a'].push_back(i);
if(n==1)
{
cout<<0<<endl;
return;
}
int cnt=0;
set<int>st;
for(char c='z'; c>'a'; c--)
{
for(int j=0; j<a[c-'a'].size(); j++)
{
int ind=a[c-'a'][j];
if(st.find(ind)==st.end())
{
int k1=ind+1;
int k2=ind-1;
while(k1<n && (s[k1]==c || st.find(k1)!=st.end()))
{
k1++;
}
while(k2>=0 && (s[k2]==c || st.find(k2)!=st.end()))
{
k2--;
}
if(k1<n && s[k1]==(c-1))
{
for(int k=ind; k<k1; k++)
{
if(st.find(k)==st.end())
{
st.insert(k);
cnt++;
}
}
}
else if(k2>=0 && s[k2]==(c-1))
{
for(int k=ind; k>k2; k--)
{
if(st.find(k)==st.end())
{
st.insert(k);
cnt++;
}
}
}
}
}
}
cout<<cnt<<endl;
}
int32_t main()
{
//freopen("00_input.txt","r+",stdin);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int test=1;
//cin>>test;
for(int t=1; t<=test; t++)
{
solve(t);
}
return 0;
}
| cpp |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define fr(i, a, b) for (int i = a; i < b; i++)
#define frr(i, a, b) for (int i = a; i >= b; i--)
#define pb push_back
#define ff first
#define ss second
#define pr pair<int,int>
// #define M 1000000007
#define lld long double
#define timetaken cerr<<"Time : "<<1000*(long double)clock()/(long double)CLOCKS_PER_SEC<<"ms\n"
int oo=999999999999999999;
int no=-999999999999999999;
//vector<vector<int>> vec(n,vector<int>(m,0));
const int N=250005;
void solve()
{
int n,M;
cin>>n>>M;
int fact[N];
fact[0]=fact[1]=1;
fr(i,2,N)
fact[i]=(fact[i-1]*i)%M;
int ans=0;
fr(j,0,n)
{
int x=((n-j)*(n-j))%M;
x=(x*fact[j+1])%M;
x=(x*fact[n-j-1])%M;
ans=(ans+x)%M;
}
cout<<ans;
}
int32_t main()
{
ios_base::sync_with_stdio(false); cin.tie(NULL);
int t=1;
// cin>>t;
while(t--)
{
solve();
cout<<"\n";
}
timetaken;
} | cpp |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | #pragma GCC optimize ("O3")
#include <bits/stdc++.h>
#define ll long long
#define endl '\n'
#define fast ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define file freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
using namespace std;
const int OO = 0x3f3f3f3f, N = 1e5 + 5, mod = 1e9 + 7;
int n, p, k;
vector<pair<int, int>> a;
int s[N][10];
ll dp[N][1 << 7];
ll go(int idx, int msk) {
if (idx == n && msk == (1 << p) - 1)
return 0;
if (idx == n)
return INT64_MIN;
ll &ans = dp[idx][msk];
if (~ans)
return ans;
ans = 0;
ans = go(idx + 1, msk);
if (idx - __builtin_popcount(msk) + 1 <= k) {
ans = go(idx + 1, msk) + a[idx].first;
}
for (int j = 0; j < p; j++) {
if (!((1 << j) & msk)) {
ans = max(ans, go(idx + 1, msk | (1 << j)) + s[a[idx].second][j]);
}
}
return ans;
}
void solve() {
cin >> n >> p >> k;
int tot = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a.push_back({x, i});
}
for (int j = 0; j < n; j++) {
for (int i = 0; i < p; i++) {
cin >> s[j][i];
}
}
sort(a.rbegin(), a.rend());
memset(dp, -1, sizeof dp);
cout << go(0, 0) << endl;
}
int main() {
fast;
int tc = 1;
// cin >> tc;
while (tc--) {
solve();
}
}
| cpp |
1324 | E | E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good. | [
"dp",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
/*-----------------*/
#define ll long long
#define ld long double
#define ever (;;)
#define all(v) v.begin(),v.end()
#define allr(v) v.rbegin(),v.rend()
#define PB push_back
#define F first
#define S second
#define MOD 1000000007
#define Dracarys ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//string binary=bitset<8>(n).to_string();
const int N = 1e5 + 10;
int n, h, l, r;
vector<int>v;
int DP[2001][2001];
bool check(int num) { return (num >= l && num <= r); }
int Dp(int i, int Time)
{
if (i == n)
return 0;
int& ret = DP[i][Time];
if (ret != -1)
return ret;
int val1 = (Time + v[i]) % h;
int val2 = (Time + v[i] - 1) % h;
int Ans1, Ans2;
if (check(val1))
Ans1 = Dp(i + 1, val1) + 1;
if (!check(val1))
Ans1 = Dp(i + 1, val1);
if (check(val2))
Ans2 = Dp(i + 1, val2) + 1;
if (!check(val2))
Ans2 = Dp(i + 1, val2);
return ret = max(Ans1, Ans2);
}
void OverFlow()
{
cin >> n >> h >> l >> r;
v.resize(n);
for (auto& it : v)cin >> it;
memset(DP, -1, sizeof(DP));
cout << Dp(0, 0);
}
int main()
{
Dracarys
int t = 1;
//cin >> t;
while (t--)
{
OverFlow();
}
return 0;
}
| cpp |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <ranges>
#include <set>
#include <string>
#include <vector>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V> &x) {
cerr << '{';
__print(x.first);
cerr << ',';
__print(x.second);
cerr << '}';
}
template <typename T>
void __print(const T &x) {
int f = 0;
cerr << '{';
for (auto &i : x) cerr << (f++ ? "," : ""), __print(i);
cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
__print(t);
if (sizeof...(v)) cerr << ", ";
_print(v...);
}
#ifdef DUPA
#define debug(x...) \
cerr << "[" << #x << "] = ["; \
_print(x)
#else
#define debug(x, ...)
#endif
typedef long long LL;
// HMMMM
#define int LL
int sum(vector<int> &tree, int k) {
k++;
int s = 0;
while (k >= 1) {
s += tree[k];
k -= k & -k;
}
return s;
}
void add(vector<int> &tree, int k, int x) {
k++;
while (k < tree.size()) {
tree[k] += x;
k += k & -k;
}
}
typedef pair<int, int> PII;
typedef pair<int, PII> PIII;
const int INF = 1e18 + 1;
vector<PII> clean(vector<PII> a) {
sort(all(a), [](PII i, PII j) { return i.second < j.second; });
vector<PII> res;
for (auto [x, y] : a) {
if (res.empty())
res.push_back({x, y});
else {
assert(res.back().second <= y);
if (res.back().second == y) {
if (res.back().first <= x) {
res.pop_back();
res.push_back({x, y});
}
} else {
assert(res.back().second < y);
if (res.back().first < x) {
res.push_back({x, y});
}
}
}
}
for (int i = 1; i < res.size(); i++) {
assert(res[i - 1].first < res[i].first);
assert(res[i - 1].second < res[i].second);
}
return res;
}
const int inf = INF;
typedef vector<int> vi;
struct Node {
Node *l = 0, *r = 0;
int lo, hi, mset = -inf, madd = 0, val = -inf;
~Node() {
if (!l) return;
delete l;
delete r;
}
Node(int _lo, int _hi) : lo(_lo), hi(_hi) {} // Large interva l of −in f
Node(vi &v, int _lo, int _hi) : lo(_lo), hi(_hi) {
if (lo + 1 < hi) {
int mid = lo + (hi - lo) / 2;
l = new Node(v, lo, mid);
r = new Node(v, mid, hi);
val = max(l->val, r->val);
} else
val = v[lo];
}
int query(int L, int R) {
if (R <= lo || hi <= L) return inf;
if (L <= lo && hi <= R) return val;
push();
return max(l->query(L, R), r->query(L, R));
}
void set(int L, int R, int x) {
if (R <= lo || hi <= L) return;
if (L <= lo && hi <= R)
mset = val = x, madd = 0;
else {
push(), l->set(L, R, x), r->set(L, R, x);
val = max(l->val, r->val);
}
}
void add(int L, int R, int x) {
if (R <= lo || hi <= L) return;
if (L <= lo && hi <= R) {
if (mset != -inf)
mset += x;
else
madd += x;
val += x;
} else {
push(), l->add(L, R, x), r->add(L, R, x);
val = max(l->val, r->val);
}
}
void push() {
if (!l) {
int mid = lo + (hi - lo) / 2;
l = new Node(lo, mid);
r = new Node(mid, hi);
}
if (mset != -inf)
l->set(lo, hi, mset), r->set(lo, hi, mset), mset = -inf;
else if (madd)
l->add(lo, hi, madd), r->add(lo, hi, madd), madd = 0;
}
};
const int MAXN = 1e6 + 100;
int solve(vector<PII> a, vector<PII> b, vector<tuple<int, int, int>> c) {
a = clean(a);
b = clean(b);
sort(rall(c));
int res = -INF;
// vector<int> d(MAXN + 1, -INF);
Node *tr = new Node(0, MAXN + 1);
for (auto [j, bj] : b) {
// d[j] = -bj;
tr->set(j, j + 1, -bj);
}
for (auto [i, ci] : a) {
while (!c.empty() && get<0>(c.back()) < i) {
auto x = get<1>(c.back());
auto y = get<2>(c.back());
// for (int j = x + 1; j < d.size(); j++) d[j] += y;
tr->add(x + 1, MAXN + 1, y);
c.pop_back();
}
// int curr = -INF;
// for (auto j : d) curr = max(curr, j);
// assert(curr == tr->query(0, MAXN + 1));
int curr = tr->query(0, MAXN + 1);
res = max(res, curr - ci);
}
delete tr;
return res;
}
int solve2() {
int n, m, p;
cin >> n >> m >> p;
vector<PII> a(n), b(m);
vector<tuple<int, int, int>> c(p);
for (auto &[x, y] : a) cin >> x >> y;
for (auto &[x, y] : b) cin >> x >> y;
for (auto &[x, y, z] : c) cin >> x >> y >> z;
return solve(a, b, c);
}
#undef int
int main() {
ios::sync_with_stdio(false);
cin.exceptions(cin.failbit);
cin.tie(0);
int t = 1;
#ifdef DUPA
#endif
for (int i = 0; i < t; i++) cout << solve2() << "\n";
}
| 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>
#define REP(i,n) for(int i = 0; i< (n);i++)
#define all(x) (x).begin(), (x).end()
#define f first
#define s second
#define SZ(a) (int)a.size()
#define bit(x,i)(((x)>>(i))&1)
typedef long long ll;
using namespace std;
ll m;
void solve(){
ll n; cin >> n >> m;
vector<ll> v(n);
ll ans = 1;
for(auto &x : v){
cin >> x;
}
if(n > m){
cout << 0 << endl;
return;
}
for(int i = 0; i < n; ++i){
for(int j = i + 1; j < n; ++j){
ans *= abs(v[i] - v[j]);
ans %= m;
}
}
cout << ans << endl;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
solve();
}
| cpp |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define all(x) x.begin(),x.end()
#define pb push_back
#define ll long long
#define repp(n) for(int i=0;i<n;i++)
//typedef __int128 lll;
const ll MOD=998244353;
const ll mod = 1e9+7;
#define ret(a) cout<<a<<"\n"; return
void solve(){
ll n,q;
cin>>n>>q;
ll a[2][n];
memset(a,0,sizeof(a));
ll block=0;
while(q--){
ll x,y;
cin>>x>>y;
x--;y--;
ll temp = x;
temp--;
if(temp<0)
temp+=2;
//cout<<temp<<endl;
for(int i=-1;i<=1;i++){
if(a[x][y]){
if(y+i>=0 && y+i<n){
if(a[temp][y+i])block--;
}
}
else{
if(y+i>=0 && y+i<n){
if(a[temp][y+i])block++;
}
}
}
a[x][y]--;
a[x][y]%=2;
//cout<<block<<endl;
if(block)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// int t;
// cin>>t;
// while(t--)
solve();
return 0;
} | cpp |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, q;
scanf("%d%d", &n, &q);
set<pair<int,int>> cells; // O(log) per operation
int bad_nei = 0;
for(int i = 0; i < q; i++) {
int row, col;
scanf("%d%d", &row, &col);
bool was_forbidden = cells.count({row, col});
for(int r = row - 1; r <= row + 1; r++) {
for(int c = col - 1; c <= col + 1; c++) {
if(r == row) {
continue;
}
if(!(1 <= r && r <= 2 && 1 <= c && c <= n)) {
continue;
}
if(cells.count({r, c})) {
if(was_forbidden) {
bad_nei--;
}
else {
bad_nei++;
}
}
}
}
if(cells.count({row, col})) {
cells.erase({row, col});
}
else {
cells.insert({row, col});
}
if(bad_nei >= 1) {
puts("NO");
}
else {
puts("YES");
}
}
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<iostream>
#include<cstring>
#include<vector>
#include<array>
#include<cassert>
using namespace std;
using LL = long long;
const int maxn = 5005;
int s[maxn][maxn];
vector<pair<int, int> > p[maxn];
template<const int T>
struct ModInt {
const static int mod = T;
int x;
ModInt(int x = 0) : x(x % mod) {}
ModInt(long long x) : x(int(x % mod)) {}
int val() { return x; }
ModInt operator + (const ModInt &a) const { int x0 = x + a.x; return ModInt(x0 < mod ? x0 : x0 - mod); }
ModInt operator - (const ModInt &a) const { int x0 = x - a.x; return ModInt(x0 < 0 ? x0 + mod : x0); }
ModInt operator * (const ModInt &a) const { return ModInt(1LL * x * a.x % mod); }
ModInt operator / (const ModInt &a) const { return *this * a.inv(); }
void operator += (const ModInt &a) { x += a.x; if (x >= mod) x -= mod; }
void operator -= (const ModInt &a) { x -= a.x; if (x < 0) x += mod; }
void operator *= (const ModInt &a) { x = 1LL * x * a.x % mod; }
void operator /= (const ModInt &a) { *this = *this / a; }
friend ostream &operator<<(ostream &os, const ModInt &a) { return os << a.x;}
ModInt pow(int64_t n) const {
ModInt res(1), mul(x);
while(n){
if (n & 1) res *= mul;
mul *= mul;
n >>= 1;
}
return res;
}
ModInt inv() const {
int a = x, b = mod, u = 1, v = 0;
while (b) {
int t = a / b;
a -= t * b; swap(a, b);
u -= t * v; swap(u, v);
}
if (u < 0) u += mod;
return u;
}
};
typedef ModInt<1000000007> mint;
int mx[maxn];
int main(){
#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; i++){
int x;
cin >> x;
for(int j = 1; j <= n; j++)
s[i][j] = s[i - 1][j];
s[i][x]++;
}
for(int i = 1; i <= m; i++){
int f, h;
cin >> f >> h;
pair<int, int> t;
if (s[n][f] >= h){
for(int j = 1; j <= n; j++){
if (s[j][f] == h){
t.first = j;
break;
}
}
for(int j = n; j >= 1; j--){
if (s[n][f] - s[j - 1][f] == h){
t.second = j;
break;
}
}
p[f].push_back(t);
}
}
int t = 0;
for(int i = 0; i <= n; i++){
for(int j = 1; j <= n; j++){
int cnt1 = 0, cnt2 = 0, cnt3 = 0;
for(auto [x, y] : p[j]){
if (x <= i && y > i) cnt3++;
else if (x <= i) cnt1++;
else if (y > i) cnt2++;
}
if (cnt3 == 0) mx[i] += min(1, cnt1) + min(1, cnt2);
else mx[i] += min(2, cnt1 + cnt2 + cnt3);
}
t = max(t, mx[i]);
}
if (t == 0){
cout << 0 << ' ' << 1 << '\n';
return 0;
}
mint inv2 = mint(2).inv();
auto C2 = [&](int x){
return mint(x) * mint(x - 1) * inv2;
};
auto solve = [&](int last){
if (mx[last] != t) return mint(0);
mint ans = 1;
for(int i = 1; i <= n; i++){
int cnt1 = 0, cnt2 = 0, cnt3 = 0;
int type = 0;
for(auto [x, y] : p[i]){
if (last == x){
if (x <= last && y > last) type = 3;
else if (x <= last) type = 1;
else if (y > last) type = 2;
}
else{
if (x <= last && y > last) cnt3++;
else if (x <= last) cnt1++;
else if (y > last) cnt2++;
}
}
assert(type != 2);
if (cnt1 + cnt2 + cnt3 == 0) continue;
if (type == 0){
if (cnt3 == 0){
ans *= mint(max(1, cnt1)) * mint(max(1, cnt2));
}
else{
if (cnt1 == 0 && cnt2 == 0){
if (cnt3 > 1) ans *= C2(cnt3) * mint(2);
else ans *= mint(2);
}
else{
mint cnt = C2(cnt3) * mint(2);
if (cnt1 >= 1 && cnt2 >= 1)
cnt += mint(cnt1) * mint(cnt2);
if (cnt1 >= 1)
cnt += mint(cnt1) * mint(cnt3);
if (cnt2 >= 1)
cnt += mint(cnt2) * mint(cnt3);
ans *= cnt;
}
}
}
else if (type == 1){
if (cnt2 + cnt3 > 0) ans *= mint(cnt2 + cnt3);
}
else if (type == 2){
if (cnt1 + cnt3 > 0) ans *= mint(cnt1 + cnt3);
}
else{
if (cnt1 + cnt2 + cnt3 > 0) ans *= mint(cnt1 + cnt2 + cnt3);
}
}
return ans;
};
mint ans = solve(0);
for(int i = 1; i <= n; i++){
for(auto [x, y] : p[i]){
ans += solve(x);
}
}
cout << t << ' ' << ans << '\n';
} | cpp |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"data structures",
"dp",
"greedy"
] | #include<bits/stdc++.h>
#define int long long
using namespace std;
const int MAX = 5e5 + 5;
int arr[MAX], ldp[MAX], rdp[MAX], ans[MAX];
signed main(){
//ios_base::sync_with_stdio(0), cin.tie(0);
int n;
cin >> n;
for(int i = 1; i <= n; ++i) cin >> arr[i];
stack<int> stk;
for(int i = 1; i <= n; ++i){
while(!stk.empty() && arr[stk.top()] >= arr[i]) stk.pop();
if (!stk.empty()){
int last = stk.top();
ldp[i] = arr[i]*(i-last) + ldp[last];
}else ldp[i] = arr[i]*i;
stk.push(i);
}
stk = stack<int>();
for(int i = n; i >= 1; --i){
while(!stk.empty() && arr[stk.top()] >= arr[i]) stk.pop();
if (!stk.empty()){
int last = stk.top();
rdp[i] = arr[i]*(last-i) + rdp[last];
}else rdp[i] = arr[i]*(n-i+1);
stk.push(i);
}
int id = 0;
auto cnt = [&](int idx){return ldp[idx]+rdp[idx]-arr[idx];};
for(int i = 1; i <= n; ++i)
if (!id || (cnt(id) < cnt(i))) id = i;
int tmp = id;
int now = arr[id];
while(id >= 1){
if (arr[id] < now) now = arr[id];
ans[id--] = now;
}
id = tmp;
now = arr[id];
while(id <= n){
if (arr[id] < now) now = arr[id];
ans[id++] = now;
}
for(int i = 1; i <= n; ++i)
cout << ans[i] << " \n"[i == n];
return 0;
}
| 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"
] | # include <bits/stdc++.h>
using namespace std;
int T;
int n,m,f[60];
inline char get_(int x) { return x==1 ? 'C' : x==2 ? 'H' : 'O';}
int main() {
scanf("%d",&T);
while (T--) {
memset(f,0,sizeof(f));
scanf("%d",&n);
printf("? CC\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=1, f[x+1]=1;
printf("? CH\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=1, f[x+1]=2;
printf("? CO\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=1, f[x+1]=3;
printf("? OH\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=3, f[x+1]=2;
if (n>4) {
printf("? HH\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=2;
for (int i=2;i<n;i++) if (!f[i]) f[i]=3;
if (f[1]&&f[n]) {
printf("! ");
for (int i=1;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
else if (f[1]) {
printf("? ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
}
else {
printf("! ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("O\n"), fflush(stdout);
scanf("%d",&m);
}
}
else if (f[n]) {
printf("? O");
for (int i=2;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! O");
for (int i=2;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
else {
printf("! H");
for (int i=2;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
}
else {
printf("? O");
for (int i=2;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! O");
for (int i=2;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
continue;
}
printf("? O");
for (int i=2;i<n;i++) printf("%c",get_(f[i]));
printf("O\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! O");
for (int i=2;i<n;i++) printf("%c",get_(f[i]));
printf("O\n"), fflush(stdout);
scanf("%d",&m);
continue;
}
printf("? H");
for (int i=2;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! H");
for (int i=2;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
continue;
}
printf("! H");
for (int i=2;i<n;i++) printf("%c",get_(f[i]));
printf("O\n"), fflush(stdout);
scanf("%d",&m);
}
}
else {
if (f[1]||f[n]) {
printf("? HH\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=2;
for (int i=2;i<n;i++) if (!f[i]) f[i]=3;
if (f[1]&&f[n]) {
printf("! ");
for (int i=1;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
else if (f[1]) {
printf("? ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
}
else {
printf("! ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("O\n"), fflush(stdout);
scanf("%d",&m);
}
}
else {
printf("? O");
for (int i=2;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! O");
for (int i=2;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
else {
printf("! H");
for (int i=2;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
}
}
else if (f[2]==1&&f[3]==3) {
printf("? OC\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=3, f[x+1]=1;
if (!f[1]) f[1]=2;
if (!f[4]) f[4]=3;
printf("! ");
for (int i=1;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
else if (f[2]==1&&f[3]==2) {
printf("? HC\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=1;
if (!f[1]) f[1]=3;
if (f[n]) {
printf("! ");
for (int i=1;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
else {
printf("? %cCHO\n",get_(f[1])), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! %cCHO\n",get_(f[1])), fflush(stdout);
scanf("%d",&m);
}
else {
printf("! %cCHH\n",get_(f[1])), fflush(stdout);
scanf("%d",&m);
}
}
}
else if (f[2]==3&&f[3]==2) {
printf("? HO\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=3;
if (!f[1]) f[1]=3;
if (f[n]) {
printf("! ");
for (int i=1;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
else {
printf("? %cOHC\n",get_(f[1])), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! %cOHC\n",get_(f[1])), fflush(stdout);
scanf("%d",&m);
}
else {
printf("! %cOHH\n",get_(f[1])), fflush(stdout);
scanf("%d",&m);
}
}
}
else {
printf("? HH\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=2, f[x+1]=2;
if (m) {
if (f[4]) {
printf("! HHHH\n"), fflush(stdout);
scanf("%d",&m);
}
else {
if (!f[3]) f[3]=3;
printf("? ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x);
if (m) {
printf("! ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("C\n"), fflush(stdout);
scanf("%d",&m);
}
else {
printf("! ");
for (int i=1;i<n;i++) printf("%c",get_(f[i]));
printf("O\n"), fflush(stdout);
scanf("%d",&m);
}
}
}
else {
printf("? OOO\n"), fflush(stdout);
scanf("%d",&m);
for (int x,i=1;i<=m;i++) scanf("%d",&x), f[x]=3, f[x+1]=3, f[x+2]=3;
if (!f[1]) f[1]=2;
if (!f[n]) f[n]=1;
printf("! ");
for (int i=1;i<=n;i++) printf("%c",get_(f[i]));
printf("\n"), fflush(stdout);
scanf("%d",&m);
}
}
}
}
return 0;
} | cpp |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | #include<bits/stdc++.h>
#define int long long
#define fa(i,a,n) for(int i=a;i<n;i++)
#define pb push_back
#define bp pop_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define vi vector<int>
#define Utaval ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
void solve(){
int n;
cin>>n;
string s;
cin>>s;
map<pair<int,int>,int>m;
int ans = INT_MAX;
m[{0,0}]=0;
int x=0,y=0,co1,co2;
fa(i,0,n){
if(s[i]=='R')x++;
else if(s[i]=='L')x--;
else if(s[i]=='U')y++;
else y--;
if(m[{x,y}] || x==0 && y==0){
// cout<<i+1<<" "<<m[{x,y}]<<endl;
if(i+1-m[{x,y}]<ans){
co1=m[{x,y}]+1;
co2=i+1;
ans = i+1-m[{x,y}];
}
}
m[{x,y}]=i+1;
}
if(ans==INT_MAX)cout<<-1<<endl;
else cout<<co1<<" "<<co2<<endl;
return;
}
signed main()
{
Utaval;
int t=1;
cin>>t;
while(t--)
solve();
} | 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>
#define nl "\n"
#define fi first
#define se second
#define pi 3.14159
#define ll long long
#define odd(a) (a&1)
#define even(a) !(a&1)
#define Mod 1'000'000'007
#define INF 2'000'000'000
#define sz(x) int(x.size())
#define charToInt(s) (s - '0')
#define ull unsigned long long
#define number_line iota(all(vec) , 1)
#define all(s) s.begin(), s.end()
#define rall(v) v.rbegin() , v.rend()
#define fixed(n) fixed << setprecision(n)
#define Num_of_Digits(n) ((int)log10(n) + 1)
#define to_decimal(bin) stoll(bin, nullptr, 2)
#define Ceil(n, m) (((n) / (m)) + ((n) % (m) ? 1 : 0))
#define Floor(n, m) (((n) / (m)) - ((n) % (m) ? 0 : 1))
#define Upper(s) transform(all(s), s.begin(), ::toupper);
#define Lower(s) transform(all(s), s.begin(), ::tolower);
#define cout_map(mp) for(auto& [f, s] : mp) cout << f << " " << s << "\n";
// ----- bits-------
#define pcnt(n) __builtin_popcount(n)
#define pcntll(n) __builtin_popcountll(n)
#define clz(n) __builtin_clz(n) // <---100
#define clzll(n) __builtin_clzll(n)
#define ctz(n) __builtin_ctz(n) // 0001---->
#define ctzll(n) __builtin_ctzll(n)
using namespace std;
template < typename T = int > istream& operator >> (istream &in, vector < T > & v){
for(auto & x : v) in >> x;
return in;
}
template < typename T = int > ostream& operator << (ostream &out, const vector < T > & v){
for(const T & x : v) out << x << " ";
return out;
}
void esraa()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif
}
void solve(){
ll a , b , c;
cin >> a >> b >> c;
ll x , y , z , mini = 1e18;
for(ll i = 1; i <= 2 * a; i++){
for(ll j = i; j <= 2 * b; j += i){
for(ll k = j; k <= 2 * c; k += j){
ll temp = abs(a - i) + abs(b - j) + abs(c - k);
if(temp < mini){
mini = temp;
x = i;
y = j;
z = k;
}
}
}
}
cout << mini << nl;
cout << x << " " << y << " " << z << nl;
}
int main()
{
esraa();
int t = 1;
cin >> t;
//cin.ignore();
while(t--)
solve();
return 0;
} | cpp |
1290 | F | F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is: | [
"dp"
] | #include <bits/stdc++.h>
using namespace std;
typedef double db;
//#define int long long
#define fi first
#define se second
#define mk make_pair
#define pb emplace_back
#define poly vector<int>
#define Bt(a) bitset<a>
#define bc __builtin_popcount
#define pc putchar
#define ci const int&
char sss;
const int mod = 998244353;
const db eps = 1e-10;
inline int Max(ci x, ci y) {return x > y ? x : y;}
inline int Min(ci x, ci y) {return x < y ? x : y;}
inline db Max(db x, db y) {return x - y > eps ? x : y;}
inline db Min(db x, db y) {return x - y < eps ? x : y;}
inline int Add(ci x, ci y, ci M = mod) {return (x + y) >= M ? (x + y - M) : (x + y);}
inline int Mul(ci x, ci y, ci M = mod) {return 1ll * x * y % M;}
inline int Dec(ci x, ci y, ci M = mod) {return (x - y) < 0 ? (x - y + M) : (x - y);}
typedef pair<int, int> pii;
inline int Abs(int x) {return x < 0 ? -x : x;}
//char buf[1<<21],*p1=buf,*p2=buf;
//#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
char Obuf[105000],*O=Obuf;//Siz shoule be the size of Out File
int pst[30],ptop;
inline void Fprint(){fwrite(Obuf,1,O-Obuf,stdout);}
inline void Fwrite(int x){
if(x==0){*O++='0';if(O-Obuf>100000)Fprint(),O=Obuf;return;}
if(x<0)*O++='-',x=-x;ptop=0;
while(x)pst[++ptop]=x%10,x/=10;
while(ptop)*O++=pst[ptop--]+'0';
if(O-Obuf>100000)Fprint(),O=Obuf;
}
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') w = -1;ch = getchar();}
while (isdigit(ch)) {s = s * 10 + ch - '0';ch = getchar();}
return s * w;
}
inline void write(int x) {
if (x < 0)putchar('-'), x = -x;
if (x > 9)write(x / 10);
pc(x % 10 + '0');
}
inline int qpow(int x, int y) {
int res = 1;
while (y) {if (y & 1)res = Mul(res, x);x = Mul(x, x);y >>= 1;}
return res;
}
inline void cadd(int &x, int y) {x += y;}
inline void cmul(int &x, int y) {x *= y;}
inline void cmax(int &x, int y) {x = Max(x, y);}
inline void cmin(int &x, int y) {x = Min(x, y);}
const int N = 1 << 24;
const int SN = 31, SM = 25;
namespace Refined_heart{
int f[SN][SM][SM][SM][SM][2][2];
int n, m, x[5], y[5];
int dfs(int now, int zx, int fx, int zy, int fy, int okx, int oky) {
if(now == 30) {
if(zx || fx || zy || fy) return 0;
if(okx || oky) return 0;
if(zx != fx || zy != fy) return 0;
return 1;
}
int &res = f[now][zx][fx][zy][fy][okx][oky];
if(~res) return res;
res = 0;
for(int i = 0; i < (1 << n); ++i) {
int nzx = zx, nzy = zy, nfx = fx, nfy = fy;
int ox = okx, oy = oky;
for(int k = 0; k < n; ++k) {
if(!(i >> k & 1)) continue;
if(x[k] > 0) nzx += x[k];
else nfx += -x[k];
if(y[k] > 0) nzy += y[k];
else nfy += -y[k];
}
int dzx = nzx & 1, dzy = nzy & 1;
int dfx = nfx & 1, dfy = nfy & 1;
if(dzx != dfx) continue;
if(dzy != dfy) continue;
if(dzx > (m >> now & 1)) ox = 1;
if(dzy > (m >> now & 1)) oy = 1;
if(dzx < (m >> now & 1)) ox = 0;
if(dzy < (m >> now & 1)) oy = 0;
int jzx = nzx >> 1, jfx = nfx >> 1;
int jzy = nzy >> 1, jfy = nfy >> 1;
int nxtv = dfs(now + 1, jzx, jfx, jzy, jfy, ox, oy);
res = Add(res, nxtv);
// if(nxtv > 0) {
// cout << "state = " << i << '\n';
// }
}
return res;
}
void solve(){
n = read(); m = read();
for(int i = 0; i < n; ++i) {
x[i] = read(); y[i] = read();
}
memset(f, -1, sizeof f);
cout << Dec(dfs(0, 0, 0, 0, 0, 0, 0), 1) << '\n';
}
}
char ttt;
signed main(){
cerr << "Memory = " << 1.0 * abs(&ttt - &sss) / 1024 / 1024 << " MB\n";
// freopen("in.txt","r",stdin);
Refined_heart::solve();
return cerr << "Time = " << 1.0 * clock() / CLOCKS_PER_SEC << '\n', 0;
}
| cpp |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
| [
"dp",
"greedy",
"strings"
] | #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()
{
string s;
cin >> s;
int n = s.length();
map<char, vector<int>> pos;
for (int i = 0; i < n; i++)
{
pos[s[i]].emplace_back(i);
}
string t;
cin >> t;
int m = t.length();
int curr = -1;
int ans = 0;
for (int i = 0; i < m; i++)
{
//找到第一个大于的数
auto it = upper_bound(pos[t[i]].begin(), pos[t[i]].end(), curr);
if (it == pos[t[i]].end())
{
if (curr == -1)
{
cout << "-1\n";
return;
}
curr = -1;
i--;
continue;
}
if (curr == -1)
{
ans++;
}
curr = pos[t[i]][it - pos[t[i]].begin()];
}
cout << ans << "\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 |
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>
long long t,a,m,ans;
int main() {
for(scanf("%lld",&t);t--;) {
scanf("%lld%lld",&a,&m);ans=m/=std::gcd(a,m);
for(long long i=2;i*i<=m;i++)if(m%i==0)
for(ans-=ans/i;m%i==0;m/=i);
printf("%lld\n",ans-(m>1)*ans/m);
}
} | cpp |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105) — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | #ifdef MY_LOCAL
#include "D://competitive_programming/debug/debug.h"
#define debug(x) cerr << "[" << #x<< "]:"<<x<<"\n"
#else
#define debug(x)
#endif
#define REP(i, n) for(int i = 0; i < n; i ++)
#define REPL(i,m, n) for(int i = m; i < n; i ++)
#define SORT(arr) sort(arr.begin(), arr.end())
#define LSOne(S) ((S)&-(S))
#define M_PI 3.1415926535897932384
#define INF 1e18
#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;
typedef long long ll;
#define int ll
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<vii> vvii;
typedef double ld;
typedef tree<int,null_type,less<int>, rb_tree_tag, tree_order_statistics_node_update> ost;
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string s;cin>>s;
int n = s.size();
int q;cin>>q;
vvi prect(n);
vi ini(26,0);
ini[s[0]-'a']++;
prect[0] = ini;
REPL(i, 1, n) {
prect[i] = prect[i-1];
prect[i][s[i] - 'a']++;
}
REP(i, q) {
int l; int r;cin>>l>>r;l--;r--;
if (l == r) {
cout<<"Yes\n";continue;
}
if (s[l] != s[r]) {
cout<<"Yes\n";continue;
}
vi curp(26);
REP(x, 26) {
curp[x] = prect[r][x] - (l == 0 ? 0 : prect[l-1][x]);
}
int diff =0 ;
REP(x, 26) {
if (curp[x] == 0) continue;
if (x != s[l] - 'a') {
diff++;
}
}
if (diff >=2) {
cout<<"Yes\n";
} else {
cout<<"No\n";
}
}
} | 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>
using namespace std;
#define int long long
#define yes cout<<"YES"<<"\n"
#define no cout<<"NO"<<"\n"
#define fori(i, a, n) for (int i = a; i < n; i++)
#define ford(i, n, a) for (int i = n-1; i >= a; i--)
#define mod 1000000007
#define PI 3.141592653589793238462
#define line cout<<"\n"
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
#ifndef DataTypeShorthands
typedef vector<int> vi;
typedef vector<string> vs;
typedef unordered_set<int> usi;
typedef unordered_set<char> usc;
typedef unordered_set<string> uss;
typedef unordered_map<int,int> umii;
typedef set<int> si;
typedef set<char> sc;
typedef set<string> ss;
typedef map<int,int> mii;
#endif
#ifndef RegularFunctions
#define pb push_back
#define ppb pop_back
#define mp make_pair
#endif
#ifndef ONLINE_JUDGE
#define debug(x) cout << #x <<" "; _print(x); cout << endl;
#define debugarr(x,s) cout<<#x<<" "; cout<<"[ "; for(int i=0;i<s;i++) cout<<x[i]<<" ";cout<<"]"; cout<<endl;
#else
#define debug(x)
#define debugarr(x,s)
#endif
void _print(ll t) {cout << t;}
void _print(string t) {cout << t;}
void _print(char t) {cout << t;}
void _print(lld t) {cout << t;}
void _print(double t) {cout << t;}
void _print(ull t) {cout << t;}
template<class T>void _print(vector<T> v){cout<<"[ "; for(T i:v){_print(i); cout<<" ";} cout<<"]";}
template<class T, class V> void _print(pair<T,V> p){cout<<"{ "; _print(p.first); cout<<","; _print(p.second);cout<<" }";}
template<class T> void _print(set<T> s){cout<<"["; for(T i: s) {_print(i); cout<<" ";} cout<<"]";}
template<class T, class V> void _print(map<T,V> m) {cout<<"[ "; for(auto i: m){_print(i); cout<<" ";}cout<<" ]";}
void arrin(int arr[], int n){for(int i=0;i<n;i++)cin>>arr[i];}
void solve()
{
int n;
cin >> n;
vector<pair<int,int>> v;
fori(i,0,n)
{
int x;
cin >> x;
x-=i;
v.pb(mp(x,x+i));
}
sort(all(v));
int maxi=INT_MIN,temp=v[0].second;
fori(i,1,n)
{
int x=v[i].first;
if(x==v[i-1].first)
{
temp+=v[i].second;
}
else
{
maxi=max(maxi,temp);
temp=v[i].second;
}
}
maxi=max(maxi,temp);
cout << maxi << endl;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// int t;
// cin >> t;
// for(int p=1;p<=t;p++)
// {
// // cout << "Case #" << p << ": ";
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 <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/trie_policy.hpp>
// #include <ext/rope>
using namespace std;
// using namespace __gnu_cxx;
// using namespace __gnu_pbds;
void Hollwo_Pelw();
signed main(){
#ifndef hollwo_pelw_local
if (fopen(".inp", "r"))
assert(freopen(".inp", "r", stdin)), assert(freopen(".out", "w", stdout));
#else
using namespace chrono;
auto start = steady_clock::now();
#endif
cin.tie(0), cout.tie(0) -> sync_with_stdio(0);
int testcases = 1;
// cin >> testcases;
for (int test = 1; test <= testcases; test++){
// cout << "Case #" << test << ": ";
Hollwo_Pelw();
}
#ifdef hollwo_pelw_local
auto end = steady_clock::now();
cout << "\nExecution time : " << duration_cast<milliseconds> (end - start).count() << "[ms]" << endl;
#endif
}
const int N = 2.5e5 + 5;
int n, h[N], par[18][N], fa[N];
vector<int> g1[N], g2[N];
void pre_dfs(int u, int p) {
h[u] = h[par[0][u] = p] + 1;
for (int i = 1; i < 18; i++)
par[i][u] = par[i - 1][par[i - 1][u]];
for (int v : g1[u]) if (v != p)
pre_dfs(v, u);
}
inline int lca(int u, int v) {
if (h[u] > h[v]) swap(u, v);
for (int i = 18; i --; )
if ((h[v] - h[u]) >> i & 1)
v = par[i][v];
if (u == v)
return u;
for (int i = 18; i --; )
if (par[i][u] ^ par[i][v])
u = par[i][u], v = par[i][v];
return par[0][u];
}
vector<tuple<int, int, int, int>> res;
inline int find(int u) { return fa[u] == u ? u : fa[u] = find(fa[u]); }
inline void merge(int v, int u) {
int fv = find(v), fu = find(u), w = lca(u, v);
// assert(fv != fu && "WTF is this");
if (find(fv) != find(w)) {
fa[fv] = par[0][fv];
res.emplace_back(fv, par[0][fv], v, u);
cout << fv << ' ' << fa[fv] << ' ' << v << ' ' << u << '\n';
} else {
for (int i = 18; i --; )
if (h[par[i][fu]] > h[w] && find(par[i][fu]) != find(w))
fu = par[i][fu];
fa[fu] = par[0][fu];
cout << fu << ' ' << fa[fu] << ' ' << v << ' ' << u << '\n';
}
}
void solve(int u, int p) {
for (int v : g2[u]) if (v != p) {
solve(v, u);
merge(v, u);
}
}
void Hollwo_Pelw(){
cin >> n;
iota(fa + 1, fa + n + 1, 1);
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
g1[u].push_back(v);
g1[v].push_back(u);
}
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
g2[u].push_back(v);
g2[v].push_back(u);
}
pre_dfs(1, 0);
cout << n - 1 << '\n';
solve(1, 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>
using namespace std;
const int MAXN = 2.1e3;
int N;
int P[MAXN];
vector<int> ch[MAXN];
int C[MAXN];
vector<int> dfs(int cur) {
vector<int> ans;
for (int nxt : ch[cur]) {
auto v = dfs(nxt);
ans.insert(ans.end(), v.begin(), v.end());
}
if (C[cur] > int(ans.size())) {
cout << "NO" << '\n';
exit(0);
}
ans.insert(ans.begin() + C[cur], cur);
return ans;
}
int A[MAXN];
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> N;
for (int i = 1; i <= N; i++) {
cin >> P[i] >> C[i];
ch[P[i]].push_back(i);
}
vector<int> ans = dfs(ch[0][0]);
for (int i = 0; i < N; i++) A[ans[i]] = i+1;
cout << "YES" << '\n';
for (int i = 1; i <= N; i++) {
cout << A[i] << " \n"[i==N];
}
return 0;
}
| cpp |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[500000];
void solve()
{
ll n;string s;
cin>>n>>s;
map<pair<ll,ll>,ll >m;
ll x=0,y=0,mi=3e9,dis,l,r;
s='0'+s;
m[{0,0}]=0;
for(int i=1;i<=n;i++)
{
if(s[i]=='L')x--;
if(s[i]=='R')x++;
if(s[i]=='U')y--;
if(s[i]=='D')y++;
if(m.count({x,y}))
{
ll juli=i-m[{x,y}];
if(mi>juli)
{
mi=juli;
l=m[{x,y}]+1;
r=i;
}
}
m[{x,y}]=i;
}
if(mi==3e9)cout<<"-1"<<endl;
else cout<<l<<" "<<r<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
solve();
} | 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"
] | #include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define mkp make_pair
#define vi vector<int>
#define pii pair<int,int>
#define SZ(x) ((int)x.size())
#define FI(n) FastIO::read(n)
#define FO(n) FastIO::write(n)
#define ull unsigned long long
#define mst(a,b) memset(a,b,sizeof(a))
#define foR(i,k,j) for(int i=(k);i>=(j);i--)
#define For(i,k,j) for(int i=(k);i<=(j);i++)
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define Fin(s) freopen(s,"r",stdin)
#define Fout(s) freopen(s,"w",stdout)
#define file(s) Fin(s".in"),Fout(s".out")
#define INF ((1<<30)-1)
//#define int long long
const int P=998244353; //
using namespace std;
template<typename T>void ckmax(T &a,T b) {(a<b)&&(a=b);}
template<typename T>void ckmin(T &a,T b) {(a>b)&&(a=b);}
inline int mul(int a,int b) {return 1ull*a*b%P;}
inline int add(int a,int b) {return a+b>=P?a+b-P:a+b;}
inline int sub(int a,int b) {return a-b>=0?a-b:a-b+P;}
inline void mulmod(int &a,int b) {a=mul(a, b);}
inline void addmod(int &a,int b) {((a+=b)>=P)&&(a-=P);}
inline void submod(int &a,int b) {((a-=b)<0)&&(a+=P);}
void fprint(const int &x,char c=' ') {fprintf(stderr,"%d%c",x,c);}
void fprint(const pii &x,char c=' ') {fprintf(stderr,"{%d,%d}%c",x.first,x.second,c);}
template<typename T> void fprint(const T &f) { for(auto &it:f) fprint(it); fprintf(stderr,"%c",'\n');}
template<typename T> void fprint(const T *f,const int &n) {for(int i=1;i<=n;i++) fprint(f[i]); fprintf(stderr,"%c",'\n');}
inline int ksm(int a,int b) {int ans=1; for(;b;b>>=1) {if(b&1) ans=1ll*ans*a%P;a=1ll*a*a%P;}return ans;}
inline int inv(int a) {return ksm(a,P-2);}
mt19937_64 rnd(time(0)); int Rnd(int l,int r) { return rnd()%(r-l+1)+l; }
namespace FastIO {
const int SIZE=1<<16; char buf[SIZE],obuf[SIZE],str[64]; int bi=SIZE,bn=SIZE,opt;
int read(char *s) {
while (bn) {for (;bi<bn&&buf[bi]<=' ';bi++);if (bi<bn) break; bn=fread(buf,1,SIZE,stdin),bi=0;}
int sn=0;while (bn) {for (;bi<bn&&buf[bi]>' ';bi++) s[sn++]=buf[bi];if (bi<bn) break; bn=fread(buf,1,SIZE,stdin),bi=0;}s[sn]=0;return sn;
}
bool read(int& x) {if(x)x=0;int bf=0,n=read(str); if(!n) return 0; int i=0; if (str[i]=='-') bf=1,i=1; for(x=0;i<n;i++) x=x*10+str[i]-'0'; if(bf) x=-x; return 1;}
void write(int x) {
if(!x) obuf[opt++]='0'; else {if(x<0) obuf[opt++]='-',x=-x;int sn=0; while(x)str[sn++]=x%10+'0',x/=10;for (int i=sn-1;i>=0;i--) obuf[opt++]=str[i];}
if (opt>=(SIZE>>1)){fwrite(obuf,1,opt,stdout); opt=0;}
}
void write(char x) {obuf[opt++]=x;if (opt>=(SIZE>>1)){fwrite(obuf,1,opt,stdout); opt=0;}}
void Fflush() {if (opt) fwrite(obuf,1,opt,stdout); opt=0;}
};
inline int read() {int x=0; FI(x); return x;}
const int MN=2005+10;
string s[105];
char get(string s,string t) {
int cnt[26]; mst(cnt,0);
for(auto it:s) cnt[it-'a']++;
for(auto it:t) cnt[it-'a']--;
For(i,0,25) if(cnt[i]) {cnt[i]=0; return i+'a';}
return -1;
}
string solve(int n) {
cout<<"? "<<1<<' '<<n<<endl;
multiset<string>tmp;
For(i,1,(n+1)*n/2) {string s; cin>>s; sort(s.begin(),s.end()); tmp.insert(s); }
if(n==1) {
return *tmp.begin();
}
cout<<"? "<<2<<' '<<n<<endl;
For(i,1,n*(n-1)/2) {string s; cin>>s; sort(s.begin(),s.end()); tmp.erase(tmp.find(s)); }
int t=0; for(auto it:tmp) s[++t]=it;
sort(s+1,s+1+t,[&](string x,string y){return SZ(x)<SZ(y);});
string ans;
For(i,1,n) {
if(i==1) ans+=s[1][0];
else {
ans+=get(s[i],s[i-1]);
}
}
return ans;
}
int cnt[MN][26],suf[MN][26],now[26],z[26];
void works() {
int n; cin>>n;
if(n<=2) {
string ans=solve(n);
cout<<"! "<<ans<<endl;
}
else {
string tmp=solve(n/2);
cout<<"? "<<1<<' '<<n<<endl;
For(i,1,(n+1)*n/2) {
string s; cin>>s;
int l=SZ(s);
for(auto it:s) cnt[l][it-'a']++;
}
For(l,0,n/2) {
For(i,0,25) cnt[l][i]=cnt[l+1][i]-cnt[l][i];
}
foR(i,n/2,0) {
if(i) suf[i][tmp[i-1]-'a']++;
For(j,0,25) suf[i][j]+=suf[i+1][j];
}
foR(i,(n-1)/2,0) {
int l=i+1,r=n-i;
For(j,0,25) z[j]=cnt[i][j]-suf[l][j]-now[j];
For(j,0,25) {
if(z[j]) {
now[j]++,tmp.pb(j+'a');
z[j]=0; break;
}
}
}
cout<<"! "<<tmp<<endl;
}
}
signed main() {
// #ifdef wasa855
// freopen("pro.in","r",stdin);
// freopen("pro.out","w",stdout);
// #endif
// IOS;
int T=1;
while(T--) {
works();
}
return FastIO::Fflush(),0;
}
/*
¶þÁ÷¶Ô×Ô ¹±µã·Ö¸ù µ÷±íµ¹²î
*/
| cpp |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int main (){
int t;
cin >> t;
while (t--){
int a , b ;
cin >> a >> b;
if (a==b) cout<<0<<endl;
else cout<< 1 + int((a < b) ^ ((b - a) & 1)) << endl;
}
}
| cpp |
1290 | F | F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is: | [
"dp"
] | #include<bits/stdc++.h>
#define ll long long
#define fir first
#define sec second
#define pii pair<int,int>
using namespace std;
const int maxn=6;
const int inf=0x3f3f3f3f;
const int mod=998244353;
struct mint {
int val;
mint():val(0) {}
mint(ll tval) {
if(-mod<=tval&&tval<2*mod) {
if(tval>=mod) {
tval-=mod;
}
if(tval<0) {
tval+=mod;
}
} else {
tval%=mod;
if(tval<0) {
tval+=mod;
}
}
val=tval;
}
mint& operator += (const mint &b) {
val=val+b.val>=mod?val+b.val-mod:val+b.val;
return *this;
}
mint& operator -= (const mint &b) {
val=val-b.val<0?val-b.val+mod:val-b.val;
return *this;
}
mint& operator *= (const mint &b) {
val=1ll*val*b.val>=mod?1ll*val*b.val%mod:val*b.val;
return *this;
}
mint& operator /= (const mint &b) {
*this*=b.inv();
return *this;
}
friend mint operator + (const mint &a,const mint &b) {
mint ans=a;
ans+=b;
return ans;
}
friend mint operator - (const mint &a,const mint &b) {
mint ans=a;
ans-=b;
return ans;
}
friend mint operator * (const mint &a,const mint &b) {
mint ans=a;
ans*=b;
return ans;
}
friend mint operator / (const mint &a,const mint &b) {
mint ans=a;
ans/=b;
return ans;
}
friend bool operator < (const mint &a,const mint &b) {
return a.val<b.val;
}
friend bool operator == (const mint &a,const mint &b) {
return a.val==b.val;
}
friend bool operator != (const mint &a,const mint &b) {
return a.val!=b.val;
}
friend istream& operator >> (istream &is,mint &x) {
ll val;
cin>>val;
x.val=val%mod;
return is;
}
friend ostream& operator << (ostream &os,const mint &x) {
os<<x.val;
return os;
}
mint qpow(ll y) const {
mint x=*this,ans=1;
while(y) {
if(y&1) {
ans*=x;
}
x*=x;
y>>=1;
}
return ans;
}
mint inv() const {
// mod must be a prime
return qpow(mod-2);
}
mint sqrt() {
mint a=*this;
auto check=[&](mint x) {
return x.qpow((mod-1)/2)==1;
};
static mt19937 rnd(73385);
mint b=rnd()%mod;
while(check(b*b-a)) {
b=rnd()%mod;
}
static mint val=b*b-a;
struct Complex {
mint real,imag;
Complex(mint treal=0,mint timag=0):real(treal),imag(timag) {}
Complex operator * (const Complex &rhs) {
return {real*rhs.real+imag*rhs.imag*val,real*rhs.imag+imag*rhs.real};
}
Complex& operator *= (const Complex &rhs) {
return *this=*this*rhs;
}
};
auto qpow=[&](Complex x,int y) {
Complex ans={1};
while(y) {
if(y&1) {
ans*=x;
}
x*=x;
y>>=1;
}
return ans;
};
mint ans=qpow({b,1},(mod+1)/2).real;
return min(ans,mod-ans);
}
};
int n,m;
int dx[maxn];
int dy[maxn];
bool vis[35][25][25][25][25][2][2];
mint f[35][25][25][25][25][2][2];
#define state p][x][nx][y][ny][fx][fy
mint dfs(int p,int x,int nx,int y,int ny,bool fx,bool fy) {
if(vis[state]) {
return f[state];
}
if(p==30) {
return !x&&!nx&&!y&&!ny&&fx&&fy;
}
auto ck=[&](bool f,int x,int m) {
return x!=m?x<m:f;
};
mint ans=0;
for(int s=0;s<=(1<<n)-1;s++) {
auto trans=[&](int v) {
for(int i=1;i<=n;i++) {
if((s>>(i-1))&1) {
if(dx[i]>=0) {
x+=dx[i]*v;
} else {
nx-=dx[i]*v;
}
if(dy[i]>=0) {
y+=dy[i]*v;
} else {
ny-=dy[i]*v;
}
}
}
};
trans(1);
if((x&1)==(nx&1)&&(y&1)==(ny&1)) {
ans+=dfs(p+1,x>>1,nx>>1,y>>1,ny>>1,ck(fx,(x&1),(m>>p)&1),ck(fy,(y&1),(m>>p)&1));
}
trans(-1);
}
// cerr<<p<<" "<<x<<" "<<nx<<" "<<y<<" "<<ny<<" "<<fx<<" "<<fy<<": "<<ans<<"\n";
vis[state]=true;
return f[state]=ans;
}
signed main() {//asd
// freopen("d.in","r",stdin);
// freopen("m.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>m;
m++;
for(int i=1;i<=n;i++) {
cin>>dx[i]>>dy[i];
}
cout<<dfs(0,0,0,0,0,0,0)-1<<"\n";
} | cpp |
1322 | E | E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5
1 2 1 2 1
OutputCopy2
1 1 1 1 1
InputCopy6
1 3 2 5 4 6
OutputCopy1
1 2 3 4 5 6
InputCopy6
1 1 2 2 1 1
OutputCopy0
1 1 2 2 1 1
NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00. | [
"data structures"
] | #include<bits/stdc++.h>
#define For(i,a,b) for(register int i=(a);i<=(b);++i)
#define Rep(i,a,b) for(register int i=(a);i>=(b);--i)
#define int long long
using namespace std;
inline int read()
{
char c=getchar();int x=0;bool f=0;
for(;!isdigit(c);c=getchar())f^=!(c^45);
for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48);
if(f)x=-x;return x;
}
#define fi first
#define se second
#define pb push_back
#define mkp make_pair
typedef pair<int,int>pii;
typedef vector<int>vi;
#define maxn 500005
#define inf 0x3f3f3f3f
int n,a[maxn],res[maxn];
int f[maxn][21],g[maxn][21],lg[maxn];
inline pii ask(int l,int r){
r--; int k=lg[r-l+1];
return mkp(max(f[l][k],f[r-(1<<k)+1][k]),min(g[l][k],g[r-(1<<k)+1][k]));
}
signed main()
{
n=read();
For(i,1,n)a[i]=read();
For(i,1,n-1) f[i][0]=min(a[i],a[i+1]),g[i][0]=max(a[i],a[i+1]);
For(i,2,n)lg[i]=lg[i>>1]+1;
For(j,1,20)
For(i,1,n+1-(1<<j))
f[i][j]=max(f[i][j-1],f[i+(1<<(j-1))][j-1]),
g[i][j]=min(g[i][j-1],g[i+(1<<(j-1))][j-1]);
int mx=0;
For(i,1,n)
{
int l=1,r=min(i,n-i+1),p=0;
// 二分 0/1 交替 长度
while(l<r){
int mid=l+r>>1;
pii now=ask(i-mid,i+mid);
if(now.fi<now.se) p=mid,l=mid+1;
else r=mid;
}
mx=max(mx,p);
if(!p) {res[i]=a[i];continue;}
pii now=ask(i-p,i+p);
res[i]=(((p&1)^(a[i]<a[i-1]))?now.fi:now.se);
}
cout<<mx<<endl;
For(i,1,n) printf("%d ",res[i]);
return 0;
} | cpp |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
#define endl '\n'
#define int long long
#define all(a) a.begin(),a.end()
#define pb push_back
#define mod 1000000007
#define inf 1e18
#define ppb pop_back
#define ff first
#define ss second
/// order_of_key return number of elements less than x -> os.order_of_key(x)
/// cout << "oth element : " << *os.find_by_order(0) << endl; so it returns value of index
int lcm(int x,int y)
{
return (x * 1LL * y) / __gcd(x,y);
}
// Graph on 2D Grid
/*----------------------Graph Moves----------------*/
//const int dx[]={+1,-1,+0,+0};
//const int dy[]={+0,+0,+1,-1};
//const int dx[]={+0,+0,+1,-1,-1,+1,-1,+1}; // Kings Move
//const int dy[]={-1,+1,+0,+0,+1,+1,-1,-1}; // Kings Move
//const int dx[]={-2, -2, -1, -1, 1, 1, 2, 2}; // Knights Move
//const int dy[]={-1, 1, -2, 2, -2, 2, -1, 1}; // Knights Move
/*------------------------------------------------*/
#define debug(x); cerr << #x <<" "; _print(x); cerr << endl;
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(double t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
void solve()
{
int n,x,y,i,mx,mn;
cin >> n >> x >> y;
if(x > y)
{
swap(x , y);
}
cout << max(1LL , min(n , x+y+1-n)) << " ";
mx = max((n-x) - (y-1) , 0LL);
cout << n - mx << endl;
}
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while(t--)
{
solve();
}
}
/**
Test Case :
**/ | 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 <algorithm>
#include <iostream>
#include <numeric>
#include <cmath>
#include <conio.h>
#include <iomanip>
#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 ld long double
#define el '\n'
#define pi 3.14159265358979323846
#define NumOfDigit(w) (int)(log10(w) + 1)
#define fr(p_) for(auto &p__ : p_) cout<<p__<<" ";
#define debug(x) cout<<"[" << #x << " is:" << x << "]"<<el;
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
// decimal --> fixed << setprecision
#define orderedset template<class T> using ordered_set = tree<T, null_type, std::less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define tree typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;
//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
bool sortbyPair(const pair<int, int> &a, const pair<int, int> &b) {
if (a.second != b.second)
return (a.second > b.second);
else
return (a.first < b.first);
}
ll fast_power(ll base, ll exp) {
if (!exp) return 1;
ll ans = fast_power(base, exp / 2);
ans = (ans % 1000000007 * ans % 1000000007) % 1000000007;
if (exp & 1)
ans = (ans % 1000000007 * base % 1000000007) % 1000000007;
return ans;
}
ll convert_binary_to_decimal(long long n) {
int dec = 0, i = 0, rem;
while (n != 0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
i++;
}
return dec;
}
bool is_prime(ll n) {
if (n == 0 or n == 1)
return 0;
for (int i = 2; i < n; ++i) {
if (n % i == 0)
return 0;
}
return 1;
}
ll gcd(ll a, ll b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
ll lcm(ll a, ll b) {
return ((((a / gcd(a, b)) % 1000000009) * (b % 1000000009)) % 1000000009);
}
//ll ncr2(ll n, ll r) {
// ll ans = 1, fact = 2;
// for (ll i = n - r + 1; i <= n; i++) {
// ans *= i;
// if (ans % fact == 0 and fact <= r)
// ans /= fact++;
// }
// return ans;
//}
//ll factorial[1000006], inversefactorial[1000006];
//
//void calcFacAndInv(ll n) {
// factorial[0] = inversefactorial[0] = 1;
// for (ll i = 1; i <= n; i++) {
// factorial[i] = (i * factorial[i - 1]) % 1000000007;
// inversefactorial[i] = fast_power(factorial[i], 1000000007 - 2);
// }
//}
//
//ll ncr1(ll n, ll r) {
// return ((factorial[n] % 1000000007 *
// ((inversefactorial[n - r] % 1000000007 * inversefactorial[r] % 1000000007) % 1000000007) % 1000000007) %
// 1000000007);
//}
//
//
//ll npr(ll n, ll r) {
// return ((factorial[n] % 1000000007 * inversefactorial[n - r] % 1000000007) % 1000000007);
//}
//vector<bool> sieve(ll n) {
// vector<bool> isPrime(n + 1, 1);
// isPrime[0] = isPrime[1] = 0;
// for (ll i = 2; i <= n; i++)
// if (isPrime[i])
// for (ll j = 2 * i; j <= n; j += i)
// isPrime[j] = 0;
// return isPrime;
//}
//vector<pair<ll, ll>> factorize(ll n) {
// vector<pair<ll, ll>> fact;
// for (ll i = 2; i * i <= n; i++) {
// int cnt = 0;
// while (n % i == 0) {
// n /= i;
// cnt++;
// }
// if (cnt) fact.push_back({i, cnt});
// }
// if (n > 1) fact.push_back({n, 1});
// return fact;
//}
//vector<int> getdivisors(ll n) {
// vector<int> divs;
// for (ll i = 1; i * i <= n; i++) {
// if (n % i == 0) {
// divs.push_back(i);
// if (i != n / i) divs.push_back(n / i);
// }
// }
// return divs;
//}
// upper_bound -->(greater than only) -->return iterator
// lower_bound -->(greater than or equal) -->return iterator
//vector<ll> factorize(ll n) {
// vector<ll> fact;
// for (ll i = 2; i * i <= n; i++) {
// while (n % i == 0) {
// n /= i;
// fact.push_back(i);
// }
// }
// if (n > 1) fact.push_back(n);
// return fact;
//}
ll n, g, b;
int main() {
fast
int t;
cin >> t;
while (t--) {
ll n, g, b;
cin >> n >> g >> b;
ll need = (n + 1) / 2;
ll lo = n, hi = 1e18, mid, ans = LONG_LONG_MAX;
while (lo <= hi) {
mid = (lo + hi) / 2;
ll R = (mid / (g + b));
ll rem = mid % (g + b);
ll good = R * g;
good += min(g, rem);
if (good >= need) {
hi = mid - 1;
ans = mid;
} else
lo = mid + 1;
}
cout << ans << el;
}
return 0;
} | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.