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 |
---|---|---|---|---|---|
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include <bits/stdc++.h>
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")
using namespace std;
typedef long long ll;
#define int long long
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pi pair<int,int>
#define tp tuple<int,int,int>
#define X first
#define Y second
#define hehehehaw ios::sync_with_stdio(0);cin.tie(0);
template<typename A, typename B>
ostream& operator << (ostream& o, pair<A, B> a){
return o << a.X << ' ' << a.Y;
}
template<typename A, typename B>
istream& operator >> (istream& o, pair<A, B> &a){
return o >> a.X >> a.Y;
}
//---------94i87----------//
const int N=2e5+10;
int pa[N],dep[N];
vector<int> adj[N];
void dfs(int v,int p){
for(int u:adj[v]) if (u!=p && dep[u]==0){
dep[u]=dep[v]+1;
pa[u]=v;
dfs(u,v);
}
}
void solve(int n){
dfs(1,-1);
int c=0;
for(int i=1;i<=n;i++){
if (dep[i]>dep[c]) c=i;
}
memset(dep,0,sizeof(dep));
dfs(c,-1);
int d=0,ans=0;
for(int i=1;i<=n;i++){
if (dep[i]>dep[d]) d=i;
}
int temp=d,ttemp=d;
ans+=dep[d];
memset(dep,0,sizeof(dep));
dep[c]=-1;
while(d!=c) {dep[d]=-1;d=pa[d];}
while(temp!=c){
dfs(temp,-1);
temp=pa[temp];
}
int e=1;
while(e==c || e==ttemp) e++;
for(int i=1;i<=n;i++){
if (dep[i]!=-1 && dep[i]>=dep[e]) e=i;
}
cout << ans+dep[e]+1 << '\n';
cout << c << ' ' << ttemp << ' ' << e << '\n';
}
signed main(signed argc,char** argv){
hehehehaw;
int n;cin >> n;
for(int i=1;i<n;i++){
int u,v;
cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
solve(n);
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 |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | #include<bits/stdc++.h>
using namespace std;
void solve(){
long long int n,k,b[200]={0},y=0,x;
cin>>n>>k;
for(int i=0;i<n;i++){
cin>>x;
long long int a=0;
while(x>0){
b[a]+=x%k;
if(b[a]>1){y++;break;}
x/=k;a++;}
}
if(y>0)cout<<"NO\n";
else cout<<"YES\n";
}
int main(){
int t;
cin>>t;
while(t--) solve();
return 0;
} | cpp |
1311 | E | E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example: | [
"brute force",
"constructive algorithms",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
constexpr int N = int(4e2) + 5;
constexpr int inf = 0x7f7f7f7f;
constexpr int MOD = int(1e9) + 7;
void solve(){
int n, d;
cin >> n >> d;
if(n * (n - 1) / 2 < d){
cout << "NO\n";
return;
}
n--;
vector<int> v = {1};
while(n){
d -= min(n, v.back() * 2) * v.size();
v.push_back(min(n, v.back() * 2));
n -= v.back();
}
if(0 > d){
cout << "NO\n";
return;
}
while(d){
if(v.back() > 1) v.push_back(0);
for(int i = v.size() - 1; i && v[i - 1] != 1 && d; i--){
while(d && 2 * (v[i - 1] - 1) >= v[i] + 1){
v[i]++;
v[i - 1]--;
d--;
}
}
}
cout << "YES\n";
//for(auto& i : v) cout << i << ' ';
vector<vector<int>> v2(v.size());
for(int i = 0, j = 1; i < v.size(); i++){
while(v[i] > v2[i].size()){
v2[i].push_back(j++);
}
}
for(int i = 1; i < v.size(); i++){
for(int j = 0; j < v2[i].size(); j++){
cout << v2[i - 1][j >> 1] << ' ';
}
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
cin >> t;
while(t--){
solve();
}
} | cpp |
1324 | A | A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process. | [
"implementation",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
int main(){
ios_base::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr);
int T=1; cin>>T;
while(T--) {
int n,lc=1,x,gd;
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
lc=lcm(lc,x);
if(i) gd=__gcd(gd,x);
else gd=x;
}
if((lc-gd)%2==0)cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
} | cpp |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33 | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | /**
* Author: Richw818
* Created: 01.23.2023 16:53:05
**/
#include <bits/stdc++.h>
using namespace std;
struct blift{
int N, LOG;
vector<vector<int>> adj, up;
vector<int> dep;
blift(int _n){
N = _n;
LOG = 0;
int curr = 1;
while(curr <= N){
LOG++;
curr <<= 1;
}
adj.resize(N); dep.resize(N);
up.resize(LOG, vector<int>(N, -1));
}
void add_edge(int u, int v){
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfs(int n, int p, int d){
up[0][n] = p;
dep[n] = d;
for(int next : adj[n]){
if(next != p) dfs(next, n, d + 1);
}
}
void build(int r){
dfs(r, -1, 0);
for(int i = 1; i < LOG; i++){
for(int j = 0; j < N; j++){
int p = up[i-1][j];
if(p != -1) up[i][j] = up[i-1][p];
}
}
}
int lca(int a, int b){
if(dep[a] < dep[b]) swap(a, b);
int diff = dep[a] - dep[b];
for(int i = 0; i < LOG; i++){
if((1 << i) & diff) a = up[i][a];
}
if(a == b) return a;
for(int i = LOG - 1; i >= 0; i--){
if(up[i][a] != up[i][b]){
a = up[i][a];
b = up[i][b];
}
}
return up[0][a];
}
int kth(int a, int k){
for(int i = 0; i < LOG; i++){
if(a == -1) return -1;
if((1 << i) & k) a = up[i][a];
}
return a;
}
int dist(int a, int b){
return dep[a] + dep[b] - 2 * dep[lca(a, b)];
}
};
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
blift bl(n);
for(int i = 0; i < n - 1; i++){
int u, v; cin >> u >> v;
u--, v--;
bl.add_edge(u, v);
}
bl.build(0);
auto valid = [&](int d, int k) -> bool {
return d <= k && d % 2 == k % 2;
};
int q; cin >> q;
while(q--){
int x, y, a, b, k; cin >> x >> y >> a >> b >> k;
x--, y--, a--, b--;
int d1 = bl.dist(a, b);
int d2 = bl.dist(a, x) + 1 + bl.dist(y, b);
int d3 = bl.dist(a, y) + 1 + bl.dist(x, b);
cout << (valid(d1, k) || valid(d2, k) || valid(d3, k) ? "YES" : "NO") << '\n';
}
return 0;
} | cpp |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
int a[510],f[510],s[510],t,n;
int main(){
cin>>n;
for (int i=1;i<=n;i++) cin>>a[i];
for (int i=1;i<=n;i++){
for (int j=1;j<=i;j++){
t=0; s[++t]=a[j];
for (int k=j+1;k<=i;k++){
s[++t]=a[k];
while (s[t]==s[t-1]) s[t-1]++,t--;}
f[i]=max(f[i],f[j-1]+(i-j+1-t));}}
cout<<n-f[n];
return 0;
} | cpp |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
#define int int64_t
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
map<int, int> mp; int maxi=0;
int n; cin>>n;
for (int i=0; i<n; i++)
{
int u; cin>>u;
mp[i-u]+=u;
if (mp[i-u]> maxi) maxi=mp[i-u];
}
cout <<maxi <<endl;
} | cpp |
1291 | F | F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"graphs",
"interactive"
] | #pragma GCC optimize("O3")
#pragma GCC optimize ("unroll-loops")
#pragma GCC target("avx,avx2,fma")
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
using ii = pair<int, int>;
using ull = unsigned long long;
using uint = unsigned int;
#define pb push_back
#define F first
#define S second
#define f(i, a, b) for(int i = a; i < b; i++)
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define sz(x) (int)(x).size()
#define mp(x,y) make_pair(x,y)
#define popCnt(x) (__builtin_popcountll(x))
#define int ll
const int N = 3e5+5, A = 12, LG = 18, MOD = (119 << 23) + 1;
const long double PI = acos(-1);
const long double EPS = 1e-9;
const int BLK = 450;
int p[N*2], c[N*2];
int n, m;
int get(int i){return p[i]==i?i:p[i]=get(p[i]);}
int calc(int i){return min(c[get(i)],c[get(i+m)]);}
bitset<1024> bt;
void doWork() {
int n, k;
cin >> n >> k;
k = max(k, 2ll);
k /= 2;
for(int i = 1; i < n / k; i++)
for(int j = 0; j < i; j++) {
for(int l = j * k; l < n; l++) {
cout << "? " << l + 1 << endl;
string ret; cin >> ret;
bt[l] = bt[l] | ret == "Y";
if(l%k == k-1)
l += k * (i - 1);
}
cout << "R" << endl;
}
cout << "! " << n - bt.count() << endl;
}
int32_t main() {
#ifdef ONLINE_JUDGE
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif // ONLINE_JUDGE
int t = 1;
// cin >> t;
while (t--) {
doWork();
}
return 0;
}
| cpp |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | #include<bits/stdc++.h>
#pragma GCC optimize ("Ofast")
using namespace std;
#define all(v) v.begin(), v.end()
#define F first
#define S second
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N=1e5+5;
vector<int>v[N], w[N];
int n, a[N], cnt[N], m[N];
bool cop(const int &j){
ll res=0;
for(int i: v[j])
res+=m[i]*cnt[i];
return res;
}
ll ans(int i){
ll res=0, ls=0;
stack<int>st;
reverse(all(w[i]));
int mm=1e5;
memset(cnt, 0, 4*mm/i+8);
for(int j: w[i]){
ls=0;
while(!st.empty() && cop(j)){
for(int u:v[st.top()])
--cnt[u];
ls=st.top();
st.pop();
}
res=max(res, ls*j);
for(int u: v[j])
++cnt[u];
st.push(j);
}
return res;
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>n;
for(int i=0;i<n;++i)
cin>>a[i];
sort(a, a+n);
for(int i=1;i<N;++i){
for(int j=i;j<N;j+=i)
v[j].push_back(i);
}
for(int i=0;i<n;++i){
for(int j: v[a[i]])
w[j].push_back(a[i]/j);
}
m[1]=1;
for(int i=2;i<N;++i){
int x=i/v[i][1];
if(x%v[i][1])
m[i]=-m[x];
}
ll jav=0;
for(int i=1;i<N;++i)
jav=max(jav, ans(i)*i);
cout<<jav<<'\n';
}
| 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"
] | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
/*CPPCode*/
using namespace std;
#define ll long long
#define mod 1000000007
#define vi vector<int>
#define vvi vector<vector<int>>
#define vc vector<char>
#define vs vector<string>
#define vpi vector<pair<int,int>>
#define pi pair<int,int>
#define ff first
#define ss second
#define int long long int
#define endl "\n"
#define uii unordered_map<int,int>
#define rep(i,s,l) for(int i=s;i<l;i++)
#define all(x) begin(x), end(x)
void input(vi &v){rep(i,0,v.size())cin>>v[i];}
void output(vi &v){rep(i,0,v.size())cout<<v[i]<<" ";cout<<endl;}
#define maxn 10007
int fact[maxn], ifact[maxn];
int mpow(int a,int b) {
int res = 1;
while(b) {
if(b&1) res *= a, res %= mod;
a *= a;
a %= mod;
b >>= 1;
}
return res;
}
void pre() {
fact[0] = fact[1] = ifact[0] = ifact[1] = 1;
for(int i = 2; i < maxn; i++) fact[i] = fact[i - 1]*i, fact[i] %= mod;
for(int i = 2; i < maxn; i++) ifact[i] = ifact[i - 1]*mpow(i, mod - 2), ifact[i] %= mod;
}
int comb(int a,int b) {
if(b == 0) return 1LL;
int ans = fact[a];
ans *= ifact[b];
ans %= mod;
ans *= ifact[a - b];
ans %= mod;
return ans;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin>>n;
int t;
cin>>t;
vvi grid(2,vi(n,0));
int blocked=0;
while(t--)
{
int x,y;
cin>>x>>y;
x--;
y--;
int val=(grid[x][y]==0?-1:1);
grid[x][y]=1-grid[x][y];
for(int i=-1;i<=1;i++){
if(y+i<0||y+i>=n){
continue;
}
else{
if(grid[1-x][y+i])
blocked+=val;
}
}
if(blocked==0){
cout<<"Yes\n";
}
else{
cout<<"No\n";
}
}
return 0;
}
| cpp |
1299 | D | D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept. | [
"bitmasks",
"combinatorics",
"dfs and similar",
"dp",
"graphs",
"graphs",
"math",
"trees"
] | #include<bits/stdc++.h>
#define mset(a,b) memset((a),(b),sizeof((a)))
#define rep(i,l,r) for(int i=(l);i<=(r);i++)
#define dec(i,l,r) for(int i=(r);i>=(l);i--)
#define cmax(a,b) (((a)<(b))?(a=b):(a))
#define cmin(a,b) (((a)>(b))?(a=b):(a))
#define Next(k) for(int x=head[k];x;x=li[x].next)
#define vc vector
#define ar array
#define pi pair
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define N 100010
#define M 1000100
using namespace std;
typedef double dd;
typedef long double ld;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
//#define int long long
typedef pair<int,int> P;
const int INF=0x3f3f3f3f;
const dd eps=1e-9;
const int mod=1e9+7;
template<typename T> inline void read(T &x) {
x=0; int f=1;
char c=getchar();
for(;!isdigit(c);c=getchar()) if(c == '-') f=-f;
for(;isdigit(c);c=getchar()) x=x*10+c-'0';
x*=f;
}
int n,m,tot,ID[M],IID[500];
struct edge{
int to,next,w;
inline void Init(int to_,int ne_,int w_){
to=to_;next=ne_;w=w_;
}
}li[N<<1];
int head[N],tail,f[N][376];
#define LinearBasis LB
struct LinearBasis{
int p[5];
inline bool Insert(int x){
if(x==0) return 1;
dec(i,0,4) if((x>>i)&1){
if(p[i]){x^=p[i];}
else{
p[i]=x;
rep(j,0,i-1) if(p[j]&&((p[i]>>j)&1)) p[i]^=p[j];
rep(j,i+1,4) if(p[j]&&((p[j]>>i)&1)) p[j]^=p[i];return 1;
}
}
return 0;
}
inline int Hash(){return p[0]|(p[1]<<1)|(p[2]<<3)|(p[3]<<6)|(p[4]<<10);}
inline void IHash(int x){
int now=1;
rep(i,0,4){
p[i]=x&((1<<now)-1);
x>>=now;now++;
}
}
}A,lb[N];
bool tag[N],vis[N],vi[N],ok[N];
int W[N];
int d[N],ow[N];
map<P,int> Map;
inline void Add(int from,int to,int w){
li[++tail].Init(to,head[from],w);head[from]=tail;
}
inline void dfs(int k){
LB now=A;
if(k==32){
if(ID[A.Hash()]) return;ID[A.Hash()]=++tot;IID[tot]=A.Hash();return;
}
dfs(k+1);A=now;if(A.Insert(k)) dfs(k+1);A=now;
}
inline void Dfs(int k,int fa,int xo,int id){
// printf("k=%d\n",k);
vis[k]=1;d[k]=xo;Next(k){
int to=li[x].to,w=li[x].w;
if(to==fa) continue;
if(tag[to]&&tag[k]){vi[k]=1;vi[to]=1;ow[k]=to;ow[to]=k;Map[mp(to,k)]=Map[mp(k,to)]=w;continue;}
if(!vis[to]) Dfs(to,k,xo^w,id);
else{
// printf("k=%d to=%d\n",k,to);
if(k<to) continue;
// printf("Insert %d\n",d[to]^xo^w);printf("d[%d]=%d xo=%d w=%d\n",to,d[to],xo,w);
if(!lb[id].Insert(d[to]^xo^w)||!(d[to]^xo^w)){ok[id]=0;}
}
}
}
int main(){
// freopen("my.in","r",stdin);
// freopen("my.out","w",stdout);
read(n);read(m);dfs(1);
//tot=374
rep(i,1,m){
int u,v,w;read(u);read(v);read(w);Add(u,v,w);Add(v,u,w);
}
Next(1){
int to=li[x].to;tag[to]=1;ok[to]=1;W[to]=li[x].w;
}
Next(1){
int to=li[x].to;Dfs(to,1,li[x].w,to);
// printf("ok[%d]=%d\n",to,ok[to]);
}
int last=0;mset(f,0);f[0][1]=1;
for(int x=head[1];x;x=li[x].next){
int to=li[x].to;
if(!vi[to]){
rep(j,1,374) f[to][j]=(f[to][j]+f[last][j])%mod;
if(ok[to])rep(j,1,374)if(f[last][j]){
LB now;now.IHash(IID[j]);
bool op=1;
rep(k,0,4) if(!now.Insert(lb[to].p[k])){op=0;break;}
if(!op) continue;
f[to][ID[now.Hash()]]=(f[to][ID[now.Hash()]]+f[last][j])%mod;
}
}
else{
if(ow[to]<to) continue;
// printf("to=%d\n",to);
int a=to,b=ow[to],w=Map[mp(a,b)];
rep(j,1,374) f[a][j]=(f[a][j]+f[last][j])%mod;
LB now=lb[a];
bool op=1;
rep(j,0,4) if(!now.Insert(lb[b].p[j])){op=0;break;}
if(op&&ok[a]&&ok[b])rep(j,1,374)if(f[last][j]){
LB nowj;nowj.IHash(IID[j]);
bool op2=1;
rep(k,0,4) if(!nowj.Insert(now.p[k])){op2=0;break;}
if(!op2) continue;
f[a][ID[nowj.Hash()]]=(f[a][ID[nowj.Hash()]]+1ll*f[last][j]*2%mod)%mod;
}
// printf("op=%d\n",op);
op&=now.Insert(W[a]^W[b]^w);
// printf("op=%d\n",op);
op&=(bool)(W[a]^W[b]^w);
// printf("op=%d w=%d W[%d]=%d W[%d]=%d\n",op,w,a,W[a],b,W[b]);
if(op&&ok[a]&&ok[b])rep(j,1,374)if(f[last][j]){
LB nowj;nowj.IHash(IID[j]);
bool op2=1;
rep(k,0,4) if(!nowj.Insert(now.p[k])){op2=0;break;}
if(!op2) continue;
f[a][ID[nowj.Hash()]]=(f[a][ID[nowj.Hash()]]+f[last][j])%mod;
}
}
last=to;
// rep(j,1,374) printf("f[%d][%d]=%d\n",last,j,f[last][j]);
}
int ans=0;
rep(i,1,374) ans=(ans+f[last][i])%mod;
printf("%d\n",ans);
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"
] | #pragma optimize("Bismillahirrahmanirrahim")
//█▀█─█──█──█▀█─█─█
//█▄█─█──█──█▄█─█■█
//█─█─█▄─█▄─█─█─█─█
//Allahuekber
//ahmet23 orz...
//Sani buyuk Osman Pasa Plevneden cikmam diyor.
//FatihSultanMehmedHan
//YavuzSultanSelimHan
//AbdulhamidHan
#define author tolbi
#include <bits/stdc++.h>
#ifdef LOCAL
#include "23.h"
#endif
#define int long long
#define endl '\n'
#define vint(x) vector<int> x
#define deci(x) int x;cin>>x;
#define decstr(x) string x;cin>>x;
#define cinarr(x) for (auto &it : x) cin>>it;
#define coutarr(x) for (auto &it : x) cout<<it<<" ";cout<<endl;
#define sortarr(x) sort(x.begin(),x.end())
#define sortrarr(x) sort(x.rbegin(),x.rend())
#define det(x) cout<<"NO\0YES"+x*3<<endl;
#define INF LONG_LONG_MAX
#define rev(x) reverse(x.begin(),x.end());
#define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define tol(bi) (1LL<<((int)(bi)))
const int MOD = 1e9+7;
using namespace std;
mt19937 ayahya(chrono::high_resolution_clock().now().time_since_epoch().count());
int32_t main(){
ios;
int t=1;
int tno = 0;
if (!t) cin>>t;
while (t-(tno++)){
deci(n);
vint(arr(n));
cinarr(arr);
vector<int> barr;
map<int,bool> mp;
for (int i = 0; i < n; ++i)
{
mp[arr[i]]=true;
}
for (auto it : mp) {
barr.push_back(it.first);
}
vector<vector<int>> dp(2,vector<int>(barr.size(),-1));
dp[0].back()=abs(arr.back()-barr.back());
for (int i = barr.size()-2; i >= 0; i--){
dp[0][i]=min(dp[0][i+1],abs(arr.back()-barr[i]));
}
for (int i = n-2; i >= 0; i--){
dp[1].back()=abs(arr[i]-barr.back())+dp[0].back();
for (int j = barr.size()-2; j >= 0; j--){
dp[1][j] = min(dp[1][j+1],dp[0][j]+abs(arr[i]-barr[j]));
}
swap(dp[0],dp[1]);
}
cout<<dp[0][0]<<endl;
}
} | cpp |
1284 | F | F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4
1 2
2 3
4 3
1 3
2 4
1 4
OutputCopy3
3 2 4 2
2 1 1 3
4 3 1 4
InputCopy5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
OutputCopy4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
InputCopy9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
OutputCopy8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
| [
"data structures",
"graph matchings",
"graphs",
"math",
"trees"
] | #include<cstdio>
#include<vector>
std::vector<int> v[300010],g[300010];
int f[300010][20],d[300010],n,q[300010];
int find(int x){while(x!=q[x])x=q[x]=q[q[x]];return x;}
void dfs1(int x){
d[x]=d[f[x][0]]+1,q[x]=x;
for(int i=1;i<19;i++)f[x][i]=f[f[x][i-1]][i-1];
for(auto u:v[x])if(u!=f[x][0])f[u][0]=x,dfs1(u);
}
void link(int x,int y){
x=find(x),y=find(y);
for(int i=18;~i;i--) if(d[find(f[x][i])]>d[y]) x=find(f[x][i]);
if(find(f[x][0])==y) x=find(x);
else x=find(y);
printf("%d %d ",x,q[x]=f[x][0]);
}
void dfs2(int x,int fa){
for(auto u:g[x])if(u!=fa) dfs2(u,x),link(x,u),printf("%d %d\n",x,u);
}
int main(){
scanf("%d",&n);
for(int i=1,x,y;i<n;i++)scanf("%d%d",&x,&y),v[x].push_back(y),v[y].push_back(x);
for(int i=1,x,y;i<n;i++)scanf("%d%d",&x,&y),g[x].push_back(y),g[y].push_back(x);
printf("%d\n",n-1);
dfs1(1),dfs2(1,0);
return 0;
} | cpp |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int n,i;
string s,t;
stack<int>l[256],r[256],a,b;
#define c(x,y)for(;!x.empty()&&!y.empty();)a.push(x.top()),b.push(y.top()),x.pop(),y.pop();
int main(){
for(cin>>n>>s>>t;i<n;i++)l[s[i]].push(i),r[t[i]].push(i);
for(i='a';i<='z';i++){c(l[i],r[i])c(l[i],r['?'])c(l['?'],r[i])}
c(l['?'],r['?'])
cout<<a.size()<<endl;
for(;!a.empty();)cout<<a.top()+1<<" "<<b.top()+1<<"\n",a.pop(),b.pop();
} | 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"
] | #pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
#include <array>
// #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using lld = long double;
using ull = unsigned long long;
using vll = vector<ll>;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x<<" "; _print(x); cerr << endl;
#else
#define debug(x) ((void)0);
#endif
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define loop(i,k,n) for(ll i = k; i < n;i++)
#define MOD 1000000007
#define MOD1 998244353
#define nl "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define UNIQUE(X) X.erase(unique(all(X)),X.end())
const ll INF = 1e18;
template<class A> void read(vector<A>& v);
template<class T> void read(T& x) {
cin >> x;
}
template<class H, class... T> void read(H& h, T&... t) {
read(h);
read(t...);
}
template<class A> void read(vector<A>& x) {
for (auto& a: x)
read(a);
}
template<class A> void read1(vector<A>& x) {
for(ll i = 1; i <= sz(x) - 1; i++){
read(x[i]);
}
}
void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull 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 << "]";}
template<class T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
void google(int t) {cout << "Case #" << t << ": ";}
ll mul(ll a, ll b, ll m) {
if (a < (1 << 14)) {
return (a * b) % m;
}
ll c = mul(a >> 14, b, m);
c <<= 14;
c %= m;
c = (c + (a % (1 << 14)) * b) % m;
return c;
}
ll fast_power(ll p, ll e, ll m) {
if (e == 0) {
return 1 % m;
}
if (e % 2 == 0) {
return fast_power(mul(p, p, m), e / 2, m);
}
else {
return mul(fast_power(p, e - 1, m), p, m);
}
}
// #define N 200005 // change N here
// vector<vll> adjl(N);
// vll visited(N);
// ll n, m;
// vector<ll> adj[N];
// void dfs(ll u){
// visited[u] = 1;
// for(ll v: adj[u]){
// if(!visited[v]){
// dfs(v);
// }
// }
// }
// vll dist;
// void bfs(ll s) {
// dist.assign(n + 1, -1); // n must be defined(i.e global)
// queue<ll> q;
// dist[s] = 0; q.push(s);
// while (q.size()) {
// ll u = q.front(); q.pop();
// for (ll v : adj[u]) {
// if (dist[v] == -1) {
// dist[v] = dist[u] + 1;
// q.push(v);
// }
// }
// }
// }
// const ll maxn = 1000; // set maxn accordingly
// ll C[maxn + 1][maxn + 1];
// void makenCr(){
// C[0][0] = 1;
// for (ll n = 1; n <= maxn; ++n) {
// C[n][0] = C[n][n] = 1;
// for (ll k = 1; k < n; ++k)
// C[n][k] = C[n - 1][k - 1] + C[n - 1][k];
// // C[n][k] %= MOD;
// }
// }
void solve(){
ll n; cin >> n;
vll a(n); read(a);
ll idx = -1, ans = -1;
loop(i, 0, n){
ll val1 = a[i], val2 = a[i], cnt = a[i];
for(ll j = i + 1; j < n; j ++){
val2 = min(a[j], val2);
cnt += val2;
}
for(ll j = i - 1; j >= 0; j --){
val1 = min(val1, a[j]);
cnt += val1;
}
if(ans < cnt){
ans = cnt;
idx = i;
}
}
ll val1 = a[idx], val2 = a[idx];
for(ll j = idx + 1; j < n; j ++){
a[j] = min(val2, a[j]);
val2 = a[j];
}
for(ll j = idx - 1; j >= 0; j --){
a[j] = min(a[j], val1);
val1 = a[j];
}
for(auto x: a) cout << x << " ";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
cout << "---------------------" << nl;
cout << "OUTPUT:" << nl;
freopen("error.txt", "w", stderr);
#endif
int t = 1;
// cin>>t;
for(ll i = 1; i <= t; i ++)
{
// google(i);
solve();
// cout << "\n";
}
return 0;
}
| cpp |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | #define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<algorithm>
#include<vector>
#include<string>
#include<math.h>
#define ll long long
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3f
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--)
{
ll n;
int m;
vector<int>e(65,0);
cin >> n >> m;
ll now = 0;
for (int i = 1; i <= m; i++)
{
int tem;
cin >> tem;
now += tem;
e[log2(tem)]++;
}
if (now < n)
{
cout << -1 << endl;
continue;
}
ll ans = 0;
for (int i = 0; i <= 63 && n; i++)
{
if (n & 1 == 1)
{
int j = i;
while (e[j] == 0)
j++;
while (j != i)
{
e[j]--;
j--;
e[j] += 2;
ans++;
}
e[i]--;
}
e[i + 1] += e[i] / 2;
n >>=1;
}
cout << ans << endl;
}
}
| cpp |
1295 | E | E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
| [
"data structures",
"divide and conquer"
] | #include<bits/stdc++.h>
typedef long long int ll;
using namespace std;
typedef vector <ll> Row;
typedef vector <Row> Matrix;
#define T while(t--)
#define TASHLEEF ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define all(x) x.begin() , x.end()
#define debv(v) for(auto p : v) cout << p << " ";
#define deb(x) cout << #x << " = " << x << " ";
#define f(i,n) for(i;i<n;i++)
#define endl '\n'
#define LFT 2*p, L, (L+R)/2
#define RGT 2*p+1, (L+R)/2+1, R
#define PI 3.14159265
#define pb push_back
ll seg[800400],lzy[800800];
ll n,idx[200200],b[200200];
pair <ll,ll> a[200200];
void push(int p)
{
if(lzy[p] != 0)
{
seg[2*p] += lzy[p],seg[2*p+1]+= lzy[p];
lzy[2*p] += lzy[p],lzy[2*p+1] += lzy[p];
lzy[p] = 0;
}
}
ll mrg(ll a,ll b)
{
return min(a,b);
}
ll build(int p,int L,int R)
{
if(L == R) return seg[p] = b[L];return seg[p] = mrg(build(LFT),build(RGT));
}
ll qry(int i,int j,int p,int L,int R)
{
if(j<L || R<i) return 1e18;
if(i<=L && R<=j) {
return seg[p];
}
push(p);
return mrg(qry(i,j,LFT) , qry(i,j,RGT));
}
ll upd(int i, int j, int inc, int p, int L, int R){
if(j<L || R<i) return seg[p];
if(i<=L && R<=j) {
lzy[p]+=inc;
return seg[p]+=inc;
}
push(p);
return seg[p] = mrg(upd(i, j, inc, LFT) , upd(i, j, inc, RGT));
}
void solve()
{
cin >> n;
for(int i = 0; i<n; i++) cin >> a[i].first,idx[a[i].first] = i;
for(int i = 0;i<n;i++) cin >> a[i].second ,b[i] = a[i].second;
for(int i = 1;i<n;i++) b[i] += b[i-1];
ll ans = min(b[0],a[n-1].second);
build(1,0,n-1);
for(int i = 1;i<=n;i++)
{
ans = min(ans,qry(0,n-1,1,0,n-1));
upd(0,idx[i]-1,a[idx[i]].second,1,0,n-1);
upd(idx[i],n-2,-a[idx[i]].second,1,0,n-1);
}
cout << ans;
}
int main ()
{
int t = 1;
//cin >> t;
while(t--)
{
solve();
cout << endl;
}
}
| 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;
#define pb push_back
#define ppb pop_back
#define pf push_front
#define ppf pop_front
#define eb emplace_back
#define ef emplace_front
#define lowbit(x) (x & (-x))
#define ti chrono::system_clock::now().time_since_epoch().count()
#define Fin(x) freopen(x, "r", stdin)
#define Fout(x) freopen(x, "w", stdout)
#define Fio(x) Fin(x".in"), Fout(x".out");
// #define SGT
// #define int long long // int main() -> signed
// #define PAIR
#define ll long long
#ifdef PAIR
#define fi first
#define se second
#endif
#ifdef SGT
#define lson (p << 1)
#define rson (p << 1 | 1)
#define mid ((l + r) >> 1)
#endif
const int maxn = 1e5 + 10;
int n, m, dep[maxn], f[maxn], sz;
vector<int> edge[maxn];
bool vis[maxn];
int ind[maxn];
vector<int> ans;
void dfs(int u){
dep[u] = dep[f[u]] + 1;
for(int v : edge[u]) if(v != f[u]){
if(!dep[v]) f[v] = u, dfs(v);
else if(dep[u] - dep[v] + 1 >= sz){
printf("2\n%d\n%d ", dep[u] - dep[v] + 1, u);
do{u = f[u], printf("%d ", u);}while(u != v);
exit(0);
}
}
}
signed main(){
scanf("%d%d", &n, &m), sz = ceil(sqrt(n));
for(int i = 1, x, y; i <= m; i++){
scanf("%d%d", &x, &y);
edge[x].pb(y), edge[y].pb(x);
}
dfs(1), iota(ind + 1, ind + n + 1, 1), puts("1");
sort(ind + 1, ind + n + 1, [](int x, int y){return dep[x] > dep[y];});
for(int i = 1; i <= n; i++) if(!vis[ind[i]]){
ans.pb(ind[i]);
for(int j : edge[ind[i]]) vis[j] = 1;
vis[ind[i]] = 1; if(ans.size() == sz) break;
}
assert(ans.size() == sz);
for(int i : ans) printf("%d ", i);
return 0;
} | cpp |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | // LUOGU_RID: 101282622
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define max_n 500
#define inf 0x3f3f3f3f
int n;
int a[max_n+2];
int w[max_n+2][max_n+2];
int dp[max_n+2][max_n+2];
int main(){
#ifndef ONLINE_JUDGE
freopen("CF1312E_1.in","r",stdin);
freopen("CF1312E_1.out","w",stdout);
#endif
scanf("%d",&n);
for(int i=1;i<=n;++i)scanf("%d",a+i);
memset(dp,inf,sizeof(dp));
for(int i=1;i<=n;++i){
w[i][i]=a[i];
dp[i][i]=1;
}
for(int p=1;p<=n;++p){
for(int l=1,r;l+p-1<=n;++l){
r=l+p-1;
for(int k=l;k<r;++k){
dp[l][r]=min(dp[l][r],dp[l][k]+dp[k+1][r]);
if(dp[l][k]==1&&dp[k+1][r]==1&&w[l][k]==w[k+1][r]){
w[l][r]=w[l][k]+1;
dp[l][r]=1;
}
}
}
}
printf("%d\n",dp[1][n]);
return 0;
}
| 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 Zeoy std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0)
#define debug(x) cerr << #x << "=" << x << endl;
#define all(x) (x).begin(), (x).end()
#define int long long
#define mpk 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 = 5e5 + 10;
int n;
int a[N];
int minl[N], minr[N];
int pre[N], suf[N];
int stk[N], tt;
void solve()
{
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> a[i];
for (int i = 1; i <= n; ++i)
{
while (tt && a[stk[tt]] >= a[i])
tt--;
if (tt)
minl[i] = stk[tt];
else
minl[i] = 0;
stk[++tt] = i;
}
tt = 0;
for (int i = n; i >= 1; --i)
{
while (tt && a[stk[tt]] >= a[i])
tt--;
if (tt)
minr[i] = stk[tt];
else
minr[i] = n + 1;
stk[++tt] = i;
}
for (int i = 1; i <= n; ++i)
pre[i] += pre[minl[i]] + (i - minl[i]) * a[i];
for (int i = n; i >= 1; i--)
suf[i] = suf[minr[i]] + (minr[i] - i) * a[i];
int ans = 0, pos = -1;
for (int i = 1; i <= n; ++i)
{
if (ans < pre[i] + suf[i] - a[i])
{
ans = pre[i] + suf[i] - a[i];
pos = i;
}
}
vector<int> res(n + 2);
int p = pos;
while (p != 0)
{
for (int i = minl[p] + 1; i <= p; ++i)
res[i] = a[p];
p = minl[p];
}
p = pos;
while (p != n + 1)
{
for (int i = p; i <= minr[p] - 1; ++i)
res[i] = a[p];
p = minr[p];
}
for (int i = 1; i <= n; ++i)
cout << res[i] << " ";
cout << endl;
}
signed main(void)
{
Zeoy;
int T = 1;
// cin >> T;
while (T--)
{
solve();
}
return 0;
}
| cpp |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vb = vector<bool>;
using vll = vector<ll>;
using vs = vector<string>;
#define ALL(v) v.begin(), v.end()
#define SORT(v) sort(ALL(v))
#define SZ(v) int(v.size())
#ifdef DLOCAL
#include <local.h>
#else
#define deb(...);
#endif
void solve() {
int n; cin >> n;
map<char, int> a, b;
map<char, queue<int>> ai, bi;
string l, r; cin >> l >> r;
for (int i = 0; i < n; ++i) {
if (l[i] == '?') l[i] = '{';
if (r[i] == '?') r[i] = '{';
a[l[i]]++;
b[r[i]]++;
ai[l[i]].push(i + 1);
bi[r[i]].push(i + 1);
}
vector<pii> answer;
for (auto it = a.begin(); it != a.end(); ++it) {
if (it->first == '{') {
for (auto it2 = b.begin(); it2 != b.end(); ++it2) {
if (it2->second == 0) continue;
int total = min(it2->second, it->second);
it->second -= total;
it2->second -= total;
for (int i = 0; i < total; ++i) {
answer.emplace_back(make_pair(ai[it->first].front(), bi[it2->first].front()));
ai[it->first].pop();
bi[it2->first].pop();
}
}
}
else {
auto it2 = b.find(it->first);
if (it2->second != 0) {
int total = min(it2->second, it->second);
it->second -= total;
it2->second -= total;
for (int i = 0; i < total; ++i) {
answer.emplace_back(make_pair(ai[it->first].front(), bi[it2->first].front()));
ai[it->first].pop();
bi[it2->first].pop();
}
}
if (it->second == 0) continue;
it2 = b.find('{');
if (it2 != b.end() && it2->second != 0)
{
int total = min(it2->second, it->second);
it->second -= total;
it2->second -= total;
for (int i = 0; i < total; ++i) {
answer.emplace_back(make_pair(ai[it->first].front(), bi[it2->first].front()));
ai[it->first].pop();
bi[it2->first].pop();
}
}
}
}
cout << SZ(answer) << "\n";
for (int i = 0; i < SZ(answer); ++i) {
cout << answer[i].first << " " << answer[i].second << "\n";
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
//ifstream cin ("puzzle_name.in");
//ofstream cout ("puzzle_name.out");
solve();
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"
] | // Lynkcat.
// Problem: E. Cow and Treats
// Contest: Codeforces - Codeforces Round #621 (Div. 1 + Div. 2)
// URL: https://codeforces.com/contest/1307/problem/E
// Memory Limit: 256 MB
// Time Limit: 1000 ms
#include<bits/stdc++.h>
#define poly vector<int>
#define IOS ios::sync_with_stdio(false)
#define ll long long
#define mp make_pair
#define mt make_tuple
#define pa pair < int,int >
#define fi first
#define se second
#define inf 1e9
#define mod 1000000007
#define int ll
#define N 5005
using namespace std;
int cnt[N][4];
int tot,nowans;
poly L[N],R[N];
int stat[N];
int s[N],f[N],h[N],l[N],r[N];
int n,m;
int mx,ans;
inline int quickPower(int x,int y)
{
int res=1;
while (y)
{
if (y&1) res=res*x%mod;
x=x*x%mod;
y>>=1;
}
return res;
}
void del(int x,int y)
{
int o=0;
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
if ((i&1)&&((j>>1)&1))
{
if (i==j) o=max(o,min(2ll,cnt[f[x]][i]));
else
o=max(o,(int)(cnt[f[x]][i]>0)+(cnt[f[x]][j]>0));
}
tot-=o;
int nowans=0;
if (o==2)
{
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
if ((i&1)&&((j>>1)&1))
{
int now=0;
if (i==j) now=min(2ll,cnt[f[x]][i]);
else
now=(cnt[f[x]][i]>0)+(cnt[f[x]][j]>0);
if (now==o)
{
if (i==j)
{
nowans=(nowans+cnt[f[x]][i]*(cnt[f[x]][i]-1+mod)%mod)%mod;
}
else
{
nowans=(nowans+cnt[f[x]][i]*cnt[f[x]][j]%mod)%mod;
}
}
}
} else
if (o==1)
{
for (int i=0;i<4;i++)
if (i&1) nowans=(nowans+cnt[f[x]][i])%mod;
for (int i=0;i<4;i++)
if ((i>>1)&1) nowans=(nowans+cnt[f[x]][i])%mod;
} else nowans=1;
::nowans=::nowans*quickPower(nowans,mod-2)%mod;
}
void add(int x,int y)
{
int o=0;
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
if ((i&1)&&((j>>1)&1))
{
if (i==j) o=max(o,min(2ll,cnt[f[x]][i]));
else
o=max(o,(int)(cnt[f[x]][i]>0)+(cnt[f[x]][j]>0));
}
tot+=o;
int nowans=0;
if (o==2)
{
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
if ((i&1)&&((j>>1)&1))
{
int now=0;
if (i==j) now=min(2ll,cnt[f[x]][i]);
else
now=(cnt[f[x]][i]>0)+(cnt[f[x]][j]>0);
if (now==o)
{
if (i==j)
{
nowans=(nowans+cnt[f[x]][i]*(cnt[f[x]][i]-1+mod)%mod)%mod;
}
else
{
nowans=(nowans+cnt[f[x]][i]*cnt[f[x]][j]%mod)%mod;
}
}
}
} else
if (o==1)
{
for (int i=0;i<4;i++)
if (i&1) nowans=(nowans+cnt[f[x]][i])%mod;
for (int i=0;i<4;i++)
if ((i>>1)&1) nowans=(nowans+cnt[f[x]][i])%mod;
} else nowans=1;
::nowans=::nowans*nowans%mod;
}
void ers(int x,int y)
{
del(x,y);
cnt[f[x]][stat[x]]--;
stat[x]-=(1<<y);
cnt[f[x]][stat[x]]++;
add(x,y);
}
void ins(int x,int y)
{
del(x,y);
cnt[f[x]][stat[x]]--;
stat[x]+=(1<<y);
cnt[f[x]][stat[x]]++;
add(x,y);
}
int qry(int x,int o)
{
int nowans=0;
if (o==2)
{
for (int i=0;i<4;i++)
if ((i>>1)&1) nowans=(nowans+cnt[f[x]][i])%mod;
} else
if (o==1)
{
for (int i=0;i<4;i++)
if (i&1) nowans=(nowans+cnt[f[x]][i])%mod;
} else nowans=1;
return nowans;
}
void BellaKira()
{
cin>>n>>m;
for (int i=1;i<=n;i++)
cin>>s[i];
for (int i=1;i<=m;i++)
{
cin>>f[i]>>h[i];
int x=0;
for (int j=1;j<=n;j++)
{
x+=(s[j]==f[i]);
if (x==h[i])
{
l[i]=j;
break;
}
}
if (!l[i]) l[i]=n+1;
x=0;
for (int j=n;j>=1;j--)
{
x+=(s[j]==f[i]);
if (x==h[i])
{
r[i]=j;
break;
}
}
L[l[i]].push_back(i);
R[r[i]].push_back(i);
}
nowans=1;
for (int i=1;i<=n;i++) cnt[f[i]][stat[i]]++;
for (int i=1;i<=n;i++)
for (auto u:R[i])
ins(u,1);
if (tot>mx)
{
mx=tot;
ans=nowans;
}
for (int i=1;i<=n;i++)
{
for (auto u:L[i])
ins(u,0);
for (auto u:R[i])
ers(u,1);
int x=tot,y=nowans;
for (auto u:L[i])
{
if (tot>mx)
{
mx=tot;
ers(u,0);
int oo=0;
if (stat[u]>1)
ers(u,1),oo=1;
del(u,0);
if (mx-tot==2)
ans=(nowans*qry(u,2)%mod)%mod;
else ans=(nowans)%mod;
add(u,0);
ins(u,0);
if (oo) ins(u,1);
} else
if (tot==mx)
{
mx=tot;
ers(u,0);
int oo=0;
if (stat[u]>1)
ers(u,1),oo=1;
del(u,0);
if (mx-tot==2)
ans=(ans+nowans*qry(u,2)%mod)%mod;
else ans=(ans+nowans)%mod;
add(u,0);
ins(u,0);
if (oo) ins(u,1);
}
}
}
if (mx==0) return cout<<"0 1\n",void();
cout<<mx<<" "<<ans<<'\n';
}
signed main()
{
IOS;
cin.tie(0);
int T=1;
while (T--)
{
BellaKira();
}
}
| 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>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define ll long long
#define vll vector<ll>
#define pb push_back
#define FAST ios::sync_with_stdio(false); cin.tie(nullptr);
#define vp vector<pair<ll,ll>>
#define tc ll t; cin >> t; for(ll i = 0; i < t; i++){solve(i, t);}
#define tc1 solve(1, 1);
#define mpvll map<ll, vll>
#define vfast vll a(n); for (ll i = 0; i < n; i++) { cin >> a[i]; }
#define mpll map<ll,ll>
#define vll2 vector<vector<ll>> dp(m, vector<ll>(n));
#define FIXED(A) cout << fixed; cout.precision(20); cout << A << "\n";
#define mp(A, B) make_pair(A, B)
#define all(x) (x).begin(), (x).end()
#define pll pair<ll,ll>
template <typename num_t>
using ordered_set = tree<num_t, null_type, less_equal<num_t>, rb_tree_tag, tree_order_statistics_node_update>;
void setIO(string name) {freopen((name+".in").c_str(),"r",stdin);freopen((name+".out").c_str(),"w",stdout);}
ll rd(ll a, ll b){return (a+b-1) / b;}
ll isqrt(ll x){ll ans = 0; for(ll k = 1LL << 30; k != 0; k /= 2){if ((ans + k) * (ans + k) <= x) {ans += k;} } return ans; }
vll prime(ll x){ll n = x; vll ans; while (n % 2 == 0) {ans.pb(2);n = n/2;} for (int i = 3; i <= sqrt(n); i = i + 2) {while (n % i == 0){ans.pb(i);n = n/i;}}if (n > 2){ans.pb(n);} return ans;}
ll binpow(ll a, ll b, ll m) { a %= m; ll res = 1; while (b > 0) { if (b & 1){res = res * a % m;}a = a * a % m; b >>= 1;} return res;}
ll lg2(ll n){ll cnt=0;while(n){cnt++;n/=2;}return cnt;}
template<class T>
class seg {
private:
T comb(T a, T b) { return a + b; }
const T DEFAULT = 0;
vector<T> segtree;
int len;
public:
seg(int len) : len(len), segtree(len * 2, DEFAULT) {}
void set(int ind, T val) {
assert(0 <= ind && ind < len);
ind += len;
segtree[ind] = val;
for (; ind > 1; ind /= 2) {
segtree[ind >> 1] = comb(segtree[ind], segtree[ind ^ 1]);
}
}
T sum(int start, int end) {
assert(0 <= start && start < len && 0 < end && end <= len);
T sum = DEFAULT;
for (start += len, end += len; start < end; start /= 2, end /= 2) {
if ((start & 1) != 0) {
sum = comb(sum, segtree[start++]);
}
if ((end & 1) != 0) {
sum = comb(sum, segtree[--end]);
}
}
return sum;
}
};
void solve(ll TC, ll TC2) {
ll n; cin >> n;
vll a(n+1); for(ll i = 1 ; i <= n; i++){cin >> a[i]; }
seg<ll> s(n+3); for(ll i = 1; i <= n; i++){s.set(i , a[i]);}
stack<pair<ll, ll>> st;
st.push({0, 0});
vll ends(n+1);
vll starts(n+1);
for(ll i = 1; i <= n; i++){
while(!st.empty() && st.top().first >= a[i]){st.pop();}
ends[i] = st.top().second;
st.push({a[i],i});
}
while(!st.empty()){st.pop();}
st.push({0, n+1});
for(ll i = n; i >= 1; i--){
while(!st.empty() && st.top().first >= a[i]){st.pop();}
starts[i] = st.top().second;
st.push({a[i],i});
}
vll dp1(n+2);
for(ll i = 1; i <= n; i++){
if(ends[i] == i -1){dp1[i] = dp1[i-1];}
else{
dp1[i] = dp1[ends[i]] + s.sum(ends[i]+1,i) - ((i - ends[i] - 1) * a[i]);
}
}
vll dp2(n+2);
for(ll i = n; i > 0; i--){
if(starts[i] == i +1){dp2[i] = dp2[i+1];}
else{
dp2[i] = dp2[starts[i]] + s.sum(i+1, starts[i]) - ((starts[i] - i - 1) * a[i]);
}
}
ll mn = 1e18;
for(ll i = 1; i <= n; i++){
mn = min(mn, dp1[i] + dp2[i]);
}
for(ll i = 1; i <= n; i++){
if(dp1[i] + dp2[i] == mn){
vll ans(n+2); ll cmax = 0;
ans[i] = a[i];
cmax = a[i];
for(ll j = i+1; j <= n; j++){
cmax = min(cmax, a[j]);
ans[j] = cmax;
}
cmax = a[i];
for(ll j = i - 1; j > 0; j--){
cmax = min(cmax, a[j]);
ans[j] = cmax;
}
for(ll j = 1; j <= n; j++){cout << ans[j] << " ";}
return;
}
}
}
int main() {
FAST;
tc1;
} | 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"
] | //Srijan Krishna 2113094
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define ll long long int
#define ook order_of_key //log(n)
#define fbo find_by_order //log(n)
typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll>>, rb_tree_tag,
tree_order_statistics_node_update>
os; //Pair<ll,ll> Ordered_set
#define um unordered_map
#define pb push_back
#define pob pop_back()
#define pof pop_front()
#define ps pr.second
#define pf pr.first
#define mp make_pair
#define pq priority_queue
ll ga[110];
ll getbit(ll n){
ll ct=0;
while(n){
ct=ct+(n&1);
n=n>>1;
}
return ct;
}
ll binary_search_upper(vector<ll>&v,ll k){
ll lo=0;
ll hi=v.size()-1;
ll mid;
while(lo<=hi){
mid=lo+(hi-lo)/2;
if(v[mid]==k){
return mid;
}
else if(k>v[mid]){
lo=mid+1;
}
else{
hi=mid-1;
}
}
if(v[mid]>k){
return mid;
}
else{
if(mid==v.size()-1){
return -1;
}
else{
return mid+1;
}
}
}
ll binary_search_lower(vector<ll>&v,ll k){
ll lo=0;
ll hi=v.size()-1;
ll mid;
while(lo<=hi) {
mid=lo+(hi-lo)/2;
if(v[mid]==k){
return mid;
}
else if(k>v[mid]){
lo=mid+1;
}
else{
hi=mid-1;
}
}
if(v[mid]<k){
return mid;
}
else if(v[mid]>k){
if(mid==0){
return -1;
}
else{
return mid-1;
}
}
}
ll binary_search(vector<ll>&q,ll k){
ll lo=0;
ll hi=q.size()-1;
ll mid;
while(lo<=hi){
mid=lo+(hi-lo)/2;
if(q[mid]==k){
return mid;
}
else if(k>q[mid]){
lo=mid+1;
}
else{
hi=mid-1;
}
}
return -1;
}
void print(pq<ll>q){
while(!q.empty()){
cout<<q.top()<<" ";
q.pop();
}
cout<<endl;
}
ll mei(ll a,ll b,ll c){
if(a<b && a<c){
return a;
}
else if(b<c && b<a){
return b;
}
return c;
}
ll mulmod(ll a,ll b,ll c)
{
if (b==0)
return 0;
ll s = mulmod(a, b/2, c);
if (b%2==1)
return (a%c+2*(s%c)) % c;
else
return (2*(s%c)) % c;
}
ll fac(ll n){
if(n==1 || n==0){
return 1;
}
ll fac=1;
for(ll i=1;i<=n;i++){
ll a=fac;
ll b=i;
ll c=1000000007;
fac=mulmod(a,b,c);
}
return fac;
}
bool palindrome(string s){
for(ll i=0;i<s.length()/2;i++){
if(s[i]!=s[s.length()-i-1]){
return false;
}
}
return true;
}
ll subSum(deque<ll>q){
ll sum=0;
ll maxi=INT_MIN;
for(ll i=0;i<q.size();i++){
sum=sum+q[i];
maxi=max(maxi,sum);
if(sum<0){
sum=0;
}
}
return maxi;
}
void nextLargerElement(ll arr[],ll n)
{
vector<unordered_map<string,ll> > s;
for (ll i = 0; i < n; i++) {
while (s.size() > 0
&& s[s.size() - 1]["value"] < arr[i]) {
unordered_map<string,ll> d = s[s.size() - 1];
s.pop_back();
arr[d["ind"]] = arr[i];
}
unordered_map<string,ll> e;
e["value"] = arr[i];
e["ind"] = i;
s.push_back(e);
}
while (s.size() > 0) {
unordered_map<string,ll> d = s[s.size() - 1];
s.pop_back();
arr[d["ind"]] = -1;
}
}
#define MAXN 100001
ll spf[MAXN];
void sieve(){
spf[1] =1;
for (ll i=2; i<MAXN; i++)
spf[i] = i;
for (ll i=4; i<MAXN; i+=2)
spf[i] = 2;
for (ll i=3; i*i<MAXN; i++){
if (spf[i] == i){
for (ll j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
void getFactorization(ll x,um<ll,ll>&m)
{
while (x != 1)
{
m[spf[x]]++;
x = x / spf[x];
}
}
ll div_two(ll &n){
ll ct=0;
while(n%2==0){
ct++;
n=n/2;
}
return ct;
}
void primeFactors(ll n,um<ll,ll>&m){
while(n%2==0){
m[2]++;
n/=2;
}
for(ll i=3;i<=sqrt(n);i=i+2){
while(n%i==0){
m[i]++;
n/=i;
}
}
if(n>2){
m[n]++;
}
}
bool isprime(ll n){
if(n==1){
return false;
}
if(!(n%2) && n>2){
return false;
}
if(n==2){
return true;
}
else{
for(ll i=3;i*i<=n;i+=2){
if(n%i==0){
return false;
}
}
}
return true;
}
ll binaryToDecimal(string n)
{
string num = n;
ll dec_value = 0;
ll base = 1;
ll len = num.length();
for (ll i = len - 1; i >= 0; i--) {
if (num[i] == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
ll logg(ll a,ll b)
{
return (a > b - 1)
? 1 + logg(a / b, b)
: 0;
}
ll mod_pow(ll x,ll y,ll p)
{
ll res = 1;
x = x % p;
if (x == 0) return 0;
while (y > 0)
{
if (y & 1)
res = (res*x) % p;
y = y>>1;
x = (x*x) % p;
}
return res;
}
ll powr(ll x,ll y)
{
ll temp;
if (y == 0)
return 1;
temp=powr(x, y / 2);
if (y % 2 == 0)
return temp*temp;
else
return x*temp*temp;
}
bool palind(vector<ll>&arr){
ll n=arr.size();
for(ll i=0;i<arr.size()/2;i++){
if(arr[i]!=arr[n-i-1]){
return false;
}
}
return true;
}
void printv(vector<ll>v){
for(ll i=0;i<v.size();i++){
cout<<v[i]<<" ";
}
}
void printarr(ll arr[],ll n){
for(ll i=0;i<n;i++){
cout<<arr[i]<<" ";
}
}
void sortall(vector<ll>&v){
sort(v.begin(),v.end());
}
void get(ll arr[],ll n){
for(ll i=0;i<n;i++){
cin>>arr[i];
}
}
bool ch_pow2(ll n){
ll ch=logg(n,2);
if(powr(2,ch)==n){
return 1;
}
return 0;
}
class solution{
public:
string getstr(){
string s;
cin>>s;
return s;
}
vector<ll> getmin(string s){
vector<ll>open,close;
for(ll i=0;i<s.size();i++){
if(s[i]=='('){
open.pb(i+1);
}
else{
close.pb(i+1);
}
}
ll i=0;ll j=close.size()-1;
vector<ll>v;
if(open.size()>0 && close.size()>0){
while(open[i]<close[j] && i<open.size() && j>=0){
v.pb(open[i]);v.pb(close[j]);i++;j--;
}
}
return v;
}
}solution;
ll dp[105][105];
int main(){
string s=solution.getstr();
vector<ll>v=solution.getmin(s);
if(v.size()>0){
cout<<"1"<<endl;
cout<<v.size()<<endl;sortall(v);
for(auto x:v){
cout<<x<<" ";
}
cout<<endl;
}
else{
cout<<"0"<<endl;
}
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 <iostream>
#include <vector>
#include <map>
#include <string.h>
#include <math.h>
#include <set>
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define cy cout << "YES\n"
#define cn cout << "NO\n"
#define nl "\n"
#define fi first
#define se second
#define MOD 1000000007
#define all(v) v.begin(), v.end()
#define sz(s) s.size()
#define f0r(j, n) for (ll i = j; i < n; i++)
#define cin_2d(vec, n, m) \
for (int i = 0; i < n; i++) \
for (int j = 0; j < m && cin >> vec[i][j]; j++) \
;
#define ceil(w, m) (((w) / (m)) + ((w) % (m) ? 1 : 0)
#define Time cerr << "Time Taken: " << (float)clock() / CLOCKS_PER_SEC << " Secs" \
<< "\n";
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 sherry()
{
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;
cin >> a >> b;
vector<int> v(a), v2(a), pos(a);
cin >> v;
v2 = v;
sort(all(v2));
for (int i = 0; i < b; i++)
{
int num;
cin >> num;
pos[num - 1]++;
}
while (true)
{
bool flag = 0;
for (int i = 0; i < a; i++)
{
if (pos[i] == 1 and v[i] > v[i + 1])
{
swap(v[i], v[i + 1]);
flag = 1;
}
}
if (!flag)
{
break;
}
}
if (v2 == v)
cy;
else
cn;
}
int main()
{
sherry();
int t = 1;
cin >> t;
while (t--)
solve();
Time return 0;
} | cpp |
1304 | F2 | F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp",
"greedy"
] | // Judges with GCC >= 12 only needs Ofast
// #pragma GCC optimize("O3,no-stack-protector,fast-math,unroll-loops,tree-vectorize")
// MLE optimization
// #pragma GCC optimize("conserve-stack")
// Old judges
// #pragma GCC target("sse4.2,popcnt,lzcnt,abm,mmx,fma,bmi,bmi2")
// New judges. Test with assert(__builtin_cpu_supports("avx2"));
// #pragma GCC target("avx2,popcnt,lzcnt,abm,bmi,bmi2,fma,tune=native")
// Atcoder
// #pragma GCC target("avx2,popcnt,lzcnt,abm,bmi,bmi2,fma")
#include<bits/stdc++.h>
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
uniform_real_distribution<> pp(0.0,1.0);
#define ld long double
#define pii pair<int,int>
#define piii pair<int,pii>
#define fi first
#define se second
const int inf=1e9;
const int mod=998244353;
const int mod2=1e9+7;
const int maxn=55;
const int maxm=20005;
const int maxq=500005;
const int maxl=20;
const int maxa=1000005;
int power(int a,int n){
int res=1;
while(n){
if(n&1) res=res*a%mod;
a=a*a%mod;n>>=1;
}
return res;
}
struct node{
int Max[3];
node(){Max[0]=Max[1]=Max[2]=inf;}
friend node operator+(node a,node b){
node res;
for(int i=0;i<3;i++) res.Max[i]=max(a.Max[i],b.Max[i]);
return res;
}
};
int n,m,k,a[maxn][maxm],pre[maxm],suf[maxm],dp[maxm],cur[maxm];
namespace Segtree{
node tree[4*maxm];
void build(int l,int r,int id){
if(l==r){
tree[id].Max[0]=dp[l];
tree[id].Max[1]=dp[l]+suf[l+k];
tree[id].Max[2]=dp[l]+pre[l-1];
return;
}
int mid=(l+r)>>1;
build(l,mid,id<<1);build(mid+1,r,id<<1|1);
tree[id]=tree[id<<1]+tree[id<<1|1];
}
int query(int l,int r,int id,int tl,int tr,int t){
if(r<tl || tr<l) return -inf;
if(tl<=l && r<=tr) return tree[id].Max[t];
int mid=(l+r)>>1;
return max(query(l,mid,id<<1,tl,tr,t),query(mid+1,r,id<<1|1,tl,tr,t));
}
}
void solve(){
cin >> n >> m >> k;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++) cin >> a[i][j];
}
for(int i=1;i<=k;i++) dp[1]+=a[1][i]+a[2][i];
for(int i=2;i<=m-k+1;i++) dp[i]=dp[i-1]-a[1][i-1]-a[2][i-1]+a[1][i+k-1]+a[2][i+k-1];
for(int i=1;i<=m;i++) cur[i]=cur[i-1]+a[2][i];
for(int i=3;i<=n+1;i++){
for(int j=1;j<=m;j++){pre[j]=cur[j];cur[j]=cur[j-1]+a[i][j];}
for(int j=m;j>=1;j--) suf[j]=suf[j+1]+a[i-1][j];
Segtree::build(1,m-k+1,1);
for(int j=1;j<=m-k+1;j++){
dp[j]=Segtree::query(1,m-k+1,1,max(1,j-k+1),j,1)-suf[j+k]+cur[j+k-1]-cur[j-1];
//cout << dp[j] << ' ';
dp[j]=max(dp[j],Segtree::query(1,m-k+1,1,j,min(j+k-1,m-k+1),2)-pre[j-1]+cur[j+k-1]-cur[j-1]);
//cout << dp[j] << ' ';
if(j>k) dp[j]=max(dp[j],Segtree::query(1,m-k+1,1,1,j-k,0)+pre[j+k-1]-pre[j-1]+cur[j+k-1]-cur[j-1]);
//cout << dp[j] << ' ';
if(j+k<=m-k+1) dp[j]=max(dp[j],Segtree::query(1,m-k+1,1,j+k,m-k+1,0)+pre[j+k-1]-pre[j-1]+cur[j+k-1]-cur[j-1]);
//cout << dp[j] << ' ' << pre[j+k-1]-pre[j-1]+cur[j+k-1]-cur[j-1] << '\n';
}
//cout << '\n';
}
int ans=0;
for(int i=1;i<=m-k+1;i++) ans=max(ans,dp[i]);
cout << ans << '\n';
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
int test=1;//cin >> test;
while(test--) solve();
}
| cpp |
1288 | F | F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB
| [
"constructive algorithms",
"flows"
] | #include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 9;
//Works for both directed, undirected and with negative cost too
//doesn't work for negative cycles
//for undirected edges just make the directed flag false
//Complexity: O(min(E^2 *V log V, E logV * flow))
using T = long long;
const T inf = 1LL << 61;
struct MCMF {
struct edge {
int u, v;
T cap, cost; int id;
edge(int _u, int _v, T _cap, T _cost, int _id){
u = _u; v = _v; cap = _cap; cost = _cost; id = _id;
}
};
int n, s, t, mxid; T flow, cost;
vector<vector<int>> g; vector<edge> e;
vector<T> d, potential, flow_through;
vector<int> par; bool neg;
MCMF() {}
MCMF(int _n) { // 0-based indexing
n = _n + 10;
g.assign(n, vector<int> ());
neg = false; mxid = 0;
}
void add_edge(int u, int v, T cap, T cost, int id = -1, bool directed = true) {
if(cost < 0) neg = true;
g[u].push_back(e.size());
e.push_back(edge(u, v, cap, cost, id));
g[v].push_back(e.size());
e.push_back(edge(v, u, 0, -cost, -1));
mxid = max(mxid, id);
if(!directed) add_edge(v, u, cap, cost, -1, true);
}
bool dijkstra() {
par.assign(n, -1);
d.assign(n, inf);
priority_queue<pair<T, T>, vector<pair<T, T>>, greater<pair<T, T>> > q;
d[s] = 0;
q.push(pair<T, T>(0, s));
while (!q.empty()) {
int u = q.top().second;
T nw = q.top().first;
q.pop();
if(nw != d[u]) continue;
for (int i = 0; i < (int)g[u].size(); i++) {
int id = g[u][i];
int v = e[id].v; T cap = e[id].cap;
T w = e[id].cost + potential[u] - potential[v];
if (d[u] + w < d[v] && cap > 0) {
d[v] = d[u] + w;
par[v] = id;
q.push(pair<T, T>(d[v], v));
}
}
}
for (int i = 0; i < n; i++) { // update potential
if(d[i] < inf) potential[i] += d[i];
}
return d[t] != inf;
}
T send_flow(int v, T cur) {
if(par[v] == -1) return cur;
int id = par[v];
int u = e[id].u; T w = e[id].cost;
T f = send_flow(u, min(cur, e[id].cap));
cost += f * w;
e[id].cap -= f;
e[id^1].cap += f;
return f;
}
//returns {maxflow, mincost}
pair<T, T> solve(int _s, int _t, T goal = inf) {
s = _s; t = _t;
flow = 0, cost = 0;
potential.assign(n, 0);
if (neg) {
// run Bellman-Ford to find starting potential
d.assign(n, inf);
for (int i = 0, relax = true; i < n && relax; i++) {
for (int u = 0; u < n; u++) {
for (int k = 0; k < (int)g[u].size(); k++) {
int id = g[u][k];
int v = e[id].v; T cap = e[id].cap, w = e[id].cost;
if (d[v] > d[u] + w && cap > 0) {
d[v] = d[u] + w;
relax = true;
}
}
}
}
for(int i = 0; i < n; i++) if(d[i] < inf) potential[i] = d[i];
}
while (flow < goal && dijkstra()) flow += send_flow(t, goal - flow);
flow_through.assign(mxid + 10, 0);
for (int u = 0; u < n; u++) {
for (auto v: g[u]) {
if (e[v].id >= 0) flow_through[e[v].id] = e[v ^ 1].cap;
}
}
return make_pair(flow, cost);
}
};
//flow_through[i] = extra flow beyond 'low' sent through edge i
//it finds the feasible solution with minimum cost
//not necessarily with maximum flow
struct LR_Flow{
MCMF F;
int n, s, t;
T target;
LR_Flow() {}
LR_Flow(int _n) {
n = _n + 10; s = n - 2, t = n - 1; target = 0;
F = MCMF(n);
}
void add_edge(int u, int v, T l, T r, T cost = 0, int id = -1) {
assert(0 <= l && l <= r);
if (l != 0) {
F.add_edge(s, v, l, cost);
F.add_edge(u, t, l, 0);
target += l;
}
F.add_edge(u, v, r - l, cost, id);
}
pair<T, T> solve(int _s, int _t) {
F.add_edge(_t, _s, inf, 0);
auto ans = F.solve(s, t);
if (ans.first < target) return {-1, -1}; //not feasible
return ans;
}
};
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n1, n2, m, r, b; cin >> n1 >> n2 >> m >> r >> b;
string s1, s2; cin >> s1 >> s2;
int s = n1 + n2 + 10, t = s + 1;
LR_Flow F(t);
for (int i = 0; i < m; i++) {
int u, v; cin >> u >> v; --u; --v;
F.add_edge(u, v + n1, 0, 1, r, i);
F.add_edge(v + n1, u, 0, 1, b, i + m);
}
for (int i = 0; i < n1; i++) {
if (s1[i] == 'R') F.add_edge(s, i, 1, inf, 0);
else if (s1[i] == 'B') F.add_edge(i, t, 1, inf, 0);
else F.add_edge(s, i, 0, inf, 0), F.add_edge(i, t, 0, inf, 0);
}
for (int i = 0; i < n2; i++) {
if (s2[i] == 'B') F.add_edge(s, i + n1, 1, inf, 0);
else if (s2[i] == 'R') F.add_edge(i + n1, t, 1, inf, 0);
else F.add_edge(s, i + n1, 0, inf, 0), F.add_edge(i + n1, t, 0, inf, 0);
}
auto ans = F.solve(s, t);
if (ans.first == -1) cout << -1 << '\n';
else {
cout << ans.second << '\n';
for (int i = 0; i < m; i++) {
if (F.F.flow_through[i]) cout << "R";
else if (F.F.flow_through[i + m]) cout << "B";
else cout << "U";
}
cout << '\n';
}
return 0;
} | cpp |
1295 | F | F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212. | [
"combinatorics",
"dp",
"probabilities"
] | #line 1 "library/my_template.hpp"
#if defined(LOCAL)
#include <my_template_compiled.hpp>
#else
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) \
vector<vector<vector<type>>> name( \
h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name( \
a, vector<vector<vector<type>>>( \
b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c))
#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)
#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) \
overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)
#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define stoi stoll
template <typename T, typename U>
T SUM(const vector<U> &A) {
T sum = 0;
for (auto &&a: A) sum += a;
return sum;
}
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) \
sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
template <typename T>
T pick(deque<T> &que) {
T a = que.front();
que.pop_front();
return a;
}
template <typename T>
T pick(pq<T> &que) {
T a = que.top();
que.pop();
return a;
}
template <typename T>
T pick(pqg<T> &que) {
assert(que.size());
T a = que.top();
que.pop();
return a;
}
template <typename T>
T pick(vc<T> &que) {
assert(que.size());
T a = que.back();
que.pop_back();
return a;
}
template <typename T, typename U>
T ceil(T x, U y) {
return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U>
T floor(T x, U y) {
return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
T q = floor(x, y);
return {q, x - q * y};
}
template <typename F>
ll binary_search(F check, ll ok, ll ng) {
assert(check(ok));
while (abs(ok - ng) > 1) {
auto x = (ng + ok) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return ok;
}
template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
FOR(iter) {
double x = (ok + ng) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return (ok + ng) / 2;
}
template <class T, class S>
inline bool chmax(T &a, const S &b) {
return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
return (a > b ? a = b, 1 : 0);
}
vc<int> s_to_vi(const string &S, char first_char) {
vc<int> A(S.size());
FOR(i, S.size()) { A[i] = S[i] - first_char; }
return A;
}
template <typename T, typename U>
vector<T> cumsum(vector<U> &A, int off = 1) {
int N = A.size();
vector<T> B(N + 1);
FOR(i, N) { B[i + 1] = B[i] + A[i]; }
if (off == 0) B.erase(B.begin());
return B;
}
template <typename CNT, typename T>
vc<CNT> bincount(const vc<T> &A, int size) {
vc<CNT> C(size);
for (auto &&x: A) { ++C[x]; }
return C;
}
// stable
template <typename T>
vector<int> argsort(const vector<T> &A) {
vector<int> ids(A.size());
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
return ids;
}
// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
int n = len(I);
vc<T> B(n);
FOR(i, n) B[i] = A[I[i]];
return B;
}
#endif
#line 1 "library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace fastio {
// クラスが read(), print() を持っているかを判定するメタ関数
struct has_write_impl {
template <class T>
static auto check(T &&x) -> decltype(x.write(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_write : public decltype(has_write_impl::check<T>(std::declval<T>())) {
};
struct has_read_impl {
template <class T>
static auto check(T &&x) -> decltype(x.read(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_read : public decltype(has_read_impl::check<T>(std::declval<T>())) {};
struct Scanner {
FILE *fp;
char line[(1 << 15) + 1];
size_t st = 0, ed = 0;
void reread() {
memmove(line, line + st, ed - st);
ed -= st;
st = 0;
ed += fread(line + ed, 1, (1 << 15) - ed, fp);
line[ed] = '\0';
}
bool succ() {
while (true) {
if (st == ed) {
reread();
if (st == ed) return false;
}
while (st != ed && isspace(line[st])) st++;
if (st != ed) break;
}
if (ed - st <= 50) {
bool sep = false;
for (size_t i = st; i < ed; i++) {
if (isspace(line[i])) {
sep = true;
break;
}
}
if (!sep) reread();
}
return true;
}
template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
while (true) {
size_t sz = 0;
while (st + sz < ed && !isspace(line[st + sz])) sz++;
ref.append(line + st, sz);
st += sz;
if (!sz || st != ed) break;
reread();
}
return true;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
bool neg = false;
if (line[st] == '-') {
neg = true;
st++;
}
ref = T(0);
while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
if (neg) ref = -ref;
return true;
}
template <typename T,
typename enable_if<has_read<T>::value>::type * = nullptr>
inline bool read_single(T &x) {
x.read();
return true;
}
bool read_single(double &ref) {
string s;
if (!read_single(s)) return false;
ref = std::stod(s);
return true;
}
bool read_single(char &ref) {
string s;
if (!read_single(s) || s.size() != 1) return false;
ref = s[0];
return true;
}
template <class T>
bool read_single(vector<T> &ref) {
for (auto &d: ref) {
if (!read_single(d)) return false;
}
return true;
}
template <class T, class U>
bool read_single(pair<T, U> &p) {
return (read_single(p.first) && read_single(p.second));
}
template <size_t N = 0, typename T>
void read_single_tuple(T &t) {
if constexpr (N < std::tuple_size<T>::value) {
auto &x = std::get<N>(t);
read_single(x);
read_single_tuple<N + 1>(t);
}
}
template <class... T>
bool read_single(tuple<T...> &tpl) {
read_single_tuple(tpl);
return true;
}
void read() {}
template <class H, class... T>
void read(H &h, T &... t) {
bool f = read_single(h);
assert(f);
read(t...);
}
Scanner(FILE *fp) : fp(fp) {}
};
struct Printer {
Printer(FILE *_fp) : fp(_fp) {}
~Printer() { flush(); }
static constexpr size_t SIZE = 1 << 15;
FILE *fp;
char line[SIZE], small[50];
size_t pos = 0;
void flush() {
fwrite(line, 1, pos, fp);
pos = 0;
}
void write(const char val) {
if (pos == SIZE) flush();
line[pos++] = val;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
void write(T val) {
if (pos > (1 << 15) - 50) flush();
if (val == 0) {
write('0');
return;
}
if (val < 0) {
write('-');
val = -val; // todo min
}
size_t len = 0;
while (val) {
small[len++] = char(0x30 | (val % 10));
val /= 10;
}
for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
pos += len;
}
void write(const string s) {
for (char c: s) write(c);
}
void write(const char *s) {
size_t len = strlen(s);
for (size_t i = 0; i < len; i++) write(s[i]);
}
void write(const double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
void write(const long double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
template <typename T,
typename enable_if<has_write<T>::value>::type * = nullptr>
inline void write(T x) {
x.write();
}
template <class T>
void write(const vector<T> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
template <class T, class U>
void write(const pair<T, U> val) {
write(val.first);
write(' ');
write(val.second);
}
template <size_t N = 0, typename T>
void write_tuple(const T t) {
if constexpr (N < std::tuple_size<T>::value) {
if constexpr (N > 0) { write(' '); }
const auto x = std::get<N>(t);
write(x);
write_tuple<N + 1>(t);
}
}
template <class... T>
bool write(tuple<T...> tpl) {
write_tuple(tpl);
return true;
}
template <class T, size_t S>
void write(const array<T, S> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
void write(i128 val) {
string s;
bool negative = 0;
if (val < 0) {
negative = 1;
val = -val;
}
while (val) {
s += '0' + int(val % 10);
val /= 10;
}
if (negative) s += "-";
reverse(all(s));
if (len(s) == 0) s = "0";
write(s);
}
};
Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);
void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
printer.write(head);
if (sizeof...(Tail)) printer.write(' ');
print(forward<Tail>(tail)...);
}
void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
scanner.read(head);
read(tail...);
}
} // namespace fastio
using fastio::print;
using fastio::flush;
using fastio::read;
#define INT(...) \
int __VA_ARGS__; \
read(__VA_ARGS__)
#define LL(...) \
ll __VA_ARGS__; \
read(__VA_ARGS__)
#define STR(...) \
string __VA_ARGS__; \
read(__VA_ARGS__)
#define CHAR(...) \
char __VA_ARGS__; \
read(__VA_ARGS__)
#define DBL(...) \
double __VA_ARGS__; \
read(__VA_ARGS__)
#define VEC(type, name, size) \
vector<type> name(size); \
read(name)
#define VV(type, name, h, w) \
vector<vector<type>> name(h, vector<type>(w)); \
read(name)
void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 2 "library/mod/modint.hpp"
template <int mod>
struct modint {
int val;
constexpr modint(ll x = 0) noexcept {
if (0 <= x && x < mod)
val = x;
else {
x %= mod;
val = (x < 0 ? x + mod : x);
}
}
bool operator<(const modint &other) const {
return val < other.val;
} // To use std::map
modint &operator+=(const modint &p) {
if ((val += p.val) >= mod) val -= mod;
return *this;
}
modint &operator-=(const modint &p) {
if ((val += mod - p.val) >= mod) val -= mod;
return *this;
}
modint &operator*=(const modint &p) {
val = (int)(1LL * val * p.val % mod);
return *this;
}
modint &operator/=(const modint &p) {
*this *= p.inverse();
return *this;
}
modint operator-() const { return modint(-val); }
modint operator+(const modint &p) const { return modint(*this) += p; }
modint operator-(const modint &p) const { return modint(*this) -= p; }
modint operator*(const modint &p) const { return modint(*this) *= p; }
modint operator/(const modint &p) const { return modint(*this) /= p; }
bool operator==(const modint &p) const { return val == p.val; }
bool operator!=(const modint &p) const { return val != p.val; }
modint inverse() const {
int a = val, b = mod, u = 1, v = 0, t;
while (b > 0) {
t = a / b;
swap(a -= t * b, b), swap(u -= t * v, v);
}
return modint(u);
}
modint pow(int64_t n) const {
modint ret(1), mul(val);
while (n > 0) {
if (n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
void write() { fastio::printer.write(val); }
void read() { fastio::scanner.read(val); }
static constexpr int get_mod() { return mod; }
};
struct ArbitraryModInt {
static constexpr bool is_modint = true;
int val;
ArbitraryModInt() : val(0) {}
ArbitraryModInt(int64_t y)
: val(y >= 0 ? y % get_mod()
: (get_mod() - (-y) % get_mod()) % get_mod()) {}
bool operator<(const ArbitraryModInt &other) const {
return val < other.val;
} // To use std::map<ArbitraryModInt, T>
static int &get_mod() {
static int mod = 0;
return mod;
}
static void set_mod(int md) { get_mod() = md; }
ArbitraryModInt &operator+=(const ArbitraryModInt &p) {
if ((val += p.val) >= get_mod()) val -= get_mod();
return *this;
}
ArbitraryModInt &operator-=(const ArbitraryModInt &p) {
if ((val += get_mod() - p.val) >= get_mod()) val -= get_mod();
return *this;
}
ArbitraryModInt &operator*=(const ArbitraryModInt &p) {
long long a = (long long)val * p.val;
int xh = (int)(a >> 32), xl = (int)a, d, m;
asm("divl %4; \n\t" : "=a"(d), "=d"(m) : "d"(xh), "a"(xl), "r"(get_mod()));
val = m;
return *this;
}
ArbitraryModInt &operator/=(const ArbitraryModInt &p) {
*this *= p.inverse();
return *this;
}
ArbitraryModInt operator-() const { return ArbitraryModInt(get_mod() - val); }
ArbitraryModInt operator+(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) += p;
}
ArbitraryModInt operator-(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) -= p;
}
ArbitraryModInt operator*(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) *= p;
}
ArbitraryModInt operator/(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) /= p;
}
bool operator==(const ArbitraryModInt &p) const { return val == p.val; }
bool operator!=(const ArbitraryModInt &p) const { return val != p.val; }
ArbitraryModInt inverse() const {
int a = val, b = get_mod(), u = 1, v = 0, t;
while (b > 0) {
t = a / b;
swap(a -= t * b, b), swap(u -= t * v, v);
}
return ArbitraryModInt(u);
}
ArbitraryModInt pow(int64_t n) const {
ArbitraryModInt ret(1), mul(val);
while (n > 0) {
if (n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
void write() { fastio::printer.write(val); }
void read() { fastio::scanner.read(val); }
};
template <typename mint>
mint inv(int n) {
static const int mod = mint::get_mod();
static vector<mint> dat = {0, 1};
assert(0 <= n);
if (n >= mod) n %= mod;
while (int(dat.size()) <= n) {
int k = dat.size();
auto q = (mod + k - 1) / k;
int r = k * q - mod;
dat.emplace_back(dat[r] * mint(q));
}
return dat[n];
}
template <typename mint>
mint fact(int n) {
static const int mod = mint::get_mod();
static vector<mint> dat = {1, 1};
assert(0 <= n);
if (n >= mod) return 0;
while (int(dat.size()) <= n) {
int k = dat.size();
dat.emplace_back(dat[k - 1] * mint(k));
}
return dat[n];
}
template <typename mint>
mint fact_inv(int n) {
static const int mod = mint::get_mod();
static vector<mint> dat = {1, 1};
assert(-1 <= n && n < mod);
if (n == -1) return mint(0);
while (int(dat.size()) <= n) {
int k = dat.size();
dat.emplace_back(dat[k - 1] * inv<mint>(k));
}
return dat[n];
}
template <class mint, class... Ts>
mint fact_invs(Ts... xs) {
return (mint(1) * ... * fact_inv<mint>(xs));
}
template <typename mint, class Head, class... Tail>
mint multinomial(Head &&head, Tail &&... tail) {
return fact<mint>(head) * fact_invs<mint>(std::forward<Tail>(tail)...);
}
template <typename mint>
mint C_dense(int n, int k) {
static vvc<mint> C;
static int H = 0, W = 0;
auto calc = [&](int i, int j) -> mint {
if (i == 0) return (j == 0 ? mint(1) : mint(0));
return C[i - 1][j] + (j ? C[i - 1][j - 1] : 0);
};
if (W <= k) {
FOR(i, H) {
C[i].resize(k + 1);
FOR(j, W, k + 1) { C[i][j] = calc(i, j); }
}
W = k + 1;
}
if (H <= n) {
C.resize(n + 1);
FOR(i, H, n + 1) {
C[i].resize(W);
FOR(j, W) { C[i][j] = calc(i, j); }
}
H = n + 1;
}
return C[n][k];
}
template <typename mint, bool large = false, bool dense = false>
mint C(ll n, ll k) {
assert(n >= 0);
if (k < 0 || n < k) return 0;
if (dense) return C_dense<mint>(n, k);
if (!large) return fact<mint>(n) * fact_inv<mint>(k) * fact_inv<mint>(n - k);
k = min(k, n - k);
mint x(1);
FOR(i, k) { x *= mint(n - i); }
x *= fact_inv<mint>(k);
return x;
}
template <typename mint, bool large = false>
mint C_inv(ll n, ll k) {
assert(n >= 0);
assert(0 <= k && k <= n);
if (!large) return fact_inv<mint>(n) * fact<mint>(k) * fact<mint>(n - k);
return mint(1) / C<mint, 1>(n, k);
}
// [x^d] (1-x) ^ {-n} の計算
template <typename mint, bool large = false, bool dense = false>
mint C_negative(ll n, ll d) {
assert(n >= 0);
if (d < 0) return mint(0);
if (n == 0) { return (d == 0 ? mint(1) : mint(0)); }
return C<mint, large, dense>(n + d - 1, d);
}
using modint107 = modint<1000000007>;
using modint998 = modint<998244353>;
using amint = ArbitraryModInt;
#line 4 "main.cpp"
using mint = modint998;
void solve() {
const int mod = mint::get_mod();
LL(N);
VEC(pi, LR, N);
LR.insert(LR.begin(), {mod, mod});
LR.eb(-1, -1);
reverse(all(LR));
for (auto&& [a, b]: LR) ++b;
vi X;
for (auto&& [a, b]: LR) X.eb(a), X.eb(b);
UNIQUE(X);
for (auto&& [a, b]: LR) a = LB(X, a), b = LB(X, b);
ll M = len(X) - 1;
N = len(LR);
vv(mint, dp, M, N + 1); // どの区間 / 何番目
dp[0][1] = mint(1);
for (auto&& [L, R]: LR) {
vv(mint, newdp, M, N + 1);
FOR(i, L, R) FOR(j, N) { newdp[i][j + 1] += dp[i][j]; }
FOR(i, M) FOR(j, N + 1) {
mint x = dp[i][j];
if (x == mint(0)) continue;
ll n = X[i + 1] - X[i];
// n 個から、j+1 個を広義単調増加に選ぶ
x *= C<mint, true>(n + j, j + 1);
FOR(k, L, R) if (i < k) { newdp[k][0] += x; }
}
swap(dp, newdp);
}
mint total = 1;
for (auto&& [a, b]: LR) total *= mint(X[b] - X[a]);
mint ANS = dp[M - 1][0];
print(ANS / total);
}
signed main() {
solve();
return 0;
}
| cpp |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t;
cin >> t;
while(t--){
int n;
cin >> n;
string s;
cin >> s;
bool flag = false;
int cnt = 0;
int mx = 0;
for(int i = 0; i < n; i++){
if(s[i] == 'A'){
flag = true;
mx = max(mx, cnt);
cnt = 0;
}else if(flag){
cnt++;
}
}
mx = max(mx, cnt);
cout << mx << '\n';
}
return 0;
} | cpp |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
bool cmp(const int &a , const int &b) {
return a > b ;
}
int main(){
int t=0;
cin>>t;
while(t){
int a[4];
for(int q=0;q<4;q++){
cin>>a[q];
}
int b[4]={0,0,0,0};
b[0]=abs(0-a[2])*a[1];
b[1]=abs(0-a[3])*a[0];
b[2]=(a[0]-1-a[2])*a[1];
b[3]=(a[1]-1-a[3])*a[0];
sort(b,b+4,cmp);
cout<<b[0]<<endl;
t--;
}
return 0;
}
| cpp |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | #include <bits/stdc++.h>
using namespace std;
int main () {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
scanf("%d %d", &n, &m);
vector<vector<int>> a(n, vector<int>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf("%d", &a[i][j]);
}
}
const int mxsub = 1 << m;
auto exhaust = [&] (int trym) -> array<int, 2> {
vector<int> mask(n);
vector<int> id(mxsub, -1);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
mask[i] |= trym <= a[i][j] ? (1 << j) : 0;
}
id[mask[i]] = i + 1;
}
for (int mask0 = 0; mask0 < mxsub; ++mask0) {
for (int mask1 = 0; mask1 < mxsub; ++mask1) {
if ((mask0 | mask1) == mxsub - 1) {
if (~id[mask0] and ~id[mask1]) {
return {id[mask0], id[mask1]};
}
}
}
}
return {-1, -1};
};
int lans = -1, rans = -1;
int lo = 0, hi = (int) 1e9;
while (lo <= hi) {
int mid = lo + ((hi - lo) >> 1);
auto y = exhaust(mid);
if (y != array<int, 2> {-1, -1}) {
lans = y[0];
rans = y[1];
lo = mid + 1;
} else {
hi = mid - 1;
}
}
printf("%d %d\n", lans, rans);
return 0;
}
/* To be honest, saw the tag for hint.
* Tag of "Binary Search" helped a lot coming out with the solution.
* Nonetheless, hoping for the AC. Hopefully this is a correct solution. */
| 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 Cn const
#define CI Cn int&
#define N 500000
#define LN 20
#define add(x,y) (e[++ee].nxt=lnk[x],e[lnk[x]=ee].to=y)
using namespace std;
namespace FastIO
{
#define FS 100000
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define tc() (FA==FB&&(FB=(FA=FI)+fread(FI,1,FS,stdin),FA==FB)?EOF:*FA++)
#define pc(c) (FC==FE&&(clear(),0),*FC++=c)
int OT;char oc,FI[FS],FO[FS],OS[FS],*FA=FI,*FB=FI,*FC=FO,*FE=FO+FS;
void clear() {fwrite(FO,1,FC-FO,stdout),FC=FO;}struct IO_Cl {~IO_Cl() {clear();}}CL;
Tp void read(Ty& x) {x=0;while(!isdigit(oc=tc()));while(x=(x<<3)+(x<<1)+(oc&15),isdigit(oc=tc()));}
Ts void read(Ty& x,Ar&... y) {read(x),read(y...);}
Tp void write(Ty x) {while(OS[++OT]=x%10+48,x/=10);while(OT) pc(OS[OT--]);pc(' ');}
}using namespace FastIO;
int n,m,ee,lnk[N+5];struct edge {int to,nxt;}e[N<<1];
namespace U
{
int f[N+5],g[N+5];int fa(int x) {if(!f[x]) return x;int t=fa(f[x]);return g[x]^=g[f[x]],f[x]=t;}
void U(int x,int y,int z)
{
int fx=fa(x),fy=fa(y);if(fx==fy) {g[x]^g[y]^z&&(puts("-1"),exit(0),0);return;}
f[fy]=fx,g[fy]=g[x]^g[y]^z;
}
}
namespace T
{
int D[N+5],f[N+5][LN+1];
int h[N+5];int H(int x) {return h[x]?h[x]=H(h[x]):x;}
void Init(int x=1)
{
int i,y;for(i=1;i<=LN;++i) f[x][i]=f[f[x][i-1]][i-1];
for(i=lnk[x];i;i=e[i].nxt) (y=e[i].to)^f[x][0]&&(D[y]=D[f[y][0]=x]+1,Init(y),0);
}
void Mg(int x,int y)
{
#define Mg_(x,y) while(D[x=H(x)]>D[y]+1) U::U(f[x][0],x,0),h[x]=f[x][0]
D[x]<D[y]&&(swap(x,y),0);int i,x0=x,y0=y;for(i=0;D[x]^D[y];++i) (D[x]^D[y])>>i&1&&(x=f[x][i]);
if(x==y) {Mg_(x0,y);return;}for(i=0;f[x][i]^f[y][i];++i);for(--i;~i;--i) f[x][i]^f[y][i]&&(x=f[x][i],y=f[y][i]);
Mg_(x0,f[x][0]);Mg_(y0,f[y][0]);U::U(x,y,1);
}
}
int a[N+5],p[N+5],q[N+5],s[N+5][2];bool Chk(int u,int x=1,int lst=0)
{
int i,y,f,c=0,F=U::fa(x),G=U::g[x];for(i=lnk[x];i;i=e[i].nxt) if(e[i].to^lst&&!Chk(u,e[i].to,x)) return false;
for(i=lnk[x];i;i=e[i].nxt) (y=e[i].to)^lst&&(f=U::fa(y),p[f]=s[f][0]=s[f][1]=0);p[F]=0;
for(i=lnk[x];i;i=e[i].nxt) (y=e[i].to)^lst&&(f=U::fa(y),!p[f]&&(p[q[++c]=f]=1),s[f][U::g[y]]=max(s[f][U::g[y]],a[y]));
int m1=0,m2=0;for(i=1;i<=c;++i) q[i]^F&&(m1=max(m1,min(s[q[i]][0],s[q[i]][1])),m2=max(m2,max(s[q[i]][0],s[q[i]][1])));
if(m1+m2+1>u) return false;if(!p[F]) return a[x]=m1+1,true;
if(max(s[F][G],m1)+max(s[F][G^1],m2)+1<=u) return a[x]=max(s[F][G],m1)+1,true;
if(max(s[F][G],m2)+max(s[F][G^1],m1)+1<=u) return a[x]=max(s[F][G],m2)+1,true;return false;
}
int w[N+5];void Col(int u,int x=1,int lst=0)
{
int i,y,f,c=0,F=U::fa(x),G=U::g[x];w[x]=w[F]^G;
for(i=lnk[x];i;i=e[i].nxt) (y=e[i].to)^lst&&(f=U::fa(y),p[f]=s[f][0]=s[f][1]=0);p[F]=0;
for(i=lnk[x];i;i=e[i].nxt) (y=e[i].to)^lst&&(f=U::fa(y),!p[f]&&(p[q[++c]=f]=1),s[f][U::g[y]]=max(s[f][U::g[y]],a[y]));
if(!p[F]) {for(i=1;i<=c;++i) w[q[i]]=w[x]^(s[q[i]][0]>s[q[i]][1]);}else
{
int m1=0,m2=0;for(i=1;i<=c;++i) q[i]^F&&(m1=max(m1,min(s[q[i]][0],s[q[i]][1])),m2=max(m2,max(s[q[i]][0],s[q[i]][1])));
if(max(s[F][G],m1)+max(s[F][G^1],m2)+1<=u) for(i=1;i<=c;++i) q[i]^F&&(w[q[i]]=w[x]^(s[q[i]][0]>s[q[i]][1]));
else for(i=1;i<=c;++i) q[i]^F&&(w[q[i]]=w[x]^(s[q[i]][0]<s[q[i]][1]));
}
for(i=lnk[x];i;i=e[i].nxt) e[i].to^lst&&(Col(u,e[i].to,x),0);
}
int d[N+5],v[N+5];vector<int> g[N+5];
void Topo()
{
#define Add(x,y) (g[x].push_back(y),++d[y])
int i;for(i=2;i<=n;++i) w[i]?Add(i,T::f[i][0]):Add(T::f[i][0],i);
int k,H=1,T=0;for(i=1;i<=n;++i) !d[i]&&(v[q[++T]=i]=1);
while(H<=T) {k=q[H++];for(auto y:g[k]) !--d[y]&&(v[q[++T]=y]=v[k]+1);}
for(i=1;i<=n;++i) write(v[i]);
}
int main()
{
int i,x,y;for(read(n,m),i=1;i^n;++i) read(x,y),add(x,y),add(y,x);T::Init();
for(i=1;i<=m;++i) read(x,y),T::Mg(x,y);int l=1,r=n,u;while(l^r) Chk(u=l+r-1>>1)?r=u:l=u+1;
return printf("%d\n",r),Chk(r),Col(r),Topo(),0;
} | cpp |
1299 | D | D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept. | [
"bitmasks",
"combinatorics",
"dfs and similar",
"dp",
"graphs",
"graphs",
"math",
"trees"
] | #include<bits/stdc++.h>
#define For(i,a,b) for(int i=(a);i<=(b);++i)
#define Rof(i,a,b) for(int i=(a);i>=(b);--i)
using namespace std;
const int Maxn=1e5,Maxk=374,Mod=1e9+7;
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0' || ch>'9')
{
if(ch=='-') f=-1;
ch=getchar();
}
while(ch>='0' && ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
struct Node{int frm,to,nxt,w;} Edge[Maxn*2+5];
int tot=1,Head[Maxn+5];
map<pair<int,int>,int> mp;
inline void Addedge(int x,int y,int z)
{
Edge[++tot]=(Node){x,y,Head[x],z};
Head[x]=tot,mp[make_pair(x,y)]=z;
}
int n,m,fa[Maxn+5],val[Maxn+5][5];
int num[Maxn+5][5],sum[Maxn+5],vis[Maxn+5];
int dfn[Maxn+5],chk[Maxn+5],cnt[Maxn+5],ID,cur;
int id[2][4][8][16][32],st[Maxk+5][5],tyw;
int g[Maxk+5][Maxk+5],f[2][Maxk+5];
vector<int> v,w[Maxn+5];
inline int Find(int x) {return fa[x]==x?x:fa[x]=Find(fa[x]);}
int hzh[5];
inline void add(int &x,int y) {x=(x+y)%Mod;}
inline void Reset(int *A)
{
Rof(i,4,0) if(A[i]) For(j,i+1,4)
if(A[j]&(1<<i)) A[j]^=A[i];
}
inline void dfs(int i)
{
if(i>4)
{
id[hzh[0]][hzh[1]][hzh[2]][hzh[3]][hzh[4]]=++tyw;
memcpy(st[tyw],hzh,sizeof(hzh)); return;
}
hzh[i]=0; dfs(i+1);
For(j,1<<i,(1<<i+1)-1)
{
int flag=0; hzh[i]=j;
For(k,0,i-1) if(hzh[k] && j&(1<<k)) {flag=1; break;}
if(!flag) dfs(i+1);
}
}
inline void Merge(int a,int b)
{
For(i,0,4) hzh[i]=st[a][i];
For(i,0,4) if(st[b][i])
{
int x=st[b][i];
Rof(j,4,0) if(x&(1<<j))
{
if(!hzh[j]) {hzh[j]=x; break;}
x^=hzh[j];
}
if(!x) {g[a][b]=-1; return;}
}
Reset(hzh);
int idx=id[hzh[0]][hzh[1]][hzh[2]][hzh[3]][hzh[4]];
if(!idx) g[a][b]=-1;
else g[a][b]=idx;
}
inline void Build()
{
dfs(0);
For(i,1,tyw) For(j,1,tyw) Merge(i,j);
}
inline void Insert(int x,int y)
{
Rof(i,4,0) if(y&(1<<i))
{
if(!val[x][i]) {val[x][i]=y; return;}
y^=val[x][i];
}
if(!y) chk[x]=1;
}
inline void dfs(int x,int fa)
{
dfn[x]=++cur;
for(int i=Head[x];i;i=Edge[i].nxt)
{
int y=Edge[i].to,z=Edge[i].w;
if(y==fa || y==1) continue;
if(!dfn[y]) sum[y]=sum[x]^z,dfs(y,x);
else if(dfn[y]<dfn[x]) Insert(ID,sum[x]^sum[y]^z);
}
}
int main()
{
// freopen("1.in","r",stdin);
// freopen("1.out","w",stdout);
n=read(),m=read();
For(i,1,n) fa[i]=i;
For(i,1,m)
{
int a=read(),b=read(),c=read();
Addedge(a,b,c),Addedge(b,a,c);
if(a!=1 && b!=1 && Find(a)!=Find(b)) fa[Find(a)]=Find(b);
}
For(i,2,n) if(Find(i)==i) v.push_back(ID=i),dfs(i,0);
For(i,2,n) w[Find(i)].push_back(i);
for(int i=Head[1];i;i=Edge[i].nxt) cnt[Find(Edge[i].to)]++;
for(auto i:v) if(cnt[i]==2)
{
int a=0,b=0;
for(auto j:w[i]) if(mp.find(make_pair(1,j))!=mp.end()) (!a?a:b)=j;
int res=mp[make_pair(1,a)]^mp[make_pair(1,b)]^mp[make_pair(a,b)];
memcpy(num[i],val[i],sizeof(val[i])),vis[i]=chk[i];
Rof(j,4,0) if(res&(1<<j))
{
if(!num[i][j]) {num[i][j]=res; break;}
res^=num[i][j];
}
if(!res) vis[i]=1;
// printf("%d: %d %d %d\n",i,cnt[i],chk[i],vis[i]);
// For(j,0,4) printf("%d %d\n",val[i][j],num[i][j]);
}
for(auto i:v) Reset(val[i]),Reset(num[i]);
Build();
int o=0,p=1; f[0][1]=1;
for(auto i:v)
{
o^=1,p^=1,memset(f[o],0,sizeof(f[o]));
memcpy(f[o],f[p],sizeof(f[p]));
if(cnt[i]==1 && !chk[i])
{
int idx=id[val[i][0]][val[i][1]][val[i][2]][val[i][3]][val[i][4]];
For(j,1,tyw) if(f[p][j] && g[j][idx]>0) add(f[o][g[j][idx]],f[p][j]);
}
if(cnt[i]==2 && !chk[i])
{
int idx=id[val[i][0]][val[i][1]][val[i][2]][val[i][3]][val[i][4]];
For(j,1,tyw) if(f[p][j] && g[j][idx]>0) add(f[o][g[j][idx]],f[p][j]*2%Mod);
}
if(cnt[i]==2 && !vis[i])
{
int idx=id[num[i][0]][num[i][1]][num[i][2]][num[i][3]][num[i][4]];
For(j,1,tyw) if(f[p][j] && g[j][idx]>0) add(f[o][g[j][idx]],f[p][j]);
}
}
int ans=0;
For(i,1,tyw) add(ans,f[o][i]);
printf("%d\n",ans);
return 0;
} | cpp |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | #define RAGHAV_PATEL ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
#define int long long int
int find_sumdigit(int number)
{
int ans = 0;
while (number > 0)
{
ans += number % 10;
number /= 10;
}
return ans;
}
void solve()
{
int n;
cin >> n;
vector<int>v(n);
for(int i=0;i<n;i++)
cin>>v[i];
vector<int>fv(n);
vector<int>bv(n);
for(int i=0;i<n;i++){
fv[i]=i;
bv[i]=n-i-1;
}
int fr=-1,br=n;
for(int i=0;i<n;i++){
if(v[i]>=fv[i])
fr++;
else{
break;
}
}
for(int i=n-1;i>=0;i--){
if(v[i]>=bv[i])
br--;
else
break;
}
// cout<<fr<<" "<<br<<" ";
if(fr>=br)
cout<<"Yes\n";
else
cout<<"No\n";
}
signed main()
{
RAGHAV_PATEL
int t, i;
cin >> t;
// t = 1;
while (t)
{
solve();
t--;
}
}
/*
int l = ans.size();
while(l>=0&&ans[l]==0)
l--;
*/ | cpp |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include <bits/stdc++.h>
#define ll long long
#define fast ios::sync_with_stdio(NULL); cin.tie(0); cout.tie(0);
using namespace std;
vector<ll> v[200009];
ll mx,a,b,c,vis[200009],n,ans;
void dfs(ll i,ll p,ll d) {
if(d>mx){ mx=d; a=i; }
for(int x : v[i]) if(x!=p) dfs(x,i,d+1);
}
ll dfs1(ll i,ll p) {
if(i==b) return vis[i]=1;
for(int x : v[i]) if( x!=p && dfs1(x,i) ) return vis[i]=1;
return 0;
}
void dfs2(ll i,ll p,ll d) {
if(vis[i]) d=0;
if(d>mx){ mx=d; c=i; }
for(int x : v[i]) if(x!=p) dfs2(x,i,d+1);
}
int main() {
fast cin>>n;
for(int i=1;i<n;i++){ cin>>a>>b; v[a].push_back(b); v[b].push_back(a); }
dfs(1,0,0); b=a; mx=0;
dfs(b,0,0); ans+=mx; mx=0;
dfs1(a,0); dfs2(a,-1,0); ans+=mx;
if(mx==0) c=v[a].back();
cout<<ans<<endl<<a<<" "<<b<<" "<<c<<endl;
}
| 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 <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// #include <ext/rope>
#define int ll
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)a.size()
#define eq(a, b) (fabs(a - b) < EPS)
#define md(a, b) ((a) % b + b) % b
#define mod(a) md(a, MOD)
#define _max(a, b) ((a) > (b) ? (a) : (b))
#define srt(a) sort(all(a))
#define mem(a, h) memset(a, (h), sizeof(a))
#define f first
#define s second
#define forn(i, n) for(int i = 0; i < n; i++)
#define fore(i, b, e) for(int i = b; i < e; i++)
#define forg(i, b, e, m) for(int i = b; i < e; i+=m)
#define index int mid = (b + e) / 2, l = node * 2 + 1, r = l + 1;
#define DBG(x) cerr<<#x<<" = "<<(x)<<endl
#define RAYA cerr<<"=============================="<<endl
// int in(){int r=0,c;for(c=getchar();c<=32;c=getchar());if(c=='-') return -in();for(;c>32;r=(r<<1)+(r<<3)+c-'0',c=getchar());return r;}
using namespace std;
// using namespace __gnu_pbds;
// using namespace __gnu_cxx;
// #pragma GCC target ("avx2")
// #pragma GCC optimization ("O3")
// #pragma GCC optimization ("unroll-loops")
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> ii;
typedef pair<pair<int, int>, int> iii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<ll> vll;
// typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
// find_by_order kth largest order_of_key <
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// rng
const int tam = 1000010;
const int MOD = 1000000007;
const int MOD1 = 998244353;
const double DINF=1e100;
const double EPS = 1e-9;
const double PI = acos(-1);
int ar[tam], t[4 * tam], l[4 * tam];
void push(int b, int e, int node)
{
if(l[node])
{
t[node] += l[node];
if(b < e)
l[node * 2 + 1] += l[node], l[node * 2 + 2] += l[node];
l[node] = 0;
}
}
void init(int b, int e, int node)
{
if(b == e)
{
t[node] = ar[b];
return;
}
index;
init(b, mid, l);
init(mid + 1, e, r);
t[node] = max(t[l], t[r]);
}
int query(int b, int e, int node, int i, int j)
{
push(b, e, node);
if(b >= i && e <= j)
return t[node];
index;
if(mid >= j)
return query(b, mid, l, i, j);
if(mid < i)
return query(mid + 1, e, r, i, j);
return max(query(b, mid, l, i, j), query(mid + 1, e, r, i, j));
}
void update(int b, int e, int node, int i, int j, int val)
{
if(b > e) return;
push(b, e, node);
if(e < i || b > j)
return;
if(b >= i && e <= j)
{
l[node] += val;
push(b, e, node);
return;
}
index;
update(b, mid, l, i, j, val);
update(mid + 1, e, r, i, j, val);
t[node] = max(t[l], t[r]);
}
signed main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// freopen("asd.txt", "r", stdin);
// freopen("qwe.txt", "w", stdout);
fore(i, 0, tam) ar[i] = -1ll * MOD * MOD;
int n, m, p;
cin>>n>>m>>p;
vector<pair<ii, int>> sweep;
fore(i, 0, n)
{
int a, b;
cin>>a>>b;
sweep.pb({{a, -MOD}, b});
}
fore(i, 0, m)
{
int a, b;
cin>>a>>b;
ar[a] = max(ar[a], -b);
}
init(0, tam - 1, 0);
fore(i, 0, p)
{
int a, b, c;
cin>>a>>b>>c;
sweep.pb({{a, b}, c});
}
sort(all(sweep));
int res = -1ll * MOD * MOD;
// cout<<t[0]<<'\n';
// fore(i, 0, pos)
// cout<<query(0, pos - 1, 0, i, i)<<' ';
// cout<<'\n';
for(auto cat : sweep)
{
if(cat.f.s == -MOD)
{
res = max(res, t[0] - cat.s);
// cout<<"$$$ "<<t[0]<<' '<<cat.f.f<<' '<<cat.s<<'\n';
}
else
{
update(0, tam - 1, 0, cat.f.s + 1, tam - 1, cat.s);
// cout<<"%%%%%%\n";
// cout<<cat.f.f<<' '<<cat.f.s<<' '<<cat.s<<'\n';
// cout<<t[0]<<'\n';
// fore(i, 0, pos)
// cout<<ar[i]<<' '<<query(0, pos - 1, 0, i, i)<<'\n';
}
}
cout<<res<<'\n';
return 0;
}
// Se vuelve más fácil,
// cada día es un poco más fácil, pero tienes que hacerlo cada día,
// es la parte difícil, pero se vuelve más fácil.
// Crecer duele.
// La única manera de pasar esa barrera es pasandola.
// efe no más.
// Si no vá por todo, andá pa' allá bobo.
// No sirve de nada hacer sacrificios si no tienes disciplina.
// Cae 7 veces, levántate 8.
// Ale perdóname por favor :,v
| 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"
] | // Struggling
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5 + 10;
int arr[N], pf[N];
ll Mod = 1e9 + 7;
int is_prime[1000001];
void seive()
{
int Max = 1000000;
for (int i = 1; i <= Max; i++)
{
is_prime[i] = 1;
}
is_prime[0] = 0;
is_prime[1] = 0;
for (int i = 2; i * i <= Max; i++)
{
if (is_prime[i] == 1)
{
for (int j = i * i; j <= Max; j += i)
{
is_prime[j] = i;
}
}
}
}
long long binpow(long long a, long long b)
{
if (b == 0)
{
return 1ll;
}
long long res = binpow(a, b / 2ll);
if (b % 2 == 1)
{
return (((((a % Mod) * (res % Mod)) % Mod) % Mod) * (res % Mod)) % Mod;
}
else
return ((res % Mod) * (res % Mod)) % Mod;
}
int lenOfLongSubarr(int A[], int N, int K)
{
int i = 0, j = 0, sum = 0;
int maxLen = INT_MIN;
while (j < N)
{
sum += A[j];
if (sum < K)
{
j++;
}
else if (sum == K)
{
maxLen = max(maxLen, j - i + 1);
j++;
}
else if (sum > K)
{
while (sum > K)
{
sum -= A[i];
i++;
}
if (sum == K)
{
maxLen = max(maxLen, j - i + 1);
}
j++;
}
}
return maxLen;
}
bool isPalindrome(string chker)
{
int n = chker.size();
for (int i = 0; i <= (n - 1) / 2; i++)
{
if (chker[i] != chker[n - i - 1])
{
return false;
}
}
return true;
}
float checkpow(int a, int b)
{
return float(log2(a) / log2(b));
}
int lcsubstr(string str1, string str2)
{
int ans = 0;
for (int i = 0; i < str1.length(); i++)
{
for (int j = 0; j < str2.length(); j++)
{
int k = 0;
while ((i + k) < str1.length() && (j + k) < str2.length() && str1[i + k] == str2[j + k])
{
k = k + 1;
}
ans = max(ans, k);
}
}
return ans;
}
ll findClosestPerfectSquare(ll n)
{
ll left = 0, right = 2000000123;
while (left < right)
{
ll mid = (left + right) / 2;
if (mid * mid <= n)
{
left = mid + 1;
}
else
{
right = mid;
}
}
return left - 1;
}
int GetBit(int n, int i)
{
return ((n & (1 << i)) != 0);
}
int SetBit(int n, int i)
{
return (n | (1 << i));
}
int ClearBit(int n, int i)
{
return (n & (~(1 << i)));
}
int UpdateBit(int n, int i, int value)
{
int mask = ~(1 << i);
n = n & mask;
return (n | (value << i));
}
int LIS(vector<int> &v)
{
if (v.size() == 0)
{
return 0;
}
vector<int> tail(v.size(), 0);
int length = 1;
tail[0] = v[0];
for (int i = 1; i < v.size(); i++)
{
auto b = tail.begin(), e = tail.begin() + length;
auto it = lower_bound(b, e, v[i]);
if (it == tail.begin() + length)
{
tail[length++] = v[i];
}
else
{
*it = v[i];
}
}
return length;
}
void solve()
{
int n;
cin>>n;
string str;
cin>>str;
string temp=str;
int ans=0;
for(int i=0;i<n;i++)
{
string temp1=(str.substr(i+1,n-i-1));
string temp2=(str.substr(0,i+1));
if((n-i-1)&1)
reverse(temp2.begin(),temp2.end());
string s=temp1+temp2;
if(s<temp)
{
temp=s;
ans=i+2;
}
}
if(ans==0)
{
ans++;
}
cout<<temp<<'\n';
cout<<ans<<'\n';
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
ll t;
cin >> t;
// t = 1;
seive();
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>
#include <bitset>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
#define INF 0x3f3f3f3f
#define endl '\n'
#define IO ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
//#define LOCAL
int bit(int x) {
return x != 0;
}
int main(){
IO
clock_t ccc1 = clock();
#ifdef LOCAL
ifstream cin("1.in");
ofstream cout("1.out");
#endif
int n, q;
cin >> n >> q;
vector<int> a(n + 2, 0), b(n + 2, 0), c(n + 2, 0);
int x, y;
int s = 0;
while(q --) {
cin >> x >> y;
// x == 1
if(x == 1){
if(a[y]){
s -= (bit(b[y - 1]) + bit(b[y]) + bit(b[y + 1]));
// s -= (bit(b[y - 1]) + bit(b[y]) + bit(b[y + 1]));
}else {
s += (bit(b[y - 1]) + bit(b[y]) + bit(b[y + 1]));
// s += (bit(b[y - 1]) + bit(b[y]) + bit(b[y + 1]));
}
a[y] = !a[y];
}
else {
if(b[y]) {
s -= (bit(a[y - 1]) + bit(a[y]) + bit(a[y + 1]));
// s -= (bit(a[y - 1]) + bit(a[y]) + bit(a[y + 1]));
}
else {
s += (bit(a[y - 1]) + bit(a[y]) + bit(a[y + 1]));
// s += (bit(a[y - 1]) + bit(a[y]) + bit(a[y + 1]));
}
b[y] = !b[y];
}
cout << (s == 0 ? "Yes" : "No") << endl;
}
end:
cerr << "Time : " << clock() - ccc1 << "ms" << endl;
return 0;
} | cpp |
1301 | B | B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33. | [
"binary search",
"greedy",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define foru(i, l, r) for(int i = l; i <= r; i++)
#define ford(i, r, l) for(int i = r; i >= l; i--)
typedef pair<int, int> ii;
typedef pair<ii, int> iii;
typedef pair<ii, ii> iiii;
const int N = 1e6 + 5;
const int oo = 1e9 + 7, mod = 1e9 + 7;
int n, m, a[N];
vector<int> arr;
void read() {
}
void init() {
}
int ifX(int x) {
int ans=0;
foru(i,1,n-1) {
if (a[i]==-1 && a[i+1]!=-1) {
ans=max(ans, abs(x-a[i+1]));
}
if (a[i+1]==-1 && a[i]!=-1) {
ans=max(ans, abs(a[i]-x));
}
if (a[i]!=-1 && a[i+1] !=-1) {
ans=max(ans, abs(a[i+1]-a[i]));
}
ans=max(ans,0LL);
}
return ans;
}
ii ternary_search() {
double left=0.0, right=1e9+1;
int N_ITER=100;
foru(i,0,N_ITER) {
double x1=left+(right-left)/3.0;
double x2=right-(right-left)/3.0;
if ((ifX(x1) < ifX(x2))) right=x2;
else left=x1;
}
return {ifX(left), left};
}
void process() {
cin >> n;
foru(i,1,n) cin >> a[i];
ii ans=ternary_search();
cout << ans.first << ' ' << ans.second << '\n';
//foru(i,1,100) cout << ifX(i) << '\n';
}
signed main() {
cin.tie(0)->sync_with_stdio(false);
//freopen(".inp", "r", stdin);
//freopen(".out", "w", stdout);
read();
init();
int t;
cin >> t;
while (t--) process();
return 0;
}
| cpp |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t, n;
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> n;
int a[n], s = 0, k = 0;
for (int j = 0; j < n; j++)
{
cin >> a[j];
s += a[j];
}
for (int j = 0; j < n; j++)
{
if (a[j] == 0)
{
a[j] = 1;
k = k + 1;
}
}
if (k == 0 && s == 0)
k = 1;
if ((k + s) == 0)
k++;
cout << k << endl;
}
return 0;
}
| cpp |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | #include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const ll mod = 998244353;
const int mm = 2e5 + 10;
void solve(){
ll n,d;
cin>>n>>d;
ll x=max((ll)sqrt(d)-1,0ll);
if(d<=n)cout<<"YES\n";
else{
for(ll i=max(x-1000,0ll);i<=x+1000;i++){
if(i+(d+i)/(i+1)<=n){
cout<<"YES\n";
return;
}
}cout<<"NO\n";
}
}
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int t;
cin>>t;
while(t--){
solve();
}
}
| cpp |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
// #define int long long
string f(string &a,string &b)
{
int n = a.size();
string res = a;
int xorr = 'S'^'E'^'T';
for(int i=0;i<n;i++)
{
if(a[i]!=b[i])
res[i] = (char)(xorr^a[i]^b[i]);
}
return res;
}
void solve()
// int solve()
{
int n,k;
cin>>n>>k;
vector<string> v(n);
set<string> st;
for(string &s:v) cin>>s , st.insert(s);
int ans = 0;
for(int i=0;i<n;i++) for(int j=i+1;j<n;j++)
{
string res = f(v[i],v[j]);
if(st.find(res) != st.end()) ans++;
}
ans/=3;
cout<<ans<<endl;
}
main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin>>t;
while(t--)
{
solve();
// cout<<solve()<<endl;
}
return 0;
} | cpp |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | /*
(اللهم صلْ وسلم وزد وبارك على سيدنا محمد )
꧁IslaM_SobhY꧂
*/
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<pair<int,int>> vp;
#define all(v) v.begin(),v.end()
#define sz(x) x.size()
#define SUPERPOWER ios_base::sync_with_stdio(false); cout.tie(0);
#define cin(v) for(auto &i:v)cin>>i
#define cout(v) for(auto &i:v)cout<<i<< " "
#define ll long long
#define el "\12"
#define format(n) fixed<<setprecision(n)
#define YES cout << "YES" << el;
bool AdelCan(vi v,int n,ll Yasser)
{
int l = 0;
int r = 0;
ll sum = 0;
while(l < n)
{
while(r < n && sum < Yasser)
{
sum+=v[r];
r++;
}
if(sum >= Yasser && (r - l) < n)
{
return 1;
}
sum-=v[l];
l++;
}
if(sum >= Yasser && (r - l + 1) < n)
{
return 1;
}
return 0;
}
int main() {
// For getting input from input.txt file
//freopen("input.txt", "r", stdin);
// Printing the Output to output.txt file
//freopen("output.txt", "w", stdout);
SUPERPOWER;
int t = 1;cin >> t;
while(t--)
{
//write the code here
int n;cin >> n;
vi v(n);
ll Yasser = 0;
for(int i = 0; i <n; i++)
{
cin >> v[i];
Yasser+=v[i];
}
bool Adel = AdelCan(v,n,Yasser);
if(Adel)
{
cout << "NO" <<el;
}else
{
cout << "YES" <<el;
}
}
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>
using namespace std;
typedef long long ll;
void solve(){
ll n,x,y;
cin>>n>>x>>y;
cout<<max(1ll,min(x+y-n+1,n))<<' ';
cout<<min(x+y-1,n)<<' ';
cout<<'\n';
}
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
cin>>t;
for (int i=1;i<=t;i++){
solve();
}
return 0;
} | cpp |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
string s;
cin >> n >> s;
int l = -1, r = n;
map<pair<int, int>, int> vis;
pair<int, int> cur = {0, 0};
vis[cur] = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == 'L') --cur.first;
if (s[i] == 'R') ++cur.first;
if (s[i] == 'U') ++cur.second;
if (s[i] == 'D') --cur.second;
if (vis.count(cur)) {
if (i - vis[cur] + 1 < r - l + 1) {
l = vis[cur];
r = i;
}
}
vis[cur] = i + 1;
}
if (l == -1) {
cout << -1 << endl;
} else {
cout << l + 1 << " " << r + 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"
] | #pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
long long t, n, a[100001];
int main(){
cin >> t;
for(int i = 1; i <= t; i ++){
cin >> n;
int sum = 0;
while(n > 0){
long long j = 1e9;
while(n < j) j /= 10;
sum += j;
n -= j - j / 10;
}
cout << sum << '\n';
}
}
| cpp |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | #pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define ll long long
#define pb push_back
#define pob pop_back
#define ff first
#define ss second
#define mk make_pair
using namespace std;
vector<ll> a;
ll n, s, k;
void solve() {
for (ll i = 0; i <= k; i++) {
if(s - i >= 1 && find(a.begin(), a.end(), s - i) == a.end()){
cout << i << '\n';
return;
}
if(s + i <= n && find(a.begin(), a.end(), s + i) == a.end()){
cout << i << '\n';
return;
}
}
assert(false);
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
ll t;
cin >> t;
while(t--){
cin >> n >> s >> k;
a.clear();
a.resize(k);
for(auto &x: a) cin >> x;
solve();
}
}
| 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"
] | /*
*
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
#include <bits/stdc++.h>
#define bfsof main
using namespace std;
typedef long long ll;
typedef long double ld;
const ll Mod = 998244353;
const ll INF = 1e6+10;
//__builtin_popcount计算二进制中1的个数
void solve()
{
int n,m;
cin>>n>>m;
vector<ll> a(n);
map<int,bool> p;
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<m;i++)
{
int x;
cin>>x;
p[x]=true;
}
for(int i=0;i<n;i++)
{
for(int j=n-1;j>0;j--)
{
if(a[j]<a[j-1]&&p[j]==false)
{
cout<<"NO"<<endl;
return;
}
else
if(a[j]<a[j-1])
swap(a[j],a[j-1]);
}
}
cout<<"YES"<<endl;
}
int bfsof()
{
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(false);
int t;
cin >> t;
while(t --)
solve();
}
| cpp |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33 | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define inf INT_MAX
#define N 100010
ll q,n,m,k,ans=0,x,y,l,r,s,z;
ll lg[N],fa[N][21];
ll dep[N];
ll cnt=0,head[N];
bool flag;
struct edge{
ll x,y;
}e[2*N];
template<typename T>inline void read(T &n){
T w=1; n=0; char ch=getchar();
while (!isdigit(ch) && ch!=EOF){ if (ch=='-') w=-1; ch=getchar(); }
while (isdigit(ch) && ch!=EOF){ n=(n<<3)+(n<<1)+(ch&15); ch=getchar(); }
n*=w;
}
template<typename T>inline void write(T x){
if (x==0){ putchar('0'); return ; }
T tmp;
if (x>0) tmp=x;
else tmp=-x;
if (x<0) putchar('-');
char F[105];
long long cnt=0;
while (tmp){
F[++cnt]=tmp%10+48;
tmp/=10;
}
while (cnt) putchar(F[cnt--]);
}
void addedge(ll x,ll y){
cnt++;
e[cnt].x=head[x];
e[cnt].y=y;
head[x]=cnt;
return ;
}
void dfs(ll x,ll father){
fa[x][0]=father;
ll i; ll go;
for (i=head[x]; i; i=e[i].x){
go=e[i].y;
if (go==father) continue;
dep[go]=dep[x]+1;
dfs(go,x);
}
return ;
}
void init(){
ll i,j;
lg[1]=0;
for (i=2; i<=n; i++) lg[i]=lg[i>>1]+1;
for (i=1; (1<<i)<=n; i++)
for (j=1; j<=n; j++)
if (fa[j][i-1]>0 && fa[fa[j][i-1]][i-1]>0)
fa[j][i]=fa[fa[j][i-1]][i-1];
return ;
}
ll Lca(ll x,ll y){
ll i; ll k;
if (dep[x]<dep[y]) swap(x,y);
k=lg[dep[x]-dep[y]];
for (i=k; i>=0; i--)
if (dep[fa[x][i]]>=dep[y])
x=fa[x][i];
if (x==y) return x;
k=lg[dep[x]];
for (i=k; i>=0; i--)
if (fa[x][i]!=fa[y][i]){
x=fa[x][i];
y=fa[y][i];
}
return fa[x][0];
}
ll dist(ll x,ll y){
ll l=Lca(x,y);
return dep[x]+dep[y]-2*dep[l];
}
bool check(ll x,ll y){
if (x>y) return false;
if (x%2!=y%2) return false;
return true;
}
int main(){
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
ll i,j;
read(n);
for (i=2; i<=n; i++){
read(x); read(y);
addedge(x,y);
addedge(y,x);
}
dep[1]=1;
dfs(1,-1);
init();
read(q);
while (q--){
read(x); read(y); read(l); read(r); read(k);
flag=false;
flag |= check ( dist(l,r) , k );
flag |= check ( dist(l,x) + dist(r,y) + 1 , k );
flag |= check ( dist(l,y) + dist(r,x) + 1 , k );
if (flag) printf("YES\n");
else printf("NO\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;
namespace my_std
{
typedef long long ll;
const ll inf=0x3f3f3f3f;
#define fr(i,x,y) for(ll i=(x);i<=(y);++i)
#define pfr(i,x,y) for(ll i=(x);i>=(y);--i)
#define space putchar(' ')
#define enter putchar('\n')
inline ll read()
{
ll sum=0,f=1;char ch=0;
while(!isdigit(ch)){if(ch=='-'){f=-1;}ch=getchar();}
while(isdigit(ch)) sum=sum*10+(ch^48),ch=getchar();
return sum*f;
}
inline void write(ll x)
{
if(x<0) putchar('-'),x=-x;
if(x>9) write(x/10);
putchar(x%10+'0');
}
inline void writesp(ll x){write(x),space;}
inline void writeln(ll x){write(x),enter;}
}
using namespace my_std;
const ll N=1050;
ll n,m,k,tot,lcp[N][N],f[N][N],sum[N][N];char s[N];
struct sub{ll l,r,len;}a[N*N];
inline bool cmp(sub a,sub b)
{
ll len=lcp[a.l][b.l];
if(min(a.len,b.len)<=len) return a.len<b.len;
return s[a.l+len]<s[b.l+len];
}
inline ll solve(sub t)
{
f[n+1][0]=sum[n+1][0]=1;
pfr(i,n,1) sum[i][0]=1;
fr(j,1,m) pfr(i,n,1)
{
ll len=min(lcp[t.l][i],t.len),lim=i+len-1;
if(t.len<=len||s[lim+1]>s[t.l+len])
{
if(len<t.len) ++lim;
f[i][j]=sum[lim+1][j-1];
}
else f[i][j]=0;
sum[i][j]=min(k,sum[i+1][j]+f[i][j]);
}
return f[1][m];
}
int main(void)
{
n=read(),m=read(),k=read(),scanf("%s",s+1);
pfr(i,n,1) pfr(j,n,1) lcp[i][j]=(s[i]==s[j])?(lcp[i+1][j+1]+1):0;
fr(i,1,n) fr(j,i,n) a[++tot]=(sub){i,j,j-i+1};
sort(a+1,a+tot+1,cmp);ll l=1,r=tot,ans=0;
while(l<=r)
{
ll mid=(l+r)>>1;
if(solve(a[mid])>=k) ans=mid,l=mid+1;
else r=mid-1;
}
fr(i,a[ans].l,a[ans].r) putchar(s[i]);
return 0;
}////
| cpp |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | #include <iostream>
//#include <deque>
#include <vector>
using namespace std;
//vector <string> vec_s;
int main() {
int t; cin >> t;
// bool f = true;
for (int i = 1; i <= t; ++i) {
int n; cin >> n;
string s; cin >> s;
int p = 0, ans = 0;
for (int j = n - 1; j >= 0; --j) {
if (s[j] == 'P') p++;
else ans = max(ans, p), p = 0;
}
cout << ans << '\n';
}
return 0;
}
| cpp |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | #include <iostream>
#include <iomanip>
#include <cstdio>
#include <vector>
#include <math.h>
#include <algorithm>
#include <map>
using namespace std;
int main()
{
cout.tie(nullptr);
std::ios::sync_with_stdio(false);
int t; cin >> t;
while(t--){
int n,d;
cin >> n >> d;
if(n==d){
cout << "YES" << '\n';
continue;
}
int sqr=(int)sqrt(d);
int maxn = sqr;
bool f=0;
for(int i=0; i<maxn; i++) {
if(i+((d+i)/(i+1))<=n){
cout << "YES" << '\n';
f=1;
break;
}
}
if(f){
continue;
}
cout << "NO" << '\n';
}
return 0;
}
| cpp |
1310 | B | B. Double Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2n2n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 11 to 2n2n and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with 2n−12n−1 teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round 2k2k teams play a game with each other (teams are split into games by team numbers). 2k−12k−1 loosing teams are eliminated from the championship, 2k−12k−1 winning teams are playing 2k−12k−1 teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have 2k−12k−1 teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers a1,a2,...,aka1,a2,...,ak. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?InputFirst input line has two integers n,kn,k — 2n2n teams are competing in the championship. You are a fan of kk teams (2≤n≤17;0≤k≤2n2≤n≤17;0≤k≤2n).Second input line has kk distinct integers a1,…,aka1,…,ak — numbers of teams you're a fan of (1≤ai≤2n1≤ai≤2n).OutputOutput single integer — maximal possible number of championship games that include teams you're fan of.ExamplesInputCopy3 1
6
OutputCopy6
InputCopy3 3
1 7 8
OutputCopy11
InputCopy3 4
1 3 5 7
OutputCopy14
NoteOn the image; each game of the championship is denoted with an English letter (aa to nn). Winner of game ii is denoted as WiWi, loser is denoted as LiLi. Teams you're a fan of are highlighted with red background.In the first example, team 66 will play in 6 games if it looses the first upper bracket game (game cc) and wins all lower bracket games (games h,j,l,mh,j,l,m). In the second example, teams 77 and 88 have to play with each other in the first game of upper bracket (game dd). Team 88 can win all remaining games in upper bracket, when teams 11 and 77 will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship. | [
"dp",
"implementation"
] | #include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/hash_policy.hpp>
// #include <ext/pb_ds/priority_queue.hpp>
using namespace std;
// using namespace __gnu_pbds;
#define fi first
#define se second
#define fill0(a) memset(a, 0, sizeof(a))
#define fill1(a) memset(a, -1, sizeof(a))
#define fillbig(a) memset(a, 63, sizeof(a))
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define mt make_tuple
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
template <typename T1, typename T2> void chkmin(T1 &x, T2 y){
if (x > y) x = y;
}
template <typename T1, typename T2> void chkmax(T1 &x, T2 y){
if (x < y) x = y;
}
typedef pair<int, int> pii;
typedef long long ll;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef long double ld;
#ifdef FASTIO
namespace fastio {
#define FILE_SIZE 1 << 23
char rbuf[FILE_SIZE], *p1 = rbuf, *p2 = rbuf, wbuf[FILE_SIZE], *p3 = wbuf;
inline char getc() {
return p1 == p2 && (p2 = (p1 = rbuf) + fread(rbuf, 1, FILE_SIZE, stdin), p1 == p2) ? -1: *p1++;
}
inline void putc(char x) {(*p3++ = x);}
template <typename T> void read(T &x) {
x = 0; char c = getc(); T neg = 0;
while (!isdigit(c)) neg |= !(c ^ '-'), c = getc();
while (isdigit(c)) x = (x << 3) + (x << 1) + (c ^ 48), c = getc();
if (neg) x = (~x) + 1;
}
template <typename T> void recursive_print(T x) {
if (!x) return;
recursive_print (x / 10);
putc (x % 10 ^ 48);
}
template <typename T> void print(T x) {
if (!x) putc('0');
if (x < 0) putc('-'), x = -x;
recursive_print(x);
}
template <typename T> void print(T x,char c) {print(x); putc(c);}
void readstr(char *s) {
char c = getc();
while (c <= 32 || c >= 127) c = getc();
while (c > 32 && c < 127) s[0] = c, s++, c = getc();
(*s) = 0;
}
void printstr(string s) {
for (int i = 0; i < s.size(); i++) putc(s[i]);
}
void printstr(char *s) {
int len = strlen(s);
for (int i = 0; i < len; i++) putc(s[i]);
}
void print_final() {fwrite(wbuf, 1, p3 - wbuf, stdout);}
}
using namespace fastio;
#endif
const int LOG_N = 17;
const int MAXN = 131072;
int n, k, a[MAXN + 5], dp[LOG_N + 2][MAXN + 5][2][2];
int main() {
scanf("%d%d", &n, &k);
for (int i = 1, x; i <= k; i++) scanf("%d", &x), a[x - 1] = 1;
memset(dp, 0xcf, sizeof(dp));
for (int i = 0; i < (1 << n - 1); i++) {
dp[1][i][a[i << 1]][a[i << 1 | 1]] = a[i << 1] | a[i << 1 | 1];
dp[1][i][a[i << 1 | 1]][a[i << 1]] = a[i << 1] | a[i << 1 | 1];
}
for (int i = 2; i <= n; i++) for (int j = 0; j < (1 << n - i); j++)
for (int k1 = 0; k1 < 2; k1++) for (int k2 = 0; k2 < 2; k2++)
for (int k3 = 0; k3 < 2; k3++) for (int k4 = 0; k4 < 2; k4++) {
chkmax(dp[i][j][k1 | k3][k2 | k4], dp[i - 1][j << 1][k1][k2] + dp[i - 1][j << 1 | 1][k3][k4] + (k1 | k3) + (k2 | k4) * 2);
if (k1 | k3) chkmax(dp[i][j][k1 + k3 - 1][1], dp[i - 1][j << 1][k1][k2] + dp[i - 1][j << 1 | 1][k3][k4] + 2 + (k2 | k4));
}
int mx = 0;
for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++)
chkmax(mx, dp[n][0][i][j] + (i | j));
printf("%d\n", mx);
return 0;
} | cpp |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | #include <bits/stdc++.h>
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
using namespace std;
//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template<typename T> using oset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
//long long may cause TLE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#define int ll
const int MAXN = 5e3 + 2;
vector<int> g[MAXN];
int par[MAXN],d[MAXN];
int mp[MAXN][MAXN];
void dfs(int v, int pr)
{
par[v] = pr;
for (auto to : g[v]) {
if (to!=pr) {
d[to] = d[v] + 1;
dfs(to,v);
}
}
}
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<pair<int,int>> edges;
for (int i=1,a,b;i<n;i++) {
cin >> a >> b;
a--; b--;
g[a].push_back(b);
g[b].push_back(a);
edges.push_back({a,b});
}
dfs(0,0);
vector<tuple<int,int,int>> Q;
int TT;
cin >> TT;
while (TT--)
{
int a,b,c;
cin >> a >> b >> c;
a--; b--;
Q.push_back({a,b,c});
while (a!=b) {
if (d[a] > d[b]) mp[a][par[a]] = mp[par[a]][a] = max(mp[a][par[a]],c), a = par[a];
else mp[b][par[b]] = mp[par[b]][b] = max(mp[b][par[b]],c) , b = par[b];
}
}
for (auto &[a,b]:edges) {
if (mp[a][b] == 0) mp[a][b] = mp[b][a] = 1e6;
}
int ok = 1;
for (auto [a,b,c] : Q) {
int is = 0;
while (a!=b) {
if (d[a] > d[b]) {
if (mp[a][par[a]] < c) ok = 0;
if (mp[a][par[a]] == c) is = 1;
a = par[a];
}
else {
if (mp[b][par[b]] < c) ok = 0;
if (mp[b][par[b]] == c) is = 1;
b = par[b];
}
}
ok&=is;
}
if (!ok) {
cout << -1;
return 0;
}
for (auto [a,b]:edges) cout << mp[a][b] << " ";
}
| 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;
typedef long long LL;
void solve()
{
int n, m;
cin >> n >> m;
vector<int> a(n + 1), b(n + 1);
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= n; i++)
{
for(int j = n; j > i; j--)
{
if(a[i] > a[j])
{
b[i]++, b[j]--;
// cout << i << " " << j << endl;
break;
}
}
}
set<int> st;
for(int i = 0; i < m; i++)
{
int x;
cin >> x;
st.insert(x);
}
for(int i = 1; i <= n; i++) b[i] += b[i - 1];
for(int i = 1; i <= n; i++)
{
if(b[i])
{
if(!st.count(i))
{
cout << "NO\n";
return ;
}
}
}
cout << "YES\n";
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while(T--) solve();
return 0;
} | 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<iostream>
#include<iomanip>
#include<algorithm>
#include<cmath>
#include<string>
#include<vector>
#include<map>
#define _CRT_SECURE_NO_WARNINGS //scanf & printf
#define fast std::ios_base::sync_with_stdio(0);cin.tie(NULL);
#define Input freopen("filename", "r", stdin);
#define ll long long
#define endl "\n"
//cout << fixed << setprecision(9);
using namespace std;
void solve()
{
int t;
cin >> t;
int n;
int sum;
int odd;
int even;
for (int i = 0; i < t; i++) {
cin >> n;
sum = 0;
odd = 0;
even = 0;
int arr[20000];
for (int j = 0; j < n; j++) {
cin >> arr[j];
if (arr[j] % 2 != 0 || arr[j] == 1) {
odd++;
}
else {
even++;
}
sum += arr[j];
}
if (sum % 2 != 0 || sum == 1) {
cout << "YES" << endl;
}
else {
if (odd != 0 && even != 0) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
}
}
int main()
{
fast
solve();
return 0;
}
| cpp |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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 as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | #include <bits/stdc++.h>
#define tvoy ios::sync_with_stdio(false);
#define sex cin.tie(0); cout.tie(0)
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
using namespace std;
int main(){
tvoy sex;
int t;
cin>>t;
while(t--)
{
int a,b;
cin>>a>>b;
if (a%b==0) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
| cpp |
1286 | E | E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
OutputCopy1
2
4
5
7
9
12
InputCopy4
a 2
y 2
z 0
y 2
OutputCopy2
2
2
2
InputCopy5
a 7
u 5
t 3
s 10
s 11
OutputCopy7
9
11
12
13
NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313. | [
"data structures",
"strings"
] | // LUOGU_RID: 100924200
#include <bits/stdc++.h>
#define int long long
const int N = 1e6 + 10;
int n;
char s[N];
int w[N];
std::map<int, int> cnt;
int q[N], top;
int nxt[N], anc[N];
int ans1, ans2;
__int128_t ans;
int sum;
void write(__int128_t x) {
if (!x) return ;
write(x / 10);
putchar(x % 10 + '0');
}
signed main() {
scanf("%lld", &n);
nxt[1] = 0;
getchar();
s[1] = getchar();
scanf("%lld", &w[1]);
ans = w[1];
ans1 = w[1] % 26, ans2 = w[1];
q[top = 1] = 1;
if (ans == 0) {
puts("0");
}
else {
write(ans);
puts("");
}
for (int i = 2, j = 0; i <= n; ++i) {
getchar();
s[i] = getchar();
scanf("%lld", &w[i]);
s[i] = (s[i] - 'a' + ans1) % 26 + 'a';
w[i] ^= ans2;
while (j && s[j + 1] != s[i]) {
j = nxt[j];
}
if (s[j + 1] == s[i]) ++j;
nxt[i] = j;
if (s[nxt[i - 1] + 1] == s[i]) {
anc[i - 1] = anc[nxt[i - 1]];
}
else {
anc[i - 1] = nxt[i - 1];
}
for (int k = i - 1; k > 0;) {
if (s[k + 1] == s[i]) {
k = anc[k];
}
else {
int v = w[*std::lower_bound(q + 1, q + top + 1, i - k)];
--cnt[v];
sum -= v;
if (cnt[v] == 0) cnt.erase(v);
k = nxt[k];
}
}
if (s[1] == s[i]) {
++cnt[w[i]];
sum += w[i];
}
while (top && w[i] <= w[q[top]]) {
--top;
}
q[++top] = i;
int num = 0;
for (auto it = cnt.upper_bound(w[i]); it != cnt.end();) {
sum -= 1ll * (it->first) * (it->second);
num += it->second;
auto jt = std::next(it);
cnt.erase(it);
it = jt;
}
cnt[w[i]] += num;
sum += num * w[i];
int res = w[q[1]] + sum;
ans1 = (ans1 + res) % 26;
ans2 = (ans2 + res) & ((1ll << 30) - 1);
ans += res;
if (ans == 0) {
puts("0");
}
else {
write(ans);
puts("");
}
}
return 0;
} | cpp |
1284 | G | G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1). For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1) For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
O
OOO
NO
YES
OOOOO X
O O
X O O X
O
OOO X O
O O O
O OOOOO
YES
OOOOOOOOOOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
| [
"graphs"
] | #include <cstdio>
#include <vector>
#include <utility>
#define rep( i, a, b ) for( int i = (a) ; i <= (b) ; i ++ )
#define per( i, a, b ) for( int i = (a) ; i >= (b) ; i -- )
const int INF = 1e9;
const int MAXL = 25, MAXN = 3e3 + 5, MAXE = 1e6 + 5;
template<typename _T>
void read( _T &x ) {
x = 0; char s = getchar(); bool f = false;
while( ! ( '0' <= s && s <= '9' ) ) { f = s == '-', s = getchar(); }
while( '0' <= s && s <= '9' ) { x = ( x << 3 ) + ( x << 1 ) + ( s - '0' ), s = getchar(); }
if( f ) x = -x;
}
template<typename _T>
void write( _T x ) {
if( x < 0 ) putchar( '-' ), x = -x;
if( 9 < x ) write( x / 10 );
putchar( x % 10 + '0' );
}
struct MyGraph {
struct Edge {
int to, nxt, id;
} Graph[MAXE << 1];
int head[MAXN], cnt;
MyGraph(): head{}, cnt( 1 ) {}
inline Edge operator [] ( const int &idx ) const { return Graph[idx]; }
inline void AddE( const int &from, const int &to, const int &W = 0 ) {
AddEdge( from, to, W ), AddEdge( to, from, W );
}
inline void AddEdge( const int &from, const int &to, const int &W = 0 ) {
Graph[++ cnt].to = to, Graph[cnt].nxt = head[from];
Graph[cnt].id = W, head[from] = cnt;
}
inline void Clear( const int &n ) {
cnt = 1;
rep( i, 1, n ) head[i] = 0;
}
};
MyGraph bip, tre;
int dist[MAXN], q[MAXN], pre[MAXN], ntot;
std :: vector<int> asso[MAXN];
int upp[MAXN], deg[MAXN];
int col[MAXN], faE[MAXN], dep[MAXN], cTot;
int seq[MAXN], tot;
bool inde[MAXN];
int frB[MAXN], toB[MAXN], vertA[MAXN];
int fa[MAXN];
int rig[MAXL][MAXL], dow[MAXL][MAXL];
int idA[MAXL][MAXL], idB[MAXL][MAXL];
char grid[MAXL][MAXL], ans[MAXL << 1][MAXL << 1];
int N, M, vA, vB, E;
#define ID( x, y ) ( ( (x) - 1 ) * ( M - 1 ) + (y) )
inline void MakeSet( const int &n ) {
rep( i, 1, n ) fa[i] = i;
}
int FindSet( const int &u ) {
return fa[u] == u ? u : ( fa[u] = FindSet( fa[u] ) );
}
inline void UnionSet( const int &u, const int &v ) {
fa[FindSet( u )] = FindSet( v );
}
inline void Clear() {
vA = vB = E = 0;
MakeSet( N * M );
rep( i, 1, N * M ) col[i] = 0;
rep( i, 0, N ) rep( j, 0, M ) {
idA[i][j] = idB[i][j] = 0;
rig[i][j] = dow[i][j] = 0;
}
}
void DFS( const int &u, const int &fa, const int &c ) {
col[u] = c, dep[u] = dep[fa] + 1;
for( int i = tre.head[u], v ; i ; i = tre[i].nxt )
if( ( v = tre[i].to ) ^ fa )
faE[v] = i, DFS( v, u, c );
}
int main() {
int T; read( T );
while( T -- ) {
read( N ), read( M ), Clear();
rep( i, 1, N ) scanf( "%s", grid[i] + 1 );
rep( i, 1, N ) rep( j, 1, M )
if( grid[i][j] == 'O' && ( i + j ) % 2 == 0 && ( i != 1 || j != 1 ) )
idA[i][j] = ++ vA;
rep( i, 1, vA ) upp[i] = 0, asso[i].clear();
const int &bound = ( N - 1 ) * ( M - 1 ) + 1;
rep( i, 1, N ) rep( j, 1, M - 1 )
if( ! ( grid[i][j] == 'O' && grid[i][j + 1] == 'O' ) ) {
int u = i == N ? bound : ID( i, j ),
v = i == 1 ? bound : ID( i - 1, j );
UnionSet( u, v );
}
rep( i, 1, N - 1 ) rep( j, 1, M )
if( ! ( grid[i][j] == 'O' && grid[i + 1][j] == 'O' ) ) {
int u = j == M ? bound : ID( i, j ),
v = j == 1 ? bound : ID( i, j - 1 );
UnionSet( u, v );
}
rep( i, 1, bound ) {
if( ! col[FindSet( i )] )
col[FindSet( i )] = ++ vB;
col[i] = col[FindSet( i )];
}
rep( i, 1, N - 1 ) rep( j, 1, M - 1 )
idB[i][j] = col[ID( i, j )];
rep( i, 0, N ) idB[i][0] = idB[i][M] = col[bound];
rep( j, 0, M ) idB[0][j] = idB[N][j] = col[bound];
rep( i, 1, N ) rep( j, 1, M - 1 )
if( grid[i][j] == 'O' && grid[i][j + 1] == 'O' ) {
inde[rig[i][j] = ++ E] = false;
frB[E] = idB[i - 1][j], toB[E] = idB[i][j];
vertA[E] = idA[i][j] ? idA[i][j] : idA[i][j + 1];
upp[vertA[E]] ++, asso[vertA[E]].push_back( E );
}
rep( i, 1, N - 1 ) rep( j, 1, M ) {
if( grid[i][j] == 'O' && grid[i + 1][j] == 'O' ) {
inde[dow[i][j] = ++ E] = false;
frB[E] = idB[i][j - 1], toB[E] = idB[i][j];
vertA[E] = idA[i][j] ? idA[i][j] : idA[i + 1][j];
upp[vertA[E]] ++, asso[vertA[E]].push_back( E );
}
}
bool isMatroid = true;
rep( i, 1, vA )
if( upp[i] < 2 ) {
isMatroid = false;
break;
}
if( ! isMatroid ) {
puts( "NO" );
continue;
}
while( true ) {
ntot = E;
const int src = ++ ntot, snk = ++ ntot;
tot = cTot = 0;
rep( i, 1, ntot ) dist[i] = INF, pre[i] = 0;
MakeSet( vB );
tre.Clear( vB );
bip.Clear( ntot );
rep( i, 1, vA ) deg[i] = 0;
rep( i, 1, vB ) col[i] = 0;
rep( i, 1, E )
if( inde[i] ) {
tre.AddE( frB[i], toB[i], i );
deg[vertA[i]] ++, seq[++ tot] = i;
}
rep( i, 1, vB ) if( ! col[i] )
DFS( i, 0, ++ cTot );
rep( i, 1, E ) if( ! inde[i] ) {
if( col[frB[i]] ^ col[toB[i]] ) {
bip.AddEdge( src, i );
rep( j, 1, tot )
bip.AddEdge( seq[j], i );
} else {
int u = frB[i], v = toB[i];
while( u ^ v ) {
if( dep[u] < dep[v] )
std :: swap( u, v );
bip.AddEdge( tre[faE[u]].id, i );
u = tre[faE[u] ^ 1].to;
}
}
if( ! vertA[i] || deg[vertA[i]] + 1 <= upp[vertA[i]] - 2 ) {
bip.AddEdge( i, snk );
rep( j, 1, tot )
bip.AddEdge( i, seq[j] );
} else {
for( const int &w : asso[vertA[i]] )
if( inde[w] ) bip.AddEdge( i, w );
}
}
int h = 1, t = 0;
dist[q[++ t] = src] = 1;
while( h <= t ) {
int u = q[h ++];
for( int i = bip.head[u], v ; i ; i = bip[i].nxt )
if( dist[v = bip[i].to] > dist[u] + 1 )
dist[q[++ t] = v] = dist[u] + 1, pre[v] = u;
}
if( dist[snk] == INF ) break;
for( int u = pre[snk] ; 1 <= u && u <= E ; u = pre[u] )
inde[u] ^= 1;
}
int siz = 0;
rep( i, 1, E ) siz += inde[i];
if( siz != vB - 1 ) {
puts( "NO" );
continue;
}
puts( "YES" );
rep( i, 1, 2 * N - 1 )
rep( j, 1, 2 * M - 1 )
ans[i][j] = ' ';
rep( i, 1, N ) rep( j, 1, M )
ans[i * 2 - 1][j * 2 - 1] = grid[i][j];
rep( i, 1, N ) rep( j, 1, M - 1 )
if( rig[i][j] && ! inde[rig[i][j]] )
ans[2 * i - 1][2 * j] = '-';
rep( i, 1, N - 1 ) rep( j, 1, M )
if( dow[i][j] && ! inde[dow[i][j]] )
ans[2 * i][2 * j - 1] = '|';
rep( i, 1, 2 * N - 1 ) {
rep( j, 1, 2 * M - 1 )
putchar( ans[i][j] );
puts( "" );
}
}
return 0;
} | 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 fi first
#define se second
#define ll long long
#define de double
#define o 150005
#define oo 1000000007
using namespace std;
typedef pair<ll,ll> II;
struct node
{
II line;
ll l,r;
int left,right;
node(II _line= {0,-1e18},ll _l=0,ll _r=1e18)
: line(_line), l(_l),r(_r)
{
left=right=-1;
}
};
vector<node> lichao;
void inbit()
{
node nw=node({0,-1e18},0,1e18);
lichao.clear();
lichao.push_back(nw);
}
ll f(II p,ll x)
{
return p.first*x+p.second;
}
void upd(int v,II p)
{
ll l=lichao[v].l,r=lichao[v].r;
if(f(p,l)<=f(lichao[v].line,l)&&f(p,r-1)<=f(lichao[v].line,r-1))
return;
if(f(p,l)>=f(lichao[v].line,l)&&f(p,r-1)>=f(lichao[v].line,r-1))
{
lichao[v].line=p;
return;
}
ll m=(l+r)/2;
bool lef=f(p,l)>f(lichao[v].line,l);
bool mid=f(p,m)>f(lichao[v].line,m);
if(mid)
swap(lichao[v].line,p);
if(r-l==1)
return;
if(lef!=mid)
{
if(lichao[v].left!=-1)
upd(lichao[v].left,p);
else
{
node cc=node(p,l,m);
lichao.push_back(cc);
lichao[v].left=lichao.size()-1;
}
}
else
{
if(lichao[v].right!=-1)
upd(lichao[v].right,p);
else
{
node cc=node(p,m,r);
lichao.push_back(cc);
lichao[v].right=lichao.size()-1;
}
}
}
ll get(int v,ll x)
{
ll l=lichao[v].l,r=lichao[v].r;
ll m=(l+r)/2;
ll fval=f(lichao[v].line,x);
if(r-l==1)
return fval;
if(x<m)
{
if(lichao[v].left==-1)
return fval;
return max(fval,get(lichao[v].left,x));
}
else
{
if(lichao[v].right==-1)
return fval;
return max(fval,get(lichao[v].right,x));
}
}
int n;
vector<int>g[o];
int a[o];
void inp()
{
cin>>n;
for(int i=1; i<n; i++)
{
int u,v;
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
for(int i=1; i<=n; i++)
cin>>a[i];
}
ll ans=0;
int dep[o];
ll d1[o],d2[o];//d1 :cap so cong tinh ca node d2: cap so cong ko tinh node
ll sum[o]; //tong tren dd
vector<int>tv;
int s[o],parent[o],siz;
void dfs_size(int u,int dad)
{
siz++;
s[u]=1;
for(auto&v:g[u])
if(v!=dad&&!parent[v])
{
dfs_size(v,u);
s[u]+=s[v];
}
}
int check_centroid(int u,int dad)
{
for(auto&v:g[u])
if(v!=dad&&!parent[v])
if(s[v]>siz/2)return check_centroid(v,u);
return u;
}
void dfs(int u,int dad)
{
tv.push_back(u);
dep[u]=dep[dad]+1;
sum[u]=sum[dad]+a[u];
d1[u]=d1[dad]+1ll*dep[u]*a[u];
d2[u]=d2[dad]+sum[u];
ans=max(ans,d1[u]);
for(auto&v:g[u])
if(v!=dad&&!parent[v])
dfs(v,u);
}
const int N=150000;
void calc(int r)
{
inbit();
upd(0,{a[r],d1[r]});
for(auto&v:g[r])
if(!parent[v])
{
tv.clear();
dfs(v,r);
for(auto&x:tv)
ans=max(ans,get(0,dep[x]-1)+d2[x]);
for(auto&x:tv)
{
upd(0,{sum[x]+a[r],d1[x]});
}
}
}
void build_centroid(int u,int dad)
{
siz=0;
dfs_size(u,dad);
int node=check_centroid(u,dad);
dep[node]=1;
d1[node]=a[node];
d2[node]=0;
sum[node]=0;
calc(node);
reverse(g[node].begin(),g[node].end());
calc(node);
if(dad==0)parent[node]=node;
else parent[node]=dad;
for(auto&v:g[node])
if(!parent[v])
build_centroid(v,node);
}
void oup()
{
build_centroid(1,0);
cout<<ans;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
inp();
oup();
}
| cpp |
1292 | C | C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10. | [
"combinatorics",
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=3009;
ll dp[N][N];
int par[N][N],chil[N][N];
int n;
vector<int>a[N];
ll res=0;
void dfs1(int u,int pa,int g){
chil[g][u]=1;
for(int v:a[u]){
if(v!=pa){
par[g][v]=u;
dfs1(v,u,g);
chil[g][u]+=chil[g][v];
}
}
}
ll bt(int u,int v){
if(dp[u][v]!=0||u==v)return dp[u][v];
dp[u][v]=1LL*chil[u][v]*chil[v][u]+max(bt(u,par[u][v]),bt(v,par[v][u]));
return dp[u][v];
}
void giai(){
cin>>n;
for(int i=1;i<n;i++){
int x,y;
cin>>x>>y;
a[x].push_back(y);
a[y].push_back(x);
}
for(int i=1;i<=n;i++)dfs1(i,i,i);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)res=max(res,bt(i,j));
}
//for(int i=1;i<=n;i++)dfs2(i,i,i);
// for(int i=1;i<=n;i++){
// for(int j=1;j<=n;j++)cout<<i<<" "<<j<<" "<<chil[i][j]<<'\n';
// }
// cout<<'\n';
cout<<res;
}
int main(){
if(fopen("solve.inp","r")){
freopen("solve.inp","r",stdin);
freopen("solve.out","w",stdout);
}
ios_base::sync_with_stdio(false);
cin.tie(NULL);
giai();
} | cpp |
1313 | E | E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5]; | [
"data structures",
"hashing",
"strings",
"two pointers"
] | #include <bits/stdc++.h>
using namespace std;
/*
Given L, r, l, R, m
find number of ordered pair (i, j) such that
L <= i <= r
l <= j <= R
i >= j
(i - L + 1) + (R - j + 1) = m
Since: i - L + 1 + R - j + 1 = m <=> i = (m - 2 + L - R) + j
It follows: L <= (i = X + j) <= r
l + X <= (i = X + j) <= R + X
(where X = m-2+L-R )
So the number of pairs would be the number of i sastifying:
max(L, l+X) <= i <= min(r, R+X)
But because i >= j
X must be non-negative
m-2+L-R >= 0 or L + m - 2 >= R
Therefore, naive algorithm could be:
long long ans = 0;
for (int L = 0; L < n; L++) {
for (int R = L; R <= min(n - 1, L + m - 2); R++) {
int r = L + pre[L] - 1;
int l = R - suf[R] + 1;
int X = m - 2 + L - R;
ans += max(0, min(r, R + X) - max(L, l + X) + 1);
}
}
HmmmmmmmMMMmmMmmMmmMm
for each L, we need to find F(L)
where F(L) := Σmax(0, min(r, m - 2 + L) - max(L, L + m - 2 + l - R) + 1) for R = [L, min(n - 1, L + m - 2)]
since suf[R] = R - l + 1, so we can have l - r as 1 - suf[R]
F(L) := Σmax(0, min(r, m - 2 + L) - max(L, L + m - 1 - suf[R]) + 1)
F(L) := Σmax(0, min(r, m - 2 + L) - (max(L - L - m + 1, -suf[R]) + L + m - 1) + 1)
F(L) := Σmax(0, min(r, m - 2 + L) - max(1 - m, -suf[R]) - L - m + 2)
F(L) := Σmax(0, min(r, m - 2 + L) + min(m - 1, suf[R]) - L - m + 2)
let C = min(r, m - 2 + L) - L - m + 2
F(L) := Σmax(0, C + min(m - 1, suf[R]))
from here on, only consider R in range [L, min(n - 1, L + m - 2)]
for those suf[R] > m - 1, then it'd be max(0, C + m - 1)
then contribution be: cnt(m, INF).max(0, C + m - 1)
for those suf[R] <= m - 1, then it'd be max(0, C + suf[R])
only when C + suf[R] >= 0 or suf[R] >= -C
that means those suf[R] in range [-C, m - 1]
then contribution be: cnt(-C, m - 1).C + sum(-C, m - 1)
*/
struct Fenwick {
int n;
vector<long long> bit;
Fenwick(int n) : n(n), bit(n + 1, 0) {}
void add(int i, long long delta) {
for (i++; i <= n; i += i & -i) {
bit[i] += delta;
}
}
long long sum(int i) {
long long res = 0;
for (i++; i > 0; i -= i & -i) {
res += bit[i];
}
return res;
}
long long sum(int l, int r) {
l = max(0, l);
return sum(r) - sum(l - 1);
}
};
vector<int> calcBasedZ(string base, string text) {
string s = base + '#' + text;
int n = s.length();
vector<int> z(n, 0);
for (int i = 1, l = 0, r = 0; i < n; i++) {
if (i <= r) z[i] = min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++;
if (r < i + z[i] - 1) r = i + z[i] - 1, l = i;
}
vector<int> res((int)text.size());
for (int i = (int)base.size() + 1; i < n; i++) {
res[i - (int)base.size() - 1] = z[i];
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
string a, b, s;
cin >> a >> b >> s;
vector<int> pre = calcBasedZ(s, a);
string rs = s, rb = b;
reverse(rs.begin(), rs.end());
reverse(rb.begin(), rb.end());
vector<int> suf = calcBasedZ(rs, rb);
reverse(suf.begin(), suf.end());
long long ans = 0;
int toAdd = 0, toDel = 0;
Fenwick cnt(m + 1), sum(m + 1);
for (int L = 0; L < n; L++) {
while (toAdd <= min(n - 1, L + m - 2)) {
cnt.add(suf[toAdd], 1);
sum.add(suf[toAdd], suf[toAdd]);
toAdd++;
}
while (toDel < L) {
cnt.add(suf[toDel], -1);
sum.add(suf[toDel], -suf[toDel]);
toDel++;
}
int r = L + pre[L] - 1;
int C = min(r, m - 2 + L) - L - m + 2;
ans += cnt.sum(-C, m - 1) * C + sum.sum(-C, m - 1);
ans += cnt.sum(m, m) * max(0, C + m - 1);
}
cout << ans << "\n";
}
| cpp |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | #include<iostream>
using namespace std;
int main(){
int t;
cin >> t;
for (int i=0;i<t;i++){
int count=0;
int arr[3];
for(int j=0;j<3;j++){
cin >> arr[j];
}
int max;
int min;
int mid;
max=arr[0];
min=arr[0];
for(int p=0;p<3;p++){
for(int k=0;k<2-p;k++){
if (arr[k+1]<arr[k]){
int t =arr[k+1];
arr[k+1]=arr[k];
arr[k]=t;
}
}}
min =arr[0];
mid=arr[1];
max=arr[2];
if (min>0){
count+=3;
min=min-1;
mid=mid-1;
max=max-1;
if (min>1){
min=min-2;
max=max-2;
mid=mid-2;
count+=3;
if (min>0){
count=count+1;
}}
else if (min==1){
if (max!=min){
max=max-2;
min=min-1;
mid=mid-1;
count=count+2;
}
else {
count=count+1;
}
}
else if (min==0){
if (mid>0){
count=count+1;
}
}
}
else if (mid>0){
count+=2;
max=max-1;
mid=mid-1;
if (mid>0){
count=count+1;
}
}
else if(max>0){
count=count+1;
max=max-1;
}
cout<<count<<endl;
}
return 0;
} | cpp |
1292 | F | F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0. After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible: b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8]) b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible: b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4]) b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9]) b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12]) b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty. | [
"bitmasks",
"combinatorics",
"dp"
] | #include<bits/stdc++.h>
#define mset(a,b) memset((a),(b),sizeof((a)))
#define rep(i,l,r) for(int i=(l);i<=(r);i++)
#define dec(i,l,r) for(int i=(r);i>=(l);i--)
#define cmax(a,b) (((a)<(b))?(a=b):(a))
#define cmin(a,b) (((a)>(b))?(a=b):(a))
#define Next(k) for(int x=head[k];x;x=li[x].next)
#define vc vector
#define ar array
#define pi pair
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define N 63
#define M 200010
using namespace std;
typedef double dd;
typedef long double ld;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
#define int long long
typedef pair<int,int> P;
typedef vector<int> vi;
const int INF=0x3f3f3f3f;
const dd eps=1e-9;
const int mod=1e9+7;
template<typename T> inline void read(T &x) {
x=0; int f=1;
char c=getchar();
for(;!isdigit(c);c=getchar()) if(c == '-') f=-f;
for(;isdigit(c);c=getchar()) x=x*10+c-'0';
x*=f;
}
int n,a[N],id[N],rd[N],ans,jie[N],invjie[N];
vi e[N],v,S,T;
int ts[N],cnt[M],f[M][N],sum;
bool vis[N];
inline int ksm(int a,int b,int mod){
int res=1;while(b){if(b&1)res=1ll*res*a%mod;a=1ll*a*a%mod;b>>=1;}return res;
}
inline int inv(int a){return ksm(a,mod-2,mod);}
inline void dfs(int k){
vis[k]=1;v.pb(k);
for(int to:e[k])if(!vis[to]){
// printf("k=%d to=%d\n",k,to);
dfs(to);
}
}
inline int DP(){
for(int x:v){
// printf("x=%d ",x);
if(!id[x]) S.pb(a[x]);else T.pb(a[x]);
}
// puts("");
if(T.empty()){
S.clear();return -1;
}
rep(i,0,(int)T.size()-1){
int nows=0;
rep(j,0,(int)S.size()-1){
// printf("T[%d]=%d S[%d]=%d\n",i,T[i],j,S[j]);
if(T[i]%S[j]==0) nows|=(1<<j);
}
cnt[nows]++;ts[i]=nows;
// printf("ts[%d]=%d\n",i,nows);
}
rep(i,0,(int)S.size()-1){
rep(j,0,(1<<((int)S.size()))-1){
if((j>>i)&1) cnt[j]+=cnt[j^(1<<i)];
}
}
// printf("cnt[1]=%d\n",cnt[1]);
rep(i,0,(int)T.size()-1){
f[ts[i]][1]++;
}
rep(i,1,(int)T.size()-1)rep(j,0,(1<<((int)S.size()))-1)if(f[j][i]){
bool op=0;
rep(k,0,(int)T.size()-1){
if((ts[k]&j)==0) continue;
if((ts[k]&j)==ts[k]){
if(op) continue;
else{
// puts("");
f[j][i+1]=(f[j][i+1]+f[j][i]*(cnt[j]-i)%mod)%mod;op=1;
}
}
else f[j|ts[k]][i+1]=(f[j|ts[k]][i+1]+f[j][i])%mod;
}
}
int ans=f[(1<<((int)S.size()))-1][T.size()];
rep(i,0,(1<<((int)S.size()))-1)rep(j,1,T.size()) f[i][j]=0,cnt[i]=0,ts[j-1]=0;
sum+=T.size()-1;ans=ans*invjie[T.size()-1]%mod;
S.clear();T.clear();
return ans;
}
signed main(){
// freopen("my.in","r",stdin);
// freopen("my.out","w",stdout);
read(n);rep(i,1,n) read(a[i]);
jie[0]=1;rep(i,1,n) jie[i]=1ll*jie[i-1]*i%mod;
invjie[n]=inv(jie[n]);dec(i,0,n-1) invjie[i]=invjie[i+1]*(i+1)%mod;
rep(i,1,n)rep(j,1,n){
if(i==j) continue;
if(a[j]%a[i]==0){
// printf("%d %d\n",i,j);
e[i].pb(j);id[j]++;rd[i]++;e[j].pb(i);
}
}
ans=1;sum=0;
// printf("ans=%d\n",ans);
rep(i,1,n)if(!vis[i]){
v.clear();dfs(i);
int nowans=DP();
if(nowans==-1) continue;
ans=ans*nowans%mod;
// printf("nowans=%d\n",nowans);
}
ans=ans*jie[sum]%mod;
printf("%d\n",ans);
return 0;
} | cpp |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS. | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] | #include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int T,n,p[200005];
char s[200005];
int main(){
scanf("%d",&T);
while(T--){
scanf("%d%s",&n,s+1);
for(int i=1;i<=n;i++)p[i]=n-i+1;
for(int i=1,j=1;i<n;j=i=j+1){
while(s[j]=='<')j++;
reverse(p+i,p+j+1);
}
for(int i=1;i<=n;i++)printf("%d ",p[i]);
puts("");
for(int i=1;i<=n;i++)p[i]=i;
for(int i=1,j=1;i<n;j=i=j+1){
while(s[j]=='>')j++;
reverse(p+i,p+j+1);
}
for(int i=1;i<=n;i++)printf("%d ",p[i]);
puts("");
}
return 0;
} | cpp |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44. | [
"brute force",
"data structures",
"implementation"
] | // #Ashutosh Gautam </> Codes :)
#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;
// Debugging purpose :))
#ifdef AshutoshGautam
#include "AshutoshDebugger.hpp"
// #define cerr cout
#else
#define deb(...)
#endif
template <class T> void debug(vector<T>adj[], int n);
typedef long long int ll;
#define int long long int
#define double long double
#define FastandFurious ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define inf (int)1e18+2
#define all(x) (x).begin(),(x).end()
#define gcd __gcd
template<class T> using ordered_set = tree<T, null_type,less_equal<T>,rb_tree_tag,tree_order_statistics_node_update>;
// s.find_by_order(k) returns iterator to kth element starting from 0;
// s.order_of_key(k) returns count of elements strictly smaller than k;
const int N = 2e5+10;
const int mod = 1e9+7;
// For laziness ;)
vector<int>g[N],level(N),lo_prime(N,0),hi_prime(N,0);
vector<bool> isPrime(N+1, true),vis(N,false);
bool powerof2(int x){return x&& (!(x&(x-1)));}
int totalDigits(int n){if(n == 0) return 1;return floor(log10(n))+1;}
long long power(long long a, long long b);
long long powerM(long long a, long long b);
int inv(int n, int p = mod){return powerM(n, p-2);}
void primeseive();
void PrimeFactors(ll n, vector<pair<ll, ll>> &v);
void dfs(int vertex);
void bfs(int source);
/*-----------------------------#Maincode Starts! FrontEnd :) -----------------------------------*/
/*
dp[i][j][k] -> maximum value you can get from (arr[i]....to....arr[j])
if you can manipulate k people
means if chosen elememts are <= k you can manipulate them
means you can keep count of people you have chosen so far.
so your dp state will be reduced to
dp[i][j][chosen]
but wait if you know total number of chosen people & one pointer let say i
then you can calculate j in O(1) because i + (n-1-j) == chosen
so your dp state will be reduced to dp[i][j] and if chosen <= k you will minimise the
current value otherwise you will maximise
*/
vector<vector<int>>dp;
int func(int i, int j, int n, int m, int k, vector<int>&v)
{
int chosen = i + (n-1-j);
if(chosen >= m-1) return max(v[i],v[j]);
if(dp[i][j] != -1) return dp[i][j];
int ans = 0;
if(chosen < k)
ans = max(func(i+1,j,n,m,k,v),func(i,j-1,n,m,k,v));
else
ans = min(func(i+1,j,n,m,k,v),func(i,j-1,n,m,k,v));
return dp[i][j] = ans;
}
void MainCode()
{
int n, m, k; cin >> n >> m >> k;
vector<int>v(n); for(int &x : v) cin >> x;
dp.clear();
dp.resize(n,vector<int>(n+1,-1));
cout << func(0,n-1,n,m,k,v) << "\n";
}
/*-----------------------------#Maincode Ends! BackEnd :)) -------------------------------------*/
signed main()
{
FastandFurious
int TestCaseS = 1;
cin >> TestCaseS;
// primeseive();
for(int TestCase = 1; TestCase <= TestCaseS ; TestCase++)
{
// cout << "Case #" << TestCase << ": "; // Google!
MainCode();
}
return 0;
}
template <class T> void debug(vector<T>adj[], int n)
{for(int i = 0; i < n; i++){cout<<"adj["<<i<<"]=";show_me(adj[i]);cout << endl;}}
long long power(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
long long powerM(long long a, long long b) {
a %= mod;
long long res = 1;
while (b > 0) {
if (b & 1)
res = (res%mod * a%mod)%mod;
a = (a%mod * a%mod)%mod;
b >>= 1;
}
return res;
}
void primeseive()
{
isPrime[0] = isPrime[1] = false;
for (int i = 2; i < N; i++)
{
if (isPrime[i])
{
lo_prime[i] = hi_prime[i] = i; // For prime numbers
for (int j = 2 * i; j < N; j += i)
{
isPrime[j] = false;
hi_prime[j] = i; // For calculating Prime factorization in O(LogN)
if(lo_prime[j] == 0) lo_prime[j] = i;
// https://github.com/ashuthe1/myTemplates/blob/main/primeInLogN.cpp
}
}
}
}
void PrimeFactors(ll n, vector<pair<ll, ll>> &v)
{
for (int i = 2; (i * i) <= n; i++)
{
if (n % i != 0)
continue;
ll cnt = 0;
while (n % i == 0)
{
n /= i;
++cnt;
}
v.push_back({i, cnt});
}
if (n != 1)
v.push_back({n, 1});
sort(v.begin(), v.end());
}
void dfs(int vertex)
{
/* Take action on vertex after
entering the vertex
*/
vis[vertex] = true;
for(int child : g[vertex])
{
/* Take action on child before
entering the child node */
if(vis[child]) continue;
dfs(child);
/* Take action on child after
exiting the child node */
}
/* Take action on vertex
before exiting the vertex */
}
void bfs(int source)
{
queue < int > q;
q.push(source);
vis[source] = 1;
while (!q.empty())
{
int curr_v = q.front();
q.pop();
for(int child : g[curr_v]){
if(!vis[child]){
q.push(child);
vis[child] = 1;
level[child] = level[curr_v]+1;
}
}
}
} | cpp |
1313 | D | D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third. | [
"bitmasks",
"dp",
"implementation"
] | // LUOGU_RID: 97860564
#include<bits/stdc++.h>
#define ll long long
#define ff(i,s,e) for(int i=(s);i<=(e);++i)
using namespace std;
inline int read(){
int x=0,f=1;
char ch=getchar();
while(ch>'9'||ch<'0'){if(ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
return x*f;
}
const int N=1e5+5,M=(1<<8)+5;
int n,m,k;
int f[M],tong[M],cnt[M];
struct qwq{
int pos,op,id;
bool operator < (const qwq &a) const{
if(pos!=a.pos) return pos<a.pos;
return op<a.op;
}
};
vector<qwq> g;
inline void init(){
ff(i,1,(1<<k)-1){
int num=0;
ff(j,0,k-1) if(i&(1<<j)) ++num;
cnt[i]=num&1;
}
}
signed main(){
n=read(),m=read(),k=read();
init();
ff(i,1,n){
int l=read(),r=read();
g.push_back({l,1,i}),g.push_back({r+1,-1,i});
}
sort(g.begin(),g.end());
memset(f,-0x3f3f3f3f,sizeof(f));
f[0]=0;
for(int i=0;i<g.size();++i){
qwq tmp=g[i];
int pos=tmp.pos,op=tmp.op,id=tmp.id,val=0,now;
if(i!=g.size()-1) val=g[i+1].pos-pos;
if(op==1){
ff(i,1,k) if(!tong[i]){tong[i]=id,now=i;break;}
for(int s=(1<<k)-1;s>=0;--s){
if(s&(1<<now-1)) f[s]=f[s^(1<<now-1)]+val*cnt[s];
else f[s]+=val*cnt[s];
}
}
else{
ff(i,1,k) if(tong[i]==id){tong[i]=0,now=i;break;}
ff(s,0,(1<<k)-1){
if(!(s&(1<<now-1))) f[s]=max(f[s],f[s^(1<<now-1)])+val*cnt[s];
else f[s]=-0x3f3f3f3f;
}
}
}
printf("%d\n",f[0]);
return 0;
} | cpp |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
long long x0, y0, ax, ay, bx, by, xs, ys, t;
void Input() {
cin >> x0 >> y0 >> ax >> ay >> bx >> by;
cin >> xs >> ys >> t;
}
void Solve() {
vector<long long> x(1, x0), y(1, y0);
long long LIMIT = (1LL << 62) - 1;
while ((LIMIT - bx) / ax >= x.back() && (LIMIT - by) / ay >= y.back()) {
x.push_back(ax * x.back() + bx); y.push_back(ay * y.back() + by);
}
int n = x.size();
int ans = 0;
for (int i=0; i<n; i++) {
for (int j=i; j<n; j++) {
long long length = x[j] - x[i] + y[j] - y[i];
long long dist2Left = abs(xs - x[i]) + abs(ys - y[i]);
long long dist2Right = abs(xs - x[j]) + abs(ys - y[j]);
if (length <= t - dist2Left || length <= t - dist2Right) ans = max(ans, j-i+1);
}
}
cout << ans << endl;
}
int main(int argc, char* argv[]) {
ios_base::sync_with_stdio(0); cin.tie(NULL);
Input(); Solve(); return 0;
} | cpp |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | #include<bits/stdc++.h>
using namespace std; main(){long long t,a,b;for(cin>>t;t--;cout<<(int)log10(b+1)*a<<endl)cin>>a>>b;} | cpp |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int a[400007],k;
int main()
{
int n,x,y;
cin>>n>>x;
while(n--)
{
cin>>y;
a[y%x]++;
while(a[k%x]>k/x) k++;
cout<<k<<endl;
}
return 0;
}
| cpp |
1312 | G | G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier. | [
"data structures",
"dfs and similar",
"dp"
] | #include<bits/stdc++.h>
#define pii pair<int,int>
#define fi first
#define se second
#define eb emplace_back
#define ll long long
using namespace std;
const int M=1e6+9;
int n,m,sz;
int c[M][26],b[M],dp[M],L[M],R[M];
bool vis[M];
void solve(int u,int z){
if(vis[u])sz++,dp[u]=min(dp[u],z+sz);
z=min(z,dp[u]-(sz-vis[u]));
for(int i=0;i<26;++i){
if(c[u][i]){
dp[c[u][i]]=dp[u]+1;
solve(c[u][i],z);
}
}
}
int main(){
cin>>n;
for(int i=1;i<=n;++i){
int p;
char s[5];
cin>>p>>s;
c[p][s[0]-'a']=i;
}
cin>>m;
for(int i=1;i<=m;++i){
cin>>b[i];
vis[b[i]]=1;
}
solve(0,0);
for(int i=1;i<=m;++i){
cout<<dp[b[i]]<<" \n"[i==m];
}
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"
] | #include <bits/stdc++.h>
using namespace std;
int rec(vector<int> V, int b){
if (b < 0) return 0;
vector<int> A, B;
for (int i : V) (i & (1 << b)) ? A.push_back(i) : B.push_back(i);
if (A.empty() or B.empty()) return rec(V, b - 1);
return (1 << b) + min(rec(A, b - 1), rec(B, b - 1));
}
int main(){
int n; cin >> n; vector<int> A(n);
for (int &i : A) cin >> i;
cout<<rec(A, 30)<<"\n";
} | 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;
#define int long long
signed main()
{
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
int n;
string s;
cin >> n >> s;
int lo = 1, hi = 27;
int md = 0;
vector<int> col(n + 3);
vector<char> seg(29);
while (lo <= hi)
{
int mid = (lo + hi) / 2;
for (int i = 0; i <= mid; i++)
seg[i] = 'a';
bool flag = 1;
for (int i = 0; i < n; i++)
{
int u = -1;
for (int j = 1; j <= mid; j++)
{
if (s[i] < seg[j])
continue;
if (u == -1 or seg[j] > seg[u])
u = j;
}
if (u == -1)
{
flag = 0;
break;
}
col[i] = u;
seg[u] = s[i];
}
if (flag)
{
hi = mid - 1;
md = mid;
}
else
lo = mid + 1;
}
if (md > 2)
{
cout << "NO" << endl;
exit(0);
}
cout << "YES" << endl;
for (int i = 0; i < s.size(); i++)
{
if (col[i] == 1)
col[i] = 0;
else
col[i] = 1;
cout << col[i];
}
} | 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"
] | #include <bits/stdc++.h>
using namespace std;
#define inout0 ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr)
using ll [[maybe_unused]] = long long;
using ld [[maybe_unused]] = long double;
using flag [[maybe_unused]] = bool;
template<typename T>
istream &operator>>(istream &in, vector<T> &v) {
for (auto &i: v)
in >> i;
return in;
}
template<typename T>
ostream &operator<<(ostream &out, vector<T> &v) {
if (is_same<T, pair<int, int>>::value) {
for (auto &i: v)
out << i << '\n';
} else {
for (auto &i: v)
out << i << " ";
}
return out;
}
vector<pair<int, int>> heap;
void sift_down(int n) {
if (heap.size() == (2 * n + 1)) {
if (heap[n].first < heap[2 * n + 1].first) {
return;
}
else {
int tmp = heap[2 * n + 1].first;
heap[2 * n + 1] = heap[n];
heap[n].first = tmp;
sift_down(2 * n + 1);
}
}
else if (heap.size() >= (2 * n + 2)) {
if (heap[n].first < heap[2 * n + 1].first && heap[n].first < heap[2 * n + 2].first) {
return;
} else {
if (min(heap[2 * n + 1].first, heap[2 * n + 2].first) == heap[2 * n + 1].first) {
int tmp = heap[2 * n + 1].first;
heap[2 * n + 1] = heap[n];
heap[n].first = tmp;
sift_down(2 * n + 1);
}
else {
int tmp = heap[2 * n + 2].first;
heap[2 * n + 2] = heap[n];
heap[n].first = tmp;
sift_down(2 * n + 2);
}
}
}
}
void sift_up(int n) {
if (n != 0) {
if (heap[n].first < heap[(n - 1) / 2].first) {
int tmp = heap[(n - 1) / 2].first;
heap[(n - 1) / 2] = heap[n];
heap[n].first = tmp;
sift_up((n - 1) / 2);
}
}
}
int my_find(int n) {
for (int i = 0; i < heap.size(); ++i) {
if (heap[i].second == n) {
return i;
}
}
}
void prosto_remove(int n) {
int tp = my_find(n);
heap[tp] = heap[heap.size() - 1];
heap.pop_back();
sift_down(tp);
}
void insert(int num, int n) {
heap.emplace_back(num, n);
sift_up(heap.size() - 1);
}
void solve() {
string str;
cin >> str;
int i_f = -1;
int i_l = -1;
for (int i = 0; i < str.length(); ++i) {
if (str[i] == '1') {
i_f = i;
break;
}
}
for (int i = str.length() - 1; i >= 0; --i) {
if (str[i] == '1') {
i_l = i;
break;
}
}
ll ans = 0;
for (int i = i_f; i <= i_l; ++i) {
if (str[i] == '0') {
++ans;
}
}
cout << ans << '\n';
}
int main() {
inout0;
int tt = 1;
cin >> tt;
while (tt--) {
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"
] | /*
Genius is diligence
*/
#include <bits/stdc++.h>
using namespace std;
#define speed std::ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define tcase int t;cin>>t;while(t--)
#define kill(x) {cout<<x<<'\n';return;}
#define print(x) cout<<x<<"\n";
#define fxst(x) cout<<fixed<<setprecision(x);
#define down(x) transform(x.begin(),x.end(),x.begin(),::tolower)
#define up(x) transform(x.begin(),x.end(),x.begin(),::toupper)
#define rplcs(s,x,y) regex _(x); s=regex_replace(s, _, y)
#define rtt(s) rotate(s.begin(),s.begin()+1,s.end());
#define mem(dp,x) memset(dp,x,sizeof dp);
#define fr first
#define sc second
#define sz size()
#define pb push_back
#define pf push_front
#define ppb pop_back()
#define ppf pop_front()
#define pr(x,y) pair<x,y>
#define dbl double
#define ll long long
#define ull unsigned long long
#define dl dbl long
#define all(v) v.begin(),v.end()
#define allr(v) v.rbegin(),v.rend()
#define mx(v) *max_element(all(v))
#define mn(v) *min_element(all(v))
#define sm(v) accumulate(v.begin(),v.end(),0ll)
#define rvrs(v) reverse(all(v))
#define srt(v) sort(all(v))
#define srtr(v) sort(allr(v))
#define rplcv(v,x,y) replace(all(v),x,y)
#define unq(v) auto ittt=unique(all(v));v.resize(distance(v.begin(),ittt));
#define cin(v) for(auto &i : v) cin>>i
#define cinpr(v) for(auto &i : v) cin>>i.fr>>i.sc
#define cinrpr(v) for(auto &i : v) cin>>i.sc>>i.fr
#define cout(v) for(auto &i : v) cout<<i<<' '; cout<<'\n'
#define bs binary_search
#define lb lower_bound
#define ub upper_bound
int inf=INT_MAX,mod=1e9+7;
void sol(){
int x;cin>>x;
kill(1<<" "<<x-1);
}
int main(){
speed;
tcase
sol();
} | cpp |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define ll long long
#define vll vector<ll>
#define pb push_back
#define FAST ios::sync_with_stdio(false); cin.tie(nullptr);
#define vp vector<pair<ll,ll>>
#define tc ll t; cin >> t; for(ll i = 0; i < t; i++){solve(i, t);}
#define tc1 solve(1, 1);
#define mpvll map<ll, vll>
#define vfast vll a(n); for (ll i = 0; i < n; i++) { cin >> a[i]; }
#define mpll map<ll,ll>
#define vll2 vector<vector<ll>> dp(m, vector<ll>(n));
#define FIXED(A) cout << fixed; cout.precision(20); cout << A << "\n";
#define mp(A, B) make_pair(A, B)
#define all(x) (x).begin(), (x).end()
#define pll pair<ll,ll>
struct tri{ll x = 0, y = 0, z = 0;};
template <typename num_t>
using ordered_set = tree<num_t, null_type, less_equal<num_t>, rb_tree_tag, tree_order_statistics_node_update>;
void setIO(string name) {freopen((name+".in").c_str(),"r",stdin);freopen((name+".out").c_str(),"w",stdout);}
ll rd(ll a, ll b){return (a+b-1) / b;}
ll isqrt(ll x){ll ans = 0; for(ll k = 1LL << 30; k != 0; k /= 2){if ((ans + k) * (ans + k) <= x) {ans += k;} } return ans; }
vll prime(ll x){ll n = x; vll ans; while (n % 2 == 0) {ans.pb(2);n = n/2;} for (int i = 3; i <= sqrt(n); i = i + 2) {while (n % i == 0){ans.pb(i);n = n/i;}}if (n > 2){ans.pb(n);} return ans;}
ll binpow(ll a, ll b, ll m) { a %= m; ll res = 1; while (b > 0) { if (b & 1){res = res * a % m;}a = a * a % m; b >>= 1;} return res;}
ll lg2(ll n){ll cnt=0;while(n){cnt++;n/=2;}return cnt;}
template<class T>
class seg {
private:
T comb(T a, T b) { return a + b; }
const T DEFAULT = 0;
vector<T> segtree;
int len;
public:
seg(int len) : len(len), segtree(len * 2, DEFAULT) { }
void set(int ind, T val) {
assert(0 <= ind && ind < len);
ind += len;
segtree[ind] = val;
for (; ind > 1; ind /= 2) {
segtree[ind >> 1] = comb(segtree[ind], segtree[ind ^ 1]);
}
}
T sum(int start, int end) {
assert(0 <= start && start < len && 0 < end && end <= len);
T sum = DEFAULT;
for (start += len, end += len; start < end; start /= 2, end /= 2) {
if ((start & 1) != 0) {
sum = comb(sum, segtree[start++]);
}
if ((end & 1) != 0) {
sum = comb(sum, segtree[--end]);
}
}
return sum;
}
};
void solve(ll TC, ll TC2) {
vll nums; mpll cnt;
ll n; cin >> n; ll ans = 0;
seg<ll> b(n+5), c(n+5);
vp a(n); for(ll i = 0; i < n; i++){cin >> a[i].first;} for(ll i = 0; i < n; i++){cin >> a[i].second;}
sort(all(a));
for(ll i = 0; i < n; i++){cnt[a[i].second]++;if(cnt[a[i].second] == 1){nums.pb(a[i].second);}}
sort(all(nums)); mpll val;
vector<vp> d(n+5);
for(ll i = 0; i < nums.size(); i++){val[nums[i]] = i;}for(ll i = 0; i < n; i++){a[i].second = val[a[i].second];}
for(ll i =0 ; i < a.size(); i++){d[a[i].second].pb(mp(i,a[i].first)); }
vll pre(n+5); for(ll i = n-1; i >= 0; i--){pre[i] = pre[i+1] + a[i].first;}
for(ll i =0; i < nums.size(); i++){
for(pll x: d[i]){
ans += pre[x.first+1] - (x.second * (n-x.first-1));
ans -= b.sum(x.first,n+4) - (c.sum(x.first,n+4) * x.second);
//cout << x.first << " " << ans << "\n";
}
for(pll x: d[i]){
b.set(x.first, x.second); c.set(x.first,1);
}
}
cout << ans;
}
int main() {
FAST;
tc1;
} | 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"
] | #define _USE_MATH_DEFINES
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
const int n1=1000000007;
#define miv map<int,vector<int>>
#define inf 5e18
#define mlv map<ll,vector<ll>>
#define mip map<int,pair<int,int>>
#define mii map<int,int>
#define mll map<ll,ll>
#define umip unordered_map<int,pair<int,int>>
#define umii unordered_map<int,int>
#define vi vector<int>
#define vll vector<ll>
#define vvll vector<vector<ll>>
#define vvi vector<vector<int>>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vpii vector<pii>
#define vpll vector<pll>
#define pb push_back
#define f first
#define s second
#define all(x) x.begin(),x.end()
#define pi = 3.1415926535897932384626
#define INF LLONG_MAX
#define yes cout<<"YES"<<endl
#define no cout<<"NO"<<endl
#define input(a,x,n); for(int i=x;i<n;i++){cin>>a[i];}
#define output(b,x,n); for(int i=x;i<n;i++){cout<<b[i]<<" ";}
#define umill unordered_map <int,ll>
#define pvi pair<vector<int>,int>
#define piv pair<int,vector<int>>
#define in(i,x,n) for(int i=x;i<n;i++)
#define inl(i,x,n) for(ll i=x;i<n;i++)
#define de(i,x,n) for(int i=n;i>=x;i--)
#define del(i,x,n) for(ll i=n;i>=x;i--)
#define trav(it,m) for(auto it=m.begin();it!=m.end();it++)
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<pll, null_type, less<pll>,
rb_tree_tag, tree_order_statistics_node_update> ordered_set;
struct compare {
inline bool operator()(const std::string& first,
const std::string& second) const
{
return first.size() < second.size();
}
};
vll factorial(ll n)
{
vll fct(n+1);
fct[0]=1;
fct[1]=1;
inl(i,2,n+1)
{
fct[i]=((fct[i-1%n1])*(i%n1))%n1;
}
return fct;
}
vll factorial(ll n,ll m)
{
vll fct(n+1);
fct[0]=1;
fct[1]=1;
inl(i,2,n+1)
{
fct[i]=((fct[i-1]%m)*(i%m))%m;
}
return fct;
}
long long power(long long x,ll y)
{
long long res = 1;
ll p=n1;
x = x % p;
while (y > 0)
{
if (y & 1)
res = ((res%p) * (x%p)) % p;
y = y >> 1;
x = ((x%p) * (x%p)) % p;
}
return res;
}
long long modInverse(long long n)
{
return power(n, n1 - 2);
}
vector<bool> SieveOfEratosthenes(ll n){
vector<bool> prime(n + 1, 1); for (ll p = 2; p * p <= n; p++)
if (prime[p] == true) for (ll i = p * p; i <= n; i += p)
prime[i] = false; return prime;}
ll ncr(ll n,ll r,vll &fct)
{
return 1ll*(((((fct[n]%n1)*(modInverse(fct[r])%n1))%n1)*(modInverse(fct[n-r])%n1))%n1);
}
// char a[400][400];
ll cnt(int r1,int r2,int c1,int c2,vvll &pre)
{
ll cnt=0;
if(r1>0&&c1>0)
{
cnt=pre[r2][c2]-pre[r2][c1-1]-pre[r1-1][c2]+pre[r1-1][c1-1];
}
else if(r1>0)
{
cnt=pre[r2][c2]-pre[r1-1][c2];
}
else if(c1>0)
{
cnt=pre[r2][c2]-pre[r2][c1-1];
}
else
{
cnt=pre[r2][c2];
}
return cnt;
}
//ll dp[500][500];
ll ans1;
void dfs1(vvll &adj,ll node,vll &ans,ll p,vll &sub,vll &w,vll &c)
{
ans[node]=w[c[node]];
ll curr=0;
for(auto &u:adj[node])
{
if(u==p)continue;
vll v;
while(v.size()<sub[u])
{
if(curr==c[node])curr++;
v.pb(w[curr]);
curr++;
}
dfs1(adj,u,ans,node,sub,v,c);
}
}
void dfs(vvll &adj,ll node,ll p,vll &sub)
{
sub[node]=1;
for(auto &u:adj[node])
{
if(u!=p)
{
dfs(adj,u,node,sub);
sub[node]+=sub[u];
}
}
}
void build(ll l,ll r,vll &a,vll &seg,ll idx)
{
if(l==r)
{
seg[idx]=a[l];
return;
}
ll mid=(l+r)/2;
build(l,mid,a,seg,2*idx+1);
build(mid+1,r,a,seg,2*idx+2);
seg[idx]=__gcd(seg[2*idx+1],seg[2*idx+2]);
return ;
}
void build1(ll l,ll r,vll &a,vll &seg,ll idx)
{
if(l==r)
{
seg[idx]=a[l];
return;
}
ll mid=(l+r)/2;
build1(l,mid,a,seg,2*idx+1);
build1(mid+1,r,a,seg,2*idx+2);
seg[idx]=max(seg[2*idx+1],seg[2*idx+2]);
return ;
}
ll query1(ll l,ll r,ll low,ll high,ll idx,vll &seg)
{
if(low>=l and high<=r)
return seg[idx];
if(low>r or high<l)
return -1*inf;
ll mid=(low+high)/2;
ll x=query1(l,r,low,mid,2*idx+1,seg);
ll y=query1(l,r,mid+1,high,2*idx+2,seg);
return max(x,y);
}
ll query(ll l,ll r,ll low,ll high,ll idx,vll &seg)
{
if(low>=l and high<=r)
return seg[idx];
if(low>r or high<l)
return 0;
ll mid=(low+high)/2;
ll x=query(l,r,low,mid,2*idx+1,seg);
ll y=query(l,r,mid+1,high,2*idx+2,seg);
return __gcd(x,y);
}
void update(ll l,ll r,vll &seg, ll idx,ll val,ll index,mll &st)
{
if(l==r)
{
ll x=seg[idx];
if(l==0)
{
st[x]--;
if(st[x]<=0)
st.erase(x);
seg[idx]-=val;
st[seg[idx]]++;
}
else
{
seg[idx]-=val;
}
return;
}
ll mid=(l+r)/2;
if(index>=l and index<=mid)
{
update(l,mid,seg,2*idx+1,val,index,st);
}
else
{
update(mid+1,r,seg,2*idx+2,val,index,st);
}
ll x=seg[idx];
seg[idx]=min(seg[2*idx+1],seg[2*idx+2]);
if(l==0)
{
st[x]--;
if(st[x]<=0)
st.erase(x);
st[seg[idx]]++;
}
return;
}
vll kmp(string str)
{
vll v(str.size());
v[0]=0;
in(i,1,str.size())
{
ll j=v[i-1];
while(j>0 and str[i]!=str[j])
{
j=v[j-1];
}
if(str[i]==str[j])
{
j++;
}
v[i]=j;
}
return v;
}
void fun(vector<int>&A)
{
int n=A.size();
int num1=1e9;
int num2=1e9;
int c1=0;
int c2=0;
for(int i=0;i<n;i++)
{
if(A[i]==num1)
{
c1++;
}
else if(A[i]==num2)
{
c2++;
}
else if(c1==0)
{
num1=A[i];
c1++;
}
else if(c2==0)
{
num2=A[i];
c2++;
}
else
{
c1--;
c2--;
}
}
c1=0;
c2=0;
for(int i=0;i<n;i++)
{
if(A[i]==num1)
{
c1++;
}
if(A[i]==num2)
{
c2++;
}
}
cout<<num1<<" "<<num2<<endl;
if(c1>(n/3))
{
cout<<num1;
}
else if(c2>(n/3))
{
cout<<num2;
}
else
{
cout<<-1;
}
cout<<endl;
}
/*ll spf[10000001];
void sieve()
{
spf[1]=1;
in(i,2,1e7+1)
{
spf[i]=i;
}
for(int i=4;i<=1e7+1;i+=2)
{
spf[i]=2;
}
for(int i=3;i*i<=1e7+1;i++)
{
if(spf[i]==i)
{
for(int j=i*i;j<=1e7+1;j+=i)
{
if(spf[j]==j)
{
spf[j]=i;
}
}
}
}
}
*/
ll lca(vvll &dp,ll n1,ll n2,vll &dep)
{
if(dep[n1]<dep[n2])
swap(n1,n2);
de(i,0,20)
{
if(dep[n1]-(1ll<<i)>=dep[n2])
{
n1=dp[n1][i];
}
}
if(n1==n2)
return n1;
de(i,0,20)
{
if(dp[n1][i]!=dp[n2][i])
{
n1=dp[n1][i];
n2=dp[n2][i];
}
}
return dp[n1][0];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
ll tt=1;
//cin>>tt;
//vvll fcmp(200003);
/*vector<bool>v=SieveOfEratosthenes(3162);
vll primes;
in(i,2,3163)
{
if(i<v.size())
{
if(v[i])
primes.pb(i);
}
}
//cout<<primes.size()<<"LK"<<endl;
//output(primes,0,primes.size());
//cout<<endl;
//mlv fc;
*/
while(tt--)
//in(x,1,tt+1)
{
ll n;
cin>>n;
vvll adj(n+1);
vll c(n+1);
ll root=-1;
in(i,1,n+1)
{
ll p,x;
cin>>p>>x;
c[i]=x;
if(p==0){
root=i;
continue;
}
adj[p].pb(i);
adj[i].pb(p);
}
vll sub(n+1);
dfs(adj,root,0,sub);
vll w;
int f1=1;
in(i,1,n+1)
{
if(c[i]>sub[i]-1)
{
f1=0;
break;
}
w.pb(i);
}
if(!f1)
{
no;
continue;
}
vll ans(n+1);
yes;
dfs1(adj,root,ans,0,sub,w,c);
output(ans,1,n+1);
cout<<endl;
}
return 0;
}
| cpp |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 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≤15001≤n≤1500) — 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
| [
"data structures",
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define all(v) ((v).begin()), ((v).end())
#define rall(v) ((v).rbegin()), ((v).rend())
#define F first
#define S second
#define oo 1e18+5
#define MOD ll(1e9+7)
#define fvec(i,vec) for(auto i:vec)
#define pb push_back
#define mpr make_pair
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
# define M_PI 3.14159265358979323846
#define int long long
#define foor(i,a,b) for (ll i = a; i < b; i++)
#define num_ocur_insort(vec,x) equal_range(all(vec), x) /* return pair upper lower auto r=num_ocur_insort(a,6);*/
typedef int ll;
typedef unsigned long long ull;
typedef vector<ll> vi;
typedef vector<vi> vii;
typedef pair<ll,ll> pi;
typedef vector<pi> vip;
typedef vector<string> vss;
typedef map<ll,ll> mapi;
typedef unordered_map<ll,ll> umapi;
typedef vector<vip> viip;
typedef tree< ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
ll gcd(ll a, ll b) { return ((b == 0) ? a : gcd(b, a % b)); }
const int N=10000;
ll fun(vip &a) {
ll sum = 1;
ll mashgol = a[0].first;
for (int i = 1; i < a.size(); ++i) {
if (a[i].second > mashgol) {
mashgol = a[i].first;
sum++;
}
}
return sum;
}
void solve(ll hh ) {
ll n;
cin >> n;
vi a(n);
vi pr(n);
ll ans = 0, res;
map<ll, vector<pi>> mp;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
pr[0] = a[0];
for (int i = 1; i < n; ++i) {
pr[i] += pr[i - 1]+a[i];
}
for (int i = 0; i < n; ++i) {
for (int j = i ; j < n; ++j) {
ll lst = 0;
if (i)lst = pr[i - 1];
ll val = pr[j] - lst;
mp[val].push_back({j, i});
}
}
for (auto it: mp) {
auto vec = it.second;
sort(all(vec));
ll temp = fun(vec);
if (temp > ans) {
ans = temp;
res = it.first;
}
}
auto vec = mp[res];
sort(all(vec));
vip fin;
ll mas = vec[0].first;
fin.push_back({vec[0].second, vec[0].first});
for (int i = 1; i < vec.size(); ++i) {
if (vec[i].second > mas) {
mas = vec[i].first;
fin.push_back({vec[i].second, vec[i].first});
}
}
cout << ans << endl;
for (int i = 0; i < fin.size(); ++i) {
cout << fin[i].first +1<< " " << fin[i].second+1 << endl;
}
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll t = 1;
// cin >> t;
ll hh=t;
while (t--) {
solve(hh-t);
}
} | 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 read(type) readInt<type>() // Fast read
#define ll long long
#define nL "\n"
#define pb push_back
#define mk make_pair
#define pii pair<int, int>
#define vi vector<int>
#define all(x) (x).begin(), (x).end()
#define umap unordered_map
#define uset unordered_set
#define MOD 1000000007
void solve()
{
int n;
cin >> n;
int arr[n];
map<int, ll> m;
ll ans = 0;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
m[arr[i] - i] += arr[i];
}
for (auto x : m)
{
if (x.second > ans)
{
ans = x.second;
}
}
cout << ans << endl;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
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"
] | //I'm practice
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define odrse tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define odrmse tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update>
using namespace __gnu_pbds;
using namespace std;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef pair<long long,long long> pll;
typedef pair<long long, int> pli;
typedef pair<int, long long> pil;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef vector<vector<vector<ll>>> vvvl;
typedef vector<int> vi;
typedef vector<pair<long long, long long>> vll;
typedef vector<pli> vli;
typedef vector<pil> vil;
typedef vector<string> vs;
#define prqu priority_queue
typedef priority_queue<ll> pql;
typedef priority_queue<int> pqi;
typedef priority_queue<pll> pqll;
typedef priority_queue<pli> pqli;
typedef priority_queue<pil> pqil;
typedef map<ll,int> mli;
typedef map<ll,ll> mll;
typedef map<int,int> mii;
typedef map<int,ll> mil;
typedef map<pll,ll> mlll;
#define V vector
#define ff(i,a,b) for(ll i=a;i<=b;i++)
#define rep(i,a,b) for(ll i=a;i>=b;i--)
#define ffd(i,a,b,x) for(ll i=a;i<=b;i+=x)
#define repd(i,a,b,x) for(ll i=a;i>=b;i-=x)
#define fff(i,v) for(auto i : v)
#define ffi(i,v) for(ll i = 0; i <= v.sz-1; i++)
#define repi(i,v) for(ll i = v.sz-1; i >= 0; i--)
#define ffp(x1,x2,v) for(auto [x1,x2] : v)
#define ffit(it,v) for(auto it = v.begin() ; it != v.end(); it++)
#define all(x) x.begin(),x.end()
#define en cout<<endl;
#define eren cerr<<endl;
#define pb push_back
#define pf push_front
#define ppf pop_front
#define eb emplace_back
#define ft front()
#define bk back()
#define clr clear()
#define ppb pop_back
#define sqr(x) (x)*(x)
#define gcd(a,b) __gcd(a,b)
#define sz size()
#define rsz resize
#define reset(x,val) memset((x),(val),sizeof(x))
#define mtset multiset
#define cid(x) x = " "+x;
#define sstr substr
#define ins insert
#define ers erase
#define emp empty()
#define maxelm max_element
#define minelm min_element
#define ctn continue
#define rtn return
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define yesno(c) (c? "YES":"NO")
#define outyesno(c) { cout<<yesno(c)<<endl; rtn; }
#define nortn {cout<<"NO"<<endl; rtn; }
#define yesrtn { cout<<"YES"<<endl; rtn; }
#define valrtn(x) { cout<<x<<endl; rtn; }
#define x first
#define y second
#define ffmask(mask,n) for(ll mask = 1; mask <= (1<<n)-1; mask++)
//#define ffbit1(x,mask) for(x = mask;x > 0; x -= x & (-x))
#define lastbit1(x) x & (-x)
#define getbit(n,x) (1<<x)&n
#define cntbit1(x) __builtin_popcountll(x)
#define cntbit0(x) __builtin_clzll(x)
#define lwb lower_bound
#define upb upper_bound
#define tcT template <class T
#define tcTU tcT, class U
template<typename T1, typename T2> bool maxi(T1& a, T2 b) {if (a < b) {a = b; return 1;} else return 0;}
template<typename T1, typename T2> bool mini(T1& a, T2 b) {if (a > b) {a = b; return 1;} else return 0;}
template<typename T1, typename T2> bool minswap(T1& a, T2 b) {if (a > b) {swap(a,b); return 1;} else return 0;}
template<typename T1, typename T2> bool maxswap(T1& a, T2 b) {if (a < b) {swap(a,b); return 1;} else return 0;}
template <class T> using mprqu = priority_queue<T, vector<T>, greater<T>>;
#define debug(X) {auto _X=(X); cerr << "L" << __LINE__ << ": " << #X << " = " << (_X) << endl;}
#define err(x) cerr << #x << " = " << (x) << '\n'
#define verr(x) fff(k,x) cerr<<k<<" "; eren;
#define dot cerr<<".";
inline void inp(){} template<typename F, typename... R> inline void inp(F &f,R&... r){cin>>f;inp(r...);}
inline void out(){} template<typename F, typename... R> inline void out(F f,R... r){cout<<f;out(r...);}
const ll cr = 2e5 + 7;
const ll mod = 1e9 + 7;
const ll MOD = 998244353;
const ll inf = 0x3f3f3f3f;
const ll base = 311;
const ldb pi = (ldb)3.1415926535897932384626433832795;
const string Yes = "Yes";
const string No = "No";
const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
bool mem2;
#define fastIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define FILE(s) freopen(s".INP","r",stdin);freopen(s".OUT","w",stdout);ofstream fo(s".TXT");
#define GetExpert int32_t main()
#define y1 tlapluvnth
#define y2 zz16102007
#define left nthnevaluvtlap
#define right tlapstillluvnth
//MAIN PROGRAM----
//----------------
ll n,q;
set<pll> se;
void resetsolve(){
}
void init(){
cin >> n >> q;
}
void solveinsolve(){
ll cnt = 0;
while(q--) {
ll r,c;
cin >> r >> c;
ll invr = (r == 1)? 2 : 1;
if (!se.count({r,c})) {
se.ins({r,c});
cnt += se.count({invr,c-1}) + se.count({invr,c}) + se.count({invr,c+1});
} else {
se.ers({r,c});
cnt -= se.count({invr,c-1}) + se.count({invr,c}) + se.count({invr,c+1});
}
cout<<(cnt? No : Yes)<<endl;
}
}
void print(){
}
void solve(){
//remember reset and init
resetsolve();
init();
solveinsolve();
print();
}
void process(){
}
bool mem1;
GetExpert{
process();
fastIO;
//ll t = 1; cin>>t; ff(____,1,t) {
//cout<<"Case "<<____<<":"<<endl;
//cerr<<"Case "<<____<<endl;
solve();
//eren;
//}
//------------
//eren;
//cerr << "Memory Cost: " << abs(&mem1-&mem2)/1024./1024. << " MB" << endl;
//cerr << "Time Cost: " << clock()*1000./CLOCKS_PER_SEC << " MS" << endl;
} | 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>
#define Source ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL);
#define ll long long
#define int long long
#define ld long double
#define Endl '\n'
//#define t int t;cin>>t;while(t--)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define sz(a) (int)(a).size()
using namespace std;
const int N = 2e5 + 5;
const ll mod = 1e9 + 7;
int dx[] = {+0, +0, +1, -1, -1, +1, -1, +1};
int dy[] = {+1, -1, +0, +0, +1, -1, -1, +1};
int nxt[N][26];
void testCase(int cs) {
string s,t;
cin >> s >> t;
for(int i = 0; i < s.size() + 5; ++i)
for(int j = 0; j < 26; ++j)
nxt[i][j] = 1e18;
for(int i = sz(s) - 1; i >= 0; --i){
for(int j = 0; j < 26; ++j)
nxt[i][j] = nxt[i + 1][j];
nxt[i][s[i] - 'a'] = i;
}
int ans = 0, nxtIdx = 0;
for (int i = 0; i < sz(t); ++i) {
int c = t[i] - 'a';
if(nxtIdx == sz(s)) {
nxtIdx = 0;
ans++;
}
if(nxt[nxtIdx][c] == 1e18)
{
nxtIdx = 0;
ans++;
}
if(nxt[nxtIdx][c] == 1e18 && !nxtIdx)
{
cout << -1 << endl;
return;
}
nxtIdx = nxt[nxtIdx][c] + 1;
}
cout << ans + 1 << endl;
}
signed main() {
// files();
Source
ll t = 1;
int cs = 0;
cin >> t;
while (t--) {
testCase(++cs);
}
return 0;
} | cpp |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | #include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
#include <functional>
#include <cassert>
using namespace std;
#define int long long
int gauss(int x)
{
return x*(x+1)/2;
}
void solve()
{
int n;
cin>>n;
vector<pair<int,int>>a(n);
for(auto &c:a)cin>>c.first;
for(auto &c:a)cin>>c.second;
sort(a.begin(),a.end());
int sum=0,rez=0;
priority_queue<int>q;
int acm=-1;
a.push_back({2e9,-1});
for(int i=0;i<=n;)
{
while(acm!=a[i].first && q.size())
{
sum-=q.top();
q.pop();
rez+=sum;
acm++;
}
acm=a[i].first;
while(a[i].first==acm)
{
sum+=a[i].second;
q.push(a[i].second);
i++;
}
}
cout<<rez;
}
main()
{
auto sol=[](bool x)->string
{
if(x)return "YES";
return "NO";
};
int tt=1;
//cin>>tt;
while(tt--)
{
solve();
cout<<'\n';
}
}
| cpp |
1307 | G | G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3
1 2 2
2 3 2
1 3 3
5
0
1
2
3
4
OutputCopy3.0000000000
4.0000000000
4.5000000000
5.0000000000
5.5000000000
| [
"flows",
"graphs",
"shortest paths"
] | // LUOGU_RID: 99808804
#include <bits/stdc++.h>
using namespace std;
using i64=long long;
using u64=unsigned long long;
using db=double;
using pii=pair<int,int>;
using vi=vector<int>;
template<typename T>
inline T read(){
T x=0,f=0;char ch=getchar();
while(!isdigit(ch)) f|=(ch=='-'),ch=getchar();
while(isdigit(ch)) x=x*10+(ch-'0'),ch=getchar();
return f?-x:x;
}
#define rdi read<int>
#define rdi64 read<i64>
#define fi first
#define se second
#define pb push_back
const int N=55;
const i64 INFl=4e18;
int n,m,q;
struct Edge{int to,nxt,f,w;}e[N*N*4];
int head[N],tot=1;
void add_e(int x,int y,int f,int w){
e[++tot]={y,head[x],f,w};head[x]=tot;
e[++tot]={x,head[y],0,-w};head[y]=tot;
}
i64 dis[N];int pre[N];
bool spfa(int n,int S,int T){
static int inq[N];
queue<int> q;
fill(dis+1,dis+n+1,INFl);
dis[S]=0,q.push(S),inq[S]=1;
while(!q.empty()){
int x=q.front();
q.pop(),inq[x]=0;
for(int i=head[x];i;i=e[i].nxt){
int y=e[i].to;
if(e[i].f&&dis[y]>dis[x]+e[i].w){
dis[y]=dis[x]+e[i].w,pre[y]=i;
if(!inq[y]) inq[y]=1,q.push(y);
}
}
}
return dis[T]!=INFl;
}
vector<pair<int,i64>> cv;
void calc(int n,int S,int T){
int sf=0;i64 sc=0;
while(spfa(n,S,T)){
int x=T;i64 fl=INFl;
while(x!=S) fl=min(fl,(i64)e[pre[x]].f),x=e[pre[x]^1].to;
x=T,sf+=fl,sc+=fl*dis[T];
while(x!=S) e[pre[x]].f-=fl,e[pre[x]^1].f+=fl,x=e[pre[x]^1].to;
cv.pb({sf,sc});
}
}
db query(int x){
db ret=INFl;
for(auto cur:cv) ret=min(ret,1.*(cur.se+x)/cur.fi);
return ret;
}
int main(){
#ifdef LOCAL
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
n=rdi(),m=rdi();
for(int i=1;i<=m;i++){
int x=rdi(),y=rdi(),w=rdi();
add_e(x,y,1,w);
}
calc(n,1,n);
q=rdi();
while(q--){
int x=rdi();
cout<<fixed<<setprecision(7)<<query(x)<<'\n';
}
return 0;
}
| cpp |
1310 | E | E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function ff of multiset aa as the multiset of number of occurences of every number, that is present in aa.E.g., f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}.Let's define fk(a)fk(a), as applying ff to array aa kk times: fk(a)=f(fk−1(a)),f0(a)=afk(a)=f(fk−1(a)),f0(a)=a. E.g., f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}.You are given integers n,kn,k and you are asked how many different values the function fk(a)fk(a) can have, where aa is arbitrary non-empty array with numbers of size no more than nn. Print the answer modulo 998244353998244353.InputThe first and only line of input consists of two integers n,kn,k (1≤n,k≤20201≤n,k≤2020).OutputPrint one number — the number of different values of function fk(a)fk(a) on all possible non-empty arrays with no more than nn elements modulo 998244353998244353.ExamplesInputCopy3 1
OutputCopy6
InputCopy5 6
OutputCopy1
InputCopy10 1
OutputCopy138
InputCopy10 2
OutputCopy33
| [
"dp"
] | #include<bits/stdc++.h>
#define ll long long
#define gmax(x,y) x=max(x,y)
#define gmin(x,y) x=min(x,y)
#define F first
#define S second
#define P pair
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,a,b) for(int i=a;i<b;i++)
#define V vector
#define RE return
#define ALL(a) a.begin(),a.end()
#define MP make_pair
#define PB emplace_back
#define PF push_front
#define FILL(a,b) memset(a,b,sizeof(a))
#define lwb lower_bound
#define upb upper_bound
#define lc (x<<1)
#define rc ((x<<1)|1)
#define sz(x) ((int)x.size())
using namespace std;
const int mod=998244353;
void add(int &x,int y){
x+=y;
if(x>=mod)x-=mod;
}
int dp[2050][2050],n,k,cnt=0;
int val[2050],len;
bool dfs(int x){
if(len){
V<int> now;
FOR(i,1,len)now.PB(val[i]);
bool f=1;reverse(ALL(now));
rep(i,1,k-1){
int tv=0;V<int> to;
int s=0,tot=0;
for(auto u:now)tot+=u;
for(auto u:now){
tv++;FOR(j,1,u)s+=(tot--)*tv;
}
tv=0;
if(s>n){
f=0;break;
}
for(auto u:now){
++tv;
FOR(j,1,u)to.PB(tv);
}
reverse(ALL(to));
now=to;
}
if(f)cnt++;else RE 0;
}
FOR(i,x,n){
val[++len]=i;
bool now=dfs(i);
--len;
if(!now)break;
}
RE 1;
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n>>k;
if(k==1){
dp[0][0]=1;
int sum=0;
FOR(i,1,n)FOR(j,i,n){
dp[i][j]=dp[i-1][j-1];
add(dp[i][j],dp[i][j-i]);
add(sum,dp[i][j]);
}
cout<<sum<<'\n';
}else if(k==2){
dp[0][0]=1;
int ans=0;
FOR(i,1,n)FOR(j,0,n)if(dp[i-1][j]){
int mul=i*(i+1)/2;
FOR(k,0,n){
if(j+k*mul>n)break;
add(dp[i][j+k*mul],dp[i-1][j]);
if(k)add(ans,dp[i-1][j]);
}
}
cout<<ans<<'\n';
}else{
dfs(1);
cout<<cnt;
}
RE 0;
}
| cpp |
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"
] | // Time Limit: 2023-02-16 11:21:42
// Just_Chill
#include<bits/stdc++.h>
#define int long long
#define mod (int)1000000007l
#define nl cout<<"\n";
#define pb push_back
#define all(a) a.begin(),a.end()
#define pii pair<int,int>
#define vi vector<int>
#define vpi vector<pair<int,int>>
#define vvi vector<vector<int>>
#define mii map<int,int>
#define S second
#define F first
#define f(i,a,n) for(int i=a;i<n;i++)
#define fi(i,n,a) for(int i=n-1;i>=a;i--)
#define tcsolve(tcs) while(tcs--) solve();
using namespace std;
template<class T,class S> void print(map<T,S> mp) {for(auto it:mp) cout<<it.first<<" "<<it.second<<"\n";} template<class T,class S> void print(map<T,vector<S>> mp) {for(auto it:mp){ cout<<it.first<<"\n"; int l=it.second.size();for(int i=0;i<l;i++) cout<<it.second[i]<<" ";nl;}} template<class T> void print(vector<vector<T>> &v) {int n=v.size(); for(int i=0;i<n;i++){ cout<<"key : "<<i+1<<"\n";cout<<"val : ";for(auto y:v[i]){ cout<<y<<" ";}cout<<"\n\n";}} template <class T> void print(const T & c) {cout<<c<<"\n";} template <class T,class K> void print(const T & c,const K & d) {cout<<c<<" "<<d<<"\n";} template <class T,class A,class N> void print(const T & c,const A & d,const N & e) {cout<<c<<" "<<d<<" "<<e<<"\n";} template <class T> void print(vector<T> & v){int l=v.size();for(int i=0;i<l;i++) cout<<v[i]<<" ";nl;} template <class T,class S> void print(vector<pair<T,S>> & v){int l=v.size();for(int i=0;i<l;i++) cout<<v[i].first<<" "<<v[i].second<<"\n";}
#define arrayinput int n,m;cin>>n>>m;vector<int> a(n);for(int i=0;i<n;i++)cin>>a[i];
void solve()
{
arrayinput;
if(n<=m){
int p=1;
f(i,0,n){
f(j,i+1,n){
p=p*(abs(a[i]-a[j]));
p=p%m;
}
}
print(p);
}
else{
print(0);
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tcs=1;
tcsolve(tcs);
}
| 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 ll long long
#define minheap priority_queue <ll, vector<ll>, greater<ll> >
#define maxheap priority_queue <ll>
#define forn(i,a,b) for(int i=a;i<b;i++)
#define all(v) v.begin(), v.end()
#define forrn(i,n) for(int i=n-1;i>=0;i--)
#define rall(v) v.rbegin(),v.rend()
#define ub(a,n,x) upper_bound(a,a+n,x)
#define lb(a,n,x) lower_bound(a,a+n,x)
#define mae(v) max_element(all(v))
#define mie(v) min_element(all(v))
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define sz(a) (int)a.size()
#define srt(v) sort(all(v))
#define srrt(v) sort(rall(v))
#define V(v,size) vector<ll>v(size)
#define G(x) ll x; cin >> x;
const int N=2e5+5;
const ll mod=1e9+7;
const ll maxai=1000000000000ll;
const ll modulo=998244353;
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b){ return (a.second < b.second);}
int g_f_b(ll n){return 63-__builtin_clzll(n);}
int g_b_c(ll n){ return __builtin_popcountll(n);}
ll me(ll a,ll b,ll c=mod)
{
ll ans=1;
while(b>0)
{
if(b&1){
ans=(1LL*ans*a%c)%c;
}
a=(1LL*a*a)%c;
b=b>>1;
}
return ans;
}
ll lcs( string X, string Y, int m, int n )
{
if (m == 0 || n == 0)
return 0;
if (X[m-1] == Y[n-1])
return 1 + lcs(X, Y, m-1, n-1);
else
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}
bool subseq(string s1,string s2)//if s1 is subseq of s2
{
if(s1.empty()) return true;
if(s1.size()>sz(s2))return false;
if(s1.back()==s2.back())return(subseq(s1.substr(0,sz(s1)-1),s2.substr(0,sz(s2)-1)));
return subseq(s1,s2.substr(0,s2.size()-1));
}
int nt(ll i, vector<ll>&v,ll n,ll s,ll k)
{
if(i==n)
{
if(s==k)
{
//for(auto i:ds)cout<<i<<" ";
// cout<<endl;
// cout<<s;
return 1;
}
// for(auto i:ds)cout<<i<<" ";
//cout<<endl;
return 0;
//cout<<endl;
//else return 0;
}
//ds.pb(v[i]);
s+=v[i];
int l= nt(i+1,v,n,s,k);
// ds.pop_back();
s-=v[i];
int r= nt(i+1,v,n,s,k);
return l+r;
}
ll mul(ll t,ll a)
{
return(t*a)%mod;
}
void yes()
{
cout<<"YES"<<endl;
}
void no()
{
cout<<"NO"<<endl;
}
/*f1(ll n,vector<ll>&dp)
{
if(n<=1)return n;
if(dp[n]!=-1)return dp[n];
return dp[n]=f(n-1,dp)+f(n-2,dp);
}*/
// ll f(vector<ll>&v,vector<ll>&dp,ll i,ll n,ll s,ll now)
// {
// }
void solve()
{
G(n);
G(q);
vector<vector<ll>>v(2,vector<ll>(n));
ll c=0;
forn(i,0,q)
{
ll a,b;
cin>>a>>b;
a--;
b--;
v[a][b]^=1;
if(v[a][b]==1)
{
if(v[abs(1-(a))][b]==1)
c++;
if(b-1>=0)
{
if(v[abs(1-(a))][b-1]==1)
c++;
}
if(b+1<n)
{
if(v[abs(1-(a))][b+1]==1)
c++;
}
}
else
{
if(v[abs(1-(a))][b]==1)
c--;
if(b-1>=0)
{
if(v[abs(1-(a))][b-1]==1)
c--;
}
if(b+1<n)
{
if(v[abs(1-(a))][b+1]==1)
c--;
}
}
/*
for(int j=0;j<2;j++)
{
forn(k,0,n)
{
cout<<v[j][k];
}
cout<<endl;
}
cout<<c<<"a";*/
if(!c)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
// int cases;
//cin>>cases;
// while(cases--)
{
solve();
}
return 0;
}
| cpp |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | [
"math"
] | #include <iostream>
#define ll long long
using namespace std;
void FAST_IO(){
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
// freopen("##.in", "r", stdin);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif
}
ll x, y, a, b;
ll bs(ll l = 0, ll r = 1e9) {
if (r - l == 1) return (x + l * a == y - l * b ? l : -1);
ll mid = (l + r) / 2;
if (x + mid * a <= y - mid * b)
return bs(mid, r);
return bs(l, mid);
}
void solve() {
cin >> x >> y >> a >> b;
cout << bs() << "\n";
}
int main() {
FAST_IO();
int testcases = 1;
cin >> testcases;
while (testcases--)
solve();
return 0;
} | cpp |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | // LUOGU_RID: 101604469
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
const long long mod = 998244353;
int n, m;
vector<long long> fac;
long long fast_power(long long x, long long y) {
long long res = 1;
while(y > 0) {
if(y & 1) res = (res * x) % mod;
x = (x * x) % mod;
y >>= 1;
}
return res;
}
long long exgcd(long long x, long long y, long long &c_x, long long &c_y) {
if(y == 0) { c_x = 1, c_y = 0; return x; }
long long gcd_x_y = exgcd(y, x % y, c_y, c_x);
c_y -= (x / y) * c_x;
return c_x;
}
long long inv(long long x) {
long long c_x, c_mod;
exgcd(x, mod, c_x, c_mod);
return (c_x % mod + mod) % mod;
}
long long C(int n, int m) {
return (fac[n] * inv(fac[m]) % mod) * inv(fac[n - m]) % mod;
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
// 阶乘
fac.resize(1 + m);
fac[0] = 1;
for(long long i = 1; i <= m; i += 1) {
fac[i] = (i * fac[i - 1]) % mod;
}
//
long long pick_num = C(m, n - 1);
long long pick_place = n - 2;
long long arrangement = fast_power(2, n - 3);
long long ans = (pick_num * pick_place % mod) * arrangement % mod;
cout << ans << "\n" << flush;
return 0;
} | cpp |
1290 | E | E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th question.ExamplesInputCopy5
2 4 1 5 3
OutputCopy1
3
6
8
11
InputCopy6
1 2 4 5 6 3
OutputCopy1
3
6
8
12
17
NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11. | [
"data structures"
] | // LUOGU_RID: 98169450
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = a; i <= b; i++)
const int N=8e5+10;
#define int long long
int n,a[N],p[N];
struct Seg{
int c[N],v[N],s[N],tg[N],stg[N],len[N],sln[N];
long long sum[N];
void cls(){
rep(i,0,n<<2)c[i]=v[i]=s[i]=tg[i]=stg[i]=len[i]=sln[i]=sum[i]=0;
}
void pushup(int k){
int L=k<<1,R=k<<1|1;
c[k]=c[L]+c[R],len[k]=len[L]+len[R],sum[k]=sum[L]+sum[R];
if(v[L]>v[R]){
v[k]=v[L],s[k]=max(s[L],v[R]);
len[k]=len[L],sln[k]=sln[L]+len[R]+sln[R];
}else if(v[L]<v[R]){
v[k]=v[R],s[k]=max(v[L],s[R]);
len[k]=len[R],sln[k]=sln[R]+len[L]+sln[L];
}else{
v[k]=v[L],s[k]=max(s[L],s[R]);
len[k]=len[L]+len[R],sln[k]=sln[L]+sln[R];
}
}
void upd(int k,int t1,int t2){
v[k]+=t1;tg[k]+=t1;s[k]+=t2;stg[k]+=t2;
sum[k]+=1ll*t1*len[k]+1ll*t2*sln[k];
}
void pushdown(int k){
int L=k<<1,R=k<<1|1;
bool tu=v[R]>=v[L];
if(v[L]>=v[R])upd(L,tg[k],stg[k]);
else upd(L,stg[k],stg[k]);
if(tu)upd(R,tg[k],stg[k]);
else upd(R,stg[k],stg[k]);
tg[k]=stg[k]=0;
}
int adpp(int l,int r,int k,int L,int R){
if(L>r||R<l)return 0;
if(L<=l&&r<=R) return upd(k,1,1),c[k];
int mid=l+r>>1;
pushdown(k);int sum=0;
sum+=adpp(l,mid,k<<1,L,R)+adpp(mid+1,r,k<<1|1,L,R);
pushup(k);return sum;
}
void modi(int l,int r,int k,int p,int ti){
if(l==r)return sum[k]=v[k]=ti,len[k]=c[k]=1,sln[k]=0,void();
int mid=l+r>>1;
pushdown(k);
if(p<=mid)modi(l,mid,k<<1,p,ti);
else modi(mid+1,r,k<<1|1,p,ti);
pushup(k);
}
void pmin(int l,int r,int k,int L,int R,int ti){
if(L>r||R<l||ti>=v[k])return;
if(L<=l&&R>=r&&ti>=s[k]){
return upd(k,ti-v[k],0),void();
}int mid=l+r>>1;pushdown(k);
pmin(l,mid,k<<1,L,R,ti);
pmin(mid+1,r,k<<1|1,L,R,ti);
pushup(k);
}
}seg;
long long res[N];
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>n;
rep(i,1,n){cin>>a[i];p[a[i]]=i;}
rep(t,1,2){
seg.cls();
rep(i,1,n){
int w=seg.adpp(1,n,1,p[i]+1,n);
seg.modi(1,n,1,p[i],i+1);
seg.pmin(1,n,1,1,p[i]-1,i-w);
res[i]+=seg.sum[1];
}
reverse(a+1,a+n+1);
rep(i,1,n){p[a[i]]=i;}
}rep(i,1,n)cout<<res[i]-1ll*i*(i+2)<<'\n';
} | cpp |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33 | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
const int N=110000;
int n, x, y, q, par[N][21], dep[N]={0};
vector<int>e[N];
void dfs(int i, int p){
dep[i]=dep[p]+1;
par[i][0]=p;
for(int j:e[i])if(j!=p)dfs(j,i);}
int dis(int a, int b){
int res=0;
if(dep[a]!=dep[b]){
if(dep[a]<dep[b])swap(a,b);
int dif=dep[a]-dep[b];
for(int i=0; i<20; i++)if(dif&(1<<i))a=par[a][i];
res+=dif;
}
if(a==b)return res;
for(int i=19; i+1; i--){
if(par[a][i]!=par[b][i]){
a=par[a][i];
b=par[b][i];
res+=(1<<i)*2;}}
res+=2;
return res;}
bool solve(){
int x, y, a, b, k;
cin >> x >> y >> a >> b >> k;
int zz;
zz=dis(a,b);
if( !((zz^k)&1) && k>=zz )return 1;
zz= dis(a,x)+dis(b,y)+1;
if( !((zz^k)&1) && k>=zz )return 1;
zz= dis(a,y)+dis(b,x)+1;
if( !((zz^k)&1) && k>=zz )return 1;
return 0;}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n;
for(int i=1; i<n; i++){
cin >> x >> y;
e[x].push_back(y);
e[y].push_back(x);}
dfs(1,1);
for(int j=1; j<20; j++){
for(int i=1; i<=n; i++)par[i][j]=par[par[i][j-1]][j-1];
}
// for(int i=1; i<=n; i++)for(int j=i+1; j<=n; j++)cout << i << ' ' << j << ' ' << dis(i,j) << '\n';
cin >> q;
while(q--){
if(solve())cout << "YES\n";
else cout << "NO\n";
}
} | cpp |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
typedef long long ll;
using namespace std;
#define pb push_back
int main()
{
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
ll t; cin >> t;
while (t--)
{
ll n; cin >> n; vector<ll> e, o;
for (int i = 0; i < n; i++) {
ll x; cin >> x; if (x%2) o.pb(i+1); else e.pb(i+1);
}
if (e.size() || o.size() > 1) {
cout << e.size()+(o.size()-(o.size()%2)) << '\n';
if (o.size()%2) o.pop_back();
for (auto i : e) cout << i << ' ';
for (auto i : o) cout << i << ' ';
} else cout << -1;
cout << '\n';
}
return 0;
}
| cpp |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
| [
"math"
] | #include<iostream>
#include<vector>
#include<set>
#include<queue>
#include<map>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<cstring>
#include<bitset>
#include<iomanip>
#include<random>
#include<fstream>
#include<complex>
#include<time.h>
#include<stack>
using namespace std;
#define endl "\n"
#define ll long long
#define bl bool
#define ch char
#define vec vector
#define vll vector<ll>
#define sll set<ll>
#define pll pair<ll,ll>
#define mkp make_pair
#define mll map<ll,ll>
#define puf push_front
#define pub push_back
#define pof pop_front()
#define pob pop_back()
#define em empty()
#define fi first
#define se second
#define fr front()
#define ba back()
#define be begin()
#define rbe rbegin()
#define en end()
#define ren rend()
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define fo(i,x,y) for(ll i=x;i<=y;++i)
#define fa(i,v) for(auto &i:v)
#define re return
#define rz return 0;
#define sz size()
#define len length()
#define con continue;
#define br break;
#define ma(a,x) a=max(a,x)
#define mi(a,x) a=min(a,x)
#define so(v) sort(all(v))
#define rso(v) sort(rall(v))
#define rev(v) reverse(all(v))
#define i(x) for(ll i=0;i<x;++i)
#define j(x) for(ll j=0;j<x;++j)
#define k(x) for(ll k=0;k<x;++k)
#define n(x) for(ll yz=0;yz<x;++yz)
#define xx(k) while(k--)
#define wh(x) while(x)
#define st string
#define M 8611686018427387904
#define ze(x) __builtin_ctzll(x)
#define z(x) ll x=0
#define in insert
#define un(v) v.erase(unique(all(v)),v.en);
#define er(i,n) erase(i,n);
#define co(x,a) count(all(x),a)
#define lo(v,a) lower_bound(v.begin(),v.end(),a)
#define up(v,a) upper_bound(v.begin(),v.end(),a)
#define dou double
#define elif else if
#define ge(x,...) x __VA_ARGS__; ci(__VA_ARGS__);
#define fix(n,ans) cout<<fixed<<std::setprecision(n)<<ans<<endl;
void cc(){ cout<<endl; };
void ff(){ cout<<endl; };
void cl(){ cout<<endl; };
template<class T,class... A> void ff(T a,A... b){ cout<<a; (cout<<...<<(cout<<' ',b)); cout<<endl; };
template<class T,class... A> void cc(T a,A... b){ cout<<a; (cout<<...<<(cout<<' ',b)); cout<<' '; };
template<class T,class... A> void cl(T a,A... b){ cout<<a; (cout<<...<<(cout<<'\n',b)); cout<<endl; };
template<class T,class... A> void cn(T a,A... b){ cout<<a; (cout<<...<<(cout<<"",b)); };
template<class... A> void ci(A&... a){ (cin>>...>>a); };
template<class T>void ou(T v){fa(i,v)cout<<i<<" ";cout<<endl;}
template<class T>void oun(T v){fa(i,v)cout<<i;cout<<endl;}
template<class T>void ouu(T v){fa(i,v){fa(j,i)cout<<j<<" ";cout<<endl;}}
template<class T> void oul(T v){fa(i,v)cout<<i<<endl;}
template<class T>void in(T &v){fa(i,v)cin>>i;}
template<class T>void inn(T &v){fa(i,v)fa(j,i)cin>>j;}
template<class T>void oump(T &v){fa(i,v)ff(i.fi,i.se);}
template<class T,class A>void pi(pair<T,A> &p){ci(p.fi,p.se);}
template<class T,class A>void po(pair<T,A> &p){ff(p.fi,p.se);}
void init(){
ios::sync_with_stdio(false);
cin.tie(0);
}
void solve();
void ori();
ll ck(){
std::random_device seed_gen;
std::mt19937 engine(seed_gen());
// [-1.0, 1.0)の値の範囲で、等確率に実数を生成する
std::uniform_real_distribution<> dist1(1.0, 100000);
i(10000){ // 各分布法に基いて乱数を生成
ll n = dist1(engine);
} rz;
}
bl isup(ch c){
re 'A'<=c&&c<='Z';
}
bl islo(ch c){
re 'a'<=c&&c<='z';
}
//isdigit
mll pr_fa(ll x){
mll mp;
for(ll i=2;i*i<=x;++i){
while(x%i==0){
++mp[i];
x/=i;
}
}
if(x!=1)
++mp[x];
re mp;
}
ch to_up(ch a){
re toupper(a);
}
ch to_lo(ch a){
re tolower(a);
}
#define str(x) to_string(x)
#define acc(v) accumulate(v.begin(),v.end(),0LL)
#define acci(v,i) accumulate(v.begin(),v.begin()+i,0LL)
#define dq deque<ll>
int main(){
init();
solve();
rz;
}
template <typename T>class pnt{
public:
T x,y;
pnt(T x=0,T y=0):x(x),y(y){}
pnt operator + (const pnt r)const {
return pnt(x+r.x,y+r.y);}
pnt operator - (const pnt r)const {
return pnt(x-r.x,y-r.y);}
pnt operator * (const pnt r)const {
return pnt(x*r.x,y*r.y);}
pnt operator / (const pnt r)const {
return pnt(x/r.x,y/r.y);}
pnt &operator += (const pnt r){
x+=r.x;y+=r.y;return *this;}
pnt &operator -= (const pnt r){
x-=r.x;y-=r.y;return *this;}
pnt &operator *= (const pnt r){
x*=r.x;y*=r.y;return *this;}
pnt &operator /= (const pnt r){
x/=r.x;y/=r.y;return *this;}
ll dist(const pnt r){
re (x-r.x)*(x-r.x)+(y-r.y)*(y-r.y);
}
pnt rot(const dou theta){
T xx,yy;
xx=cos(theta)*x-sin(theta)*y;
yy=sin(theta)*x+cos(theta)*y;
return pnt(xx,yy);
}
};
istream &operator >> (istream &is,pnt<dou> &r){is>>r.x>>r.y;return is;}
ostream &operator << (ostream &os,pnt<dou> &r){os<<r.x<<" "<<r.y;return os;}
ll MOD= 1000000007;
//#define MOD 1000000007
//#define MOD 10007
//#define MOD 998244353
//ll MOD;
ll mod_pow(ll a, ll b, ll mod = MOD) {
ll res = 1;
for (a %= mod; b; a = a * a % mod, b >>= 1)
if (b & 1) res = res * a % mod;
return res;
}
class mint {
public:
ll a;
mint(ll x=0):a(x%MOD){}
mint operator + (const mint rhs) const {
return mint(*this) += rhs; }
mint operator - (const mint rhs) const {
return mint(*this) -= rhs; }
mint operator * (const mint rhs) const {
return mint(*this) *= rhs; }
mint operator / (const mint rhs) const {
return mint(*this) /= rhs; }
mint &operator += (const mint rhs) {
a += rhs.a; if (a >= MOD) a -= MOD; return *this; }
mint &operator -= (const mint rhs) {
if (a < rhs.a) a += MOD; a -= rhs.a; return *this; }
mint &operator *= (const mint rhs) {
a = a * rhs.a % MOD; return *this; }
mint &operator /= (mint rhs) {
ll exp = MOD - 2; while (exp) { if (exp % 2) *this *= rhs; rhs *= rhs; exp /= 2; } return *this; }
bool operator > (const mint& rhs)const{ return (this->a>rhs.a); }
bool operator < (const mint& rhs)const{ return (this->a<rhs.a); }
bool operator >= (const mint& rhs)const{ return (this->a>=rhs.a); }
bool operator <= (const mint& rhs)const{ return (this->a<=rhs.a);}
bool operator == (const mint& rhs)const{ return (this->a==rhs.a);}
};
istream& operator>>(istream& is, mint& r) { is>>r.a;return is;}
ostream& operator<<(ostream& os, const mint& r) { os<<r.a;return os;}
#define pq priority_queue<ll>
#define top top()
ll sumw(ll v,ll r){ re (v==0?0:sumw(v/10,r)*r+v%10); }
#define com complex<dou>
struct UFS{
map<st,st> par;map<st,ll>rk,siz;
st root(st x){
auto it=par.find(x);
if(it==par.en){
par[x]=x;siz[x]=1;re x;
}
if(par[x]==x)return x;
else return par[x]=root(par[x]);
}
bool same(st x,st y){ return root(x)==root(y); }
bool unite(st x,st y){
st rx=root(x),ry=root(y);
if(rx==ry) return false;
if(rk[rx]<rk[ry]) swap(rx,ry);
siz[rx]+=siz[ry];
par[ry]=rx;
if(rk[rx]==rk[ry]) rk[rx]++;
return true;
}
ll size(st s){
re siz[s];
}
};
//vector<long long> fact, fact_inv, inv;
/* init_nCk :二項係数のための前処理
計算量:O(n)
*/
vll fact,inv,fact_inv;
void init_nCk(int SIZE) {
fact.resize(SIZE + 5);
fact_inv.resize(SIZE + 5);
inv.resize(SIZE + 5);
fact[0] = fact[1] = 1;
fact_inv[0] = fact_inv[1] = 1;
inv[1] = 1;
for (int i = 2; i < SIZE + 5; i++) {
fact[i] = fact[i - 1] * i % MOD;
inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
fact_inv[i] = fact_inv[i - 1] * inv[i] % MOD;
}
}
long long nCk(int n, int k) {
return fact[n] * (fact_inv[k] * fact_inv[n - k] % MOD) % MOD;
}
struct UF{ vll par,rk,siz; UF(ll n):par(n+5,-1),rk(n+5,0){ }
ll root(ll x){ if(par[x]<0)return x; else return par[x]=root(par[x]); }
bool same(ll x,ll y){ return root(x)==root(y); }
bool unite(ll x,ll y){ ll rx=root(x),ry=root(y); if(rx==ry) return false; if(rk[rx]<rk[ry]) swap(rx,ry); par[rx]+=par[ry]; par[ry]=rx; if(rk[rx]==rk[ry]) rk[rx]++; return true; }
ll size(ll x){ return -par[root(x)]; }
};
/* O(2*10^8) 9*10^18 1LL<<62 4*10^18
~~(v.be,v.be+n,x); not include v.be+n
set.lower_bound(x);
->. *++ ! /%* +- << < == & && +=?:
*/
//vll dx={-1,-1,-1,0,0,1,1,1},dy={-1,0,1,-1,1,-1,0,1};
//vll dx={-1,0,0,1},dy={0,-1,1,0};
//#define N 11
#define N 10000000
// 1234567
void solve(){
ge(ll,t);
xx(t){
ll ans=0;
ge(ll,x);
wh(x>9){
string s="1"+string(to_string(x).sz-1,'0');
ll n=stoll(s);
ans+=n;
x-=n;
x+=n/10;
}
ans+=x;
ff(ans);
}
}
| cpp |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | #include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
#define not_less_than(v, n) lower_bound(v.begin(), v.end(), n) // n >=
#define not_more_than(v, n) lower_bound(v.rbegin(), v.rend(), n, greater<int>()) // n <=
#define more_than(v, n) upper_bound(v.begin(), v.end(), n) // n <
#define less_than(v, n) upper_bound(v.rbegin(), v.rend(), n, greater<int>()) // n >
int dx[] = {-1, -1, -1, 0, 0, +1, +1, +1};
int dy[] = {-1, +1, 0, -1, 1, -1, 0, +1};
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n; cin >> n;
vector<int> a(n), b(n);
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
vector<int> v(n);
for(int i = 0; i < n; i++)
{
cin >> b[i];
v[i] = a[i] - b[i];
}
sort(v.begin(), v.end());
int sum = 0;
for(int i = 0; i < n; i++)
{
int ans = 1 - v[i];
int l = i, r = n-1;
while(l <= r)
{
int mid = (l+r)/2;
if(v[mid] >= ans)
r = mid - 1;
else
l = mid + 1;
}
sum += n - l;
if(ans <= 0)
sum--;
}
cout << sum << endl;
} | cpp |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | #include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <array>
#include <deque>
#include <map>
#include <set>
using namespace std ;
void testCase(){
int n , s , k ;
cin >> n >> s >> k ;
map <int,int> mp ;
for ( int i=0; i<k; i++ ){
int a ;
cin >> a ;
mp[a] ++ ;
}
for ( int i=0; i<n; i++ ){
int x = s - i , y = s + i ;
if ( x <= 0 )
x = 1 ;
if ( y > n )
y = n ;
if ( mp[x] == 0 or mp[y] == 0 ){
cout << i << endl ;
return ;
}
}
}
int main(){
int t = 1 ;
cin >> t ;
while ( t -- )
testCase () ;
}
| cpp |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
#include <random>
#include <fstream>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> p32;
typedef pair<ll, ll> p64;
typedef pair<double, double> pdd;
typedef vector<ll> v64;
typedef vector<int> v32;
typedef vector<vector<int>> vv32;
typedef vector<vector<ll>> vv64;
typedef vector<vector<p64>> vvp64;
typedef vector<p64> vp64;
typedef vector<p32> vp32;
ll MOD = 998244353;
double eps = 1e-12;
#define forn(i, e) for (ll i = 0; i < e; i++)
#define forsn(i, s, e) for (ll i = s; i < e; i++)
#define rforn(i, s) for (ll i = s; i >= 0; i--)
#define rforsn(i, s, e) for (ll i = s; i >= e; i--)
#define dbg(x) cout << #x << '=' << x << endl
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define nl cout<<endl
#define ret return
#define INF 2e18
#define fast_cin() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((ll)(x).size())
#define pr(x) cout << x << endl
#define forauto(v) \
for (auto &i : v) \
cout << i << ' '; \
cout << endl;
#define iterate(x) \
for (auto itr = x.begin(); itr != x.end(); ++itr) \
{ \
cout << *itr << ' '; \
} \
cout << endl;
ll myceil(ll a, ll b)
{
if (a % b == 0)
return a / b;
else
return a / b + 1;
}
bool isPerSquare(long double a)
{
if (a < 0)
return false;
ll sr = sqrt(a);
return (sr * sr == a);
}
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)) * b;
}
void sumeet()
{
ll n;
cin >> n;
v64 v(n);
ll ct = 0;
v64 odd, even;
forn(i, n)
{
cin >> v[i];
if (v[i] % 2 == 0)
even.pb(i + 1);
else
odd.pb(i + 1);
}
if (odd.size() == 1 && even.size() == 0)
{
cout << -1;
nl;
ret;
}
if (even.size() == 0)
{
cout << "2\n";
cout << odd[0] << " " << odd[1];
nl; ret;
}
cout << "1\n";
cout << even[0];
nl;
}
int main()
{
fast_cin();
ll t = 1;
cin >> t;
for (int it = 1; it <= t; it++)
{
sumeet();
// cout << endl;
}
return 0;
}
| cpp |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
| [
"data structures",
"dp"
] | #include <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
typedef pair<int, int> PII;
typedef pair<int, PII> PIII;
const int INF = 1e18 + 1;
int n;
string s;
void solve() {
cin >> n >> s;
vector<char> v;
vector<int> res(n, 0);
for (int i = 0; i < n; i++) {
char x = s[i];
auto it = lower_bound(rall(v), x + 1);
// assert(is_sorted(rall(v)));
if (it == v.rbegin()) {
v.push_back(x);
it = v.rbegin();
assert(*it == x);
} else {
if (it != v.rend()) assert(*it > x);
it--;
assert(*it <= x);
*it = x;
}
assert(*it == x);
// assert(is_sorted(rall(v)));
res[i] = v.size() - (it - v.rbegin());
}
cout << v.size() << endl;
for (auto &x : res) cout << x << " ";
cout << "\n";
vector<vector<char>> check(v.size() + 1);
for (int i = 0; i < n; i++) {
check[res[i]].push_back(s[i]);
}
for (auto &x : check) assert(is_sorted(all(x)));
}
#undef int
int main() {
ios::sync_with_stdio(false);
cin.exceptions(cin.failbit);
cin.tie(0);
int t = 1;
#ifdef DUPA
cin >> t;
#endif
for (int i = 0; i < t; i++) solve();
}
| cpp |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes. | [
"brute force",
"strings"
] | #include<bits/stdc++.h>
using namespace std;
int main() {
int x , s , arr[9000];
cin >> x ;
while (x--){
cin >> s ;
for (int i = 0; i < s ; ++i) {
cin >> arr[i];
}
bool y = false ;
for (int i = 0; i < s ; ++i) {
for (int j = i + 2; j < s; ++j) {
if (arr[i] == arr[j]) {
y = true;
break;
}
}
if (y == true) {
break;
}
}
if (y == true) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
}
| 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"
] | // LUOGU_RID: 101363216
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cctype>
#include<vector>
typedef long long ll;
const int _=+10;
using namespace std;
void Read(){}template<typename tp,typename... A>
void Read(tp& c,A&... d){
c=0;char x=getchar();bool op=0;
while(!isdigit(x)) op|=(x=='-'),x=getchar();
while(isdigit(x)) c=(c<<1)+(c<<3)+(x^'0'),x=getchar();
if(op){c=-c;}Read(d...);
}
template<typename tp>void Write(tp c,char x='\n'){
static char Sta[30];unsigned top=0;
if(c<0) c=-c,putchar('-');
do{Sta[top++]=c%10+'0',c/=10;}while(c);
while(top) putchar(Sta[--top]);
if(x) putchar(x);
}
int dfs(int x,vector<int>& c){
if(!~x) return 0;
vector<int> a,b;
for(int i=0;i<(int)c.size();i++){
if(c[i]&(1<<x)) b.push_back(c[i]);
else a.push_back(c[i]);
}
if(a.empty()) return dfs(x-1,b);
if(b.empty()) return dfs(x-1,a);
return min(dfs(x-1,a),dfs(x-1,b))|(1<<x);
}
int main(){
int x;Read(x);
vector<int> a(x);
for(int i=0;i<x;i++) Read(a[i]);
Write(dfs(29,a));
return 0;
}
| cpp |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
typedef unsigned int ui;
typedef long long ll;
#define all(x) x.begin(), x.end()
#define F first
#define S second
#define rep(x, y, z) for(int x = y; x <= z; x++)
#define rrep(x, y, z) for(int x = y; x >= z; x--)
#define arep(x, y) for(auto & x : y)
const int mxN = 1e6 + 5;
int QU = 0;
void solve(){
int n;
cin>>n;
vector<pair<int, int>> p(n);
for(auto & [x, y] : p) cin>>x>>y;
sort(all(p));
pair<int, int> cur = {0, 0};
string ans = "";
bool is = 0;
for(auto & [x, y] : p){
if(x - cur.F < 0 || y - cur.S < 0){
cout<<"NO\n";
return;
}
ans += string(x - cur.F, 'R');
ans += string(y - cur.S, 'U');
cur = {x, y};
}
cout<<"YES\n";
cout<<ans<<'\n';
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cout<<fixed<<setprecision(20);
if(!QU) cin>>QU;
while(QU--){
solve();
}
} | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.