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 |
---|---|---|---|---|---|
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native")
#pragma GCC optimize("fast-math")
#pragma GCC optimize ("unroll-loops,Ofast,O3")
#pragma GCC target("avx,avx2,fma")
#define file(s) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)
#define all(x) (x).begin(),(x).end()
#define int long long
#define rs(p) (p<<1|1)
#define ls(p) (p<<1)
#define pb push_back
#define endl '\n'
#define sz size()
#define F first
#define S second
#define SlimShady ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
const long double eps = 1e-10;
const int MIN = LLONG_MIN;
const int M = 2e9 + 100;
const int N = 1e5 + 100;
void solve() {
int n, k;
cin >> n >> k;
int a[n + 2];
for(int i = 0; i < n; ++i) {
cin >> a[i];
}
for(int i = 1; i < n; ++i) {
while(k >= i and a[i] != 0) {
if(k >= i) {
k -= i;
a[i]--;
a[0]++;
}
}
}
cout << a[0] << endl;
}
signed main ()
{
SlimShady
int test = 1;
cin >> test;
while(test--) {
solve();
}
} | cpp |
1322 | D | D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
OutputCopy6
InputCopy2 2
1 2
0 0
2 1 -100 -100
OutputCopy2
InputCopy5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
OutputCopy62
NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11. | [
"bitmasks",
"dp"
] | // LUOGU_RID: 91777092
#include<cmath>
#include<cstdio>
#include<bitset>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<set>
#include<vector>
#include<map>
#include<random>
#include<ctime>
#include<unordered_map>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pp pair<int,int>
#define LL long long
#define ull unsigned long long
namespace IO{
const int sz=1<<22;
char a[sz+5],b[sz+5],*p1=a,*p2=a,*t=b,p[105];
inline char gc(){
// return p1==p2?(p2=(p1=a)+fread(a,1,sz,stdin),p1==p2?EOF:*p1++):*p1++;
return getchar();
}
template<class T> void gi(T& x){
x=0; int f=1;char c=gc();
if(c=='-')f=-1;
for(;c<'0'||c>'9';c=gc())if(c=='-')f=-1;
for(;c>='0'&&c<='9';c=gc())
x=x*10+(c-'0');
x=x*f;
}
inline void flush(){fwrite(b,1,t-b,stdout),t=b; }
inline void pc(char x){*t++=x; if(t-b==sz) flush(); }
template<class T> void pi(T x,char c='\n'){
if(x<0)pc('-'),x=-x;
if(x==0) pc('0'); int t=0;
for(;x;x/=10) p[++t]=x%10+'0';
for(;t;--t) pc(p[t]); pc(c);
}
struct F{~F(){flush();}}f;
}
using IO::gi;
using IO::pi;
using IO::pc;
const int mod=1e9+7;
inline int add(int x,int y){
return x+y>=mod?x+y-mod:x+y;
}
inline int dec(int x,int y){
return x-y<0?x-y+mod:x-y;
}
int qkpow(int a,int b){
int ans=1,base=a%mod;
while(b){
if(b&1)ans=1ll*ans*base%mod;
base=1ll*base*base%mod;
b>>=1;
}
return ans;
}
int fac[10000005],inv[10000005],Invn[600005];
inline int C(int n,int m){
if(n<m||m<0)return 0;
return 1ll*fac[n]*inv[m]%mod*inv[n-m]%mod;
}
void init_C(int n){
fac[0]=1;
for(int i=1;i<=n;i++)fac[i]=1ll*fac[i-1]*i%mod;
inv[0]=1;
inv[n]=qkpow(fac[n],mod-2);
for(int i=n-1;i>=1;i--)inv[i]=1ll*inv[i+1]*(i+1)%mod;
Invn[0]=Invn[1]=1;
for(int i=1;i<=200000;i++)Invn[i]=(LL)(mod-mod/i)*Invn[mod%i]%mod;
}
int n,m,a[2005],b[2005],c[4005],dp[4005][4005],val[4005][4005];
const int INF=-1e9;
struct bittree{
int t[4005];
int lowbit(int x){
return x&-x;
}
void init(){
for(int i=1;i<=n+m;i++)t[i]=INF;
}
void add(int x,int v){
while(x<=+m){
t[x]=max(t[x],v);
x+=lowbit(x);
}
}
int query(int x){
int res=INF;
while(x>=1){
res=max(res,t[x]);
x-=lowbit(x);
}
return res;
}
}T;
signed main(){
gi(n),gi(m);
for(int i=1;i<=n;i++)gi(a[i]);
T.init();
for(int i=1;i<=n;i++)gi(b[i]);
for(int i=1;i<=n+m;i++)gi(c[i]);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
dp[i][j]=val[i][j]=INF;
for(int i=n;i>=1;i--){
int fk=T.query(a[i]-1);
dp[i][1]=max(dp[i][1],c[a[i]]-b[i]+max(fk,0));
for(int j=1;j<=n;j++)
if(val[a[i]][j]!=INF)dp[i][j]=max(dp[i][j],val[a[i]][j]+c[a[i]]-b[i]);
for(int j=1;j<=n;j++){
if(dp[i][j]!=INF){
int now=a[i],gs=j,res=0;
val[now][gs+1]=max(val[now][gs+1],dp[i][j]);
while(gs){
res+=gs/2*c[now+1];
gs/=2,now++;
val[now][gs+1]=max(val[now][gs+1],dp[i][j]+res);
}
T.add(now,dp[i][j]+res);
}
}
}
int ans=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(dp[i][j]!=INF){
int now=a[i],gs=j,res=0;
while(gs){
res+=gs/2*c[now+1];
gs/=2,now++;
}
ans=max(ans,res+dp[i][j]);
}
}
}
pi(ans,'\n');
return 0;
}
/*
4 3 1 1
*/ | 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<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<unordered_map>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstdlib>
#include<stack>
#include<ctime>
#define forin(i,a,n) for(int i=a;i<=n;i++)
#define forni(i,n,a) for(int i=n;i>=a;i--)
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=3e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
int T;
int n,m,k;
int w[N];
void solve() {
n=read();
for(int i=1;i<=n;i++) w[i]=read();
int minn=1e9,maxn=-1;
for(int i=1;i<=n;i++) {
if(w[i]==-1) {
if(i-1>=1&&w[i-1]!=-1) minn=min(minn,w[i-1]),maxn=max(maxn,w[i-1]);
if(i+1<=n&&w[i+1]!=-1) minn=min(minn,w[i+1]),maxn=max(maxn,w[i+1]);
}
}
if(minn==1e9) {
printf("0 0\n");
return ;
}
int ans=(minn+maxn)/2;
int res=0;
for(int i=2;i<=n;i++) {
if(w[i-1]==-1&&w[i]==-1) res=max(res,0);
else if(w[i-1]==-1&&w[i]!=-1) res=max(res,abs(ans-w[i]));
else if(w[i-1]!=-1&&w[i]==-1) res=max(res,abs(w[i-1]-ans));
else res=max(res,abs(w[i-1]-w[i]));
}
printf("%d %d\n",res,ans);
}
int main() {
// init();
// stin();
scanf("%d",&T);
// T=1;
while(T--) solve();
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 <iostream>
#include <map>
#include <vector>
#define ll int
using namespace std;
int32_t main() {
ll t;
cin >> t;
for (ll i = 0; i < t; i++){
ll n, x, y;
cin >> n >> x >> y;
ll res1, res2;
res1 = min(std::max(1, x + y - n + 1), n);
res2 = min(x + y - 1, n);
cout << res1 << ' ' << res2 << endl;
}
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>
#define ll long long
#define ull unsigned long long
#define ff first
#define sc second
#define pb push_back
#define pii pair<int, int>
#define pll pair<ll, ll>
using namespace std;
const ll mod = 1e9 + 7;
void solve(){
int n;
cin >> n;
string a, b;
cin >> a >> b;
vector <pii> ans;
unordered_map <char, vector <int>> A;
unordered_map <char, vector <int>> B;
for(int i = 0; i < n; i++){
A[a[i]].pb(i + 1);
B[b[i]].pb(i + 1);
}
for(char i = 'a'; i <= 'z'; i++){
while(A[i].size() and B[i].size()){
ans.pb({A[i].back(), B[i].back()});
A[i].pop_back();B[i].pop_back();
}
while(A[i].size() and B['?'].size()){
ans.pb({A[i].back(), B['?'].back()});
A[i].pop_back();B['?'].pop_back();
}
while(A['?'].size() and B[i].size()){
ans.pb({A['?'].back(), B[i].back()});
A['?'].pop_back();B[i].pop_back();
}
}
while(A['?'].size() and B['?'].size()){
ans.pb({A['?'].back(), B['?'].back()});
A['?'].pop_back();B['?'].pop_back();
}
cout << ans.size() << '\n';
for(int i = 0; i < ans.size(); i++){
cout << ans[i].ff << ' ' << ans[i].sc << '\n';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int T = 1;
//cin >> T;
while(T--){
solve();
cout << '\n';
}
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 <iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
if(n%m==0){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
}
| 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: 97884369
# include <bits/stdc++.h>
using namespace std;
int n,m,K,w[200010],f[200010][300],g[300],tn[300][300];
pair<int,int> ok[100010];
vector<int> op[200010];
vector<pair<int,int> > kl;
int main() {
// freopen("in.in","r",stdin);
// freopen("out.out","w",stdout);
scanf("%d%d%d",&n,&m,&K);
for (int i=1;i<=n;i++) scanf("%d%d",&ok[i].first,&ok[i].second);
for (int i=0;i<1<<K;i++) for (int j=0;j<1<<K;j++) for (int k=0,cnt=0;k<K;k++) if (j&(1<<k)) tn[i][j]|=((i>>k)&1)<<cnt, cnt++;
vector<int> lsh;
for (int i=1;i<=n;i++) lsh.push_back(ok[i].first), lsh.push_back(ok[i].second+1);
sort(lsh.begin(),lsh.end()), lsh.erase(unique(lsh.begin(),lsh.end()),lsh.end());
for (int i=1;i<=n;i++) ok[i].first=lower_bound(lsh.begin(),lsh.end(),ok[i].first)-lsh.begin()+1, ok[i].second=lower_bound(lsh.begin(),lsh.end(),ok[i].second+1)-lsh.begin();
m=lsh.size();
for (int i=1;i<=m;i++) w[i]=lsh[i]-lsh[i-1];
for (int i=1;i<=n;i++) op[ok[i].first].push_back(ok[i].second);
for (int i=1;i<=m;i++) {
int cnt=kl.size();
for (auto o : op[i]) kl.push_back(pair<int,int> (i,o));
for (int j=0;j<1<<(int)kl.size();j++) f[i][j]=max(f[i][j],f[i-1][j&((1<<cnt)-1)]+__builtin_popcount(j)%2*w[i]);
int oi=0;
vector<pair<int,int> > kk;
for (int j=0;j<(int)kl.size();j++) if (kl[j].second>i) oi|=1<<j, kk.push_back(kl[j]);
for (int j=0;j<1<<(int)kl.size();j++) g[tn[j][oi]]=max(g[tn[j][oi]],f[i][j]);
kl=kk, memcpy(f[i],g,sizeof(g)), memset(g,0,sizeof(g));
}
printf("%d\n",f[m][0]);
return 0;
} | cpp |
1305 | H | H. Kuroni the Private Tutortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a professional private tutor; Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.The exam consists of nn questions, and mm students have taken the exam. Each question was worth 11 point. Question ii was solved by at least lili and at most riri students. Additionally, you know that the total score of all students is tt.Furthermore, you took a glance at the final ranklist of the quiz. The students were ranked from 11 to mm, where rank 11 has the highest score and rank mm has the lowest score. Ties were broken arbitrarily.You know that the student at rank pipi had a score of sisi for 1≤i≤q1≤i≤q.You wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students.InputThe first line of input contains two integers (1≤n,m≤1051≤n,m≤105), denoting the number of questions of the exam and the number of students respectively.The next nn lines contain two integers each, with the ii-th line containing lili and riri (0≤li≤ri≤m0≤li≤ri≤m).The next line contains a single integer qq (0≤q≤m0≤q≤m). The next qq lines contain two integers each, denoting pipi and sisi (1≤pi≤m1≤pi≤m, 0≤si≤n0≤si≤n). It is guaranteed that all pipi are distinct and if pi≤pjpi≤pj, then si≥sjsi≥sj.The last line contains a single integer tt (0≤t≤nm0≤t≤nm), denoting the total score of all students.OutputOutput two integers: the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students. If there is no valid arrangement that fits the given data, output −1−1 −1−1.ExamplesInputCopy5 4
2 4
2 3
1 1
0 1
0 0
1
4 1
7
OutputCopy3 2
InputCopy5 6
0 6
0 6
2 5
6 6
4 6
1
3 3
30
OutputCopy-1 -1
NoteFor the first sample; here is one possible arrangement that fits the data:Students 11 and 22 both solved problems 11 and 22.Student 33 solved problems 22 and 33.Student 44 solved problem 44.The total score of all students is T=7T=7. Note that the scores of the students are 22, 22, 22 and 11 respectively, which satisfies the condition that the student at rank 44 gets exactly 11 point. Finally, 33 students tied for first with a maximum score of 22, and it can be proven that we cannot do better with any other arrangement. | [
"binary search",
"greedy"
] | #include<bits/stdc++.h>
template <typename _Tp>void read(_Tp &x){
char ch(getchar());bool f(false);while(!isdigit(ch))f|=ch==45,ch=getchar();
x=ch&15,ch=getchar();while(isdigit(ch))x=x*10+(ch&15),ch=getchar();
if(f)x=-x;
}
template <typename _Tp,typename... Args>void read(_Tp &t,Args &...args){read(t);read(args...);}
const int N=100005;typedef long long ll;
int L[N],R[N],p[N],s[N],a[N],n,m,val[N],VAL[N];ll t,lim[N],b[N],suf[N];
ll calc1(int mid){ll tot=0;for(int i=1;i<=n;++i)tot+=std::min(R[i],std::max(L[i],mid));return tot;}
bool check(int mid){
int x=-1,y=-1;for(int i=1;i<=mid;++i)if(val[i]!=-1)(x==-1?x:y)=val[i];
if(x!=-1&&y!=-1&&x!=y)return 0;
if(x==-1&&y==-1){
ll tmp=1e18,tot=0;
for(int i=1;i<=m;++i)tot+=i>mid?VAL[i]:0,tmp=std::min(tmp,(lim[i]-tot)/std::min(i,mid));
for(int i=1;i<=m;++i)b[i]=i<=mid?tmp:VAL[i];
}
else for(int i=1;i<=m;++i)b[i]=i<=mid?x:VAL[i];
ll tot=0;for(int i=1;i<=m;++i){tot+=b[i],suf[i]=lim[i]-tot;if(tot>lim[i])return 0;}
suf[m+1]=1e18;for(int i=m;i>=1;--i)suf[i]=std::min(suf[i],suf[i+1]);
ll sum=0;for(int i=mid+1;i<=m;++i)if(val[i]==-1)b[i]=std::min(VAL[i]+suf[i]-sum,b[i-1]),sum+=b[i]-VAL[i];
for(int i=1;i<m;++i)if(b[i]<b[i+1])return 0;
return sum+tot==t;
}
int main(){
read(n,m);
for(int i=1;i<=n;++i)read(L[i],R[i]);
int q;read(q);
memset(val,-1,sizeof(val));
for(int i=1;i<=q;++i)read(p[i],s[i]),val[p[i]]=s[i],VAL[p[i]]=s[i];
for(int i=m;i>=1;--i)if(!VAL[i])VAL[i]=VAL[i+1];
read(t);int l=0,r=m,mid;
while(l<r)mid=(l+r+1)>>1,calc1(mid)<=t?l=mid:r=mid-1;
ll tot=0;for(int i=1;i<=n;++i)a[i]=std::min(R[i],std::max(L[i],l)),tot+=a[i];
for(int i=1;i<=n;++i)if(tot<t&&a[i]!=R[i]&&a[i]==l)++a[i],++tot;
std::sort(a+1,a+n+1);
for(int i=1,j=1;i<=m;++i){
while(j<=n&&a[j]<i)++j;
lim[i]=std::min(t,lim[i-1]+n-j+1);
}
l=1,r=m;while(l<r)mid=(l+r+1)>>1,check(mid)?l=mid:r=mid-1;
if(!check(l))return puts("-1 -1"),0;
printf("%d %lld\n",l,b[1]);
return 0;
} | cpp |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int a, b;
cin >> a >> b;
if (b > a) {
int x = b - a;
if (x % 2 == 0) {
cout << 2 << endl;
}
else {
cout << 1 << endl;
}
}
else if (a == b) {
cout << 0 << endl;
}
else if (a > b) {
int r = a - b;
if (r % 2 == 0) {
cout << 1 << endl;
}
else {
cout << 2 << endl;
}
}
}
return 0;
} | cpp |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--){
int a,b;
cin>>a>>b;
if(a<b){
int x=b-a;
if(x%2==0){
cout<<2<<endl;
}
else{
cout<<1<<endl;
}
}
else if(a==b){
cout<<0<<endl;
}
else{
int h=a-b;
if(h%2==0){
cout<<1<<endl;
}
else{
cout<<2<<endl;
}
}
}
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>
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
uniform_real_distribution<> pp(0.0,1.0);
#define int long long
#define pii pair<int,int>
#define maxn 150005
const int inf=1e18;
struct node{
int sum,len0,len1,cnt;
};
struct line{
mutable int a,b,p;
bool operator<(const line &o)const{return a<o.a;}
bool operator<(int o)const{return p<o;};
};
struct dcht:multiset<line,less<>>{
int div(int a,int b){
return (a/b)-((a^b)<0 && a%b);
}
bool isect(iterator x,iterator y){
if(y==end()){x->p=inf;return 0;}
if(x->a==y->a) x->p=(x->b>=y->b)?inf:-inf;
else x->p=div(y->b-x->b,x->a-y->a);
return x->p>=y->p;
}
void add_line(line l){
auto z=insert(l),y=z++,x=y;
while(isect(y,z)) z=erase(z);
if(x!=begin() && isect(--x,y)) isect(x,erase(y));
while((y=x)!=begin() && (--x)->p>=y->p) isect(x,erase(y));
}
int query(int v){
auto l=*lower_bound(v);
return l.a*v+l.b;
}
}s[2];
vector<int> edge[maxn];
int n,a[maxn],ans,child[maxn],sz;
bool used[maxn];
vector<node> total[maxn];
void dfs(int u,int par){
child[u]=1;
for(int v:edge[u]){
if(v==par || used[v]) continue;
dfs(v,u);
child[u]+=child[v];
}
}
int findcen(int u,int par){
for(int v:edge[u]){
if(v==par || used[v]) continue;
if(child[v]>sz/2) return findcen(v,u);
}
return u;
}
void calc(int u,int par,int anc,int add,int len0,int len1,int sum,int cnt){
cnt++;sum+=a[u];
len0+=cnt*a[u];len1+=sum;
total[anc].push_back({sum,len0,len1,cnt});
ans=max(ans,len0+s[1].query(sum+add)+sum+add);
ans=max(ans,len1+(cnt+1)*add+s[0].query(cnt+1));
for(int v:edge[u]){
if(v==par || used[v]) continue;
calc(v,u,anc,add,len0,len1,sum,cnt);
}
}
void decompose(int u,int par){
dfs(u,par);sz=child[u];
int cen=findcen(u,par);
used[cen]=true;
s[0].clear();s[1].clear();
for(int v:edge[cen]){
if(v==par || used[v]) continue;
total[v].clear();
calc(v,cen,v,a[cen],0,0,0,0);
for(node x:total[v]){
s[0].add_line({x.sum,x.len0,inf});
s[1].add_line({x.cnt,x.len1,inf});
}
}
for(int v:edge[cen]){
if(v==par || used[v]) continue;
decompose(v,cen);
}
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
cin >> n;
for(int i=1;i<n;i++){
int u,v;cin >> u >> v;
edge[u].push_back(v);
edge[v].push_back(u);
}
for(int i=1;i<=n;i++) cin >> a[i];
decompose(1,0);
cout << ans << '\n';
}
| cpp |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | #pragma GCC optimize("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[1000001];
string s;
int main(){
cin >> t;
cin >> s;
cout << t + 1;
}
| cpp |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | #include <bits/stdc++.h>
using namespace std;
/*<DEBUG>*/
#define tem template <typename
#define can_shift(_X_, ...) enable_if_t<sizeof test<_X_>(0) __VA_ARGS__ 8, debug&> operator<<(T i)
#define _op debug& operator<<
tem C > auto test(C *x) -> decltype(cerr << *x, 0LL);
tem C > char test(...);
tem C > struct itr{C begin, end; };
tem C > itr<C> get_range(C b, C e) { return itr<C>{b, e}; }
struct debug{
#ifdef _LOCAL
~debug(){ cerr << endl; }
tem T > can_shift(T, ==){ cerr << boolalpha << i; return *this; }
tem T> can_shift(T, !=){ return *this << get_range(begin(i), end(i)); }
tem T, typename U > _op (pair<T, U> i){
return *this << "< " << i.first << " , " << i.second << " >"; }
tem T> _op (itr<T> i){
*this << "{ ";
for(auto it = i.begin; it != i.end; it++){
*this << " , " + (it==i.begin?2:0) << *it;
}
return *this << " }";
}
#else
tem T> _op (const T&) { return *this; }
#endif
};
tem T>
string _ARR_(T* arr, int sz){
string ret = "{ " + to_string(arr[0]);
for(int i = 1; i < sz; i++) ret += " , " + to_string(arr[i]);
ret += " }"; return ret;
}
#define exp(...) " [ " << #__VA_ARGS__ << " : " << (__VA_ARGS__) << " ]"
/*</DEBUG>*/
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef unsigned int uint;
typedef pair<int, int> pii;
//mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
#define pb push_back
#define FAST ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define TC int __TC__; cin >> __TC__; while(__TC__--)
#define ar array
const int INF = 1e9 + 7;
const int N = 100005, X = 320;
int n, m, a[N], out[N], jmp[N];
void calc(int start, int end){
for(int i = start; i >= end; --i){
if(a[i] + i > n || i/X < (a[i] + i) / X){
out[i] = i;
jmp[i] = 1;
}
else{
out[i] = out[a[i] + i];
jmp[i] = 1 + jmp[a[i] + i];
}
}
return;
}
int main()
{
FAST;
cin >> n >> m;
for(int i = 1; i <= n; ++i) cin >> a[i];
calc(n, 0);
for(int i = 0; i < m; ++i){
int t; cin >> t;
if(!t){
int x, v; cin >> x >> v;
a[x] = v;
calc(min(n, (x/X)*X + X), (x/X)*X);
}else{
int x; cin >> x;
int jumps = 0;
while(out[x] + a[out[x]] <= n){
jumps += jmp[x];
x = out[x] + a[out[x]];
}
jumps += jmp[x];
cout << out[x] << ' ' << jumps << '\n';
}
}
return 0;
}
| cpp |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105) — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | #include<cstdio>
int a[200100][30],Q,l,r;
char S[200100];
int main(){
scanf("%s",S+1);
for(int i=1;S[i];i++){
for(int j=0;j<26;j++)
a[i][j]=a[i-1][j];
a[i][S[i]-'a']++;
}
scanf("%d",&Q);
while(Q--){
scanf("%d%d",&l,&r);
int cnt=0;
for(int i=0;i<26;i++)
if(a[l-1][i]!=a[r][i])cnt++;
if(cnt>2||S[l]!=S[r]||l==r)puts("Yes");
else puts("No");
}
} | 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 ll long long
#define sz(x) (x).size()
#define all(x) (x).begin(), (x).end()
#define tv ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
ll n,m,t;
void x(){
int a,b;
cin>>a>>b;
if(a<b)swap(a,b);
if(a%b==0)cout<<"YES\n";
else cout<<"NO\n";
}
int main(){tv cin>>t;
while(t--){
x();
}
return 0;
}
| cpp |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | #include <bits/stdc++.h>
#define all(x) x.begin(), x.end()
#define r_all(x) x.rbegin(), x.rend()
#define sz(x)(ll) x.size()
#define g_max(x, y) x = max(x, y)
#define g_min(x, y) x = min(x, y)
#define rsz(a, n) a.resize(n)
#define ass(a, n) a.assign(n, 0)
#define YES() cout << "YES\n"
#define Yes cout << "Yes\n"
#define NO() cout << "NO\n"
#define No() cout << "No\n"
#define n_line() cout << "\n"
using namespace std;
using ll = long long;
using ld = long double;
using vll = vector<ll>;
using vvll = vector<vll>;
using vc = vector<char>;
using vvc = vector<vc>;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
using vvpll = vector<vpll>;
using stkll = stack<ll>;
using qll = queue<ll>;
using dqll = deque<ll>;
using sll = set<ll>;
using sc = set<char>;
using msll = multiset<ll>;
using mll = map<ll, ll>;
using vsll = vector<sll>;
using pcll = pair<char, ll>;
template<class T>
vector<T> operator+(vector<T> a, vector<T> b) {
a.insert(a.end(), b.begin(), b.end());
return a;
}
pll operator+(pll a, pll b) {
pll ans = {a.first + b.first, a.second + b.second};
return ans;
}
template<class A, class B>
ostream &operator<<(ostream &os,
const pair<A, B> &p) {
os << p.first << " " << p.second;
return os;
}
template<class A, class B>
istream &operator>>(istream &is, pair<A, B> &p) {
is >> p.first >> p.second;
return is;
}
template<class T>
ostream &operator<<(ostream &os,
const vector<T> &vec) {
for (auto &x: vec) {
os << x << " ";
}
return os;
}
template<class T>
istream &operator>>(istream &is, vector<T> &vec) {
for (auto &x: vec) {
is >> x;
}
return is;
}
template<class T>
ostream &operator<<(ostream &os,
const set<T> &vec) {
for (auto &x: vec) {
os << x << " ";
}
return os;
}
template<class A, class B>
ostream &operator<<(ostream &os,
const map<A, B> d) {
for (auto &x: d) {
os << "(" << x.first << " " << x.second << ") ";
}
return os;
}
template<class A>
void read_arr(A a[], ll from, ll to) {
for (ll i = from; i <= to; i++) {
cin >> a[i];
}
}
template<class A>
void print_arr(A a[], ll from, ll to) {
for (ll i = from; i <= to; i++) {
cout << a[i] << " ";
}
cout << "\n";
}
template<class A>
void set_arr(A a[], A val, ll from, ll to) {
for (ll i = from; i <= to; i++) {
a[i] = val;
}
}
ll dr[] = {0, 1, 0, -1}, dc[] = {-1, 0, 1, 0};
//ll dr[] = {1, 0}, dc[] = {0, 1};
const ll INF = 1e18;
const ll MOD = 1e9 + 7;
const ll M = 13010;
struct Dsu {
ll n;
vll par;
void init(ll n_sz) {
n = n_sz;
par.assign(n, 0);
for (ll i = 0; i < n; i++) {
par[i] = i;
}
}
ll find_st(ll v) {
return (par[v] == v) ? par[v] : par[v] = find_st(par[v]);
}
ll union_st(ll u, ll v) {
u = find_st(u), v = find_st(v);
if (u == v) {
return 0;
}
par[v] = u;
return 1;
}
};
struct Smt {
ll n;
vll tree;
void init(ll _n) {
n = _n;
tree.assign(4 * n + 10, 0);
}
void build(ll left, ll right, ll node, vll &v) {
if (left == right) {
tree[node] = v[left];
return;
}
ll mid = (left + right) >> 1;
build(left, mid, 2 * node + 1, v);
build(mid + 1, right, 2 * node + 2, v);
tree[node] = max(tree[2 * node + 1], tree[2 * node + 2]);
return;
}
ll query(ll left, ll right, ll node, ll from, ll to) {
if (left > to || right < from) {
return -INF;
}
if (left >= from && right <= to) {
return tree[node];
}
ll mid = (left + right) >> 1;
ll q1 = query(left, mid, 2 * node + 1, from, to);
ll q2 = query(mid + 1, right, 2 * node + 2, from, to);
return max(q1, q2);
}
void update(ll left, ll right, ll node, ll id, ll val) {
if (left > id || right < id) {
return;
}
if (left == right) {
tree[node] = val;
return;
}
ll mid = (left + right) >> 1;
update(left, mid, 2 * node + 1, id, val);
update(mid + 1, right, 2 * node + 2, id, val);
tree[node] = max(tree[2 * node + 1], tree[2 * node + 2]);
}
};
void memset64(ll dest[], ll val, ll sz) {
for (ll i = 0; i < sz; i++) {
dest[i] = val;
}
}
void print(ll a[], ll from, ll to) {
for (ll i = from; i <= to; i++) {
cout << a[i] << " ";
}
cout << "\n";
}
ll gcd_extended(ll a, ll b, ll *x, ll *y) {
if (a == 0) {
*x = 0LL, *y = 1LL;
return b;
}
ll x1, y1;
ll g = gcd_extended(b % a, a, &x1, &y1);
*x = y1 - (b / a) * x1;
*y = x1;
return g;
}
ll mod_pow(ll p, ll n) {
ll res = 1;
while (n) {
if (n & 1) {
res = (res * p) % MOD;
}
p = (p * p) % MOD;
n >>= 1;
}
return res;
}
ll mod_inverse(ll b) {
ll x, y;
ll g = gcd_extended(b, MOD, &x, &y);
if (g != 1) {
return -1;
}
return (x % MOD + MOD) % MOD;
}
ll mod_divide(ll a, ll b) {
a %= MOD;
ll inv = mod_inverse(b) % MOD;
if (inv == -1) {
return -1;
}
return (a * inv) % MOD;
}
ll mod_fact(ll n) {
if (n < 0) {
return 0;
}
ll ans = 1;
for (ll i = 2; i <= n; i++) {
ans *= i;
ans %= MOD;
}
return ans;
}
ll nPr(ll n, ll r) {
if (n < r) {
return 0;
}
if (r == 0) {
return 1;
}
ll ans = mod_fact(n) * mod_inverse(mod_fact(n - r));
ans %= MOD;
return ans;
}
ll nCr(ll n, ll r) {
if (n < r) {
return 0;
}
ll ans = mod_fact(n) * (mod_inverse(mod_fact(n - r)) % MOD);
ans %= MOD;
ans = (ans * mod_inverse(mod_fact(r)));
return ans;
}
mll factorize(ll x) {
mll dict;
ll tmp = x;
while (x % 2 == 0) {
dict[2]++;
x /= 2;
}
for (ll i = 3; i * i <= tmp; i++) {
while (x % i == 0) {
x /= i;
dict[i]++;
}
}
if (x > 1) {
dict[x]++;
}
return dict;
};
ll is_palindrome(string &str) {
string rev = str;
reverse(all(str));
return rev == str;
}
const ll N = 3e5 + 100;
ll n, m, k, q;
ll a[N], b[N];
vvll grid;
string s, s1, s2;
ll fact[N];
void init() {
}
ll get_ans() {
fact[0] = 1;
for (ll i = 1; i <= n; i++) {
fact[i] = (fact[i - 1] * i) % m;
}
ll ans = 0;
for (ll len = 0; len <= n; len++) {
ll cur = (fact[n - len + 1] * fact[len]) % m;
cur = (cur * (n - len + 1)) % m;
ans = (ans + cur) % m;
}
return ans;
}
void single(ll t_id = 0) {
cin >> n >> m;
cout << get_ans() << "\n";
}
void multiple() {
init();
ll t;
cin >> t;
for (ll i = 0; i < t; i++) {
single(i);
}
}
//#endif
#if 0
void multiple() {
while (cin >> n >> m) {
if (n == 0 && m == 0) {
break;
}
single();
}
#endif
int main(int argc, char *argv[]) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
// freopen("../input.txt", "r", stdin);
// multiple();
single();
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: 101230917
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,sse2,sse3,sse4,mmx,arch=cannonlake,tune=cannonlake")
#define query(pos) (a[*lower_bound(stk + 1, stk + 1 + r, (pos))])
#define endl '\n'
using std::cin;
using std::cout;
using std::lower_bound;
using std::map;
using std::string;
using std::upper_bound;
constexpr long long N = 6e5 + 514;
constexpr long long mask = (1 << 30) - 1;
long long nxt[N], anc[N];
string s;
long long a[N]; // 串和 w 数组
long long stk[N]; // 单调栈
long long r; // 栈顶
__int128 ans, sum;
long long tmp1, tmp2; // tmp for output
long long n;
char c;
map<long long, long long> cnt;
void output(__int128 out) {
std::ios::sync_with_stdio(false);
cout.tie(nullptr);
constexpr long long P = 1e18;
if (out < P) {
cout << (long long)out << endl;
} else {
tmp1 = out / P, tmp2 = out % P;
cout << tmp1 << std::setw(18) << std::setfill('0') << tmp2 << endl;
}
}
int main() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
s.reserve(N);
cin >> n;
cin >> c >> a[0];
s += c; // 第一次加字符不需要加密
ans = a[0]; // 第一次加数字同理
stk[++r] = 0;
cout << a[0] << endl; // 因此直接输出就行了
for (long long i = 1, j = 0; i < n; ++i) {
cin >> c >> a[i];
c = (c - 'a' + ans % 26) % 26 + 'a';
s += c; // 字符加密
a[i] = a[i] ^ (ans & mask); // 数字加密
/* KMP */
while (j && c != s[j]) {
j = nxt[j];
}
if (s[j] == c) {
++j;
}
nxt[i + 1] = j;
if (c == s[nxt[i]]) {
anc[i] = anc[nxt[i]];
} else {
anc[i] = nxt[i];
}
for (long long k = i; k > 0;) {
if (s[k] == c) {
k = anc[k];
} else {
long long v = query(i - k);
--cnt[v];
sum -= v;
if (cnt[v] == 0) {
cnt.erase(v);
}
k = nxt[k];
}
}
if (s[0] == c) {
++cnt[a[i]];
sum += a[i];
}
/* 单调栈 */
while (r && a[i] <= a[stk[r]]) {
--r;
}
stk[++r] = i;
long long ncnt = 0; // 当前长度 border 的数量(大概
for (auto it = cnt.upper_bound(a[i]);;) {
if (it == cnt.end()) break;
sum -= (it->first - a[i]) * it->second;
ncnt += it->second;
auto j = std::next(it);
cnt.erase(it);
it = j;
}
cnt[a[i]] += ncnt;
ans += a[stk[1]] + sum;
output(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 <bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll tc = 1;
cin >> tc;
while (tc--) {
ll n;
cin >> n;
string s;
cin >> s;
vector<ll> small(n, -1), big(n, -1);
ll off = n, st = 1;
for (ll x = 0; x < n - 1; x++) {
if (s[x] == '>') {
small[x] = off;
big[x] = off;
off--;
}
}
for (ll x = n - 1; x >= 0; x--) {
if (small[x] == -1) {
ll y = x;
while (small[y] == -1) {
y--;
}
for (ll z = y + 1; z <= x; z++) {
small[z] = st++;
}
}
}
for (auto x : small) {
cout << x << " ";
}
cout << '\n';
st = 1;
for (auto &x : big) {
if (x == -1) {
x = st++;
}
cout << x << " ";
}
cout << '\n';
}
return 0;
} | cpp |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
#include<iostream>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#include<math.h>
#include<algorithm>
#include<vector>
#include<stdbool.h>
using std::cout;
const int N = 3000008;
using namespace std;
int main(){
ll t;
cin>>t;
while(t--){
ll n;
cin>>n;
set<ll> b;
while(n--){
int a;
cin>>a;
b.insert(a);
}
cout<<b.size()<<"\n";
}
} | cpp |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences. | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define ll long long
#define MOD 1000000007
using namespace std;
int main()
{
ll n,cou=0,ans=0;
cin >> n;
vector<ll> arr1,arr2;
for(ll i=0;i<n;i++){
ll x,mx=-1,mn=1000000,f=0;
cin >> x;
vector<ll> a(x+100);
for(ll i=0;i<x;i++){
ll y;
cin >> a[i];
if(a[i]>mn)f=1;
mx= max(mx,a[i]);
mn= min(mn,a[i]);
}
if(!f){
arr1.push_back(mn);
arr2.push_back(mx);
}
else {
cou++;
}
}
sort(arr1.begin(),arr1.end());
sort(arr2.begin(),arr2.end());
for(ll i=0;i<arr2.size();i++){
ll p= lower_bound(arr1.begin(),arr1.end(),arr2[i])- arr1.begin();
if(arr1[p]>arr2[i])
ans+= p;
else ans+= p;
}
ans+= arr1.size()*cou*2 + cou*cou;
cout << ans << 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;
const int N = 1505;
int sums[N];
void solve() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> sums[i];
sums[i] += sums[i - 1];
}
unordered_map<int, vector<pair<int, int>>> pos;
for (int j = 1; j <= n; ++j) { // 这样就不需要排序了
for (int i = 1; i <= j; ++i) {
// cout << i << " " << j << "\n";
pos[sums[j] - sums[i - 1]].emplace_back(i, j);
}
}
// for (auto &[fi, se] : pos[3]) cout << fi << " " << se << "\n";
int cnt = 0, val = 0;
for (auto &[v, vec] : pos) {
if (vec.size() < cnt) continue;
int last = -1, cur = 0;
for (auto &[fi, se] : vec) {
if (fi <= last) continue;
++cur;
last = se;
}
if (cur > cnt) {
cnt = cur;
val = v;
}
}
cout << cnt << '\n';
int last = -1;
for (auto &[fi, se] : pos[val]) {
if (fi <= last) continue;
cout << fi << " " << se << "\n";
last = se;
}
}
int main() {
cin.tie(0)->sync_with_stdio(0);
solve();
return 0;
} | cpp |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | #include<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 |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
| [
"math"
] | #include <bits/stdc++.h>
#define nl << "\n"
#define spc << " " <<
#define pt cout <<
using namespace std;
typedef long long ll;
#define int long long
#define pii pair<int, int>
int mod = 1e9 + 7;
int MAX = 1e9 + 1;
int MIN = -1e9;
double eps = 1e-7;
int dieTime(int req,vector<int> &arr,int n){
for(int i=0;i<n;i++){
req += arr[i];
if(req <= 0)
return i+1;
}
return n;
}
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int h,n,netDam = 0,minDam = MAX; cin >> h >> n;
vector<int> arr(n);
for(int i=0;i<n;i++){
cin >> arr[i];
netDam += arr[i];
minDam = min(minDam,netDam);
}
minDam = abs(minDam);
if(h <= minDam)
pt dieTime(h, arr, n) nl;
else if(netDam >= 0)
pt -1 nl;
else{
netDam = abs(netDam);
// pt minDam spc h spc netDam nl;
int num = ceil((double)(h-minDam)/netDam);
// pt num nl;
h = h-num*netDam;
int ans = num*n;
// pt ans nl;
ans += dieTime(h, arr, n);
pt ans nl;
}
}
| cpp |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | #include<bits/stdc++.h>
#define endl '\n'
#define iloveds std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define all(a) a.begin(),a.end()
#define int long long
using namespace std;
typedef long long ll ;
const int N = 1e5 + 100;
ll u, v;
signed main(){
iloveds;
cin >> u >> v;
ll delta = v - u;
if(delta < 0 || (delta & 1)){
cout << -1 << endl;
return 0;
}
if(!delta){
if(!u) {
cout << 0 << endl;
} else {
cout << 1 << '\n' << u << endl;
}
}else{
ll haf = delta >> 1;
if((haf & u) == 0) cout << 2 << '\n' << haf << ' ' << (haf ^ u) << endl;
else cout << 3 << '\n' << haf << ' ' << haf << ' ' << u << endl;
}
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;
#define ll long lon
int main()
{
ios::sync_with_stdio(0);
cout.tie(0), cin.tie(0);
int t;
cin >> t;
while (t--) {
int a, b, x, y;
cin >> a >> b >> x >> y;
cout << max({x * b, a * y, (a - x - 1) * b, a * (b - y - 1)}) << endl;
}
return 0;
}
| cpp |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | #include <stdio.h>
#include <string.h>
#include <iostream>
#include <cmath>
using namespace std;
int fang(int a,int b,int c,int d,int e,int f)//判断是否在三点是否共线
{
if((long long)(f-b)*(c-a)==(long long)(d-b)*(e-a))
return 1;
return 0;
}
int xie(int x,int y,int a,int b,int p,int q)//判断两线段的夹角是否在0~90之间
{
if((long long)(a-x)*(p-x)+(long long)(b-y)*(q-y)<0)
return 0;
return 1;
}
int juli(int x,int y,int m,int n,int a,int b)//判断分割的线段是否长:短<0.25
{
if(x!=a)
{
if(a>x)
{
if((a-x)*5<(m-x)) return 0;
if((a-x)*5>(m-x)*4) return 0;
return 1;
}
else
{
if((x-a)*5<(x-m)) return 0;
if((x-a)*5>(x-m)*4) return 0;
return 1;
}
}
else
{
if(b>y)
{
if((b-y)*5<(n-y))return 0;
if((b-y)*5>(n-y)*4)return 0;
return 1;
}
else
{
if((y-b)*5<(y-n))return 0;
if((y-b)*5>(y-n)*4)return 0;
return 1;
}
}
}
struct note
{
int x,y,z,zz;
} a[7];
int main()
{
int t,x,y,m,n,p,q,x1,y1,x2,y2;
int count1,count2;
//int cnt=0;
while(~scanf("%d",&t))
{
while(t--)
{
//cnt++;
for(int i=0; i<3; i++)
scanf("%d%d%d%d",&a[i].x,&a[i].y,&a[i].z,&a[i].zz);
/*if(cnt==11)
{
for(int i=0;i<3;i++)
printf("(%d %d %d %d)\n",a[i].x,a[i].y,a[i].z,a[i].zz);
}*/
for(int i=0; i<2; i++)
for(int j=i+1; j<3; j++)
{
if(a[i].x==a[j].x&&a[i].y==a[j].y)
{
x=a[i].x,y=a[i].y;
m=a[i].z,n=a[i].zz;
p=a[j].z,q=a[j].zz;
count1=i;
count2=j;
}
else if(a[i].x==a[j].z&&a[i].y==a[j].zz)
{
x=a[i].x,y=a[i].y;
m=a[i].z,n=a[i].zz;
p=a[j].x,q=a[j].y;
count1=i;
count2=j;
}
else if(a[i].z==a[j].z&&a[i].zz==a[j].zz)
{
x=a[i].z,y=a[i].zz;
m=a[i].x,n=a[i].y;
p=a[j].x,q=a[j].y;
count1=i;
count2=j;
}
else if(a[i].z==a[j].x&&a[i].zz==a[j].y)
{
x=a[i].z,y=a[i].zz;
m=a[i].x,n=a[i].y;
p=a[j].z,q=a[j].zz;
count1=i;
count2=j;
}
}
for(int i=0; i<3; i++)
if(i!=count1&&i!=count2)
{
x1=a[i].x,y1=a[i].y,x2=a[i].z,y2=a[i].zz;
break;
}
int flag=1;
if(xie(x,y,m,n,p,q)==0)
flag=0;
if(flag)
{
if(fang(x,y,m,n,x1,y1)&&fang(x,y,p,q,x2,y2))
{
if(juli(x,y,m,n,x1,y1)==0)
flag=0;
if(juli(x,y,p,q,x2,y2)==0)
flag=0;
}
else if(fang(x,y,p,q,x1,y1)&&fang(x,y,m,n,x2,y2))
{
if(juli(x,y,m,n,x2,y2)==0)
flag=0;
if(juli(x,y,p,q,x1,y1)==0)
flag=0;
}
else
flag=0;
}
if(flag==1)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
| cpp |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | #include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update> ;
template<class T> using ordered_multi_set = tree<T, null_type, less_equal<T>, rb_tree_tag,tree_order_statistics_node_update> ;
// ub --> lb, lb-->ub
// order_of_key(x) --> no. of elements strictly less than x, returns an integer
// find_by_order(x) --> returns an iterator to xth element, 0-based indexing.
using ll = long long;
using vb = vector<bool>;
using vvb = vector<vb>;
using vi = vector<int>;
using vvi = vector<vi>;
using pi = pair<int,int>;
using vpi = vector<pi>;
using vl = vector<ll>;
using vvl = vector<vl>;
using pl = pair<ll,ll>;
using vpl = vector<pl>;
using vc = vector<char>;
using vvc = vector<vc>;
using vs = vector<string>;
template<class T> using mxhp = priority_queue<T>;
template<class T> using mihp = priority_queue<T,vector<T>,greater<T>>;
const ll inf = 1e18;
const ll mod = 1e9 + 7;
//const ll mod = 998244353;
#define endl '\n'
#define ff first
#define ss second
#define pb push_back
#define ppc(x) __builtin_popcount(x)
#define ppcl(x) __builtin_popcountll(x)
#define lz(x) __builtin_clz(x) //leading zeroes
#define lzl(x) __builtin_clzll(x)
#define all(x) x.begin(),x.end()
#define sz(x) ((int) x.size())
#define fr(k,a,b) for(ll k=a;k<b;k++)
#define rfr(k,a,b) for(ll k=a;k>=b;k--)
#define raf(k,container) for(auto &k : container)
#define print(container) raf(k,container) cout<<k<<' '; cout<<endl;
#define precise(x,y) cout<< fixed << setprecision(y) << x << endl
namespace modop {
ll madd(ll a, ll b) { a = a % mod; b = b % mod; return (((a + b) % mod) + mod) % mod; }
ll msub(ll a, ll b) { a = a % mod; b = b % mod; return (((a - b) % mod) + mod) % mod; }
ll mmul(ll a, ll b) { a = a % mod; b = b % mod; return (((a * b) % mod) + mod) % mod; }
ll mpow(ll a, ll b) { a %= mod; ll res = 1; while (b) { if (b & 1) res = mmul(res,a); a = mmul(a,a); b >>= 1; } return res; }
ll minv(ll a) { return mpow(a, mod - 2); } // fermat's little theorem
ll mdiv(ll a, ll b) { a = a % mod; b = b % mod; return (mmul(a, minv(b)) + mod) % mod; }
}
using namespace modop;
namespace combop{
const int maxN = 3e5+7;
ll fact[maxN+1],ifact[maxN+1];
void computeFact(){
fact[0] = ifact[0] = fact[1] = ifact[1] = 1;
fr(i,2,maxN+1) fact[i] = mmul(fact[i-1],i);
ifact[maxN] = minv(fact[maxN]);
rfr(i,maxN-1,2) ifact[i] = mmul(i+1,ifact[i+1]);
}
ll ncr(ll n,ll r){
if(n < r) return 0;
if(r==0) return 1;
return mmul(fact[n],mmul(ifact[n-r],ifact[r]));
}
}
using namespace combop;
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
ll a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,u,v,w,x,y,z;
string s,t;
void setIO()
{
fast;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
}
/******************************************************* Code Starts **********************************************************/
void merge (vi& arr,int low,int high,ll& ans) {
vi tmp;
int mid = low+(high-low)/2;
i = low,j=high;
while(i <= mid){
while(j >= mid+1 and arr[i] > -arr[j]) j--;
ans += high-j;
i++;
}
i = low,j=mid+1;
while(i <= mid and j <= high) {
if(arr[i] <= arr[j]) tmp.pb(arr[i++]);
else tmp.pb(arr[j++]);
}
while(i <= mid) tmp.pb(arr[i++]);
while(j <= high) tmp.pb(arr[j++]);
fr(i,0,tmp.size()) arr[low+i] = tmp[i];
}
void mergesort(vi &arr,int low,int high,ll& ans) {
if(low == high) return;
int mid = low+(high-low)/2;
mergesort(arr,low,mid,ans);
mergesort(arr,mid+1,high,ans);
merge(arr,low,high,ans);
}
void solve() {
cin>>n;
vi arr(n);
fr(i,0,n) cin>>arr[i];
fr(i,0,n) {
cin>>x;
arr[i] -= x;
}
ll ans = 0;
mergesort(arr,0,n-1,ans);
cout<<ans<<endl;
}
int main() {
setIO();
// computeFact();
int tc = 1;
// cin >> tc;
for (int t = 1; t <= tc; t++) {
solve();
}
} | 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"
] | // LUOGU_RID: 102449126
#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 |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences. | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
int n, k, i, j, x, ans, t[8000321];
vector<int> g[123123], v;
void update(int v, int tl, int tr, int pos) {
if (tl == tr) {
t[v]++;
return;
}
int tm = (tl + tr) / 2;
if (pos <= tm) update(v + v, tl, tm, pos);
else update(v + v + 1, tm + 1, tr, pos);
t[v] = t[v + v] + t[v + v + 1];
}
int get(int v, int tl, int tr, int l, int r) {
if (l > r) return 0;
if (l == tl && tr == r) return t[v];
int tm = (tl + tr) / 2;
return get(v + v, tl, tm, l, min(r, tm)) + get(v + v + 1, tm + 1, tr, max(l, tm + 1), r);
}
signed main() {
cin.tie(0)->sync_with_stdio(0);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#endif
cin >> n;
for (i = 1; i <= n; i++) {
cin >> j;
while (j--) {
cin >> x;
x++;
g[i].push_back(x);
}
reverse(g[i].begin(), g[i].end());
if (is_sorted(g[i].begin(), g[i].end())) {
update(1, 1, 1e6 + 1, g[i].back());
}
reverse(g[i].begin(), g[i].end());
}
ans = n * n;
for (i = 1; i <= n; i++) {
reverse(g[i].begin(), g[i].end());
if (is_sorted(g[i].begin(), g[i].end())) {
ans -= get(1, 1, 1e6 + 1, 1, g[i][0]);
}
reverse(g[i].begin(), g[i].end());
}
cout << ans;
} | cpp |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
ll t, a, b, p;
cin >> t;
while (t--) {
cin >> a >> b >> p;
string s;
cin >> s;
int n = s.size();
int k = n, c = s[n-2];
if (c == 'A') p -= a;
else p -= b;
if (p < 0) {
cout << k << '\n';
continue;
}
for (int i = n - 2; i >= 0; i--) {
if (s[i] == c) {
k = i+1;
continue;
}
c = s[i];
if (s[i] == 'A') p -= a;
else p -= b;
if (p < 0) break;
k = i+1;
}
cout << k << '\n';
}
} | cpp |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"data structures",
"dp",
"greedy"
] | #include<bits/stdc++.h>
#define int long long
using namespace std;
int n;
const int maxn=500010;
int a[maxn];
stack<int> aft,bfr;
int f[maxn],b[maxn];
int sum,s[maxn][2],arr[maxn];
signed main(){
cin >> n;
for(int i = 0;i < n;i++) scanf("%d",&a[i]);
for(int i = 0;i < n;i++){
while(!aft.empty() and a[i] < a[aft.top()]){
f[aft.top()]=i;
aft.pop();
}
aft.push(i);
}
while(!aft.empty()){
f[aft.top()]=aft.top();
aft.pop();
}
for(int i = n-1;i >= 0;i--){
while(!bfr.empty() and a[i] < a[bfr.top()]){
b[bfr.top()]=i;
bfr.pop();
}
bfr.push(i);
}
while(!bfr.empty()){
b[bfr.top()] = bfr.top();
bfr.pop();
}
for(int i = 0;i < n;i++){
s[i][0]=s[b[i]][0]+(i-b[i])*a[i];
if(b[i]==i) s[i][0]=a[i]*(i+1);
}
for(int i = n-1;i >= 0;i--){
s[i][1]=s[f[i]][1]+(f[i]-i)*a[i];
if(f[i]==i) s[i][1]=a[i]*(n-i);
}
int maxx = -1,posi=-1;
for(int i = 0;i < n;i++){
if(s[i][0]+s[i+1][1] >= maxx){
maxx = s[i][0]+s[i+1][1];
posi = i;
}
}
for(int i = posi;i >= 0;){
int j=i;
for(j = i;j > b[i];j--) arr[j]=a[i];
i = j;
if(b[i]==i){
for(j;j>=0;j--) arr[j]=a[i];
break;
}
}
for(int i = posi+1;i < n;){
int j;
for(j = i;j < f[i];j++) arr[j]=a[i];
i = j;
if(f[i]==i){
for(j;j<n;j++) arr[j]=a[i];
break;
}
}
for(int i = 0;i < n;i++) cout << arr[i] << ' ';
return 0;
} | 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>
#define int long long
using namespace std;
int const N=200010;
int n,p[N],a[N],f[N];
struct segtree{
#define ls(x) ((x)<<1)
#define rs(x) ((x)<<1|1)
#define mid (((l)+(r))>>1)
static int const T=N<<2;
int tr[T],lt[T];
void update(int x){
tr[x]=min(tr[ls(x)],tr[rs(x)]);
}
void add(int x,int k){
tr[x]+=k,lt[x]+=k;
}
void pushdown(int x){
if(!lt[x])return;
add(ls(x),lt[x]),add(rs(x),lt[x]),lt[x]=0;
}
void modify(int x,int l,int r,int ql,int qr,int k){
if(ql>qr)
return;
if(ql<=l&&r<=qr)
return add(x,k);
pushdown(x);
if(ql<=mid)
modify(ls(x),l,mid,ql,qr,k);
if(qr>mid)
modify(rs(x),mid+1,r,ql,qr,k);
update(x);
}
int query(int x,int l,int r,int ql,int qr){
if(ql<=l&&r<=qr)
return tr[x];
pushdown(x);
int res=LLONG_MAX;
if(ql<=mid)
res=min(res,query(ls(x),l,mid,ql,qr));
if(qr>mid)
res=min(res,query(rs(x),mid+1,r,ql,qr));
return res;
}
#undef ls
#undef rs
#undef mid
};
segtree tr;
signed main(){
ios::sync_with_stdio(0);
cin>>n;
for(int i=1;i<=n;i++)
cin>>p[i];
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<=n;i++)
tr.modify(1,1,n,p[i],n,a[i]);
int ans=min(a[1],a[n]);
for(int i=1;i<n;i++)
tr.modify(1,1,n,1,p[i]-1,a[i]),tr.modify(1,1,n,p[i],n,-a[i]),
ans=min(ans,tr.query(1,1,n,1,n));
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>
#include <map>
#include <vector>
int main() {
int t;
std::cin >> t;
int a, b, c, a1, b1, c1;
for (int i = 0; i < t; i++){
std::cin >> a >> b >> c;
int N = 3, res = 0;
std::vector<int> sets = {1, 2, 3, 4, 5, 6, 7};
do {
a1 = a;
b1 = b;
c1 = c;
int counter = 0;
for (auto set: sets){
bool flag = false;
std::vector<bool> bits;
for (int j = 0; j < N; j++)
bits.push_back(set & 1 << j);
if(a1 < bits[0])flag = true;
if(b1 < bits[1])flag = true;
if(c1 < bits[2])flag = true;
if (!flag){a1 -= bits[0];b1 -= bits[1];c1 -= bits[2];counter++;}
}
if (counter > res){
res = counter;
}
res = std::max(counter, res);
}
while (std::next_permutation(sets.begin(), sets.end()));
std::cout << res << std::endl;
}
return 0;
} | cpp |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | #include<bits/stdc++.h>
//#define feyn
#define int long long
#define ll __int128
using namespace std;
const int N=200010;
const int mod=1e15+7;
inline void read(int &wh){
wh=0;int f=1;char w=getchar();
while(w<'0'||w>'9'){if(w=='-')f=-1;w=getchar();}
while(w<='9'&&w>='0'){wh=wh*10+w-'0';w=getchar();}
wh*=f;return;
}
int m,n,cnt[N];
char w[N];
int p[N]={1},aa[N],bb[N],pl[N];
inline int get(int l,int r,int a[]){
ll now=(ll)a[r]-(ll)a[l-1]*p[r-l+1];
return (now%mod+mod)%mod;
}
signed main(){
#ifdef feyn
freopen("in.txt","r",stdin);
#endif
read(m);scanf("%s",w+1);int num=0;
for(int i=1;i<=m;i++)cnt[i]=cnt[i-1]+(w[i]=='0');
for(int i=1;i<=m;i++)if(w[i]=='0')pl[++num]=i&1;
for(int i=1;i<=num;i++){
p[i]=p[i-1]*2%mod;
aa[i]=(aa[i-1]*2ll+pl[i])%mod;
bb[i]=(bb[i-1]*2ll+1-pl[i])%mod;
}
read(n);
while(n--){
int x,y,len;read(x);read(y);read(len);
if(cnt[x+len-1]-cnt[x-1]!=cnt[y+len-1]-cnt[y-1]){
puts("No");continue;
}
if((x&1)==(y&1)){
if(get(cnt[x-1]+1,cnt[x+len-1],aa)==get(cnt[y-1]+1,cnt[y+len-1],aa))puts("Yes");
else puts("No");
}
else{
if(get(cnt[x-1]+1,cnt[x+len-1],aa)==get(cnt[y-1]+1,cnt[y+len-1],bb))puts("Yes");
else puts("No");
}
}
return 0;
} | cpp |
1301 | D | D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running): | [
"constructive algorithms",
"graphs",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
vector <pair<int, string>> way, ans;
int n, m, k, cur = 0;
cin >> n >> m >> k;
if (k > 4 * n * m - 2 * (n + m)) {
cout << "NO\n";
return 0;
}
cout << "YES\n";
for (int i = 0; i < n - 1; ++i) {
if(m != 1) {
way.push_back({m - 1, "R"});
way.push_back({m - 1, "L"});
}
way.push_back({1, "D"});
}
if(m != 1) way.push_back({m - 1, "R"});
for (int i = m - 1; i >= 0; --i) {
if( n != 1) way.push_back({n - 1, "U"});
if (i != 0) {
if(n != 1) way.push_back({n - 1, "D"});
way.push_back({1, "L"});
}
}
for (auto i : way) {
if (cur + i.first >= k) {
ans.push_back({k - cur, i.second});
break;
} else {
cur += i.first;
ans.push_back({i.first, i.second});
}
}
cout << (int) ans.size() << "\n";
for (auto i : ans) {
cout << i.first << " " << i.second << "\n";
}
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>
using namespace std;
const int N = 5005;
int n;
basic_string<int> e[N];
int d[N], p[N], w[N];
void dfs(int x) {
for (int y : e[x]) {
if (y == p[x])
continue;
p[y] = x;
d[y] = d[x] + 1;
dfs(y);
}
}
void vis(int a, int b, auto f) {
while (a != b) {
if (d[a] > d[b])
swap(a, b);
f(b);
b = p[b];
}
}
pair<int, int> g[N];
struct upit { int a, b, c; };
int main() {
cin >> n;
for (int i = 1, u, v; i < n; ++i)
cin >> u >> v, e[u] += v, e[v] += u, g[i] = {u, v};
dfs(1);
int q;
cin >> q;
vector<upit> v(q);
fill(w + 2, w + n + 1, 1);
for (auto &[a, b, c] : v) {
cin >> a >> b >> c;
vis(a, b, [&] (int x) { w[x] = max(w[x], c); });
}
for (auto &[a, b, c] : v) {
int mn = 1e9;
vis(a, b, [&] (int x) { mn = min(mn, w[x]); });
if (mn != c) {
cout << "-1";
return 0;
}
}
for (int i = 1; i < n; ++i) {
auto [a, b] = g[i];
cout << w[d[a] < d[b] ? b : a] << " \n"[i == n - 1];
}
} | 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: 101572938
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=150005,inf=1e18;
int n,a[maxn],pos[maxn];
struct vl
{int sum,mx,sc,cnt;
vl(){sum=0;mx=sc=-inf;cnt=0;}
};
inline vl merge(vl a,vl b)
{
vl ret;
ret.sum=a.sum+b.sum;
ret.mx=max(a.mx,b.mx);
ret.sc=-inf;
ret.cnt=0;
if(a.mx!=ret.mx)ret.sc=max(ret.sc,a.mx);
else ret.cnt+=a.cnt;
if(b.mx!=ret.mx)ret.sc=max(ret.sc,b.mx);
else ret.cnt+=b.cnt;
if(a.sc!=ret.mx)ret.sc=max(ret.sc,a.sc);
if(b.sc!=ret.mx)ret.sc=max(ret.sc,b.sc);
return ret;
}
vl val[maxn<<2];
int tag[maxn<<2],add[maxn<<2],len[maxn<<2];
inline void pushup(int i)
{
val[i]=merge(val[i<<1],val[i<<1|1]);
len[i]=len[i<<1]+len[i<<1|1];
}
inline void pushtgmin(int i,int v)
{
if(v>=val[i].mx)return;
val[i].sum-=(val[i].mx-v)*val[i].cnt;
val[i].mx=v;
tag[i]=min(tag[i],v);
return;
}
inline void pushtgadd(int i,int v)
{
add[i]+=v;
val[i].sum+=len[i]*v;
if(tag[i]!=inf)tag[i]+=v;
if(val[i].mx!=-inf)val[i].mx+=v;
if(val[i].sc!=-inf)val[i].sc+=v;
}
inline void pushdown(int i)
{
pushtgadd(i<<1,add[i]);
pushtgadd(i<<1|1,add[i]);
add[i]=0;
pushtgmin(i<<1,tag[i]);
pushtgmin(i<<1|1,tag[i]);
tag[i]=inf;
}
void update(int i,int l,int r,int L,int R,int v)
{
if(L>R)return;
if(L<=l&&r<=R){pushtgadd(i,v);return;}
int mid=l+r>>1;pushdown(i);
if(L<=mid)update(i<<1,l,mid,L,R,v);
if(R>mid)update(i<<1|1,mid+1,r,L,R,v);
pushup(i);
}
void calcmin(int i,int l,int r,int L,int R,int v)
{
//if(i==1)printf("#%d %d %d\n",L,R,v);
if(r<L||l>R||L>R)return;
if(L<=L&&r<=R&&val[i].sc<v){pushtgmin(i,v);return;}
if(l==r)return;
int mid=l+r>>1;pushdown(i);
calcmin(i<<1,l,mid,L,R,v);
calcmin(i<<1|1,mid+1,r,L,R,v);
pushup(i);
}
void build(int i,int l,int r)
{
len[i]=0;
val[i].cnt=val[i].sum=0;
val[i].mx=val[i].sc=-inf;
tag[i]=inf;add[i]=0;
if(l==r)return;
int mid=l+r>>1;
build(i<<1,l,mid);
build(i<<1|1,mid+1,r);
}
int query(int i,int l,int r,int p)
{
if(l==r)return val[i].sum;
int mid=l+r>>1;
pushdown(i);
if(p<=mid)return query(i<<1,l,mid,p);
else return query(i<<1|1,mid+1,r,p);
}
void modify(int i,int l,int r,int p,int v)
{
if(l==r)
{
val[i].cnt=1;
val[i].mx=v;
val[i].sc=-inf;
val[i].sum=v;
len[i]=1;
return;
}
int mid=l+r>>1;
pushdown(i);
if(p<=mid)modify(i<<1,l,mid,p,v);
else modify(i<<1|1,mid+1,r,p,v);
pushup(i);
}
int c[maxn];
int num[maxn];
void uadd(int p,int v){while(p<=n){c[p]+=v;p+=p&-p;}}
int ask(int p){int ret=0;while(p){ret+=c[p];p-=p&-p;}return ret;}
int sum[maxn];
signed main()
{
scanf("%lld",&n);
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
for(int i=1;i<=n;i++)
pos[a[i]]=i,num[a[i]]=ask(a[i]),uadd(a[i],1);
build(1,1,n);
for(int i=1;i<=n;i++)
{
update(1,1,n,pos[i]+1,n,1);
calcmin(1,1,n,1,pos[i]-1,num[i]);
modify(1,1,n,pos[i],i);
int S=0;
//for(int j=1,x;j<=n;j++)
// if(a[j]<=i)
// printf("%d ",(x=query(1,1,n,j))),S+=x;
// putchar('\n');
//printf("%d\n",val[1].sum);
sum[i]+=val[1].sum;
}
reverse(a+1,a+1+n);
memset(c,0,sizeof c);
for(int i=1;i<=n;i++)
pos[a[i]]=i,num[a[i]]=ask(a[i]),uadd(a[i],1);
build(1,1,n);
for(int i=1;i<=n;i++)
{
update(1,1,n,pos[i]+1,n,1);
calcmin(1,1,n,1,pos[i]-1,num[i]);
modify(1,1,n,pos[i],i);
// int S=0;
// for(int j=n,x;j>=1;j--)
// if(a[j]<=i)
// printf("%d ",i-(x=query(1,1,n,j))+1),S+=x;
// putchar('\n');
//printf("%d\n",val[1].sum);
sum[i]-=i*i-val[1].sum;
}
for(int i=1;i<=n;i++)
printf("%lld\n",sum[i]);
// putchar('\n');
return 0;
} | cpp |
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 <iostream>
#include <vector>
using namespace std;
using ll = long long;
typedef vector<ll> vi;
typedef vector<vi> vvi;
ll INF = 2e9;
ll n, q, u, v;
vi a, d;
vvi g, anc;
void dfs(ll u, ll p) {
if (p != -1) {
a[u] = p;
d[u] = d[p] + 1;
}
for (auto z:g[u]) {
if (z == p) continue;
dfs(z, u);
}
}
void ancestors() {
anc.push_back(vi(n));
for (ll i = 0; i < n; i++) anc[0][i] = a[i];
for (ll i = 1, j = 1; i < n; i *= 2, j++) {
anc.push_back(vi(n));
for (ll k = 0; k < n; k++) anc[j][k] = anc[j-1][anc[j-1][k]];
}
}
ll dist(ll u, ll v) {
ll c = d[u] + d[v];
while (d[u] > d[v]) {
ll b = d[u] - d[v];
ll k = 1, j = 0;
while (k*2 < b) {
j++;
k *= 2;
}
u = anc[j][u];
}
while (d[v] > d[u]) {
ll b = d[v] - d[u];
ll k = 1, j = 0;
while (k*2 < b) {
j++;
k *= 2;
}
v = anc[j][v];
}
while (u != v) {
ll j = 0;
while (anc[j+1][u] != anc[j+1][v]) j++;
u = anc[j][u];
v = anc[j][v];
}
return c - 2 * d[u];;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
g = vvi(n);
a = vi(n); d = vi(n);
for (ll i = 0; i < n - 1; i++) {
cin >> u >> v;
u--; v--;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(0, -1);
ancestors();
cin >> q;
while (q--) {
ll x, y, a, b, k;
cin >> x >> y >> a >> b >> k;
x--, y--, a--, b--;
ll dab = dist(a, b);
ll dax = dist(a, x);
ll day = dist(a, y);
ll dbx = dist(b, x);
ll dby = dist(b, y);
ll even = INF;
ll odd = INF;
for (ll x : {dab, dax+1+dby, day+1+dbx})
if (x % 2 == 0) even = min(even, x);
else odd = min(odd, x);
if (k % 2 == 0) cout << (k >= even ? "YES\n":"NO\n");
else cout << (k >= odd ? "YES\n":"NO\n");
}
} | 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 |
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>
using ul = std::uint32_t;
using li = std::int32_t;
using ull = std::uint64_t;
using ll = std::int64_t;
using lf = double;
using llf = long double;
using uss = std::uint8_t;
using us = std::uint16_t;
const ul maxn = 17;
li ans[1 << maxn][2][2];
bool sp[1 << maxn];
ul n, k;
const li inf = 1e9;
int main()
{
std::scanf("%u%u", &n, &k);
for (ul i = 1; i <= k; ++i) {
ul a;
std::scanf("%u", &a);
sp[a - 1] = true;
}
for (ul i = 1; i != (1 << n); ++i) {
for (ul s : {0, 1}) {
for (ul t : {0, 1}) {
ans[i][s][t] = -inf;
}
}
}
for (ul i = 0; i != (1 << n); i += 2) {
ans[1 << n - 1 | i >> 1][sp[i]][sp[i + 1]] = std::max(ans[1 << n - 1 | i >> 1][sp[i]][sp[i + 1]], li(sp[i] || sp[i + 1]));
ans[1 << n - 1 | i >> 1][sp[i + 1]][sp[i]] = std::max(ans[1 << n - 1 | i >> 1][sp[i + 1]][sp[i]], li(sp[i] || sp[i + 1]));
}
for (ul i = (1 << n - 1) - 1; i; --i) {
for (ul ls : {0, 1}) {
for (ul lt : {0, 1}) {
if (ans[i << 1][ls][lt] == -inf) {
continue;
}
for (ul rs : {0, 1}) {
for (ul rt : {0, 1}) {
if (ans[i << 1 | 1][rs][rt] == -inf) {
continue;
}
li val = ans[i << 1][ls][lt] + ans[i << 1 | 1][rs][rt];
for (ul a : {0, 1}) {
if (a && ls == rs) {
break;
}
li val1 = val + (ls || rs);
ul ys = a ? ls : rs;
ul ns = a ? rs : ls;
for (ul b1 : {0, 1}) {
if (b1 && lt == rt) {
break;
}
li val2 = val1 + (lt || rt);
ul yt = b1 ? lt : rt;
for (ul b2 : {0, 1}) {
if (b2 && ns == yt) {
break;
}
li val3 = val2 + (ns || yt);
ul yt2 = b2 ? ns : yt;
ans[i][ys][yt2] = std::max(ans[i][ys][yt2], val3);
}
}
}
}
}
}
}
}
std::printf("%d\n", std::max(std::max(ans[1][0][0], ans[1][0][1] + 1), std::max(ans[1][1][0] + 1, ans[1][1][1] + 1)));
return 0;
}
| cpp |
1284 | E | E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213 | [
"combinatorics",
"geometry",
"math",
"sortings"
] | #ifdef MY_LOCAL
#include "D://competitive_programming/debug/debug.h"
#define debug(x) cerr << "[" << #x<< "]:"<<x<<"\n"
#else
#define debug(x)
#endif
#define REP(i, n) for(int i = 0; i < n; i ++)
#define REPL(i,m, n) for(int i = m; i < n; i ++)
#define SORT(arr) sort(arr.begin(), arr.end())
#define LSOne(S) ((S)&-(S))
#define M_PI 3.1415926535897932384
#define INF 1e18
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
#define int ll
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<vii> vvii;
typedef double ld;
typedef tree<double,null_type,less<double>, rb_tree_tag, tree_order_statistics_node_update> ost;
struct point{
int x;
int y;
bool operator<(point &other) {
int nx = abs(x);
int ny = x < 0 ? -y: y;
int ox = abs(other.x);
int oy = other.x < 0? -other.y : other.y;
return ny*ox < nx*oy;
}
};
vector<ii> sorting(vii &arr) {
vector<point> neg_x;
vector<point> pos_x;
for (auto [x,y]: arr) {
if (x < 0) {
neg_x.push_back({x,y});
} else {
pos_x.push_back({x,y});
}
}
SORT(neg_x);
SORT(pos_x);
//reverse(neg_x.begin(), neg_x.end());
vii res;
for (auto [x,y]: pos_x) {
res.push_back({x,y});
}
for (auto [x,y]: neg_x) {
res.push_back({x,y});
}
return res;
}
bool check_valid(ii p1, ii p2) {
auto [x1,y1] = p1;
auto [x2, y2] = p2;
int dz = x1* y2 - x2*y1;
if (dz < 0) {
return true;
}
return false;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;cin>>n;
vii arr(n);
REP(i, n) {
int x,y;cin>>x>>y;
arr[i] = {x,y};
}
auto get_pairing = [&](int ori, int other) {
auto [x1,y1] = arr[ori];
auto [x2,y2] = arr[other];
int dx = x2-x1;
int dy = y2-y1;
return make_pair(dx,dy);
};
int totgood = 0;
REP(ori, n) {
int curbad = 0;
vii vec;
REP(i, n) {
if (i != ori) {
vec.push_back(get_pairing(ori, i));
}
}
vec = sorting(vec);
debug(vec);
int curn = n-1;
int curidx = 0;
REP(i, n-1) {
while (true) {
if (curidx + 1== curn + i) break;
ii p2 = vec[(curidx+1)%curn];
ii p1 = vec[i];
if (check_valid(p1,p2)) {
break;
}
curidx++;
}
int bad_no = curidx - i;
if (bad_no < 3) {
continue;
}
curbad += (bad_no)*(bad_no-1)*(bad_no-2)/6;
}
//assert(curbad%24==0);
int curgood = ((n-1)*(n-2)*(n-3)*(n-4)/24 - curbad);
debug(curgood);
totgood += curgood;
}
cout<<totgood<<"\n";
} | cpp |
1286 | D | D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2
1 1 100
3 1 0
OutputCopy1
InputCopy3
7 10 0
9 4 86
14 5 100
OutputCopy0
InputCopy4
6 4 50
11 25 50
13 16 50
15 8 50
OutputCopy150902884
| [
"data structures",
"math",
"matrices",
"probabilities"
] | // LUOGU_RID: 92552980
#include <bits/stdc++.h>
#define P 998244353ll
#define ll long long
using namespace std;
namespace QYB {
void exgcd(ll a, ll b, ll &x, ll &y) {
if (!b) return x = 1, y = 0, void();
exgcd(b, a % b, y, x); y -= a / b * x;
} ll inv(ll a) {
ll x, y; exgcd(a, P, x, y); return (x % P + P) % P;
} struct matrix {
ll a[2][2];
ll *operator[](int x) { return a[x]; }
matrix(ll _0 = 0, ll _1 = 0, ll _2 = 0, ll _3 = 0) { a[0][0] = _0; a[0][1] = _1; a[1][0] = _2; a[1][1] = _3; }
matrix operator*(matrix x) {
return matrix((a[0][0] * x[0][0] + a[0][1] * x[1][0]) % P, (a[0][0] * x[0][1] + a[0][1] * x[1][1]) % P, (a[1][0] * x[0][0] + a[1][1] * x[1][0]) % P, (a[1][0] * x[0][1] + a[1][1] * x[1][1]) % P);
}
} s[500005];
int n; ll ans, d[100005], v[100005], g[2][100005];
void modify(int p, int l, int r, int x, int a, int b) {
if (x < l || x > r) return;
if (l == r) return s[p][a][b] = g[a][x], void();
int mid = l + r >> 1;
modify(p << 1, l, mid, x, a, b);
modify(p << 1 | 1, mid + 1, r, x, a, b);
s[p] = s[p << 1 | 1] * s[p << 1];
} matrix query(int p, int l, int r, int L, int R) {
if (r < L || R < l) return matrix(1, 0, 0, 1);
if (L <= l && r <= R) return s[p];
int mid = l + r >> 1;
return query(p << 1 | 1, mid + 1, r, L, R) * query(p << 1, l, mid, L, R);
} int main() {
scanf("%d", &n);
vector<pair<int, int> > f;
for (int i = 1; i <= n; i++) {
scanf("%lld%lld%lld", d + i, v + i, &g[1][i]);
g[0][i] = (P + 1 - ((g[1][i] *= 828542813ll) %= P)) % P;
i == 1 || v[i - 1] - v[i] >= 0? modify(1, 1, n, i, 0, 0): f.push_back({i, 0});
i == 1 || v[i - 1] + v[i] <= 0? modify(1, 1, n, i, 0, 1): f.push_back({i, 1});
i == 1 || v[i - 1] + v[i] >= 0? modify(1, 1, n, i, 1, 0): f.push_back({i, 2});
i == 1 || v[i - 1] - v[i] <= 0? modify(1, 1, n, i, 1, 1): f.push_back({i, 3});
} sort(f.begin(), f.end(), [](pair<int, int> x, pair<int, int> y) {
auto [ix, sx] = x; auto [iy, sy] = y;
ll vx = (sx & 1? 1: -1) * v[ix - 1] + (sx & 2? -1: 1) * v[ix];
ll vy = (sy & 1? 1: -1) * v[iy - 1] + (sy & 2? -1: 1) * v[iy];
return (d[ix] - d[ix - 1]) * vy > (d[iy] - d[iy - 1]) * vx;
});
for (auto [i, st]: f) {
modify(1, 1, n, i, (st >> 1) & 1, (st >> 0) & 1);
matrix res = query(1, 1, n, i + 1, n) * (st == 0? matrix(g[0][i], 0, 0, 0): (st == 1? matrix(0, g[0][i], 0, 0): (st == 2? matrix(0, 0, g[1][i], 0): matrix(0, 0, 0, g[1][i])))) * query(1, 1, n, 1, i - 1);
(ans += (d[i] - d[i - 1]) * inv(((st & 1? 1: P - 1) * v[i - 1] % P + (st & 2? P - 1: 1) * v[i] % P) % P) % P * (res[0][0] + res[1][0]) % P) %= P;
} return !printf("%lld\n", ans);
}
} int main() {
return QYB::main();
} | cpp |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | #include <bits/stdc++.h>
#define fi first
#define se second
#define faster ios_base::sync_with_stdio(0); cin.tie(0);
#define pb push_back
using namespace std;
using ll = long long;
using pii = pair <int, int>;
mt19937_64 Rand(chrono::steady_clock::now().time_since_epoch().count());
const int maxN = 2e5 + 1;
const int inf = 0x3f3f3f3f;
const int Mod = 1e9 + 7;
ll a[maxN];
int n;
bool in[maxN * 5];
vector <int> P;
inline int rd(int l, int r){
return l + Rand() % (r - l + 1);
}
void Sieve(){
for (int i = 2; i <= 1e6; ++i){
if (!in[i]){
P.pb(i);
for (int j = i * 2; j <= 1e6; j += i)
in[j] = 1;
}
}
}
int check(ll x){
if (x == 0) return n;
vector <ll> S;
for (int i: P){
if (x % i == 0){
S.pb(i);
while (x % i == 0) x /= i;
}
}
if (x != 1) S.pb(x);
ll res = n;
for (ll i: S){
ll cnt = 0;
for (int j = 1; j <= n; ++j){
cnt += min(a[j] < i ? n : a[j] % i, i - (a[j] % i));
}
res = min(res, cnt);
}
return res;
}
void Init(){
cin >> n;
Sieve();
for (int i = 1; i <= n; ++i){
cin >> a[i];
}
vector <int> b;
for (int i = 0; i < 20; ++i) b.pb(rd(1, n));
int ans = n;
for (int i: b){
ans = min(ans, check(a[i]));
ans = min(ans, check(a[i] - 1));
ans = min(ans, check(a[i] + 1));
}
cout << ans;
}
#define taskname "test"
signed main(){
faster
if (fopen(taskname ".inp", "r")){
freopen(taskname ".inp", "r", stdin);
freopen(taskname ".out", "w", stdout);
}
int tt = 1;
//cin >> tt;
while (tt--){
Init();
}
if (fopen("timeout.txt", "r")){
ofstream timeout("timeout.txt");
cerr << "Time elapsed: " << signed(double(clock()) / CLOCKS_PER_SEC * 1000) << "ms\n";
timeout << signed(double(clock()) / CLOCKS_PER_SEC * 1000);
timeout.close();
}
}
| cpp |
1292 | D | D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3
2 1 4
OutputCopy5
InputCopy4
3 1 4 4
OutputCopy6
InputCopy4
3 1 4 1
OutputCopy6
InputCopy5
3 1 4 1 5
OutputCopy11
NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66. | [
"dp",
"graphs",
"greedy",
"math",
"number theory",
"trees"
] | #include<bits/stdc++.h>
#define N 5000
#define M 5000005
using namespace std;
int tot,n,pr[N+5],cnt,s[N+5][705],son[M],a[M],v[N+5],p[N+5][705];
long long asw,sum[M];
bool vi[N+5];
struct nood {
int to,next,v;
} g[M];
inline void add(int x,int y,int z) {
g[++cnt].v=z,g[cnt].to=y,g[cnt].next=a[x],a[x]=cnt;
}
inline void dfs(int u) {
for(int j,i=a[u]; i; i=g[i].next) {
dfs(j=g[i].to),son[u]+=son[j],sum[u]+=sum[j]+1ll*son[j]*g[i].v;
}
}
inline void Dfs(int u) {
for(int j,i=a[u]; i; i=g[i].next) {
if(son[j=g[i].to]*2>son[0]) {
asw-=1ll*g[i].v*(son[j]*2-son[0]);
return Dfs(j);
}
}
}
int main() {
for(int i=2; i<=N; i++) {
if(!vi[i]) pr[++pr[0]]=i;
for(int j=1; j<=pr[0]; j++) {
if(i*pr[j]>N) break;
vi[i*pr[j]]=1;
if(i%pr[j]==0) break;
}
}
scanf("%d",&n);
for(int x,i=1; i<=n; i++) scanf("%d",&x),v[max(x,1)]++;
son[0]=v[1];
for(int i=2; i<=N; i++) {
int op=0;
for(int j=pr[0]; j; j--) {
if(pr[j]>i) continue;
int k=i;
while(k) s[i][j]+=k/pr[j],k/=pr[j];
if(op) add(p[i][j+1],p[i][j]=++tot,s[i][j]);
else if(s[i-1][j]!=s[i][j]) {
add(p[i-1][j],p[i][j]=++tot,s[i][j]-s[i-1][j]),op=1;
} else p[i][j]=p[i-1][j];
}
son[tot]=v[i];
}
dfs(0),asw=sum[0],Dfs(0),printf("%lld",asw);
} | 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"
] | // S2OJ Submission #67633 @ 1675042177406
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 6e5 + 5;
int n, w, s[N], mn[N<<2], ne[N], fa[N][26], sum;
map<int, int> mp;char op;
__int128 ans;
void pushup(int x){
mn[x] = min(mn[x<<1], mn[x<<1|1]);
}
void update(int x, int l, int r, int pos, int k){
if(l == r){
mn[x] = k;
return;
}
int mid = (l + r) >> 1;
if(pos <= mid) update(x<<1, l, mid, pos, k);
else update(x<<1|1, mid + 1, r, pos, k);
pushup(x);
}
int query(int x, int l, int r, int l1, int r1){
if(l1 <= l && r <= r1) return mn[x];
int mid = (l + r) >> 1, res = 1e18;
if(l1 <= mid) res = min(res, query(x<<1, l, mid, l1, r1));
if(r1 > mid) res = min(res, query(x<<1|1, mid + 1, r, l1, r1));
return res;
}
void add(int x, int k){
mp[x] += k, sum += x*k;
}
int insert(int w){
int res = 0;
vector<map<int, int>::iterator> vec;
for(auto it = mp.upper_bound(w); it != mp.end(); it++){
res += it->second, sum -= it->first * it->second;
vec.push_back(it);
}
for(auto it:vec) mp.erase(it);
return res;
}
template <typename T>
void write(T x){
if(x > 9) write(x/10);
cout << (char)(x%10 + '0');
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n;
cin >> op >> w;
s[1] = op - 'a';
update(1, 1, n, 1, w);
ans = w;
write(ans);
cout << '\n';
for(int i = 2, j = 0; i <= n; i++){
cin >> op >> w;
s[i] = (op - 'a' + ans%26)%26;
w = w ^ (ans & ((1<<30) - 1));
while(j && s[j + 1] != s[i]) j = ne[j];
if(s[j + 1] == s[i]) j++;
ne[i] = j;
if(s[i] == s[1]) add(w, 1);
update(1, 1, n, i, w);
ans += query(1, 1, n, 1, i);
for(int c = 0; c < 26; c++) fa[i][c] = fa[ne[i]][c];
fa[i][s[ne[i] + 1]] = ne[i];
for(int c = 0; c < 26; c++){
if(c == s[i]) continue;
for(int k = fa[i - 1][c]; k; k = fa[k][c]) add(query(1, 1, n, i - k, i - 1), -1);
}
add(w, insert(w));
ans += sum;
write(ans);
cout << '\n';
}
return 0;
} | cpp |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44. | [
"brute force",
"data structures",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 10;
int a[N];
int n, m, k;
void solve() {
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) cin >> a[i];
k = min(k,m-1);
int ans = 0;
for (int i = 0; i <= k; i++) {
int minx = 1e18;
for (int j = 0; j <= m - k - 1; j++)
minx = min(minx, max(a[1 + i + j], a[n + i - m + 1 + j]));
ans = max(ans, minx);
}
cout << ans << endl;
}
signed main() {
int t;
cin >> t;
while (t--) solve();
return 0;
}
| 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 main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int q, x, y, ans;
map<int, int>mp;
cin>>q>>x;
ans = 0;
for(int i=1;i<=q;++i)
{
cin>>y;
++mp[y%x];
while(mp[ans%x])
{
--mp[ans%x];
++ans;
}
cout<<ans<<"\n";
}
return 0;
} | 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"
] | //saw tutorial
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
int n=s.length(),i,j,k,l,m,c=0;
for(i=0; i<n; i++)
{
if(s[i]=='1')
{
k=i;
break;
}
else
{
k=-1;
}
}
for(j=n-1; j>=0; j--)
{
if(s[j]=='1')
{
m=j;
break;
}
else
{
m=-1;
}
}
if(k==-1 && m==-1)
{
cout<<0<<endl;
}
else
{
for(l=k; l<=m; l++)
{
if(s[l]=='0')
{
c++;
}
}
cout<<c<<endl;
}
}
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>
using namespace std;
// clang-format off
namespace { enum operand_type_enum : uint32_t { RAW = 0, COMPOSED = 1 << 1, REQUIRE_PARAM = 1 << 2, }; template <class T> concept has_operand_type = requires() { { T::operand_type } -> convertible_to<uint32_t>; }; template <class T> class operand_type { public: inline static constexpr uint32_t value() { if constexpr (has_operand_type<T>) return T::operand_type; else return operand_type_enum::RAW; } }; template <class T> constexpr uint32_t operand_type_v = operand_type<decay_t<T>>::value();
template <class T> concept is_raw = ((operand_type_v<T> & RAW) == RAW); template <class T> concept is_composed = ((operand_type_v<T> & COMPOSED) == COMPOSED); template <class T> concept require_param = ((operand_type_v<T> & REQUIRE_PARAM) == REQUIRE_PARAM); template <class T> concept require_no_param = !require_param<T>; template <class left_t, class right_t> class composed_operation_t { public: inline static constexpr uint32_t operand_type = COMPOSED | operand_type_v<right_t> | operand_type_v<left_t>;
left_t left; right_t right; }; template <class left_t, class right_t> requires(is_composed<left_t> && (!is_composed<right_t>)) auto operator|(left_t&& left, right_t&& right) { return left.left | (left.right | right); } template <class left_t, class right_t> requires(is_raw<left_t>&& require_param<right_t>) auto operator|(left_t&& left, right_t&& right) { return composed_operation_t<left_t, right_t>(left, right); } namespace array_binding_details { template <typename T> class array_binding_t_full { public:
inline static constexpr uint32_t operand_type = RAW; T* array; int l, r; T* begin() { return array + l; } T* end() { return array + r + 1; } void resize(const size_t sz) { r = l + sz - 1; } }; class array_binding_t_l_r { public: inline static constexpr uint32_t operand_type = RAW; template <typename T> friend array_binding_t_full<T> operator|(T* array, const array_binding_t_l_r& binding) { return array_binding_t_full<T>{array, binding.l, binding.r}; } int l, r; }; class array_binding_t_l { public:
inline static constexpr uint32_t operand_type = REQUIRE_PARAM; array_binding_t_l_r operator|(const int r) const { return array_binding_t_l_r{l, r}; } int l; }; class array_binding_t_empty { public: inline static constexpr uint32_t operand_type = REQUIRE_PARAM; array_binding_t_l operator|(const int l) const { return array_binding_t_l{l}; } }; static_assert(has_operand_type<array_binding_t_empty>); static_assert(require_param<array_binding_t_empty>); } enum general_operation_t { REVERSE, };
enum comparable_operation_t { SORT, UNIQUE, PREFIX_MIN, PREFIX_MAX, }; enum integer_operation_t { PREFIX_AND, PREFIX_OR, PREFIX_XOR, }; enum number_operation_t { PREFIX_SUM, PREFIX_PROD, }; enum single_input_operation_t { NEXT_INPUT, }; enum array_input_operation_t { ARRAY_INPUT, INDEX_1, }; enum array_output_operation_t { OUTPUT_1LINE, OUTPUT_1_PER_LINE, }; template <typename container_t> auto operator|(container_t&& a, const general_operation_t& op) { switch (op) {
case REVERSE: reverse(a.begin(), a.end()); break; default: assert(false); }; return a; } template <typename container_t> auto operator|(container_t&& a, const comparable_operation_t& op) { switch (op) { case SORT: { sort(a.begin(), a.end()); break; }; case UNIQUE: { sort(a.begin(), a.end()); a.resize(unique(a.begin(), a.end()) - a.begin()); break; } case PREFIX_MIN: { auto begin = a.begin(); ++begin; while (begin < a.end()) { (*begin) = min(*begin, *(begin - 1)); begin++; } break; } case PREFIX_MAX: {
auto begin = a.begin(); ++begin; while (begin < a.end()) { (*begin) = max(*begin, *(begin - 1)); begin++; } break; } default: assert(false); } return a; } template <typename container_t> auto operator|(container_t&& a, const number_operation_t& op) { switch (op) { case PREFIX_SUM: { for (size_t i = 1; i < a.size(); i++) a[i] += a[i - 1]; break; } case PREFIX_PROD: { for (size_t i = 1; i < a.size(); i++) a[i] *= a[i - 1]; break; } default: assert(false); } return a; } template <typename container_t>
auto operator|(container_t&& a, const integer_operation_t& op) { switch (op) { case PREFIX_AND: { for (size_t i = 1; i < a.size(); i++) a[i] &= a[i - 1]; break; } case PREFIX_OR: { for (size_t i = 1; i < a.size(); i++) a[i] |= a[i - 1]; break; } case PREFIX_XOR: { for (size_t i = 1; i < a.size(); i++) a[i] ^= a[i - 1]; break; } default: break; } return a; } template <typename container_t> auto operator|(container_t&& a, const array_input_operation_t& op) { switch (op) { case ARRAY_INPUT: {
for (auto&& x : a) cin >> x; break; } default: assert(0); } return a; } template <typename container_t> auto operator|(container_t&& a, const array_output_operation_t& op) { switch (op) { case OUTPUT_1LINE: { for (auto&& x : a) cout << x << ' '; cout << '\n'; break; } case OUTPUT_1_PER_LINE: { for (auto&& x : a) cout << x << '\n'; cout << '\n'; break; } default: assert(0); } return a; } constexpr array_binding_details::array_binding_t_empty ARRAY; }
// clang-format on
// #define MULTI_TEST
// #define SKIP_ASSERT
#ifdef SKIP_ASSERT
#define assert(x) (x)
#endif
int n;
int a[150001];
vector<int> g[150001];
bool removed[150001];
int64_t ans = 0;
int turn;
int done[150001];
int sz[150001];
int tree_size;
void centroid_dfs(int u) {
done[u] = turn;
sz[u] = 1;
for (auto&& v : g[u])
if (!removed[v]) {
if (done[v] == turn) continue;
centroid_dfs(v);
sz[u] += sz[v];
}
}
const vector<tuple<int, int64_t, int64_t>> dummy;
vector<vector<tuple<int, int64_t, int64_t>>> update;
void dfs(int u, int64_t height = 1, int64_t weighted_sum = 0, int64_t sum = 0) {
weighted_sum += height * a[u];
sum += a[u];
done[u] = turn;
bool is_leaf = 1;
for (auto&& v : g[u])
if (!removed[v]) {
if (done[v] == turn) continue;
dfs(v, height + 1, weighted_sum, sum);
is_leaf = 0;
}
if (is_leaf) {
update.back().emplace_back(height, weighted_sum, sum);
}
}
class line_segment_tree_t {
public:
inline static vector<int64_t> query_point;
line_segment_tree_t *left, *right;
int64_t l, r, m;
int64_t a, b;
line_segment_tree_t(int l, int r) : l(query_point[l]), r(query_point[r]), m((l + r) / 2), a(0), b(-1e18) {
// assert(r < query_point.size());
// assert(l >= 0);
if (l != r) {
left = new line_segment_tree_t(l, m);
right = new line_segment_tree_t(m + 1, r);
} else {
left = right = nullptr;
}
m = query_point[m];
}
~line_segment_tree_t() {
if (left) {
delete left;
delete right;
}
}
void update(const int64_t& p, const int64_t& q) {
// assert(l <= r);
bool better_l = (p * l + q) >= (a * l + b);
bool better_r = (p * r + q) >= (a * r + b);
if (better_l && better_r) {
a = p;
b = q;
} else if (better_l || better_r) {
left->update(p, q);
right->update(p, q);
}
}
int64_t get(const int64_t& u) {
if (l == r) {
return a * u + b;
}
if (m >= u) return max(a * u + b, left->get(u));
else return max(a * u + b, right->get(u));
}
};
void centroid(int u) {
turn++;
centroid_dfs(u);
tree_size = sz[u];
{
find_again:;
for (auto&& v : g[u]) {
if (done[v] != turn) continue;
if ((sz[v] < sz[u]) && (sz[v] * 2 > tree_size)) {
u = v;
goto find_again;
}
}
}
// cerr << "found: " << u << '\n';
turn++;
// we need to pair [height, wsum, sum] with another [height, wsum, sum]
// let this be [h1, w1, s1] and [h2, w2, s2]
// then the answer if we go from leaf 1 to 2 is
// w2 + s2 * (h1 + 1) + ((h1 + 1) * s1 - w1) + a[u] * (h1 + 1)
// rewrite as w2 + (s2 + a[u]) * (h1 + 1) + ((h1 + 1) * s1 - w1)
// this call for a dynamic CHT, which we will have to be able to look up with both range and slope
// the range s2 + a[u] is too big for line segment tree, but we can store all the query first, which ultimately lead to an
// easier implementation.
update.clear();
update.emplace_back(dummy);
update.back().emplace_back(0, 0, 0);
done[u] = turn;
for (auto&& v : g[u]) {
if ((!removed[v]) && (done[v] != turn)) {
update.emplace_back(dummy);
done[v] = turn;
dfs(v);
}
}
for (int direction = 0; direction <= 1; direction++) {
line_segment_tree_t::query_point.clear();
for (auto&& branch : update) {
for (auto&& [h, w, s] : branch) {
line_segment_tree_t::query_point.emplace_back(s + a[u]);
}
}
line_segment_tree_t::query_point | UNIQUE;
static line_segment_tree_t* tree = nullptr;
if (tree) delete tree;
tree = new line_segment_tree_t(0, line_segment_tree_t::query_point.size() - 1);
for (auto&& branch : update) {
for (auto&& [h, w, s] : branch) {
// cerr << h << ' ' << w << ' ' << s << '\n';
ans = max(ans, w + tree->get(s + a[u]));
}
for (auto&& [h, w, s] : branch) tree->update(h + 1, s * (h + 1) - w);
}
update | REVERSE;
}
removed[u] = 1;
for (auto&& v : g[u])
if (!removed[v]) centroid(v);
}
void solve() {
cin >> n;
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
g[u].emplace_back(v);
g[v].emplace_back(u);
}
a | ARRAY | 1 | n | ARRAY_INPUT;
centroid(1);
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
#ifdef MULTI_TEST
cin >> t;
#endif
while (t--) solve();
} | cpp |
1286 | F | F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3
1 10 100
OutputCopy3
InputCopy3
5 3 -2
OutputCopy2
InputCopy1
0
OutputCopy0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed. | [
"brute force",
"constructive algorithms",
"dp",
"fft",
"implementation",
"math"
] | // LUOGU_RID: 102585203
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 22
ll n;
ll p[N],a[N];
ll f[1<<N];
ll cnn[1<<N];
bool vis[1<<N];
inline ll suan(ll x){
if(f[x]!=-1)return f[x];
ll an=(vis[x]);
for(int i=(x-1)&x;i;i=(i-1)&x){
if(!vis[x^i])continue;
if(cnn[i]/2+1<=an)continue;
an=max(an,suan(i)+1);
}return f[x]=an;
}
map<ll,ll>dui;
ll cc=0;
vector<ll>hs[1<<(N-2)];
int main()
{
// freopen("test1.in","r",stdin);
//freopen(".in","r",stdin);
//freopen("test1.out","w",stdout);
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
ll len;cin>>len;
for(int i=1;i<=len;i++)cin>>p[i];
for(int i=1;i<=len;i++)if(p[i]!=0)a[++n]=p[i];
for(int i=1;i<(1<<n);i++){
ll sum=0,cn=0;
for(int j=1;j<=n;j++){
if(i&(1<<(j-1)))sum+=a[j],p[++cn]=a[j];
}cnn[i]=cn;
bool kz=0;
if(cn>=2&&((sum+cn-1)&1)==0){
for(ll k=(sum-cn+1)/2;k<=(sum+cn-1)/2;k++){
if(dui.find(k)!=dui.end()){
for(auto o:hs[dui[k]])if((o|i)==i){kz=1;break;}
}if(kz)break;
}
}
if(dui.find(sum)==dui.end())dui[sum]=++cc;
hs[dui[sum]].push_back(i);
if(!kz)continue;
vis[i]=1;
}memset(f,-1,sizeof(f));
cout<<n-suan((1<<n)-1);
return 0;
}
| cpp |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
int t; cin >> t;
while (t--) {
int n; cin >> n;
vector<int> fin(n);
for (int i = 0; i < n; ++i)
cin >> fin[i];
int pref_num = -1, suff_num = n;
for (int i = 0; i < n; ++i) {
if (fin[i] < i) break;
pref_num = i;
}
for (int i = n-1; i >= 0; --i) {
if (fin[i] < (n-1)-i) break;
suff_num = i;
}
if (suff_num <= pref_num) // Non-empty intersection
cout << "Yes\n";
else
cout << "No\n";
}
}
| cpp |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | #include <iostream>
#include <cmath>
using std::cin, std::cout;
int main(){
int t,n,n1,m,a,b,x,y,c;
cin >> t;
while(t--){
cin>> n;
n1 = n;
b=0,a=0,x=0,y=0,m=3;
if(n%2 == 0){
a = 2;
while(n%2 == 0){
n /= 2;
x++;
}
}
else{
while(m*m < n1){
while(n%m == 0){
n /= m;
x++;
}
if(x != 0){a = m; break;}
m += 2;
}
}
if((n == 1 && x < 6) || m*m >= n1){cout<<"NO"<<'\n';}
else if(n == 1){
cout<<"YES"<<'\n';
b = a*a;
c = pow(a,x-3);
cout<< a <<' '<< b <<' '<< c <<'\n';}
else if(x > 2){
cout<<"YES"<<'\n';
b = pow(a,x-1);
c = n1/pow(a,x);
cout<< a <<' '<< b <<' '<< c <<'\n';}
else{
while(m*m < n1){
while(n%m == 0){
n /= m;
y++;
}
if(y != 0){b = m; break;}
m += 2;
}
if((n == 1 && x+y < 4) || m*m >= n1){cout<<"NO"<<'\n';}
else if(n == 1 && x==1){
cout<<"YES"<<'\n';
c = pow(b,y-1);
cout<< a <<' '<< b <<' '<< c <<'\n';}
else if(n == 1 && y==1){
cout<<"YES"<<'\n';
c = pow(a,x-1);
cout<< a <<' '<< b <<' '<< c <<'\n';}
else if(n == 1){
cout<<"YES"<<'\n';
c = a*b;
a = pow(a,x-1);
b = pow(b,y-1);
cout<< a <<' '<< b <<' '<< c <<'\n';}
else{
cout<<"YES"<<'\n';
a = pow(a,x);
b = pow(b,y);
cout<< a <<' '<< b <<' '<< n <<'\n';
}
}
}
} | cpp |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t,i;
cin >> t;
while(t--)
{
int a,b;
cin >> a>> b;
if(a==b) cout << 0 << endl;
else if(b>a)
{
if(a%2==0 && b%2!=0) cout << 1 << endl;
else if(a%2!=0 && b%2==0) cout << 1 << endl;
else cout << 2 << endl;
}
else if(b<a)
{
if(a%2==0 && b%2!=0) cout << 2 << endl;
else if(a%2!=0 && b%2==0) cout << 2 << endl;
else cout << 1 << endl;
}
}
return 0;
}
| cpp |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define fast \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
#define ll long long int
void solve()
{
int n;
cin >> n;
set<int> s;
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
s.insert(temp);
}
cout << s.size() << endl;
}
int main()
{
fast;
ll t = 1;
cin >> t;
while (t--)
{
solve();
}
return 0;
} | cpp |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string a,b="";
cin>>a;
bitset<26>mp;
int i=0;
bool flag=true;
for(auto c:a)
if(mp[c-'a']==1)
{
if(i<b.size()-1&&b[i+1]==c)
i++;
else if(i!=0 &&b[i-1]==c)
i--;
else
flag=false;
}
else
{
mp[c-'a']=1;
if(i==b.size()-1)
b+=c,i++;
else if(i==0)
b=c+b;
else
flag=false;
}
if(flag)
{
cout<<"YES"<<endl<<b;
for(int i=0;i<26;i++)
if(!mp[i])
cout<<char(i+'a');
cout<<endl;
}
else cout<<"NO"<<endl;
}
} | 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>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define ll long long
#define f first
#define s second
using namespace std;
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// order_of_key (k) : Number of items strictly smaller than k .
// find_by_order(k) : K-th element in a set (counting from zero).
const int inf = 1e9 + 7;
int dp[510][510];
int ans[510];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int n; cin >> n;
for (int i = 1; i <= n; i++) {
cin >> dp[i][i];
}
for (int len = 2; len <= n; len++) {
for (int l = 1; l + len - 1 <= n; l++) {
int r = l + len - 1;
for (int j = l; j < r; j++) {
if (dp[l][j] == dp[j + 1][r] and dp[l][j]) {
dp[l][r] = dp[l][j] + 1;
}
}
}
}
for (int i = 1; i <= n; i++) {
ans[i] = inf;
for (int j = 0; j < i; j++) {
if (dp[j + 1][i]) {
ans[i] = min(ans[i], ans[j] + 1);
}
}
}
cout << ans[n] << '\n';
return 0;
} | cpp |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | #include<bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//#define pbds tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update>
//using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
typedef double db;
typedef long double lld;
typedef unsigned long long ull;
typedef char ch;
typedef vector<int> vi;
typedef vector<long long int> vl;
typedef vector<double> vd;
typedef vector<long double> vld;
typedef vector<int,int> vpii;
typedef vector<long long int,int> vpli;
typedef vector<long long int,long long int> vpll;
typedef vector<int,long long int> vpil;
typedef vector<double,double> pdd;
typedef unordered_map<int,int> umii;
typedef unordered_map<long long int,long long int> umll;
typedef unordered_map<long long int,int> umli;
typedef unordered_map<int,long long int> umil;
typedef unordered_map<int,char> umic;
typedef unordered_map<long long int,char> umlc;
#define ST string
#define F first
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define S second
#define store(x) store.count(x)
#define PB push_back
#define MP make_pair
#define FORI(i,a,b) for(int i=a;i<b;i++)
#define FORL(i,a,b) for(long long i=a;i<b;i++)
#define FORS(s) for(auto i:s)
#define FORV(V) for(auto i:V)
#define sortVector(V) sort(V.begin(),V.end);
#define vecInput(V,n) for(ll i=0;i<n;i++) cin>>V[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.F); cerr << ","; _print(p.S); 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, class V> void _print(unordered_map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
//Modular
const int mod = 998244353;
template <const int32_t MOD> struct modint {
int32_t value;
modint() = default;
modint(int32_t value_) : value(value_) {}
modint(int64_t value_) : value(value_ % MOD) {}
inline modint<MOD> operator+(modint<MOD> other) const {
int32_t c = this->value + other.value;
return modint<MOD>(c >= MOD ? c - MOD : c);
}
inline modint<MOD> operator-(modint<MOD> other) const {
int32_t c = this->value - other.value;
return modint<MOD>(c < 0 ? c + MOD : c);
}
inline modint<MOD> operator*(modint<MOD> other) const {
int32_t c = (int64_t)this->value * other.value % MOD;
return modint<MOD>(c < 0 ? c + MOD : c);
}
inline modint<MOD> &operator+=(modint<MOD> other) {
this->value += other.value;
if (this->value >= MOD)
this->value -= MOD;
return *this;
}
inline modint<MOD> &operator-=(modint<MOD> other) {
this->value -= other.value;
if (this->value < 0)
this->value += MOD;
return *this;
}
inline modint<MOD> &operator*=(modint<MOD> other) {
this->value = (int64_t)this->value * other.value % MOD;
if (this->value < 0)
this->value += MOD;
return *this;
}
inline modint<MOD> operator-() const {
return modint<MOD>(this->value ? MOD - this->value : 0);
}
modint<MOD> pow(uint64_t k) const {
modint<MOD> x = *this, y = 1;
for (; k; k >>= 1) {
if (k & 1)
y *= x;
x *= x;
}
return y;
}
modint<MOD> inv() const { return pow(MOD - 2); } // MOD must be a prime
inline modint<MOD> operator/(modint<MOD> other) const {
return *this * other.inv();
}
inline modint<MOD> operator/=(modint<MOD> other) {
return *this *= other.inv();
}
inline bool operator==(modint<MOD> other) const {
return value == other.value;
}
inline bool operator!=(modint<MOD> other) const {
return value != other.value;
}
inline bool operator<(modint<MOD> other) const { return value < other.value; }
inline bool operator>(modint<MOD> other) const { return value > other.value; }
};
template <int32_t MOD> modint<MOD> operator*(int64_t value, modint<MOD> n) {
return modint<MOD>(value) * n;
}
template <int32_t MOD> modint<MOD> operator*(int32_t value, modint<MOD> n) {
return modint<MOD>(value % MOD) * n;
}
template <int32_t MOD> istream &operator>>(istream &in, modint<MOD> &n) {
return in >> n.value;
}
template <int32_t MOD> ostream &operator<<(ostream &out, modint<MOD> n) {
return out << n.value;
}
using mint = modint<mod>;
//Modular
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
template<class T>
bool isFloatequal(T a,T b)
{
if(abs(a-b)<1e-9)
{
return true;
}
return false;
}
mint power(mint x, int y){
mint prod = 1;
while(y){
if(y&1) prod = (prod * x);
x = (x * x);
y /= 2;
}
return prod;
}
vector<mint> fact(200005,0);
mint ncr(int n, int r){
if(n < r) return 0;
mint ans = fact[n];
mint x = (fact[r] * fact[n - r]);
ans *= power(x, mod - 2);
return ans;
}
bool AreSame(double a, double b)
{
return fabs(a - b) < DBL_EPSILON;
}
void solve(){
ll n,m,p;
cin>>n>>m>>p;
ll ans=0;
bool flag=false;
for(ll i=0;i<n;i++){
ll a;
cin>>a;
if(!flag&&a%p!=0){
ans+=i;
flag=true;
}
}
flag=false;
for(ll i=0;i<m;i++){
ll a;
cin>>a;
if(!flag&&a%p!=0){
ans+=i;
flag=true;
}
}
cout<<ans<<endl;
}
int main(int argc, const char * argv[]) {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int t=1;
//cin>>t;
while(t--)
{
solve();
}
return 0;
}
| cpp |
13 | D | D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7 | [
"dp",
"geometry"
] | #include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=505;
const double eps=1e-9;
struct Point
{
int x,y;
Point(){};
Point(int _x,int _y)
{
x=_x,y=_y;
}
Point operator-(const Point &b)const
{
return Point(x-b.x,y-b.y);
}
ll operator*(const Point &b)const
{
return (ll)x*b.y-(ll)y*b.x;
}
}a[maxn],b[maxn];
int n,m,dp[maxn][maxn];
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>a[i].x>>a[i].y;
}
for(int i=1;i<=m;i++)
{
cin>>b[i].x>>b[i].y;
}
a[0]=Point(-1e9-1,-1e9-1);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if((a[i]-a[0])*(a[j]-a[0])<=0) continue;
for(int k=1;k<=m;k++)
{
int now=((b[k]-a[0])*(b[k]-a[i])>0)+((b[k]-a[i])*(b[k]-a[j])>0)+((b[k]-a[j])*(b[k]-a[0])>0);
if(now==0 || now>=3) dp[i][j]++;
}
dp[j][i]=-dp[i][j];
}
}
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
for(int k=j+1;k<=n;k++)
{
if(dp[i][j]+dp[j][k]+dp[k][i]==0)
{
// cout<<i<<" "<<j<<" "<<k<<endl;
ans++;
}
}
}
}
cout<<ans<<endl;
return 0;
} | cpp |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
// Vamos Abhinav
// NO OBSTACLE IS BIGGER THAN HUMAN CAPABILITIES
#define fo(i, n) for (i = 0; i < n; i++)
#define FO(i, n) for (i = 1; i <= n; i++)
#define ll long long
#define PI 3.1415926535897932384626
#define pb push_back
#define endl '\n'
const int mod = 596799;
const int N = 1e5, M = N;
void abhinav()
{
ll n,i;
cin>>n;
vector<ll> v(n),ans;
fo(i,n) cin>>v[i];
set<ll>s;
fo(i,2*n) s.insert(i+1);
fo(i,n) s.erase(v[i]);
fo(i,n)
{
ans.pb(v[i]);
auto it=s.upper_bound(v[i]);
if(*it<=v[i])
{
cout<<-1;
return;
}
ans.pb(*it);
s.erase(*it);
}
fo(i,ans.size()) cout<<ans[i]<<" ";
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
int t = 1;
cin >> t;
while(t--)
{
abhinav();
cout << "\n";
}
} | cpp |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | #include <bits/stdc++.h>
using namespace std;
const int MN=8e4;
int N, at=170, dist[MN], ans = MN; bool pvis[1001], vis[MN];
set<int> start; vector<int> prime, vals, adj[MN];
unordered_map<int, int> ind; // (value, index it maps to)
queue<pair<int, pair<int, int> > > next1; // (distance, (node, parent))
void bfs(int j){ memset(vis, 0, sizeof(vis)); next1.push({0, {j, j}});
while (!next1.empty()) { int d = next1.front().first;
int x = next1.front().second.first; int p = next1.front().second.second;
next1.pop(); if(vis[x]) continue; vis[x]=1; dist[x] = d; bool skip=0;
for (int i: adj[x]) if(adj[i].size()>1 || i>j) {
if (i != p || skip)
{ if (vis[i]) ans = min(ans, dist[i] + dist[x] + 1);
else next1.push({d + 1, {i, x}}); }
else skip = 1;
}
}
}
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
prime.reserve(170); prime.push_back(1);
for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.push_back(i);
for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; }
cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x;
for (int j=1; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0;
while (x%prime[j] == 0) { x /= prime[j]; cnt++; }
if (cnt%2 == 1) vals.push_back(prime[j]); }
if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; }
vals.push_back(x); if (vals.size() == 1) vals.push_back(1);
for (int k: vals) if (ind.count(k) == 0)
{ if (k > 1e3) ind[k] = at++;
else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin();
ind[k]=t; start.insert(t); } }
adj[ind[vals[0]]].push_back(ind[vals[1]]);
adj[ind[vals[1]]].push_back(ind[vals[0]]);
}
for (int j: start) if(adj[j].size()>1) bfs(j);
cout << (ans == MN ? -1 : ans) <<'\n';
} | 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;
#ifndef ONLINE_JUDGE
#define dbg(x) \
cerr << #x << " "; \
_print(x); \
cerr << endl;
#else
#define dbg(x) ;
#endif
typedef long long ll;
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(double t) { cerr << t; }
template <class T, class V>
void _print(pair<T, V> p);
template <class T>
void _print(vector<T> v);
template <class T>
void _print(set<T> v);
template <class T, class V>
void _print(map<T, V> v);
template <class T>
void _print(multiset<T> v);
template <class T, class V>
void _print(pair<T, V> p)
{
cerr << "{";
_print(p.ff);
cerr << ",";
_print(p.ss);
cerr << "}";
}
template <class T>
void _print(vector<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T>
void _print(set<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T>
void _print(multiset<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T, class V>
void _print(map<T, V> v)
{
cerr << "[ ";
for (auto i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
void solve()
{
ll n;
cin >> n;
ll arr[n];
ll count =0;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
if(arr[i]==0)
{
++count;
arr[i] = arr[i] + 1;
}
}
ll x = accumulate(arr,arr+n,0);
if(x==0)
cout << count+1 << endl;
else
cout << count << endl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("inputf.txt", "r", stdin);
freopen("outputf.txt", "w", stdout);
freopen("errorf.txt", "w", stderr);
#endif
int t;
cin >> t;
while (t--)
{
solve();
}
return 0;
} | cpp |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | // LUOGU_RID: 101755148
#pragma GCC optimize(3)
#pragma GCC target("avx")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("inline-functions")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("inline-small-functions")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("inline-functions-called-once")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
#pragma GCC optimize("Ofast", "inline", "-ffast-math")
#include <bits/stdc++.h>
using namespace std;
mt19937 gen(chrono::system_clock::now().time_since_epoch().count());
uniform_int_distribution <> dist(1, 1e9);
const int N = 1e5 + 10;
struct Node
{
int x;
long long val;
Node()
{
x = val = 0;
}
bool operator<(const Node &rhs) const
{
return val > rhs.val;
}
} a[N];
int rnd[N];
long long lcm(int a, int b)
{
return 1ll * b * a / __gcd(a, b);
}
signed main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++ i)
scanf("%d", &a[i]);
if (n <= 2500)
{
long long ans = 0;
for (int i = 1; i <= n; ++ i)
for (int j = 1; j <= n; ++ j)
ans = max(ans, lcm(a[i].x, a[j].x));
cout << ans << '\n';
}
else
{
for (int i = 1; i <= 35; ++ i)
rnd[i] = dist(gen) % n + 1;
for (int i = 1; i <= n; ++ i)
for (int j = 1; j <= 35; ++ j)
a[i].val = max(a[i].val, lcm(a[i].x, a[rnd[j]].x));
sort (a + 1, a + n + 1);
long long ans = 0;
for (int i = 1; i <= 18; ++ i)
for (int j = 1; j <= n; j ++)
ans = max(ans, lcm(a[i].x, a[j].x));
for (int i = 1; i <= 1400; ++ i)
for (int j = 1; j <= 1400; ++ j)
ans = max(ans, lcm(a[i].x, a[j].x));
cout << ans << '\n';
}
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 <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;
if(n%m==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
} | cpp |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t; cin >> t;
while(t--){
int a, b, p;
cin >> a >> b >> p;
string s; cin >> s;
int n = s.length();
int cost = 0, ans = n;
for(int i=n-2; i>=0; i--){
if(i==0){
if(s[i]=='A'){
cost+=a;
}
else{
cost+=b;
}
if(cost<=p){
ans = 1;
}
break;
}
if(s[i]!=s[i-1]){
if(s[i]=='A'){
cost+=a;
}
else{
cost+=b;
}
if(cost>p){
break;
}
else{
ans = i+1;
}
}
}
cout << ans << endl;
}
} | cpp |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
| [
"constructive algorithms",
"sortings"
] | #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define elif else if
#define accepted cout << "YES\n"
#define error cout << "NO\n"
using namespace std;
const ll N = 2e10;
const ll mod = 1e9 + 7;
void func()
{
ll n;
cin >> n;
vector < ll > a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
sort(rall(a));
for (int i = 0; i < n; i++)
cout << a[i] << " \n"[i == n - 1];
}
int main()
{
setlocale(LC_ALL, "Russian");
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
ll t = 1;
cin >> t;
while (t--)
func();
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"
] | // S2OJ Submission #67658 @ 1675085389162
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdio>
#include <map>
#define int long long
#define maxn 600005
using namespace std;
inline int read(){
int x = 0, flag = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){
if(ch == '-') flag = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
x = (x << 3) + (x << 1) + ch - '0';
ch = getchar();
}
return x * flag;
}
inline int readc(){
char ch = getchar();
while(ch < 'a' || ch > 'z') ch = getchar();
return ch - 'a' + 1;
}
const int MASK = (1 << 30) - 1;
int n, nxt[maxn], lst[maxn][30], s[maxn], w[maxn], SUM;
__int128 lstans;
bool vis[maxn];
map <int, int> mp;
int q[maxn], top;
vector <int> tmp;
int getlst(int x, int c){
if(!x) return 0;
if(!vis[x]) return x;
return lst[x][c] = getlst(lst[x][c], c);
}
void write(__int128 x){
if(x / 10) write(x / 10);
putchar(x % 10 + '0');
return;
}
signed main(){
n = read();
for(int i = 1, j = 0; i <= n; ++i){
s[i] = readc(), w[i] = read();
s[i] = ((s[i] + lstans - 1) % 26) + 1;
w[i] = w[i] ^ (lstans & MASK);
// cout<<s[i]<<' '<<w[i]<<endl;
int now = i - 1;
while(now = getlst(lst[now][s[i]], s[i])){
vis[now] = 0;
int mn = w[q[lower_bound(q + 1, q + top + 1, i - now) - q]];
SUM -= mn;
--mp[mn];
if(!mp[mn]) mp.erase(mn);
// cout<<"del "<<mn<<endl;
}
int cnt = 0;
for(auto id = mp.end(); id != mp.begin(); --id){
auto x = id; --x;
if(x -> first > w[i]){
// cout << "change "<<x.first<<endl;
cnt += x -> second;
SUM -= x -> second * x -> first;
tmp.push_back(x -> first);
}else break;
}
for(auto x : tmp) mp.erase(x);
tmp.clear();
mp[w[i]] += cnt;
SUM += cnt * w[i];
while(top && w[q[top]] >= w[i]) --top;
q[++top] = i;
if(s[i] == s[1]) ++mp[w[i]], SUM += w[i];
lstans += SUM;
write(lstans), putchar('\n');
if(i == 1) continue;
while(j && s[i] != s[j + 1]) j = nxt[j];
if(s[i] == s[j + 1]) ++j;
nxt[i] = j;
for(int c = 1; c <= 26; ++c){
if(s[nxt[i] + 1] != c) lst[i][c] = nxt[i];
else lst[i][c] = lst[nxt[i]][c];
// cout << "lst "<<i<<' '<<c<<" = "<<lst[i][c]<<endl;
}
}
return 0;
} | cpp |
1316 | F | F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212. | [
"data structures",
"divide and conquer",
"probabilities"
] | #include <bits/stdc++.h>
#define st first
#define nd second
using lint = int64_t;
constexpr int mod = int(1e9) + 7;
constexpr int inf = 0x3f3f3f3f;
constexpr int ninf = 0xcfcfcfcf;
constexpr lint linf = 0x3f3f3f3f3f3f3f3f;
const long double pi = acosl(-1.0);
// Returns -1 if a < b, 0 if a = b and 1 if a > b.
int cmp_double(double a, double b = 0, double eps = 1e-9) {
return a + eps > b ? b + eps > a ? 0 : 1 : -1;
}
using namespace std;
template<class T> struct segtree_range {
int H, N;
vector<T> ts;
segtree_range() {}
explicit segtree_range(int N_) {
for (H = 0, N = 1; N < N_; ++H, N *= 2) {}
ts.resize(2*N);
}
template<class Q> explicit segtree_range(const vector<Q>& qs) {
const int N_ = int(qs.size());
for (H = 1, N = 1; N < N_; ++H, N *= 2) {}
ts.resize(2*N);
for (int i = 0; i < N_; ++i) at(i) = T(qs[i]);
build();
}
T& at(int a) { return ts[a + N]; }
void build() { for (int a = N; --a; ) merge(a); }
inline void push(int a) { ts[a].push(ts[2 * a], ts[2 * a + 1]); }
inline void merge(int a) { ts[a].merge(ts[2*a], ts[2*a+1]); }
void for_parents_down(int a, int b) {
for (int h = H; h; --h) {
const int l = (a >> h), r = (b >> h);
if (l == r) {
if ((l << h) != a || (r << h) != b) push(l);
} else {
if ((l << h) != a) push(l);
if ((r << h) != b) push(r);
}
}
}
void for_parents_up(int a, int b) {
for (int h = 1; h <= H; ++h) {
const int l = (a >> h), r = (b >> h);
if (l == r) {
if ((l << h) != a || (r << h) != b) merge(l);
} else {
if ((l << h) != a) merge(l);
if ((r << h) != b) merge(r);
}
}
}
template<class F, class... Args> void update(int a, int b, F f, Args&&... args) {
if (a == b) return;
a += N; b += N;
for_parents_down(a, b);
for (int l = a, r = b; l < r; l /= 2, r /= 2) {
if (l & 1) (ts[l++].*f)(args...);
if (r & 1) (ts[--r].*f)(args...);
}
for_parents_up(a, b);
}
T query(int a, int b) {
if (a == b) return T();
a += N; b += N;
for_parents_down(a, b);
T lhs, rhs, t;
for (int l = a, r = b; l < r; l /= 2, r /= 2) {
if (l & 1) { t.merge(lhs, ts[l++]); lhs = t; }
if (r & 1) { t.merge(ts[--r], rhs); rhs = t; }
}
t.merge(lhs, rhs); return t;
}
template<class Op, class E, class F, class... Args>
auto query(int a, int b, Op op, E e, F f, Args&&... args) {
if (a == b) return e();
a += N; b += N;
for_parents_down(a, b);
auto lhs = e(), rhs = e();
for (int l = a, r = b; l < r; l /= 2, r /= 2) {
if (l & 1) lhs = op(lhs, (ts[l++].*f)(args...));
if (r & 1) rhs = op((ts[--r].*f)(args...), rhs);
}
return op(lhs, rhs);
}
// find min i s.t. T::f(args...) returns true in [a, i) from left to right
template<class F, class... Args> int find_right(int a, F f, Args &&... args) {
assert(0 <= a && a <= N);
if ((T().*f)(args...)) return a;
if (a == N) return 1 + N;
a += N;
for (int h = H; h; --h) push(a >> h);
for (; ; a /= 2) if (a & 1) {
if ((ts[a].*f)(args...)) {
for (; a < N; ) {
push(a);
if (!(ts[a <<= 1].*f)(args...)) ++a;
}
return a - N + 1;
}
++a;
if (!(a & (a - 1))) return N + 1;
}
}
// find max i s.t. T::f(args...) returns true in [i, a) from right to left
template<class F, class... Args> int find_left(int a, F f, Args &&... args) {
assert(0 <= a && a <= N);
if ((T().*f)(args...)) return a;
if (a == 0) return -1;
a += N;
for (int h = H; h; --h) push((a - 1) >> h);
for (; ; a /= 2) if ((a & 1) || a == 2) {
if ((ts[a - 1].*f)(args...)) {
for (; a <= N; ) {
push(a - 1);
if (!(ts[(a <<= 1) - 1].*f)(args...)) --a;
}
return a - N - 1;
}
--a;
if (!(a & (a - 1))) return -1;
}
}
};
template<unsigned M_> struct modnum {
static constexpr unsigned M = M_;
using ll = long long; using ull = unsigned long long; unsigned x;
constexpr modnum() : x(0U) {}
constexpr modnum(unsigned x_) : x(x_ % M) {}
constexpr modnum(int x_) : x(((x_ %= static_cast<int>(M)) < 0) ? (x_ + static_cast<int>(M)) : x_) {}
constexpr modnum(ull x_) : x(x_ % M) {}
constexpr modnum(ll x_) : x(((x_ %= static_cast<ll>(M)) < 0) ? (x_ + static_cast<ll>(M)) : x_) {}
explicit operator int() const { return x; }
modnum& operator+=(const modnum& a) { x = ((x += a.x) >= M) ? (x - M) : x; return *this; }
modnum& operator-=(const modnum& a) { x = ((x -= a.x) >= M) ? (x + M) : x; return *this; }
modnum& operator*=(const modnum& a) { x = unsigned((static_cast<ull>(x) * a.x) % M); return *this; }
modnum& operator/=(const modnum& a) { return (*this *= a.inv()); }
modnum operator+(const modnum& a) const { return (modnum(*this) += a); }
modnum operator-(const modnum& a) const { return (modnum(*this) -= a); }
modnum operator*(const modnum& a) const { return (modnum(*this) *= a); }
modnum operator/(const modnum& a) const { return (modnum(*this) /= a); }
modnum operator+() const { return *this; }
modnum operator-() const { modnum a; a.x = x ? (M - x) : 0U; return a; }
modnum pow(ll e) const {
if (e < 0) return inv().pow(-e);
modnum x2 = x, xe = 1U;
for (; e; e >>= 1) {
if (e & 1) xe *= x2;
x2 *= x2;
}
return xe;
}
modnum inv() const {
unsigned a = x, b = M; int y = 1, z = 0;
while (a) {
const unsigned q = (b/a), c = (b - q*a);
b = a, a = c; const int w = z - static_cast<int>(q) * y;
z = y, y = w;
} assert(b == 1U); return modnum(z);
}
friend modnum inv(const modnum& a) { return a.inv(); }
template<typename T> friend modnum operator+(T a, const modnum& b) { return (modnum(a) += b); }
template<typename T> friend modnum operator-(T a, const modnum& b) { return (modnum(a) -= b); }
template<typename T> friend modnum operator*(T a, const modnum& b) { return (modnum(a) *= b); }
template<typename T> friend modnum operator/(T a, const modnum& b) { return (modnum(a) /= b); }
friend bool operator==(const modnum& a, const modnum& b) { return a.x == b.x; }
friend bool operator!=(const modnum& a, const modnum& b) { return a.x != b.x; }
friend ostream &operator<<(ostream& os, const modnum& a) { return os << a.x; }
friend istream &operator>>(istream& in, modnum& n) { ull v_; in >> v_; n = modnum(v_); return in; }
};
using mint = modnum<mod>;
vector<mint>inv2, p2;
struct seg_node{
mint val, lo, hi;
int sz;
seg_node(mint p = 0, int c = 0): val(0), lo(p), hi(p*inv2[1]), sz(c) {}
void push(seg_node& l, seg_node& r){}
void merge(const seg_node& l, const seg_node& r){
val = l.val + r.val + l.lo * r.hi * inv2[l.sz];
lo = l.lo + r.lo * p2[l.sz];
hi = l.hi + r.hi * inv2[l.sz];
sz = l.sz + r.sz;
}
void rem(){
val = lo = hi = 0;
sz = 0;
}
void add(mint p){
val = 0;
lo = p;
hi = p * inv2[1];
sz = 1;
}
mint get_val() { return val; }
};
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
{
p2 = inv2 = vector<mint>(1100000);
p2[0] = inv2[0] = 1;
mint inv = mint(1)/mint(2);
for(int i=1;i<1100000;i++){
p2[i] = 2 * p2[i-1];
inv2[i] = inv * inv2[i-1];
}
}
int n, q;
cin>>n;
vector<int>a(n);
for(int i=0;i<n;i++) cin>>a[i];
vector<int>v = a;
cin>>q;
vector<pair<int, int>>qr(q);
for(int i=0;i<q;i++){
int j, x;
cin>>j>>x; j--;
qr[i] = {j, x};
v.push_back(x);
}
sort(v.begin(), v.end());
int m = n + q;
vector<int>pos(m);
segtree_range<seg_node>seg(m);
for(int i=0;i<n;i++){
a[i] = int(lower_bound(v.begin(), v.end(), a[i]) - v.begin());
a[i] += pos[a[i]]++;
seg.at(a[i]) = seg_node(v[a[i]], 1);
}
seg.build();
cout<<seg.query(0, m).get_val()<<"\n";
for(int i=0;i<q;i++){
auto [j, x] = qr[i];
x = int(lower_bound(v.begin(), v.end(), x) - v.begin());
x += pos[x]++;
seg.update(a[j], a[j]+1, &seg_node::rem);
a[j] = x;
seg.update(a[j], a[j]+1, &seg_node::add, v[a[j]]);
cout<<seg.query(0, m).get_val()<<"\n";
}
return 0;
}
/*
[ ]Leu o problema certo???
[ ]Ver se precisa de long long
[ ]Viu o limite dos fors (é n? é m?)
[ ]Tamanho do vetor, será que é 2e5 em vez de 1e5??
[ ]Testar sample
[ ]Testar casos de borda
[ ]1LL no 1LL << i
[ ]Testar mod (é 1e9+7, mesmo?, será que o mod não ficou negativo?)
*/
| cpp |
13 | D | D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7 | [
"dp",
"geometry"
] | //https://codeforces.com/problemset/problem/13/D
#include<bits/stdc++.h>
#define VI vector<int>
typedef long double db;
using namespace std;
const db eps=1e-20;
const db PI = acos(-1.);
int sign(db x) {return x<-eps?-1:x>eps;}
int cmp(db x, db y) {return sign(x-y);}
struct Point{
db x,y;
Point(){}
Point(db _x, db _y):x(_x),y(_y){}
Point operator+(Point p) const { return {x+p.x,y+p.y}; }
Point operator-(Point p) const { return {x-p.x,y-p.y}; }
// Point operator*(db d) const{ return {1.*x*d,1.*y*d}; }
// Point operator/(db d) const{ return {1.*x/d,1.*y/d}; }
db det(Point p) { return x*p.y-y*p.x; }
db dot(Point p) { return x*p.x+y*p.y; }
db abs2() {return x*x+y*y;}
db abs() {return sqrt(abs2());}
db dist(Point p) {return (*this-p).abs(); }
// Point unit() {return *this/abs();}
// Point rot90() {return {y,-x};}
bool quad() {return sign(y)==0?sign(x)>=0:sign(y)>0;}
}center;
int n,m;
struct P{
Point p;
int col;
}a[1005];
bool ang(P a, P b) {
if ((a.p-center).quad()^(b.p-center).quad()) {
return (a.p-center).quad();
}
return sign((a.p-center).det(b.p-center))>0;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for (int i=1; i<=n; ++i) {
cin>>a[i].p.x>>a[i].p.y;
a[i].col=1;
}
for (int i=n+1; i<=n+m; ++i){
cin>>a[i].p.x>>a[i].p.y;
a[i].col=0;
}
vector<P> v;
for (int i=n+m; i; i--) {
v.push_back(a[i]);
}
int ans=0;
for (int i=1; i<=n; ++i) {
center=v.back().p;
v.pop_back();
auto b=v;
sort(b.begin(),b.end(),ang);
b.insert(b.end(),b.begin(),b.end());
for (int j=0; j<n+m-i; ++j) {
if (b[j].col) {
// cout << "the" << j << "th point:" << b[j].p.x << ' ' << b[j].p.y << endl;
Point mx = b[j].p-center;
for (int k=j+1; k<b.size(); ++k) {
if (sign((b[j].p-center).det(b[k].p-center))<0 || k-j==n+m-i) break;
if (b[k].col) {
if (mx.det(b[k].p-b[j].p)>0) ++ans;
}
else {
if (mx.det(b[k].p-b[j].p)>0) mx=b[k].p-b[j].p;
}
}
// cout << j << ": " << ans << endl;
}
}
// cout << ans << endl;
}
cout << ans << '\n';
} | 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<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
pair<long long int,int> p[n+1];
for(int i=0; i<n; i++){
cin>>p[i].first;
}
for(int i=0; i<n; i++)
cin>>p[i].second;
sort(p,p+n);
p[n].first=2*(pow(10,9));
p[n].second=0;
long long int ans=0;
priority_queue<int> q;
q.push(p[0].second);
long long int size=p[0].second;
for( int i=1; i<n+1; i++ ){
long long int c=p[i].first-p[i-1].first;
while((!q.empty())&&(c>0)){
size-=q.top();
q.pop();
ans+=size;
c--;
}
q.push(p[i].second);
size+=p[i].second;
}
cout<<ans<<"\n";
}
| cpp |
1311 | C | C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11. | [
"brute force"
] | #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> fre(26), v;
string s;
cin >> s;
v.assign(a, 0);
while (b--)
{
int num;
cin >> num;
v[0]++;
v[num]--;
//cout << v << nl;
}
int sum = 1;
for (int i = 0; i < a; i++)
{
sum += v[i];
fre[s[i] - 'a'] += sum;
}
for (int i = 0; i < 26; i++)
{
cout << fre[i] << " ";
}
cout << nl;
}
int main()
{
sherry();
int t = 1;
cin >> t;
while (t--)
solve();
Time 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>
#include <fstream>
#include <stack>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <array>
#include <bitset>
#include <queue>
#include <cstring>
#include <iomanip>
#define int long long
#define all(v) begin(v), end(v)
#define ve vector
#define vi vector<int>
#define vd vector<double>
#define pb push_back
#define pii pair<int,int>
#define rep(i, n) for(int i = 0; i < (n); i++)
using namespace std;
using ll = long long;
using ull = unsigned long long;
const double pi = atan(1) * 4;
void fast() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cout << fixed; cout.precision(10);
}
void solve() {
int x, y, a, b;
cin >> x >> y >> a >> b;
if ((y - x) % (a + b) == 0) {
int t = (y - x) / (a + b);
cout << t << "\n";
}
else {
cout << "-1\n";
}
}
signed main() {
#ifdef LOCAL
freopen("local.in", "r", stdin);
freopen("local.out", "w", stdout);
#endif
fast();
int T = 1;
cin >> T;
while (T--)
solve();
return 0;
} | cpp |
1284 | G | G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1). For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1) For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
O
OOO
NO
YES
OOOOO X
O O
X O O X
O
OOO X O
O O O
O OOOOO
YES
OOOOOOOOOOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
| [
"graphs"
] | #include <bits/stdc++.h>
using namespace std;
const int maxn = 810;
int T, n, m, fa[maxn], d[maxn], pre[maxn], lim[maxn], eid[22][22][2];
bool bad[maxn], mark[maxn], vis[maxn], in1[maxn], in2[maxn], ban[maxn];
vector<int> G[maxn];
char str[22][22], ans[42][42];
int id(int x, int y) {
return (x - 1) * m + y;
}
int find(int x) {
while (x ^ fa[x]) x = fa[x] = fa[fa[x]];
return x;
}
int main() {
scanf("%d", &T);
while (T--) {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%s", str[i] + 1);
for (int j = 1; j <= m; j++) ban[id(i, j)] = str[i][j] == 'X';
}
memset(mark, 0, sizeof(mark));
memset(eid, -1, sizeof(eid));
memset(lim, 0, sizeof(lim));
memset(bad, 0, sizeof(bad));
int cnt = 0;
vector<array<int, 2>> E;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) if (str[i][j] == 'O') {
cnt++, bad[id(i, j)] = (i + j + 1) % 2 && (i > 1 || j > 1);
if (i < n && str[i + 1][j] == 'O') {
eid[i][j][0] = E.size(), E.push_back({id(i, j), id(i + 1, j)});
lim[id(i, j)]++, lim[id(i + 1, j)]++;
}
if (j < m && str[i][j + 1] == 'O') {
eid[i][j][1] = E.size(), E.push_back({id(i, j), id(i, j + 1)});
lim[id(i, j)]++, lim[id(i, j + 1)]++;
}
}
}
bool ok = 1;
for (int i = 1; i <= n * m; i++) {
if (bad[i] && (lim[i] -= 2) < 0) { ok = 0; break; }
}
if (!ok) { puts("NO"); continue; }
while (count(mark, mark + E.size(), 0) >= cnt) {
vector<int> I, J;
for (int i = 0; i < E.size(); i++) {
G[i].clear(), (mark[i] ? I : J).push_back(i);
}
for (int i : I) {
fill(d + 1, d + n * m + 1, 0);
for (int j : I) {
if (i ^ j) d[E[j][0]]++, d[E[j][1]]++;
}
for (int j : J) {
if (d[E[j][0]] < lim[E[j][0]] && d[E[j][1]] < lim[E[j][1]]) G[j].push_back(i);
}
}
for (int i : J) {
iota(fa + 1, fa + n * m + 1, 1);
for (int j : J) {
if (i ^ j) fa[find(E[j][0])] = find(E[j][1]);
}
int num = 0;
for (int j = 1; j <= n * m; j++) {
if (!ban[j] && j == find(j)) num++;
}
for (int j : I) {
if (num == 1 || num == 2 && find(E[j][0]) ^ find(E[j][1])) G[j].push_back(i);
}
}
fill(in1, in1 + E.size(), 0);
fill(in2, in2 + E.size(), 0);
for (int i : J) {
iota(fa + 1, fa + n * m + 1, 1);
fill(d + 1, d + n * m + 1, 0);
bool flag = 0;
for (int j = 0; j < E.size(); j++) {
if (i ^ j && !mark[j]) fa[find(E[j][0])] = find(E[j][1]);
else if (++d[E[j][0]] > lim[E[j][0]] || ++d[E[j][1]] > lim[E[j][1]]) flag = 1;
}
int num = 0;
for (int j = 1; j <= n * m; j++) {
if (!ban[j] && j == find(j)) num++;
}
in1[i] = num == 1, in2[i] = !flag;
}
fill(vis, vis + E.size(), 0);
queue<int> Q;
for (int i = 0; i < E.size(); i++) {
if (in1[i]) Q.push(i), vis[i] = 1;
}
bool flag = 0;
while (!Q.empty()) {
int u = Q.front(); Q.pop();
if (in2[u]) {
while (1) {
mark[u] ^= 1;
if (in1[u]) break;
u = pre[u];
}
flag = 1; break;
}
for (int v : G[u]) if (!vis[v]) {
Q.push(v), vis[v] = 1, pre[v] = u;
}
}
if (!flag) break;
}
if (count(mark, mark + E.size(), 0) >= cnt) {
puts("NO"); continue;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ans[2 * i - 1][2 * j - 1] = str[i][j];
ans[2 * i][2 * j - 1] = ~eid[i][j][0] && mark[eid[i][j][0]] ? ' ' : 'O';
ans[2 * i - 1][2 * j] = ~eid[i][j][1] && mark[eid[i][j][1]] ? ' ' : 'O';
ans[2 * i][2 * j] = ' ';
}
}
puts("YES");
for (int i = 1; i < 2 * n; i++) {
for (int j = 1; j < 2 * m; j++) putchar(ans[i][j]);
putchar('\n');
}
}
return 0;
} | cpp |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | [
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
//-------------------------------------------------------
void fast(){ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);}
//-------------------------------------------------------
#define endl '\n'
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define sz(s) (int)(s.size())
#define inf 0x3f3f3f3f3f3f3f3fLL
#define watch(x) cout<<(#x)<<" = "<<x<<endl
#define clr(arr, val) memset(arr, val, sizeof(arr))
string ABC = "abcdefghijklmnopqrstuvwxyz";
//const int dr[] {-1, -1, 0, 1, 1, 1, 0, -1};
//const int dc[] {0, 1, 1, 1, 0, -1, -1, -1};
typedef long long ll;
const int OO = 0x3f3f3f3f;
///-------------- may need them -----------------//
//int n;cin>>n;vector<int>ar(n);for(int &i:ar){cin>>i;}
//int dx[] = {2,-2,2,-2,1,1,-1,-1}, dy[] = {1,1,-1,-1,2,-2,2,-2}; // knight moves
//int dx[] = {0,0,1,1,1,-1,-1,-1}, dy[] = {-1,1,-1,0,1,-1,0,1}; // 8 adjacent neighbours
//int dx[] = {0, 0, 1, -1}, dy[] = {-1, 1, 0, 0}; //4 adjacent neighbours
int const N = 3e5+5;
int const M = 2*N;
///---------------------------//
void main1()
{
int n,x=0,y=0,eq=0;cin>>n;
int a[n],b[n];
for(int i=0;i<n;++i){
cin>>a[i];
}
for(int i=0;i<n;++i){
cin>>b[i];
if((b[i] && a[i])||(!b[i] && !a[i]))
eq++;
else if(b[i] && !a[i])
++y;
else
++x;
}
if(eq==n)
cout<<"-1";
else if(x>y)
cout<<1;
else if(x==y){
for(int i=0;i<n;++i){
if(a[i]!=b[i]){
cout<<2;return;
}
cout<<-1;
}
}else{
if(!x)
cout<<-1;
else cout<<(y/x)+1;
}
}
int main()
{
fast();
int T=1;//cin>>T;
//freopen("input.txt" ,"r" ,stdin);
//freopen("output.txt" ,"w" ,stdout);
while(T--) //cin.ignore();
{
main1();
if(T)cout<<endl;
}
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 <iostream>
#include <vector>
#include <bitset>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#include <set>
#include <cstring>
#include <array>
#pragma GCC optimize(2)
#include <bits/stdc++.h>
#define rep(i,from,to) for(int i=from;i<to;i++)
#define ite2(x,y,arr) for(auto [x,y]:arr)
#define pdd pair<double, double>
#define ite(i,arr) for(auto &i:arr)
#define MID(l,r) int mid=(l+r)>>1
#define ALL(arr) arr.begin(),arr.end()
#define AXY(a,x,y) int x=a.first,y=a.second
#define vc vector
#define vi vector<int>
#define vll vector<long long>
#define pii pair<int,int>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
namespace dbg {
#ifdef FTY
template <typename T>
void __print_var(string_view name, const T& x) { std::cerr << name << " = " << x; }
template <typename T>
void __print_var(string_view name, const vector<T>& x) {
std::cerr << name << " = ";
bool is_first = true;
for (auto& ele : x) std::cerr << (is_first ? (is_first = false, "[") : ", ") << ele;
std::cerr << "]";
}
template <typename T>
void __print_var(string_view name, const set<T>& x) {
std::cerr << name << " = ";
bool is_first = true;
for (auto& ele : x) std::cerr << (is_first ? (is_first = false, "{") : ", ") << ele;
std::cerr << "}";
}
template <typename K, typename V>
void __print_var(string_view name, const map<K, V>& x) {
std::cerr << name << " = ";
bool is_first = true;
for (auto& [k, v] : x) std::cerr << (is_first ? (is_first = false, "{") : ", ") << "(" << k << ": " << v << ")";
std::cerr << "}";
}
template <typename T>
void __log(string_view name, const T& x) {
__print_var(name, x); std::cerr << endl;
}
#define LOG(args)\
{ std::cerr << "line " << __LINE__ << ": " << __func__ << "(): ";\
__log(#args, ##args); }
#else
#define LOG(...)
#endif
}
//#define int ll
const double eps = 1e-8;
const double PI = acos(-1);
struct Point {
double x, y;
Point() {
x = 0, y = 0;
}
Point(double x, double y) {
this->x = x;
this->y = y;
}
};
Point operator +(Point a, Point b) {
return Point(a.x + b.x, a.y + b.y);
}
Point operator -(Point a, Point b) {
return Point(a.x - b.x, a.y - b.y);
}
Point operator *(double a, Point b) {
return Point(a * b.x, a * b.y);
}
Point operator *(Point b, double a) {
return Point(a * b.x, a * b.y);
}
Point operator /(Point b, double a) {
return Point(b.x / a, b.y / a);
}
double len(Point a) {
return sqrt(a.x * a.x + a.y * a.y);
}
double dis(Point a, Point b) {
return len(a - b);
}
bool operator ==(Point a, Point b) {
return dis(a, b) <= eps;
}
bool operator !=(Point a, Point b) {
return !(a == b);
}
double operator *(Point a, Point b) {
return a.x * b.x + a.y * b.y;
}
double operator ^(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
double getAngel(double b, double a, double c) {
return acos((a * a + c * c - b * b) / (2 * a * c));
}
double getAngel(Point a, Point b) {
return acos(a * b / len(a) / len(b));
}
int mod = 1e9 + 7;
using namespace dbg;
template <class T>
T __gcd(T a, T b) {
if (a < b) swap(a, b);
return b ? __gcd(b, a % b) : a;
}
template <class T>
T __lcm(T a, T b) {
T num = __gcd(a, b);
return a / num * b;
}
inline int lowbit(int num) { return num & (-num); }
inline int qmi(int a, int b) {
a %= mod;
ll res = 1;
while (b) {
if (b & 1) res = (ll)res * a % mod;
a = (ll)a * a % mod;
b >>= 1;
}
return res;
}
int inv(int num) {
return qmi(num, mod - 2);
}
const int N = 5e5 + 10;
ll fact[(int)N + 5];
ll inv_fact[(int)N + 5];
int prime[(int)N + 5];
int valid[(int)N + 5];
int pn = 0;
inline void getPrime() {
rep(i, 2, N + 1) {
if (!valid[i]) {
valid[i] = i;
prime[pn++] = i;
}
for (int j = 0; j < pn && i * prime[j] <= N; j++) {
valid[i * prime[j]] = prime[j];
if (i % prime[j] == 0) break;
}
}
}
inline void getFact() {
fact[0] = fact[1] = 1;
for (int i = 2; i <= N; i++) {
fact[i] = i * fact[i - 1] % mod;
}
}
inline void getInv() {
inv_fact[N] = inv(fact[N]);
for (int i = N - 1; i >= 0; i--) {
inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod;
}
}
inline ll CC(int n, int m) {
if (m > n) {
return 0;
}//不输出0是为了好debug 此处会有RE !!!
if (m < 0) {
return 1;
}
ll res = fact[n] * inv_fact[m] % mod * inv_fact[n - m] % mod;
return res;
}
int n;
vc<vi> edge;
vi fa;
vi h;
vi value;
map<pii,pii> res;
void dfs(int p, int father,int height) {
fa[p] = father;
h[p] = height;
ite(u, edge[p]) {
if (u != father) {
dfs(u, p,height+1);
}
}
}
bool cherk(int u, int v, int w) {
if (h[u] < h[v]) {
swap(u, v);
}
while (h[u] > h[v]) {
if (value[u] == w) return true;
u = fa[u];
}
while (u != v) {
if (value[u] == w) return true;
u = fa[u];
if (value[v] == w) return true;
v = fa[v];
}
return false;
}
void func(int u, int v, int w) {
if (h[u] < h[v]) {
swap(u, v);
}
while (h[u] > h[v]) {
value[u] = max(value[u], w);
u = fa[u];
}
while (u != v) {
value[u] = max(value[u], w);
u = fa[u];
value[v] = max(value[v], w);
v = fa[v];
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int q = 1;
//cin >> q;
while (q--) {
int n;
cin >> n;
edge.resize(n);
fa.resize(n,-1);
h.resize(n);
value.resize(n, 1);
rep(i, 0, n - 1) {
int u, v;
cin >> u >> v;
u--,v--;
edge[u].push_back(v);
edge[v].push_back(u);
res[{min(u, v), max(u, v) }] = { 1,i };
}
dfs(0, -1,1);
int m;
cin >> m;
queue<array<int, 3>> que;
rep(i, 0, m) {
int u, v;
cin >> u >> v;
u--, v--;
int w;
cin >> w;
func(u, v, w);
array<int, 3> tmp = { u,v,w };
que.push(tmp);
}
int flag = 1;
while (que.size()) {
auto cur = que.front();
que.pop();
int u = cur[0], v = cur[1], w = cur[2];
if (!cherk(u, v, w)) {
flag = 0;
break;
}
}
rep(i, 1, n) {
res[{min(i, fa[i]), max(i, fa[i])}].first = value[i];
}
if (flag) {
vi ans(n - 1);
ite2(__, v, res) {
ans[v.second] = v.first;
}
ite(i, ans) cout << i << ' ';
cout << endl;
}
else {
cout << -1 << endl;
}
}
return 0;
}
| cpp |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample: | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | #define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int, int>pi;
typedef pair<ll, ll>pl;
typedef vector<pi>vpi;
typedef vector<pl>vpl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef priority_queue<int> pqi;
typedef priority_queue<int, vi, greater<int>> pqI;
typedef priority_queue<ll> pql;
typedef priority_queue<ll, vl, greater<ll>> pqL;
const long double PI = acos(-1);
const int oo = 1e9 + 7;
const int MOD = 1e9 + 7;
const int N = 1e5 + 7;
#define endl '\n'
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define read(v) for (auto& it : v) scanf("%d", &it);
#define readL(v) for (auto& it : v) scanf("%lld", &it);
#define print(v) for (auto it : v) printf("%d ", it); puts("");
#define printL(v) for (auto it : v) printf("%lld ", it); puts("");
void solve() {
int n;
scanf("%d", &n);
if (n == 2) {
puts("0");
return;
}
vvi g(n + 1);
map<pi, int>idx;
vi ans(n - 1, -1);
for (int i = 0, u, v; i < n - 1; i++) {
scanf("%d %d", &u, &v);
g[u].push_back(v);
g[v].push_back(u);
idx[{u, v}] = idx[{v, u}] = i;
}
int cur = 0;
for (int i = 1; i <= n; i++)
if (g[i].size() == 1)
ans[idx[{i, g[i][0]}]] = cur++;
for (int i = 0; i < n - 1; i++)
if (ans[i] == -1)
ans[i] = cur++;
for (auto& it : ans)
printf("%d\n", it);
}
int t = 1;
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
//scanf("%d", &t);
while (t--) solve();
} | cpp |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
#define sz(s) (int)(s.size())
#define all(v) v.begin(),v.end()
#define clr(d, v) memset(d,v,sizeof(d))
#define ll long long
void file() {
std::ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
}
int main() {
file();
int n;
cin >> n;
vector<int> v(n);
for (auto &it: v)cin >> it;
map<ll, vector<pair<int, int>>> mp;
for (int r = 0; r < n; r++) {
ll sum = 0;
for (int l = r; l >= 0; l--) {
sum += v[l];
mp[sum].emplace_back(l, r);
}
}
vector<pair<int, int>> ans;
for (auto it: mp) {
int last = -1;
vector<pair<int, int>> temp;
for (auto it2: it.second) {
if (it2.first > last) {
temp.push_back(it2);
last = it2.second;
}
}
if (temp.size() > ans.size()) {
ans = temp;
}
}
cout << ans.size() << "\n";
for (auto it: ans)cout << it.first + 1 << " " << it.second + 1 << "\n";
} | cpp |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll t;
cin >> t;
while (t--)
{
ll a, b, c, n;
cin >> a >> b >> c >> n;
ll sum = a + b + c + n;
if ((sum % 3 == 0) && (sum / 3 >= a) && (sum / 3 >= b) && (sum / 3 >= c))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
| cpp |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7. | [
"brute force",
"combinatorics",
"math",
"number theory"
] | #include "bits/stdc++.h"
using namespace std;
#define ll long long
#define pb push_back
#define pob pop_back()
#define mp make_pair
#define add_m(a, b,mod) (((a % mod) + (b % mod)) % mod)
#define sub_m(a, b,mod) (((a % mod) - (b % mod) + mod) % mod)
#define mul_m(a, b,mod) (((a % mod) * (b % mod)) % mod)
/*
Use pigon hole principle
if (n > m) then there must exist 2 numbers (ai) and (aj) such that ai == aj (modulo m) , i != j
so the answer is 0
else
n <= m i.e. n <= 1e6, we can use O(n*n) brute force
*/
signed main()
{
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
ll n,m;
scanf("%lld%lld", &n,&m);
ll arr[n];
for (ll i = 0; i < n; i++)
scanf("%lld", &arr[i]);
if (n > m) cout<< 0<<"\n";
else
{ ll p = 1;
for (ll i = 0 ;i < n ; i++)
for (ll j = i+1 ; j < n;j++)
p = mul_m(p,abs(arr[i]-arr[j]),m);
cout<<p<<'\n';
}
return 0;
} | cpp |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = tuple<int, int>;
using vi = vector<ll>;
using vii = vector<ii>;
using vvi = vector<vi>;
using si = set<ll>;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
ll n, m, p, a, b;
cin >> n >> m >> p;
int k = -1, l = -1;
for (int i=0; i<n; i++) {
cin >> a;
if (a%p != 0 && k < 0) k=i;
}
for (int j=0; j<m; j++) {
cin >> b;
if (b%p != 0 && l < 0) l=j;
}
cout << k+l << endl;
} | cpp |
1299 | E | E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2
| [
"interactive",
"math"
] | #include<bits/stdc++.h>
#define ll long long
#define rep(i, x, y) for(int i = (x), stOyny = (y); i <= stOyny; ++i)
#define irep(i, x, y) for(int i = (x), stOyny = (y); i >= stOyny; --i)
#define pb emplace_back
#define pii pair<int, int>
#define vint vector<int>
#define fi first
#define se second
#define let const auto
#define il inline
#define ci const int
#define all(S) S.begin(), S.end()
int read() {
int res = 0, flag = 1; char c = getchar();
while(c < '0' || c > '9') { if(c == '-') flag = -1; c = getchar(); }
while(c >= '0' && c <= '9') res = res * 10 + c - '0', c = getchar();
return res * flag;
}
using namespace std;
template<typename T>
il void tmax(T &x, const T y) { if(x < y) x = y; }
template<typename T>
il void tmin(T &x, const T y) { if(x > y) x = y; }
mt19937 rnd(time(0));
int myans[805], ct = 0;
bool query(vint a) {
ct++;
cout << "? " << a.size() << ' ';
for(int x : a) cout << x << ' ';
cout << endl;
bool res;
cin >> res;
// int cur = 0;
// for(int x : a) cur += myans[x];
// return cur % a.size() == 0;
return res;
}
int ans[805], n;
void print() {
if(ans[1] > n / 2) rep(i, 1, n) ans[i] = n + 1 - ans[i];
cout << "! ";
rep(i, 1, n) cout << ans[i] << ' ';
// rep(i, 1, n) assert(myans[i] == ans[i]);
cout << endl;
exit(0);
}
void solve(vint a, int n, int dep, int va) {
if(!dep) return;
vint nxt, gg;
for(int x : a) {
vint b;
for(int y : a) if(y != x) b.pb(y);
if(query(b)) ans[x] = va, gg.pb(x);
else nxt.pb(x);
}
solve(nxt, n - 2, dep - 1, va + 1);
}
vint plac, value;
int m, mxS, sum[1024];
vint prime;
vector<pair<int, vint>> ma[4];
void init() {
rep(s, 0, mxS) rep(i, 0, m - 1) if((s >> i) & 1) sum[s] += value[i];
rep(xby, 0, 3) {
const int mod = prime[xby];
auto &nma = ma[xby];
nma.resize(mod);
rep(i, 0, mod - 1) nma[i].fi = i;
shuffle(all(nma), rnd);
rep(i, 0, mod - 2) {
bool ok = true;
rep(s, 0, mxS) if(__builtin_popcount(s) == mod - 1 && sum[s] % mod == (mod - nma[i].fi) % mod) {
ok = false;
rep(j, 0, m - 1) if((s >> j) & 1) nma[i].se.pb(plac[j]);
break;
}
}
}
}
int query(int x) {
vint res(4);
rep(xby, 0, 3) {
int mod = prime[xby];
let nma = ma[xby];
res[xby] = nma.back().fi;
rep(i, 0, mod - 2) {
vint cur = nma[i].se;
cur.pb(x);
if(query(cur)) { res[xby] = nma[i].fi; break; }
}
}
rep(i, 1, n) {
bool ok = true;
rep(j, 0, 3) if(i % prime[j] != res[j]) ok = false;
if(ok) return i;
}
return -1;
}
signed main() {
memset(ans, -1, sizeof(ans));
cin >> n;
// rep(i, 1, n) myans[i] = i;
// shuffle(myans + 1, myans + n + 1, rnd);
// if(myans[1] > n / 2) rep(i, 1, n) myans[i] = n + 1 - myans[i];
// rep(i, 1, n) cerr << myans[i] << ' '; cerr << '\n';
vint a;
rep(i, 1, n) a.pb(i);
solve(a, n, n <= 70 ? (n >> 1) : (n > 420 ? 5 : 4), 1);
int pl = 0;
rep(i, 1, n) if(ans[i] == 1) { ans[pl = i] = n; break; }
rep(i, 1, n) if(ans[i] > 1 && ans[i] < n) {
if(query(vint({pl, i})) == (n + ans[i]) % 2) ans[i] = n + 1 - ans[i];
}
if(n <= 70) print();
rep(i, 1, n) if(~ans[i]) plac.pb(i), value.pb(ans[i]);
m = plac.size(), mxS = (1 << m) - 1;
prime = vint{3, 5, 7};
prime.pb(n <= 210 ? 2 : ((n <= 420) ? 4 : 8));
init();
rep(i, 1, n) if(ans[i] == -1) ans[i] = query(i);
print();
return 0;
}
| cpp |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
set<int> s;
for (int i = 0, x; i < n; i++) {
cin >> x;
s.insert(x);
}
cout << s.size() << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
} | cpp |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define IOS ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int,null_type, less<int>,rb_tree_tag, tree_order_statistics_node_update>order_set;
typedef pair<int,int>pr;
#define all(i) i.begin() , i.end()
#define ft first
#define sn second
#define pb push_back
#define en "\n"
#define dbg cout<<"rony\n";
#define MAXN 200010
#define inf 1e8
const int mod = 998244353;
vector<int>g[MAXN];
ll fact[MAXN];
ll bigmod(ll a,ll n)
{
ll rs = 1;
while(n)
{
if(n%2 == 0){
n /= 2;
a = a * a; a %= mod;
}
else{
n--;
rs *= a; rs %= mod;
}
}
return rs;
}
void factorial(ll n)
{
fact[0] = fact[1] = 1;
for(ll i = 2;i <= n;i++){
fact[i] = fact[i - 1] * i;
fact[i] %= mod;
}
}
ll nCr(ll n,ll r)
{
ll an = fact[n];
an *= bigmod(fact[n - r],mod - 2);
an %= mod;
an *= bigmod(fact[r], mod - 2); an%=mod;
return an;
}
void solve()
{
ll n,m;
cin >> n >> m;
if(n == 2){
cout<<0<<en;return;
}
factorial(m);
ll an = nCr(m,n-1);
an *= (n - 2); an %= mod;
an *= bigmod(2,n-3);
an %= mod;
cout<<an<<en;
}
int main()
{
IOS;
int t;
t = 1;
// cin >> t;
int c = 0;
while ( t-- )
{
//cout<<"Case "<<++c<<": ";
solve();
}
return 0;
} | cpp |
1286 | F | F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3
1 10 100
OutputCopy3
InputCopy3
5 3 -2
OutputCopy2
InputCopy1
0
OutputCopy0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed. | [
"brute force",
"constructive algorithms",
"dp",
"fft",
"implementation",
"math"
] | #include<bits/stdc++.h>
#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 21
#define M 2000100
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;
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],f[M],lg[M],b[N],bt,sum[M];
inline vi Get(int nl,int nr){
vi v;v.clear();
if(nl==nr){
if(b[nl]>0){v.pb(-b[nl]);v.pb(b[nl]);}
else{v.pb(b[nl]);v.pb(-b[nl]);}return v;
}
v=Get(nl+1,nr);
vi v1,v2;v1.clear();v2.clear();
rep(i,0,(int)v.size()-1) v1.pb(v[i]-b[nl]);
rep(i,0,(int)v.size()-1) v2.pb(v[i]+b[nl]);
vi now;now.clear();
int l=0,r=0;
while(l<(int)v1.size()&&r<(int)v2.size()){
if(v1[l]<v2[r]) now.pb(v1[l]),l++;
else now.pb(v2[r]),r++;
}
// printf("now.size()=%d l=%d r=%d\n",now.size(),l,r);
while(l<(int)v1.size()) now.pb(v1[l]),l++;
while(r<(int)v2.size()) now.pb(v2[r]),r++;
// printf("v1.size()=%d v2.size()=%d\n",v1.size(),v2.size());
// printf("now.size()=%d\n",now.size());
return now;
}
inline bool Check(int S){
if(__builtin_popcount(S)==1){
if(sum[S]==0) return 1;return 0;
}
int siz=__builtin_popcount(S)-1;
if((sum[S]-siz)&1) return 0;bt=0;
rep(i,0,n-1) if((S>>i)&1) b[++bt]=a[i+1];int mid=(1+bt)>>1;
vi L=Get(1,mid),R=Get(mid+1,bt);
// printf("mid=%d\n",mid);
int l=R.size(),r=R.size()-1;
// puts("L:");for(int x:L) printf("%d ",x);puts("");
// puts("R:");for(int x:R) printf("%d ",x);puts("");
int nd=1+(abs(sum[S])<=siz)*2;
// printf("nd=%d\n",nd);
for(int i=0;i<L.size();i++){
while(l&&L[i]+R[l-1]>=-siz) l--;
while(r>=0&&L[i]+R[r]>siz) r--;
// printf("l=%d r=%d\n",l,r);
nd-=min(nd,r-l+1);
// if(l<=r&&r!=R.size()) return 1;
// if(r==-1) return 0;
}
return (nd==0);
}
signed main(){
// freopen("my.in","r",stdin);
// freopen("my.out","w",stdout);
read(n);rep(i,1,n) read(a[i]),lg[1<<i]=i;
rep(i,1,n) sum[1<<(i-1)]+=a[i];
rep(i,0,n-1)rep(j,0,(1<<n)-1) if((j>>i)&1) sum[j]+=sum[j^(1<<i)];
lg[1]=0;
// printf("Check(7)=%d\n",Check(7));
for(int T=0;T<(1<<n);T++){
if(!f[T]&&Check(T)){
// puts("Now");
int t=T^((1<<n)-1);
for(int S=t;;S=(S-1)&t){
// printf("T|S=%d T=%d S=%d\n",T|S,T,S);
cmax(f[T|S],f[S]+1);
if(!S) break;
}
}
// printf("f[%d]=%d\n",T,f[T]);
}
printf("%lld\n",n-f[(1<<n)-1]);
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 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | #include<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 1000000000
// 123456789
void solve(){
ge(ll,t);
xx(t){
//a!=b,b!=c,c!=a
//2<=a,b,c<=10^3
//a*b*c==n
//2<=n<=10^9
//O(10^6)
ll done=0;
ge(ll,n);
for(ll a=2;done==0&&a*(a+1)*(a+2)<=n;++a){
for(ll b=a+1;a*b*(b+1)<=n;++b){
ll c=n/a/b;
if(a*b*c==n&&a!=c&&b!=c&&2<=c){
ff("YES");
ff(a,b,c);
done=1;break;
}
}
}
if(done==0)
ff("NO");
}
}
| 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 mod 1000000007
using namespace std;
int n,m,t=0,edge_t=0,rt_t=0,i0=0,i1=1,ans=0;
int la[100002],rt[100002],pre[100002],deg[100002],sum[100002];
int num[382][382],f[2][382];
bool u[100002];
vector<int> Vec;
vector<int> vec[382],vec2[100002];
unordered_map<int,int> mp;
struct aaa
{
int to,nx,val;
}edge[200002];
struct bbb
{
int a[5];
inline bool ins(int x)
{
for(int i=4;~i;--i)
if((x>>i)&1)
{
if(!a[i])
{
a[i]=x;
for(int j=0;j<i;++j)if((a[i]>>j)&1)a[i]^=a[j];
for(int j=4;j>i;--j)if((a[j]>>i)&1)a[j]^=a[i];
return 1;
}
x^=a[i];
}
return 0;
}
inline int getHs()
{
return a[0]|(a[1]<<1)|(a[2]<<3)|(a[3]<<6)|(a[4]<<15);
}
}A[382],B[100002],tmp;
inline void add(int &x,int y)
{
if((x+=y)>=mod)x-=mod;
}
inline void add_edge(int x,int y,int z)
{
edge[++edge_t]=(aaa){y,la[x],z},la[x]=edge_t;
edge[++edge_t]=(aaa){x,la[y],z},la[y]=edge_t;
}
inline void dfs(int x,bbb a)
{
vec[++t]=Vec,A[mp[a.getHs()]=t]=a;
if(x>31)return ;
for(int i=x;i<32;++i)if((tmp=a).ins(i) && !mp.count(tmp.getHs()))Vec.push_back(i),dfs(i+1,tmp),Vec.pop_back();
}
inline void init()
{
dfs(1,(bbb){{}});
for(int i=1;i<=t;++i)
for(int j=1;j<=t;++j)
{
tmp=A[j],num[i][j]=1;
for(int k=0;k<=4;++k)if(A[i].a[k])num[i][j]&=tmp.ins(A[i].a[k]);
if(num[i][j])num[i][j]=mp[tmp.getHs()];
}
}
inline void dfs(int x,int f)
{
rt[x]=rt_t;
for(int i=la[x],v;i;i=edge[i].nx)
{
if(!rt[v=edge[i].to])pre[v]=(pre[x]^edge[i].val),dfs(v,x);
else if(rt[v]==rt[x] && v!=f && x<v && !B[rt_t].ins(pre[x]^pre[v]^edge[i].val))u[rt_t]=1;
}
}
int main()
{
init(),scanf("%d%d",&n,&m),rt[1]=-1,f[1][1]=1;
for(int i=1,x,y,z;i<=m;++i)scanf("%d%d%d",&x,&y,&z),add_edge(x,y,z);
for(int i=la[1],v;i;i=edge[i].nx)
{
if(!rt[v=edge[i].to])++rt_t,dfs(v,1);
vec2[rt[v]].push_back(v),sum[rt[v]]^=edge[i].val,++deg[rt[v]];
}
for(int i=1,x;i<=rt_t;++i)
{
if(u[i])continue;
i0^=1,i1^=1;
for(int j=1;j<=t;++j)f[i1][j]=f[i0][j];
x=mp[B[i].getHs()];
for(int j=1;j<=t;++j)
{
add(f[i1][num[x][j]],f[i0][j]);
if(deg[i]>1)add(f[i1][num[x][j]],f[i0][j]);
}
if(deg[i]==1)continue;
for(int j=la[vec2[i][0]],v;j;j=edge[j].nx)if((v=edge[j].to)==vec2[i][1])sum[i]^=edge[j].val;
if(B[i].ins(sum[i]))
{
x=mp[B[i].getHs()];
for(int j=1;j<=t;++j)add(f[i1][num[x][j]],f[i0][j]);
}
}
for(int i=1;i<=t;++i)add(ans,f[i1][i]);
return 0&printf("%d",ans);
} | cpp |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | #include <cstdio>
#include <cmath>
#include <vector>
int main() {
long long x0, y0, ax, ay, bx, by;
long long xs, ys, t;
scanf("%lld %lld %lld %lld %lld %lld", &x0, &y0, &ax, &ay, &bx, &by);
scanf("%lld %lld %lld", &xs, &ys, &t);
long long xl = xs + t, yl = ys + t;
using Point = std::pair<long long, long long>;
auto dist = [](Point a, Point b) {
return std::abs(a.first - b.first) + std::abs(a.second - b.second);
};
std::vector<Point> points;
while (x0 <= xl && y0 <= yl) {
points.emplace_back(x0, y0);
x0 = ax * x0 + bx;
y0 = ay * y0 + by;
}
int n = points.size();
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
long long len = dist(points[i], points[j]);
long long left = dist(points[i], {xs, ys});
long long right = dist(points[j], {xs, ys});
if (len + left <= t || len + right <= t) ans = std::max(ans, j - i + 1);
}
}
printf("%d\n", ans);
return 0;
} | 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>
#define ll long long int
#define srv(v) sort(v.begin(),v.end())
#define rrv(s1) sort(s1.begin(),s1.end(),greater<int>())
#define str string
#define sz size()
#define dv(v) vector<ll> v
#define ds(s) set<ll> s
#define dm(mp) map<ll,ll> mp
#define debug(x) cout<<#x<<" "<<x<<endl
#define MOD 1000000007
int binpow(int a, int b){if (b==1){return a;}else if (b==0){return 1;}ll one = binpow(a,b/2);if (b%2==0){return one*one;}else{return a*one*one;}}
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,x;
cin>>n>>x;
int st=0;
vector<int> v(x,0);
// dm(mp);
// 0 1 2
// 2
for (int i = 0; i < n; i++)
{
int y;
cin>>y;
if (y%x==st%x)
{
st++;
}
else
{
// mp[(y%x)]++;
v[(y%x)]++;
}
while (v[st%x]>0)
{
v[st%x]--;
st++;
}
cout<<st<<endl;
}
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 |
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<iostream>
#include<iterator>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
#include "local_dbg.cpp"
#else
#define debug(...) 101;
#endif
typedef long long int ll;
typedef long double ld;
typedef std::vector<int> vi;
typedef std::vector<ll> vll;
typedef std::vector<ld> vld;
typedef std::vector<std::vector<ll> > vvll;
typedef std::vector<std::vector<ld> > vvld;
typedef std::vector<std::vector<std::vector<ll> > > vvvll;
typedef std::vector<string> vstr;
typedef std::vector<std::pair<ll,ll> > vpll;
typedef std::pair<ll,ll> pll;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb push_back
#define nl "\n"
#define all(c) (c).begin(),(c).end()
#define iotam1 cout<<-1<<nl
#define cty cout<<"YES"<<nl
#define ctn cout<<"NO"<<nl
#define lmax LLONG_MAX
#define lmin LLONG_MIN
#define sz(v) (v).size()
#define deci(n) fixed<<setprecision(n)
#define c(x) cout<<(x)
#define csp(x) cout<<(x)<<" "
#define c1(x) cout<<(x)<<nl
#define c2(x,y) cout<<(x)<<" "<<(y)<<nl
#define c3(x,y,z) cout<<(x)<<" "<<(y)<<" "<<(z)<<nl
#define c4(a,b,c,d) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<nl
#define c5(a,b,c,d,e) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<" "<<(e)<<nl
#define c6(a,b,c,d,e,f) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<" "<<(e)<<" "<<(f)<<nl
#define f(i_itr,a,n) for(ll i_itr=a; i_itr<n; i_itr++)
#define rev_f(i_itr,n,a) for(ll i_itr=n; i_itr>a; i_itr--)
#define arri(n, arr) for(ll i_itr=0; i_itr<n; i_itr++) cin>>arr[i_itr]
#define a_arri(n, m, arr) for(ll i_itr=0; i_itr<n; i_itr++) for (ll j_itr=0; j_itr<m; j_itr++) cin>>arr[i_itr][j_itr]
#define pb push_back
#define fi first
#define se second
#define print(vec,a,b) for(ll i_itr=a;i_itr<b;i_itr++) cout<<vec[i_itr]<<" ";cout<<"\n";
#define input(vec,a,b) for(ll i_itr = a;i_itr<b;i_itr++) cin>>vec[i_itr];
#define ms(a,val) memset(a,val,sizeof(a))
const ll mod = 1000000007;
const long double pi=3.14159265358979323846264338327950288419716939937510582097494459230;
ll pct(ll x) { return __builtin_popcount(x); } // #of set bits
ll poww(ll a, ll b) { ll res=1; while(b) { if(b&1) res=(res*a); a=(a*a); b>>=1; } return res; }
ll modI(ll a, ll m=mod) { ll m0=m,y=0,x=1; if(m==1) return 0; while(a>1) { ll q=a/m; ll t=m; m=a%m; a=t; t=y; y=x-q*y; x=t; } if(x<0) x+=m0; return x;}
ll powm(ll a, ll b,ll m=mod) {ll res=1; while(b) { if(b&1) res=(res*a)%m; a=(a*a)%m; b>>=1; } return res;}
void ipgraph(ll,ll);
void ipgraph(ll); ///for tree
void dfs(ll node,ll par);
//******************************************************************************************************************************************* /
const ll N=2e5+5;
ll inp[N];
// vll adj[N]; ///for graph(or tree) use this !!-><-!!
void ok_boss()
{
ll n;
cin >> n;
vll another;
f(i,0,n)
{
cin>>inp[i];
}
f(i,0,n)
{
if(inp[i]!=-1)
{
if((i && inp[i-1]==-1) || (i+1<n && inp[i+1]==-1))
{
another.pb(inp[i]);
}
}
}
ll k=0;
if(sz(another))
{
debug(another);
ll mmin=*min_element(all(another));
ll mmax=*max_element(all(another));
k=(mmin+mmax)>>1ll;
}
f(i,0,n)
{
if(inp[i]==-1)
{
inp[i]=k;
}
}
debug(k);
ll m=0;
f(i,1,n)
{
m=max(m,abs(inp[i]-inp[i-1]));
}
debug(m);
c2(m,k);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
#endif
fast;
/// std::cout << fixed<<setprecision(15); ///activate it if the answers are in decimal.
ll qq_itr = 1;
cin >> qq_itr;
while (qq_itr--)
ok_boss();
return 0;
}
/*
void ipgraph(ll nodes_ipg,ll edgs_ipg)
{
f(i,0,nodes_ipg)
adj[i].clear();
ll fir,sec;
while(edgs_ipg--)
{
cin>>fir>>sec;
fir--,sec--; ///turn it off if it is 0-indexed
adj[fir].pb(sec);
adj[sec].pb(fir); ///remove this if directed !!!
}
return;
}
void ipgraph(ll nodes_ipg)
{
ipgraph(nodes_ipg,nodes_ipg-1);
}
void dfs(ll node,ll par=-1)
{
for(ll chd : adj[node])
{
if(chd==par)
continue;
dfs(chd,node);
}
return;
}
*/ | cpp |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | #include <bits/stdc++.h>
#pragma GCC optimize ("unroll-loops")
#pragma GCC optimize ("O3")
#define ll long long
#define st string
#define ull unsigned ll
#define pii pair <int, int>
#define pll pair <ll, ll>
#define pb push_back
#define ins insert
#define F first
#define S second
//#define int ll
using namespace std;
int32_t main () {
//freopen ("points.in", "r", stdin);
//freopen ("points.out", "w", stdout);
ios_base::sync_with_stdio();
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t --) {
int n;
cin >> n;
st s;
cin >> s;
int sum = 0;
for (int i = 0; i < n; i ++) {
sum += int(s [i] - '0');
}
//cout << sum << "\n";
if (sum % 2 == 0 && (int(s [n-1] - '0') % 2) == 1) {
cout << s << "\n";
}
else {
if (int(s [n-1] - '0') % 2 == 0) {
while (int(s [n-1] - '0') % 2 == 0 && n) {
sum -= int(s [n-1] - '0');
s.erase(n-1, 1);
n --;
}
}
if (sum % 2 == 1) {
for (int i = 0; i < n; i ++) {
if (int(s [i] - '0') % 2 == 1) {
sum -= int(s [i] - '0');
s.erase(i, 1);
n --;
break;
}
}
}
while (s [0] == '0') {
s.erase(0, 1);
n --;
}
if (sum % 2 == 0 && int(s [n-1] - '0') % 2 == 1) {
cout << s << "\n";
}
else cout << "-1\n";
}
}
return 0;
}
| cpp |
1313 | D | D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third. | [
"bitmasks",
"dp",
"implementation"
] | /*
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
*/
#include<bits/stdc++.h>
using namespace std;
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define eb emplace_back
#define PI 3.14159265359
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define BIT(x,i) (1&((x)>>(i)))
#define MASK(x) (1LL<<(x))
#define task "tnc"
typedef long long ll;
const ll INF=1e18;
const int maxn=1e6+5;
const int mod=1e9+7;
const int mo=998244353;
using pi=pair<ll,ll>;
using vi=vector<ll>;
using pii=pair<pair<ll,ll>,ll>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int n,m,s1;
pair<int,int>ed[maxn];
vector<int>qu;
vector<int>l[maxn];
vector<int>r[maxn];
int dp[2][1<<8];
int used=0;
int id[maxn];
int doi[9];
int trc=0;
signed main()
{
cin.tie(0),cout.tie(0)->sync_with_stdio(0);
//freopen(task".inp" , "r" , stdin);
//freopen(task".out" , "w" , stdout);
cin>>n>>m>>s1;
for(int i=1;i<=n;i++){
int l,r;
cin>>l>>r;
ed[i]={l,r+1};
qu.pb(l);
qu.pb(r+1);
}
sort(qu.begin(),qu.end());
qu.resize(distance(qu.begin(),unique(qu.begin(),qu.end())));
for(int i=1;i<=n;i++){
ed[i].fi=lower_bound(qu.begin(),qu.end(),ed[i].fi)-qu.begin();
ed[i].se=lower_bound(qu.begin(),qu.end(),ed[i].se)-qu.begin();
l[ed[i].fi].pb(i);
r[ed[i].se].pb(i);
}
int ans=0;
for(int i=0;i<qu.size()-1;i++){
int aft=(i&1);
int bef=(aft^1);
memset(doi,0,sizeof(doi));
trc=used;
for(auto v:r[i]){
used^=(1<<id[v]);
doi[id[v]]=1;
}
for(auto v:l[i]){
for(int j=0;j<8;j++){
if(((used>>j)&1)==0){
id[v]=j;
used^=(1<<j);
doi[j]=1;
break;
}
}
}
for(int j=used;;j=(j-1)&used){
int sus=0;
int bat=0;
for(int check=0;check<8;check++){
if(doi[check]==0 ){
sus+=(1<<check);
if(BIT(j,check)==1){
bat+=(1<<check);
}
}
}
int trc1=sus^trc;
for(int k=trc1;;k=(k-1)&trc1){
int ok=0;
int f=__builtin_popcount(j);
dp[aft][j]=max(dp[aft][j],dp[bef][k^bat]+((f%2)==1?(qu[i+1]-qu[i]):0));
ans=max(ans,dp[aft][j]);
if(k==0)break;
}
if(j==0)break;
}
}
cout<<ans;
return 0;
}
| 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"
] | // LUOGU_RID: 98244252
#include <bits/stdc++.h>
using namespace std;
const int N=5e5+5;
int n,m,k,sz[N],d[N],so[N],tp[N],fa[N],s[N],h[N],c[N*2],b[N*2],p[N*2],f[N*2];
vector<int> e[N],g[N];
inline void cmi(int&x,int y) {if(x>y) x=y;}
inline void cmx(int&x,int y) {if(x<y) x=y;}
int getf(int x) {return f[x]==x?x:f[x]=getf(f[x]);}
void merge(int x,int y){
b[x]=b[y]=1;
x=getf(x);y=getf(y);
if(x==y) return;
f[x]=y;
}
void dfs1(int x){
sz[x]=1;
for(int y:e[x]) if(y!=fa[x]){
d[y]=d[fa[y]=x]+1;
dfs1(y);sz[x]+=sz[y];
if(sz[y]>sz[so[x]]) so[x]=y;
}
}
void dfs2(int x){
if(!tp[x]) tp[x]=x;
if(so[x]) tp[so[x]]=tp[x],dfs2(so[x]);
for(int y:e[x]) if(y!=fa[x]&&y!=so[x]) dfs2(y);
}
int lca(int x,int y){
while(tp[x]!=tp[y])
if(d[tp[x]]<d[tp[y]]) y=fa[tp[y]];
else x=fa[tp[x]];
return d[x]<d[y]?x:y;
}
int anc(int x,int y){
while(tp[x]!=tp[y]){
if(fa[tp[x]]==y) return tp[x];
x=fa[tp[x]];
}
return so[y];
}
void dfs3(int x){
for(int y:e[x]) if(y!=fa[x]) dfs3(y),s[x]+=s[y];
if(s[x]) merge(x,fa[x]),merge(x+n,fa[x]+n);
}
bool solve(int x){
int l=1,r=k,tl=1,tr=(k+1)/2;
for(int y:e[x]) if(y!=fa[x]){
if(!solve(y)) return 0;
if(!b[y]) continue;
if(f[x]==f[y]) cmx(l,h[y]+1);
else if(f[x+n]==f[y]) cmi(r,k-h[y]);
else if(f[y]<=n) cmx(p[f[y]],h[y]+1);
else cmi(p[f[y]],k-h[y]);
}
for(int y:g[x]){
if(p[y]>p[y+n]) return 0;
cmx(tl,min(p[y],k-p[y+n]+1));
cmi(tr,min(p[y+n],k-p[y]+1));
}
cmx(l,tl);cmi(r,k-tl+1);
int rr=k+1-tr;
if(l>r||(tr<l&&r<rr)) return 0;
return (h[x]=(l<=tr||l>=rr)?l:rr);
}
bool chk(){
fill_n(p+1,n,1);fill_n(p+n+1,n,k);
return solve(1);
}
void print(int x,int op){
for(int y:e[x]) if(y!=fa[x]){
if(!b[y]) {print(y,0);continue;}
if(f[x]==f[y]) print(y,op);
else if(f[x+n]==f[y]) print(y,op^1);
else if(f[y]<=n) c[f[y]]|=h[y]>=h[x];
else c[f[y]]|=h[x]>=k-h[y]+1;
}
for(int y:e[x]) if(y!=fa[x]&&b[y]&&f[x]!=f[y]&&f[x+n]!=f[y]){
int t=f[y]-(f[y]>n)*n;
print(y,op^(f[y]>n)^(c[t]||c[t+n]));
}
if(op) h[x]=k-h[x]+1;
}
int main(){
scanf("%d%d",&n,&m);
iota(f,f+n*2+1,0);
for(int i=1,u,v;i<n;i++) scanf("%d%d",&u,&v),e[u].push_back(v),e[v].push_back(u);
dfs1(1);dfs2(1);
for(int u,v;m--;){
scanf("%d%d",&u,&v);
if(d[u]>d[v]) swap(u,v);
int l=lca(u,v),fu,fv;
s[v]++;s[fv=anc(v,l)]--;
if(l!=u) s[u]++,s[fu=anc(u,l)]--,merge(fu,fv+n),merge(fu+n,fv);
else b[fv]=b[fv+n]=1;
}
dfs3(1);
for(int i=1;i<=n;i++) if(getf(i)==getf(i+n)) return puts("-1"),0;
for(int x=1;x<=n;x++){
for(int y:e[x]) if(f[x]!=f[y]&&f[x+n]!=f[y]&&f[y]<=n) g[x].push_back(f[y]);
sort(g[x].begin(),g[x].end());
g[x].erase(unique(g[x].begin(),g[x].end()),g[x].end());
}
int l=1,r=n,ans=0;
while(l<=r){
k=l+r>>1;
if(chk()) r=(ans=k)-1;
else l=k+1;
}
printf("%d\n",k=ans);
chk();print(1,0);
for(int i=1;i<=n;i++) printf("%d ",h[i]);
return 0;
} | cpp |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences. | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | #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=2e5+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;
struct Node{
int fi,se;
bool flag;
bool operator < (const Node &k) const {
if(fi!=k.fi) return fi<k.fi;
else return se<k.se;
}
};
Node w[N];
int sum[N];
void solve() {
n=read();
int res=0;
for(int i=1;i<=n;i++) {
m=read();
int maxn=-1,minn=INF;
bool flag=false;
int last;
for(int j=1;j<=m;j++) {
int c=read();
if(j==1) last=c;
else if(j>=2) {
if(c>last) flag=true;
last=min(last,c);
}
maxn=max(maxn,c);
minn=min(minn,c);
}
if(flag) res++;
w[i]={minn,maxn,flag};
}
sort(w+1,w+1+n);
for(int i=1;i<=n;i++) {
if(w[i].flag) sum[i]=sum[i-1]+1;
else sum[i]=sum[i-1];
}
ll ans=0;
for(int i=1;i<=n;i++) {
if(w[i].flag) {
ans+=(ll)n;
continue;
}
int l=0,r=n;
while(l<r) {
int mid=l+r+1>>1;
if(w[mid].fi<w[i].se) l=mid;
else r=mid-1;
}
ans+=(ll)l-sum[l]+res;
}
printf("%lld\n",ans);
}
int main() {
// init();
// stin();
// scanf("%d",&T);
T=1;
while(T--) solve();
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"
] | // LUOGU_RID: 92191453
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
#define fi first
#define sc second
#define mkp make_pair
#define pii pair<int,int>
typedef long long ll;
const int N=65,M=(1<<12)+5,oo=1e9,mod=1e9+7;
inline int read() {
int x=0,flag=0;char ch=getchar();
while(ch<'0'||ch>'9') {flag|=(ch=='-');ch=getchar();}
while('0'<=ch&&ch<='9') {x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return flag?-x:x;
}
inline int mx(int x,int y) {return x>y?x:y;}
inline int mn(int x,int y) {return x<y?x:y;}
inline void swp(int &x,int &y) {x^=y^=x^=y;}
inline int as(int x) {return x>0?x:-x;}
int n,a[N],F[N],cnt,st[N],top,tag[N],vc[N];
int S[M],f[N][M],C[N][N];
pii Ans[N]; bool vis[N];
int ff(int x) {return F[x]==x?x:F[x]=ff(F[x]);}
inline void merge(int x,int y) {
int fx=ff(x),fy=ff(y);
if(fx!=fy) F[fy]=fx;
}
inline void ADD(int&x,int y) {x=(x+y>=mod?x+y-mod:x+y);}
inline pii solve(int p) {
top=0; memset(vis,0,sizeof vis);memset(tag,0,sizeof tag);
for(int i=1;i<=n;++i)
if(ff(i)==p) st[++top]=a[i];
sort(st+1,st+top+1);
int tt=0; vc[0]=0;
for(int i=1,sum;i<=top;++i) {
sum=0;
for(int j=1;j<i;++j)
if(st[i]%st[j]==0&&vis[j])
sum|=(1<<tag[j]);
if(!sum) vis[i]=1,tag[i]=tt++;
else vc[++vc[0]]=sum;
}
if(!vc[0]) return mkp(0,1);
memset(S,0,sizeof S);
for(int i=1;i<=vc[0];++i)
for(int j=1;j<(1<<tt);++j)
if((j&vc[i])==vc[i])
++S[j];
memset(f,0,sizeof f); f[0][0]=1;
for(int i=1;i<=vc[0];++i)
for(int j=0;j<(1<<tt);++j) {
if(!f[i-1][j]) continue;
for(int k=1;k<=vc[0];++k)
if(((vc[k]&j)!=vc[k]&&(vc[k]&j))||!j) ADD(f[i][vc[k]|j],f[i-1][j]);
if(S[j]-i>=0) ADD(f[i][j],1ll*(S[j]-i+1)*f[i-1][j]%mod);
}
return mkp(vc[0]-1,f[vc[0]][(1<<tt)-1]);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
n=read(); bool flag=0;
for(int i=1;i<=n;++i) {
a[i]=read();
if(a[i]==1) flag=1;
}
if(flag) {
int sum=0,ans=1;
for(int i=1;i<=n;++i)
sum+=(a[i]>1);
for(int i=1;i<=sum;++i) ans=1ll*ans*i%mod;
printf("%d\n",ans);
return 0;
}
for(int i=1;i<=n;++i) F[i]=i;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
if(i!=j&&a[i]%a[j]==0)
merge(i,j);
for(int i=1;i<=n;++i)
if(ff(i)==i) Ans[++cnt]=solve(i);
C[0][0]=1;
for(int i=1;i<=n;++i) {
C[i][0]=C[i][i]=1;
for(int j=1;j<i;++j)
C[i][j]=(C[i-1][j-1]+C[i-1][j])%mod;
}
int pos=0,ans=1;
for(int i=1;i<=cnt;++i)
ans=1ll*ans*Ans[i].sc%mod*C[pos+Ans[i].fi][Ans[i].fi]%mod,
pos+=Ans[i].fi;
printf("%d\n",ans);
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"
] | /// endless ?
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
#define ll long long
#define F first
#define S second
#define pii pair<int, int>
#define all(x) x.begin(), x.end()
#define vi vector<int>
#define vii vector<pii>
#define pb push_back
#define pf push_front
#define wall cout <<'\n'<< "-------------------------------------" <<'\n';
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define int ll
const ll MAXN = 1e5 + 43;
const ll MOD = 1e9 + 7; ///998244353;
const ll INF = 1e18 + 19763;
const ll LG = 19;
ll pw(ll a, ll b){return b == 0 ? 1LL : (pw(a * a , b / 2) * (b % 2 == 0 ? 1LL : a));}
void solve()
{
fast
int n, k; cin >> n >> k;
int cnt = 0;
while (cnt <= 10 && pw(10, cnt) - 1 <= k)
{
cnt ++;
}
cout << n * (cnt - 1) << '\n';
}
int32_t main ()
{
fast
int t = 1; cin >> t;
while (t --)
{
solve();
}
}
/// Thanks GOD :)
| cpp |
1320 | E | E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1
| [
"data structures",
"dfs and similar",
"dp",
"shortest paths",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define all(a) begin(a), end(a)
#define len(a) int((a).size())
namespace rn = ranges;
namespace vw = rn::views;
#ifdef LOCAL
#include "debug.h"
#else
#define dbg(...)
#define dprint(...)
#define debug if constexpr (false)
#endif // LOCAL
template<typename T, typename merge_t>
struct sparse_table {
std::vector<std::vector<T>> sparse;
const merge_t merge;
sparse_table(const merge_t &merge) : merge(merge) {}
sparse_table(const std::vector<T> &a, const merge_t &merge) : merge(merge) {
if (a.empty())
return;
const int n = int(a.size()), lg = std::__lg(n);
sparse.reserve(lg + 1);
sparse.push_back(a);
for (int level = 1; level <= lg; level++) {
sparse.push_back(std::vector<T>(n - (1 << level) + 1));
for (int i = 0; i < int(sparse[level].size()); i++)
sparse[level][i] = merge(sparse[level - 1][i], sparse[level - 1][i + (1 << (level - 1))]);
}
}
sparse_table& operator=(const sparse_table<T, merge_t> &another) {
sparse = another.sparse;
return *this;
}
T query(int l, int r) const {
assert(l < r);
const int level = std::__lg(r - l);
return merge(sparse[level][l], sparse[level][r - (1 << level)]);
}
};
template<typename T = int>
struct lca_tree {
int n;
std::vector<std::vector<std::pair<int, T>>> g;
std::vector<int> tin, tout;
std::vector<std::pair<int, int>> order;
std::vector<T> depth;
inline static auto merge_min = [](const std::pair<int, int> &a, const std::pair<int, int> &b) -> std::pair<int, int> {
return a < b ? a : b;
};
using sparse_table_t = sparse_table<std::pair<int, int>, decltype(merge_min)>;
sparse_table_t sparse;
lca_tree(int n = 0) : n(n), g(n), sparse(merge_min) {}
lca_tree(const std::vector<std::vector<std::pair<int, T>>> &graph) :
n(graph.size()), g(graph), sparse(merge_min)
{}
lca_tree(const std::vector<std::vector<int>> &graph) : n(graph.size()), g(n), sparse(merge_min) {
for (int v = 0; v < int(graph.size()); v++) {
g[v].reserve(graph[v].size());
for (int u : graph[v])
g[v].emplace_back(u, 1);
}
}
lca_tree(int n, const std::vector<std::pair<int, int>> &edges) : n(n), g(n), sparse(merge_min) {
for (const auto &[v, u] : edges)
add(v, u);
}
void add(int v, int u, T w = 1) {
g[v].emplace_back(u, w);
g[u].emplace_back(v, w);
}
int size() const {
return n;
}
void build(int root = 0) {
tin.resize(n);
tout.resize(n);
order.reserve(n - 1);
depth.resize(n);
int timer = 0;
std::function<void(int, int, int)> dfs = [&](int v, int p, int dep) {
tin[v] = timer++;
for (auto &[u, w] : g[v]) {
if (u == p)
continue;
depth[u] = depth[v] + w;
order.emplace_back(dep, v);
dfs(u, v, dep + 1);
}
tout[v] = timer;
};
dfs(root, -1, 0);
sparse = sparse_table_t(order, merge_min);
}
int lca(int v, int u) const {
if (v == u)
return v;
auto [l, r] = std::minmax(tin[v], tin[u]);
return sparse.query(l, r).second;
}
T dist(int v, int u) const {
return depth[v] - 2 * depth[lca(v, u)] + depth[u];
}
bool is_ancestor(int v, int u) const {
return tin[v] <= tin[u] && tout[u] <= tout[v];
}
};
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int n;
cin >> n;
lca_tree<int> lca(n);
for (int i = 1; i < n; i++) {
int v, u;
cin >> v >> u, v--, u--;
lca.add(v, u);
}
lca.build(0);
vector<pair<int, int>> dist(n);
vector<vector<int>> g(n);
auto add_edge = [&](int v, int u) {
dprint("add edge", v, u);
g[v].push_back(u);
g[u].push_back(v);
};
int q;
cin >> q;
while (q--) {
dprint();
dprint("solving");
int k, m;
cin >> k >> m;
static vector<int> vers;
vers.clear();
vector<pair<int, int>> a(k);
for (auto &[v, s] : a) {
cin >> v >> s, v--;
vers.push_back(v);
}
vector<int> queries(m);
for (auto &v : queries) {
cin >> v, v--;
vers.push_back(v);
}
rn::sort(vers, less{}, [&](int v) { return lca.tin[v]; });
int prev_size = len(vers);
for (int i = 0; i < prev_size - 1; i++) {
vers.push_back(lca.lca(vers[i], vers[i + 1]));
}
rn::sort(vers);
vers.resize(rn::unique(vers).begin() - vers.begin());
rn::sort(vers, less{}, [&](int v) { return lca.tin[v]; });
for (auto v : vers) {
g[v].clear();
dist[v] = {1e9, -1};
}
static vector<int> st;
st.clear();
for (auto v : vers) {
while (!st.empty() && !lca.is_ancestor(st.back(), v)) {
st.pop_back();
}
if (!st.empty()) add_edge(st.back(), v);
st.push_back(v);
}
static priority_queue<pair<pair<int, int>, int>, vector<pair<pair<int, int>, int>>, greater<>> pq;
for (int i = 0; i < k; i++) {
int v = a[i].first;
dist[v] = {0, i};
pq.emplace(dist[v], v);
}
while (!pq.empty()) {
auto [cur_dist, v] = pq.top();
pq.pop();
if (cur_dist != dist[v]) continue;
for (auto u : g[v]) {
int d = lca.dist(a[cur_dist.second].first, u);
pair<int, int> to_update{(d + a[cur_dist.second].second - 1) / a[cur_dist.second].second,
cur_dist.second};
dbg(cur_dist, v, u, to_update);
if (dist[u] > to_update) {
dist[u] = to_update;
pq.emplace(dist[u], u);
}
}
}
for (int i = 0; i < m; i++) {
cout << dist[queries[i]].second + 1 << " \n"[i == m - 1];
}
}
}
| cpp |
1310 | D | D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
OutputCopy2
InputCopy3 2
0 1 1
2 0 1
2 2 0
OutputCopy3
| [
"dp",
"graphs",
"probabilities"
] | #include <bits/stdc++.h>
using namespace std;
typedef double db;
#define int long long
#define fi first
#define se second
#define mk make_pair
#define pb emplace_back
#define poly vector<int>
#define Bt(a) bitset<a>
#define bc __builtin_popcount
#define pc putchar
#define ci const int&
const int mod = 1e9+7;
const db eps = 1e-10;
inline int Max(ci x, ci y) {return x > y ? x : y;}
inline int Min(ci x, ci y) {return x < y ? x : y;}
inline db Max(db x, db y) {return x - y > eps ? x : y;}
inline db Min(db x, db y) {return x - y < eps ? x : y;}
inline int Add(ci x, ci y, ci M = mod) {return (x + y) % M;}
inline int Mul(ci x, ci y, ci M = mod) {return 1ll * x * y % M;}
inline int Dec(ci x, ci y, ci M = mod) {return (x - y + M) % M;}
typedef pair<int, int> pii;
inline int Abs(int x) {return x < 0 ? -x : x;}
//char buf[1<<21],*p1=buf,*p2=buf;
//#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
char Obuf[105000],*O=Obuf;//Siz shoule be the size of Out File
int pst[30],ptop;
inline void Fprint(){fwrite(Obuf,1,O-Obuf,stdout);}
inline void Fwrite(int x){
if(x==0){*O++='0';if(O-Obuf>100000)Fprint(),O=Obuf;return;}
if(x<0)*O++='-',x=-x;ptop=0;
while(x)pst[++ptop]=x%10,x/=10;
while(ptop)*O++=pst[ptop--]+'0';
if(O-Obuf>100000)Fprint(),O=Obuf;
}
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') w = -1;ch = getchar();}
while (isdigit(ch)) {s = s * 10 + ch - '0';ch = getchar();}
return s * w;
}
inline void write(int x) {
if (x < 0)putchar('-'), x = -x;
if (x > 9)write(x / 10);
pc(x % 10 + '0');
}
inline int qpow(int x, int y) {
int res = 1;
while (y) {if (y & 1)res = Mul(res, x);x = Mul(x, x);y >>= 1;}
return res;
}
inline void cadd(int &x, int y) {x += y;}
inline void cmul(int &x, int y) {x *= y;}
inline void cmax(int &x, int y) {x = Max(x, y);}
inline void cmin(int &x, int y) {x = Min(x, y);}
const int N = 2e6 + 10;
namespace CG{
struct P{
db x, y;
P(db x_ = 0, db y_ = 0){
x = x_; y = y_;
}
db len() {
return sqrt(x * x + y * y);
}
P mid() {
return P(x / 2.0, y / 2.0);
}
db theta() {
return atan2(y, x);
}
};
P operator + (P x, P y) {return P(x.x + y.x, x.y + y.y);}
P operator - (P x, P y) {return P(x.x - y.x, x.y - y.y);}
P operator * (P x, db y) {return P(x.x * y, x.y * y);}
P operator * (db y, P x) {return P(x.x * y, x.y * y);}
db operator * (P x, P y) {return x.x * y.x + x.y * y.y;}
db operator ^ (P a, P b) {return a.x * b.y - a.y * b.x;}
struct Line {
P x, y; db k;
Line (P _x = P(0, 0), P _y = P(0, 0)) {
x = _x; y = _y - _x; k = _y.theta();
}
};
inline db sq(db x) {return x * x;}
inline db dis(P x, P y) {return sqrt(sq(x.x - y.x) + sq(x.y - y.y));}
inline db fdis(P x, P y) {return sq(x.x - y.x) + sq(x.y - y.y);}
P crossover(Line x, Line y) {
P C = x.x - y.x;
db t = (y.y ^ C) / (x.y ^ y.y);
return x.x + x.y * t;
}
}
namespace Refined_heart{
int n, k;
int a[101][101];
int f[101][101];
int sd = 20060727 ^ time(0);
int col[101];
int ans = (1LL << 60);
void solve(){
n = read(); k = read();
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= n; ++j) {
a[i][j] = read();
}
}
for(int T = 1; T <= 5000; ++T) {
sd += (T & 1) ? 20060710 : 20060727; sd ^= 1234567; srand(sd);
for(int i = 1; i <= n; ++i) col[i] = rand() & 1;
for(int i = 1; i <= n; ++i) {
for(int j = 0; j <= k; ++j) {
f[i][j] = (1LL << 60);
}
}
f[1][0] = 0;
for(int j = 1; j <= k; ++j) {
for(int i = 1; i <= n; ++i) {
if(f[i][j - 1] > 10000000000ll) continue;
for(int l = 1; l <= n; ++l) {
if(col[l] == col[i]) continue;
f[l][j] = Min(f[l][j], f[i][j - 1] + a[i][l]);
}
}
}
ans = Min(ans, f[1][k]);
}
cout << ans << '\n';
}
}
signed main(){
Refined_heart::solve();
return 0;
}
| cpp |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | //#pragma GCC target( "sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("Ofast,unroll-loops,fast-math,O3")
#include "bits/stdc++.h"
#define F first
#define S second
#define me "| Temirlan |"
#define ALL(a) a.begin() , a.end()
#define OK cerr << "---------------------------OK-----------------------" << endl;
#define deb(x) cerr << #x << " = " << x << endl;
#define endl '\n'
#define ll long long
#define int long long
using namespace std ;
const int N = 1e2 + 7;
const int INF = 1e18 + 7 ;
const int mod = 1e9 + 7 ;
const double eps = 1e-9 ;
const int dx[4] = { 0 , 0 , 1 , -1} , dy[4] = {1 , -1 , 0 , 0} ;
int n , m , x , y , a[N] , dnt[N] , dp[N][N][N][2] ;
void test(){
cin >> n ;
for(int i = 1; i <=n ; i++){
cin >> a[i] ;
dnt[a[i]] = 1;
}
int cnt[2] = {} ;
for(int i = 1; i <= n; i++){
if(!dnt[i]){
cnt[i % 2]++;
}
}
for(int i = 1; i <=n ;i++){
for(int j = 0; j <= cnt[0] ; j++){
for(int k = 0 ; k <= cnt[1] ;k++){
dp[i][j][k][0] = dp[i][j][k][1] = INF ;
if(a[i]){
if(a[i] % 2)
dp[i][j][k][1] = min(dp[i - 1][j][k][1] , dp[i - 1][j][k][0] + 1 ) ;
else
dp[i][j][k][0] = min(dp[i - 1][j][k][1] + 1 , dp[i - 1][j][k][0] ) ;
}
else{
if(k > 0){
dp[i][j][k][1] = min(dp[i - 1][j][k - 1][1] , dp[i- 1][j][k - 1][0] + 1 ) ;
}
if(j > 0){
dp[i][j][k][0] = min(dp[i - 1][j - 1][k][1] + 1 , dp[i - 1][j - 1][k][0]) ;
}
}
}
}
}
cout << min(dp[n][cnt[0]][cnt[1]][0] , dp[n][cnt[0]][cnt[1]][1] ) << endl;
}
signed main(){
ios_base::sync_with_stdio(false) ;
cin.tie(0) ;
cout.tie(0);
// freopen("floor.in" , "r" , stdin) ;
// freopen("floor.out" , "w" , stdout) ;
int t = 1;
//cin >> t ;
for(int i = 1 ; i <= t ;i++ ){
test() ;
}
return 0;
}
| cpp |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define cin(vec) \
for (auto &i : vec) \
cin >> i
#define cout(vec) \
for (auto &i : vec) \
cout << i << " "; \
cout << "\n";
#define sz(x) int(x.size())
#define pb(x) push_back(x)
#define Num_of_Digits(n) ((int)log10(n) + 1)
#define fi first
#define se second
#define ll long long
#define Mod 1'000'000'007
#define PI acos(-1)
#define all(vec) vec.begin(), vec.end()
#define rall(vec) vec.rbegin(), vec.rend()
#define EPS 1e-6
#define endl "\n"
#define OO INT_MAX
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 Eman_Elsayed()
{
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
}
int fn(double x, double d)
{
return x + ceil(d / (x + 1));
}
bool Bs(ll n, ll d)
{
ll l = 1, r = n;
while (l <= r)
{
ll mid = (l + r) / 2;
if (fn(mid, d) <= n)
return true;
else
r = mid - 1;
}
return false;
}
void solve()
{
ll n, s, k;
cin >> n >> s >> k;
vector<ll> v(k);
map<ll, ll> closed;
cin >> v;
for (auto &i : v)
closed[i] = true;
for (int i = 0; i < n; i++)
{
if (s - i > 0 && closed[s - i] == false)
{
cout << i << endl;
return;
}
if (s + i <= n && closed[s + i] == false)
{
cout << i << endl;
return;
}
}
}
int main()
{
Eman_Elsayed();
int t = 1;
cin >> t;
while (t--)
{
solve();
}
return 0;
} | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.