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 |
---|---|---|---|---|---|
1304 | F2 | F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp",
"greedy"
] | // LUOGU_RID: 101683569
//This code is written by Hmz(Hmz is cute!!!)
#include<bits/stdc++.h>
using namespace std;
#define TY int
#define mod (TY)(1e9+7)
#define MAXN 55
#define MAXM 20005
#define MAXK 27
#define For(i,a,b) for(TY i=(a);i<=(b);++i)
#define FOR(i,a,b) for(TY i=(a);i<(b);++i)
#define Rof(i,a,b) for(TY i=(a);i>=(b);--i)
#define ROF(i,a,b) for(TY i=(a);i>(b);--i)
inline TY qr(){
TY x=0,f=1;char op=getchar();
for(;op<'0'||op>'9';op=getchar())if(op=='-')f=-1;
for(;op>='0'&&op<='9';op=getchar())x=x*10+(op^48);
return x*f;
}inline char getc(){
char op=getchar();
while(op==' '||op=='\n'||op=='\r')op=getchar();
return op;
}inline string qs(){
string op="";char u=getchar();
while(u=='\n'||u=='\r'||u==' ')u=getchar();
while(u!='\n'&&u!='\r'&&u!=' ')op+=u,u=getchar();
return op;
}inline void qw(TY x){
if(!x){putchar('0');return;}
if(x<0)putchar('-'),x=-x;
if(x>=10)qw(x/10);putchar(x%10+'0');
}inline void qw(TY x,char op){qw(x),putchar(op);}
inline void ws(string s){FOR(i,0,s.size())putchar(s[i]);}
inline TY Ceil(TY a,TY b){return a/b+(a%b!=0);}
inline TY Mod(TY a){return (a>=mod?a-mod:a);}
inline TY Pow(TY a,TY b){
TY ans=1,base=a;
while(b){
if(b&1)ans=ans*base%mod;
base=base*base%mod;b>>=1;
}return ans;
}TY n,m,k,ans,val[MAXN][MAXM],tree[MAXM<<2],tag[MAXM<<2],dp[MAXN][MAXM];
inline void push_down(TY now){
tree[now<<1]+=tag[now],tree[now<<1|1]+=tag[now];
tag[now<<1]+=tag[now],tag[now<<1|1]+=tag[now];
tag[now]=0;
}void build(TY deep,TY now,TY l,TY r){
tag[now]=0;
if(l==r){tree[now]=dp[deep][l];return;}
TY mid=(l+r)>>1;
build(deep,now<<1,l,mid);build(deep,now<<1|1,mid+1,r);
tree[now]=max(tree[now<<1],tree[now<<1|1]);
}void update(TY now,TY l,TY r,TY x,TY y,TY w){
if(l>y||r<x)return;
if(x<=l&&r<=y){tree[now]+=w;tag[now]+=w;return;}
push_down(now);TY mid=(l+r)>>1;
update(now<<1,l,mid,x,y,w);update(now<<1|1,mid+1,r,x,y,w);
tree[now]=max(tree[now<<1],tree[now<<1|1]);
}int main(){
n=qr();m=qr();k=qr();
For(i,1,n)For(j,1,m)val[i][j]=qr();
For(i,2,n+1){
build(i-1,1,1,m);
TY l=1,r=0,sum=0;while(r<=m){
if(r-l+1<k){
++r;sum+=val[i][r]+val[i-1][r];
if(i!=2)update(1,1,m,max(1,r-k+1),r,-val[i-1][r]);
}else{
dp[i][l]=sum+tree[1];if(i==n+1)ans=max(ans,dp[i][l]);
if(i==n+1)ans=max(ans,dp[i][l]);
sum-=val[i][l]+val[i-1][l];
if(i!=2)update(1,1,m,max(1,l-k+1),l,val[i-1][l]);++l;
++r;sum+=val[i][r]+val[i-1][r];
if(i!=2)update(1,1,m,max(1,r-k+1),r,-val[i-1][r]);
}
}
}qw(ans);
return 0;
} | cpp |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | /*
* Show me your beautiful smile :)
*
* author: Ahmed khaled ( _GOM3A_ )
*
* */
#include <bits/stdc++.h>
using namespace std;
#define fast_IO(x) ios_base::sync_with_stdio(false);cin.sync_with_stdio(0); cout.sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
#define fraction cout<< fixed <<showpoint <<setprecision
#define what_is(x) cerr << #x << " is " << x << '\n';
#define PI 3.141592653589793238462643383279
#define Write(x) freopen (x,"w",stdout)
#define Read(x) freopen (x,"r",stdin)
#define all(x) x.begin(),x.end()
#define Reverse(x) reverse(all(x))
#define Sort(x) sort(all(x))
#define Yes cout<<"YES"
#define yes cout<<"yes"
#define No cout<<"NO"
#define no cout<<"no"
#define pi acos(-1);
#define ln '\n'
typedef deque<long long> dll;
typedef vector<long long> vll;
typedef set<long long> sll;
typedef long long ll;
typedef pair<ll,ll> pl;
//**prototype**//
inline void _GOM3A_(void);
template<typename T, typename ...Opts>
bool any_of(T val, Opts ...opts);
ll getRandomNumber(ll low = 0, ll high = 100);
bool isPrime(ll n);
deque<ll> factorization(ll n);
bool isPalindrome(string s);
ll binaryToDecimal(string s);
//**prototype**//
int main() {
_GOM3A_();
//********** code ***************
ll size;
cin >> size;
vll numbers(size);
ll cnt = 0;
for_each(numbers.begin() , numbers.end() , [](ll &x){cin >> x ; });
for (int i = 0; i < size; ++i) {
if( ! numbers[i] )
break;
numbers.push_back(1);
}
ll i = 0 , j = 0;
ll mx = 0;
while( i < numbers.size() && j < numbers.size() )
{
if( !numbers[j] )
{
mx = max( mx , (j-1) - i + 1);
j++;
i = j;
}
else
{
mx = max( mx , j - i + 1 );
j++;
}
}
cout<<mx;
//********** code ***************
}
//**************************************** helping function ****************************************
inline void _GOM3A_(void){
fraction(6);
fast_IO( author: _GOM3A_ );
}
template<typename T,typename ...Opts>
bool any_of(T val, Opts ...opts)
{
return ( ... || (val == opts) );
}
ll getRandomNumber(ll low , ll high ){
static ll fo = 0;
if( fo == 92233720368547758 )
fo = 0;
srand((unsigned) time(NULL) + fo );
fo++;
return ( ( rand() % (high - low + 1)) + low );
}
bool isPrime(ll n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (ll i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
deque<ll> factorization(ll n){
set<ll> result;
ll i ;
for(i = 1; i * i < n ; i++){
if( !( n%i ) )
{
result.insert(i);
result.insert(n/i);
}
}
if(i*i==n)
result.insert(i);
dll m ( all(result) );
return m;
}
bool isPalindrome(string s)
{
ll size = s.size();
ll halfSize = s.size() / 2;
for (int i = 0; i < halfSize; i++) {
if (s[i] != s[size - i - 1]) {
return false;
}
}
return true;
}
ll binaryToDecimal(string s)
{
bitset<64> bits(s);
ll number = bits.to_ulong();
return number;
//return stol(s,nullptr,2);
} | cpp |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int t,n,x,s,a;
int main(){
cin>>t;
while(t--&&cin>>n){
a=s=0;
for(int i=1;i<=n;i++){
cin>>x;
if(x==0)
a++,s++;
s+=x;
}
cout<<a+(s==0)<<'\n';
}
return 0;
}
| cpp |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define FOR(i, x, y) for (int i = x; i < y; i++)
const int mx = 1005;
int n, ans[mx][mx]; pair<int, int> A[mx][mx]; int di[] = {-1, 0, 1, 0}, dj[] = {0, 1, 0, -1};
void dfs(int i, int j, pair<int, int> mustEq, int dir){
if (A[i][j] != mustEq or ~ans[i][j]) return;
ans[i][j] = dir;
FOR(d, 0, 4) dfs(i + di[d], j + dj[d], mustEq, (d + 2) % 4);
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n;
FOR(i, 1, n + 1) FOR(j, 1, n + 1){
cin >> A[i][j].first >> A[i][j].second;
ans[i][j] = -1;
}
FOR(i, 1, n + 1) FOR(j, 1, n + 1){
if (A[i][j].first == -1){
dfs(i, j, A[i][j], 4);
FOR(d, 0, 4){
int ii = i + di[d], jj = j + dj[d];
if (A[ii][jj] == A[i][j]) ans[i][j] = d;
}
if (ans[i][j] == 4) return cout<<"INVALID\n", 0;
}
else{
dfs(A[i][j].first, A[i][j].second, A[i][j], 4);
if (ans[i][j] == -1) return cout<<"INVALID\n", 0;
}
}
char mp[] = {'U', 'R', 'D', 'L', 'X'};
cout<<"VALID\n";
FOR(i, 1, n + 1) FOR(j, 1, n + 1) cout<<mp[ans[i][j]]<<(j == n ? "\n" : "");
} | cpp |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
constexpr int N = int(4e2) + 5;
constexpr int inf = 0x7f7f7f7f;
constexpr int MOD = int(1e9) + 7;
short dp[N][N][N];
string s, t;
void solve(){
cin >> s >> t;
for(short i = 0; i <= s.size(); i++){
for(short j = 0; j <= t.size(); j++){
for(short k = 0; k < t.size(); k++){
dp[i][j][k] = 0;
}
dp[s.size()][j][t.size()] = j;
}
}
for(short i = s.size() - 1; ~i; i--){
for(short j = t.size(); ~j; j--){
for(short k = t.size(); ~k; k--){
auto& r = dp[i][j][k] = dp[i + 1][j][k];
if(s[i] == t[j]) r = max(r, dp[i + 1][j + 1][k]);
if(s[i] == t[k]) r = max(r, dp[i + 1][j][k + 1]);
}
}
}
for(int i = 0; i < t.size(); i++){
if(dp[0][0][i + 1] > i){
cout << "YES\n";
return;
}
}
cout << "NO\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
cin >> t;
while(t--){
solve();
}
}
| 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>
#define gc()(xS==xTT&&(xTT=(xS=xB)+fread(xB,1,1<<20,stdin),xS==xTT)?0:*xS++)
#define pc(x)(p3-obuf<1000000)?(*p3++=x):(fwrite(obuf,p3-obuf,1,stdout),p3=obuf,*p3++=x)
using namespace std;typedef long long ll;typedef double db;typedef long double ld;typedef unsigned long long ull;typedef unsigned int ui;char xch,xB[1<<20],*xS=xB,*xTT=xB,obuf[1000000],*p3=obuf;inline ll read(){char ch=gc();ll x=0,f=1;while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}while('0'<=ch&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=gc();}return x*f;}static char cc[20];template<typename item>inline void pt( item x){ int len=0;if(!x)pc('0');if(x<0)x=-x,pc('-');while(x)cc[len++]=x%10+'0',x/=10;while(len--)pc(cc[len]);}inline void pS(string s){for(int i=0;i<s.length();i++)pc(s[i]);}inline ll read2(){char ch=gc();ll x=0,f=1;while(ch<'0'||ch>'1'){if(ch=='-')f=-1;ch=gc();}while('0'<=ch&&ch<='9'){x=(x<<1)+(ch^48);ch=gc();}return x*f;}
const int maxn=410,maxh=25;
int h,w,n,a[maxh][maxh],T,tx[4]={0,0,1,-1},ty[4]={1,-1,0,0},hd,u[maxn<<2],v[maxn<<2],cnt,du[maxn],pre[maxn<<2],rt[maxn];bool isx[maxn<<2],isy[maxn<<2],xz[maxn<<2],vis[maxn<<2];char ans[maxh<<1][maxh<<1];
int go(){char c=gc();while(c!='O'&&c!='X')c=gc();return c=='X';}
bool in(int x,int y){return x>=1&&x<=h&&y>=1&&y<=w;}
int get(int x,int y){return (x-1)*w+y;}
int fr(int p){return rt[p]==p?p:rt[p]=fr(rt[p]);}
bool mg(int x,int y)
{
x=fr(x),y=fr(y);
if(x==y)return 0;
rt[y]=x;return 1;
}
bool zg()
{
memset(isx,0,sizeof isx),memset(isy,0,sizeof isy),memset(pre,0,sizeof pre),memset(du,0,sizeof du),memset(vis,0,sizeof vis);
queue<int>Q;
for(int i=1;i<=n;i++)rt[i]=i;
for(int i=1;i<=cnt;i++)if(xz[i])du[u[i]]++,du[v[i]]++,mg(u[i],v[i]);
for(int i=1;i<=cnt;i++)
{
if(xz[i])continue;
if(fr(u[i])!=fr(v[i]))isx[i]=1,Q.push(i),vis[i]=1;
if(du[u[i]]<2)
{
isy[i]=1;
if(isx[i]){xz[i]=1;return 1;}
}
}
while(!Q.empty())
{
int p=Q.front();Q.pop();
if(isy[p])
{
while(p)xz[p]^=1,p=pre[p];
return 1;
}
if(xz[p])
{
for(int i=1;i<=n;i++)rt[i]=i;
for(int i=1;i<=cnt;i++)if(xz[i]&&i!=p)mg(u[i],v[i]);
for(int i=1;i<=cnt;i++)
{
if(xz[i]||vis[i]||fr(u[i])==fr(v[i]))continue;
pre[i]=p,vis[i]=1,Q.push(i);
}
}
else
{
for(int i=1;i<=cnt;i++)
{
if(!xz[i]||vis[i]||du[u[p]]-(u[i]==u[p])>=2)continue;
pre[i]=p,vis[i]=1,Q.push(i);
}
}
}
return 0;
}
signed main()
{
T=read();
while(T--)
{
cnt=0;memset(xz,0,sizeof xz),hd=0;
h=read(),w=read();n=get(h,w);
for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)a[i][j]=go();
for(int i=1;i<=h;i++)
{
for(int j=(i==1?2:1);j<=w;j++)
{
if(!(i+j&1)&&!a[i][j])
{
hd+=2;
for(int t=0;t<4;t++)
{
int i2=i+tx[t],j2=j+ty[t];
if(in(i2,j2)&&!a[i2][j2])u[++cnt]=get(i,j),v[cnt]=get(i2,j2);
}
}
}
}
while(zg())hd--;
if(hd)pS("NO\n");
else
{
pS("YES\n");
if(!a[1][2])u[++cnt]=get(1,1),v[cnt]=get(1,2);
if(!a[2][1])u[++cnt]=get(1,1),v[cnt]=get(2,1);
for(int i=1;i<h<<1;i++)for(int j=1;j<w<<1;j++)ans[i][j]=' ';
for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)if(a[i][j])ans[(i<<1)-1][(j<<1)-1]='X';else ans[(i<<1)-1][(j<<1)-1]='O';
for(int i=1;i<=n;i++)rt[i]=i;
for(int i=1;i<=cnt;i++)
{
if(!xz[i])continue;
mg(u[i],v[i]);
int x1=(u[i]-1)/w+1,y1=(u[i]-1)%w+1;
int x2=(v[i]-1)/w+1,y2=(v[i]-1)%w+1;
if(x1==x2&&y1+1==y2)ans[(x1<<1)-1][y1<<1]='O';
else if(x1==x2&&y1-1==y2)ans[(x1<<1)-1][(y1-1)<<1]='O';
else if(y1==y2&&x1+1==x2)ans[x1<<1][(y1<<1)-1]='O';
else ans[(x1-1)<<1][(y1<<1)-1]='O';
}
for(int i=1;i<=cnt;i++)
{
if(xz[i]||fr(u[i])==fr(v[i]))continue;
mg(u[i],v[i]);
int x1=(u[i]-1)/w+1,y1=(u[i]-1)%w+1;
int x2=(v[i]-1)/w+1,y2=(v[i]-1)%w+1;
if(x1==x2&&y1+1==y2)ans[(x1<<1)-1][y1<<1]='O';
else if(x1==x2&&y1-1==y2)ans[(x1<<1)-1][(y1-1)<<1]='O';
else if(y1==y2&&x1+1==x2)ans[x1<<1][(y1<<1)-1]='O';
else ans[(x1-1)<<1][(y1<<1)-1]='O';
}
for(int i=1;i<h<<1;i++)
{
for(int j=1;j<w<<1;j++)pc(ans[i][j]);
pc('\n');
}
}
}
fwrite(obuf,p3-obuf,1,stdout);
return 0;
}
/*
1
10 10
OOXXXXOOXO
OOOXOOOXOO
OOXOXXOOOO
OXXOXOOXOO
OOOOOOXOOO
OOOXOXOOOX
OOXOOXOOOX
OOOXXXXXOX
OOOOXOOXOX
XOOOOOOXOX
*/
| cpp |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
#define int int64_t
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin>>t;
while (t--)
{
int n, k;
cin>>n >>k;
vector <int> v(n);
for (auto &it: v) cin>>it;
sort(v.begin(), v.end());
bool hobe=true;
for (int i=1; i<n; i++) if (v[i]==v[i-1] && v[i]) {
hobe=false;
break;
}
vector <int> ktl(64, 0);
if (hobe)
{
for (auto &it:v)
{
int i=0;
while (it)
{
ktl[i]+=it%k;
if(ktl[i]>1) {
hobe=false;
break;
}
it/=k;
i++;
}
if(!hobe) break;
}
}
if(hobe) cout<<"YES\n";
else cout <<"NO\n";
}
} | cpp |
1291 | F | F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"graphs",
"interactive"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=1024;
bool used[maxn];int a[maxn];
int qu=0;
set<int> o;
void que(int i)
{
if(used[i]) return;
cout<<"? "<<i+1<<endl;
++qu;
#ifndef LOCAL
#else
if(o.count(a[i])) used[i]=true;
o.insert(a[i]);
return;
#endif
char ans;cin>>ans;
if(ans=='Y') {used[i]=true;}
}
void cl()
{
cout<<'R'<<endl;
o.clear();
}
int32_t main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int n,k;cin>>n>>k;
#ifdef LOCAL
for(int i=0;i<n;++i) cin>>a[i];
#endif // LOCAL
if(k==1) k=2;
for(int i=0;i<2*n/k;++i)
{
for(int l=i*(k/2);l<(i+1)*(k/2);++l)
{
que(l);
}
cl();
for(int j=i+1;j<2*n/k;++j)
{
for(int l=i*(k/2);l<(i+1)*(k/2);++l)
{
que(l);
}
for(int l=j*(k/2);l<(j+1)*(k/2);++l)
{
que(l);
}
cl();
}
}
#ifdef LOCAL
cout<<qu<<" que "<<endl;
#endif // LOCAL
cout<<"! "<<(n-accumulate(used,used+n,0LL))<<endl;
return 0;
}
| cpp |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | #include<set>
#include<iostream>
#include<vector>
#include<algorithm>
#define int long long
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)
#define fi first
#define se second
#define pb push_back
#define endl '\n'
using namespace std;
const int inf = 0x3f3f3f3f;
const int mod = 998244353;
void add(int &a, int b) {
a += b;
if (a >= mod) a -= mod;
}
void solve() {
int n;
cin >> n;
vector<pair<int, int>> v(n);
rep(i, 0, n) {
cin >> v[i].fi;
}
rep(i, 0, n) {
cin >> v[i].se;
}
sort(v.begin(), v.end());
int now = v[0].fi, j = 0, sum = v[0].se, ans = 0;
multiset<int> cc;
cc.insert(v[j].se);
while (1) {
while (j + 1 < n&&v[j + 1].fi == now) {
j++;
cc.insert(v[j].se);
sum += v[j].se;
}
auto it = cc.end();
it--;
ans += sum - *it;
sum -= *it;
cc.erase(it);
if (cc.size()) {
now++;
}
else {
if (j + 1 >= n) break;
j++;
now = v[j].fi;
cc.insert(v[j].se);
sum += v[j].se;
}
}
cout << ans << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int t;
t = 1;
while (t--) {
solve();
}
}
| cpp |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int a,b,x,y;
cin>>a>>b>>x>>y;
cout<<max(max(x,a-1-x)*b,a*max(y,b-1-y))<<endl;
}
} | cpp |
1310 | F | F. Bad Cryptographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: Let's fix a finite field and two it's elements aa and bb. One need to fun such xx that ax=bax=b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 22k−122k−1 for some positive integer kk . Bitwise exclusive or (⊕⊕) operation is used as addition. One of ways to define multiplication operation (⊙⊙) is following properties: 0⊙a=a⊙0=00⊙a=a⊙0=0 1⊙a=a⊙1=a1⊙a=a⊙1=a a⊙b=b⊙aa⊙b=b⊙a a⊙(b⊙c)=(a⊙b)⊙ca⊙(b⊙c)=(a⊙b)⊙c a⊙(b⊕c)=(a⊙b)⊕(a⊙c)a⊙(b⊕c)=(a⊙b)⊕(a⊙c) If a=22na=22n for some integer n>0n>0, and b<ab<a, then a⊙b=a⋅ba⊙b=a⋅b. If a=22na=22n for some integer n>0n>0, then a⊙a=32⋅aa⊙a=32⋅a. For example: 4⊙4=64⊙4=6 8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13.8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13. 32⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=14132⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=141 5⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=85⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans;}multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a⊙k=a⊙a⊙⋯⊙ak timesa⊙k=a⊙a⊙⋯⊙a⏟k times.You need to analyze the proposed scheme strength. For pairs of numbers aa and bb you need to find such xx, that a⊙x=ba⊙x=b, or determine that it doesn't exist. InputIn the first line of input there is single integer tt (1≤t≤1001≤t≤100) — number of pairs, for which you need to find the discrete logarithm.In each of next tt line there is a pair of integers aa bb (1≤a,b<2641≤a,b<264). OutputFor each pair you should print one integer xx (0≤x<2640≤x<264), such that a⊙x=ba⊙x=b, or -1 if no such x exists. It can be shown, that if any such xx exists, there is one inside given bounds. If there are several good values, you can output any of them. ExampleInputCopy7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
OutputCopy1
1
2
4
-1
6148914691236517205
68943624821423112
| [
"math",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
using nimber = unsigned long long;
const nimber primitive = ULLONG_MAX;
const int K = 7;
int primes[K] = {3, 5, 17, 257, 65537, 641, 6700417};
unsigned long long z[K], crt_factor[K];
nimber primitive_by_prime[K];
map<nimber, int> logmaps[K];
int inversemod(int p, int q) {
return (p > 1 ? q-1LL*inversemod(q%p, p)*q/p : 1);
}
// from ecnerwala library
struct nim_prod_t {
uint64_t bit_prod[64][64]{};
constexpr nim_prod_t() {
for (int i = 0; i < 64; i++) {
for (int j = 0; j < 64; j++) {
if ((i & j) == 0) {
bit_prod[i][j] = uint64_t(1) << (i|j);
} else {
int a = (i&j) & -(i&j);
bit_prod[i][j] = bit_prod[i ^ a][j] ^ bit_prod[(i ^ a) | (a-1)][(j ^ a) | (i & (a-1))];
}
}
}
}
constexpr uint64_t operator () (uint64_t x, uint64_t y) const {
uint64_t res = 0;
for (int i = 0; i < 64 && (x >> i); i++)
if ((x >> i) & 1)
for (int j = 0; j < 64 && (y >> j); j++)
if ((y >> j) & 1)
res ^= bit_prod[i][j];
return res;
}
};
constexpr nim_prod_t nimProd;
nimber multiply(nimber a, nimber b) {
return nimProd(a, b);
}
nimber exp(nimber base, unsigned long long pow) {
nimber res = 1;
while (pow) {
if (pow & 1) res = multiply(res, base);
pow >>= 1;
base = multiply(base, base);
}
return res;
}
int discrete_log(int i, nimber x) {
// given that x = primitive^(z[i]*n), find n
int ans = 0;
while (!logmaps[i].count(x)) {
x = multiply(x, primitive_by_prime[i]);
ans--;
}
ans += logmaps[i][x];
if (ans < 0) ans += primes[i];
if (ans >= primes[i]) ans -= primes[i];
return ans;
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
for (int i = 0; i < K; i++) {
z[i] = 1;
for (int j = 0; j < K; j++) {
if (j == i) continue;
z[i] *= primes[j];
}
crt_factor[i] = z[i] * inversemod(z[i]%primes[i], primes[i]);
}
// logarithm_maps[p] is a mapping from elements of order p to their logarithm
for (int i = 0; i < K; i++) {
primitive_by_prime[i] = exp(primitive, z[i]);
int step = (primes[i] < 500 ? 1 : 100);
nimber base = exp(primitive_by_prime[i], step);
int exponent = step;
nimber val = base;
while (exponent < primes[i]) {
logmaps[i][val] = exponent;
exponent += step;
val = multiply(val, base);
}
}
int T;
cin >> T;
while (T--) {
nimber a, b;
cin >> a >> b;
bool ok = 1;
__int128 ans = 0;
unsigned long long order_a = 1;
for (int i = 0; i < K; i++) {
int res_a = discrete_log(i, exp(a, z[i]));
int res_b = discrete_log(i, exp(b, z[i]));
if (res_a == 0 && res_b != 0) {
ok = 0;
break;
}
if (!res_a) continue;
order_a *= primes[i];
ans += (__int128)(inversemod(res_a, primes[i]))*crt_factor[i]*res_b;
}
if (!ok) {
cout << "-1\n";
continue;
}
unsigned long long output = ans%order_a;
cout << output << '\n';
}
}
| cpp |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define print(a) for(auto x : a) {cout << x << " ";} cout << endl;
typedef long long lli;
typedef vector<int> vi;
typedef vector<lli> vl;
int main(){
int t;
cin >> t;
while (t --){
int n;
cin >> n;
int o = 0, e = 0;
for (int i = 0; i < n; i++){
int k;
cin >> k;
if (k % 2 == 0){
e ++;
} else {
o ++;
}
}
if (o % 2 != 0){
cout << "YES" << endl;
} else if (o % 2 == 0 && e > 0 && o > 0){
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
| cpp |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | #include<bits/stdc++.h>
#define MOD 998244353
#define eps 1e-9
#define emailam ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define MAX 200010
#define pb push_back
#define all(a) a.begin(),a.end()
#define pf push_front
#define fi first
#define se second
#define pii pair<int,int>
const int INF = INT_MAX;
using namespace std;
const int N=1e6+10;
const int mod=998244353;
/*----------------------------------------------------------------*/
int dx[] = {+0, +0, -1, +1, +1, +1, -1, -1};
int dy[] = {-1, +1, +0, +0, +1, -1, +1, -1};
/*----------------------------------------------------------------*/
void READ(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif
}
#define int long long
ll power(ll x, ll y) {
ll ret = 1;
while (y > 0) {
if (y % 2 == 0) {
x = x * x;
x %= MOD;
y = y / 2;
} else {
ret = ret * x;
ret %= MOD;
y = y - 1;
}
}
return ret;
}
int fac[N], inv[N];
void precalc() {
fac[0] = fac[1] = 1;
for (int i = 2; i < N; ++i) {
fac[i] = fac[i - 1] * i;
fac[i] %= MOD;
}
inv[0] = 1;
for (int i = 1; i < N; ++i) {
inv[i] = power(fac[i], MOD - 2);
}
}
int ncr(int x, int y) {
if (x < y)return 0;
return ((fac[x] * inv[x - y]) % MOD * inv[y]) % MOD;
}
int mul(int a,int b){
return (a*b)%mod;
}
int add(int a,int b){
return ((a)+(b)+2*mod)%mod;
}
void solve(){
int n,m;
cin>>n>>m;
cout<<mul(mul(ncr(m,n-1),power(2,max(0LL,n-3))),n-2)<<endl;
}
signed main() {
emailam
//READ();
int t=1;
precalc();
//cin>>t;
while(t--){
solve();
}
} | cpp |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb. | [
"implementation",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
int n,sum;
string a,b,c;
int main(){
cin >> n;
while(n--){
sum=0;
cin >> a >> b >> c;
for(int i=0;i<a.size();i++) if(a[i]==c[i] || c[i]==b[i]) sum++;
if(sum==a.size()) cout <<"YES\n";
else cout << "NO\n";
}
} | cpp |
1311 | E | E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example: | [
"brute force",
"constructive algorithms",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
#define rep(i, a, b) for(ll i = a; i < b; i++)
#define rrep(i, a, b) for(ll i = a; i >= b; i--)
const ll inf = 4e18;
int main(void) {
cin.tie(0);
ios::sync_with_stdio(0);
ll t;
cin >> t;
while(t--) {
ll n, d;
cin >> n >> d;
ll sum = n * (n - 1) / 2;
ll low = 0;
for(ll i = 1, cd = 0; i <= n; i++) {
if(!(i & (i - 1))) cd++;
low += cd - 1;
}
if(d < low or d > sum) {
cout << "NO" << '\n';
continue;
}
vector<ll> par(n), cnt(n, 1), dep(n);
vector<bool> bad(n);
rep(i, 0, n) {
par[i] = i - 1;
}
cnt[n - 1] = 0;
rep(i, 0, n) {
dep[i] = i;
}
bool flag = true;
while(flag and sum > d) {
ll v = -1;
rep(i, 0, n) {
if(!bad[i] and cnt[i] == 0) {
if(v == -1 or dep[v] > dep[i]) {
v = i;
}
}
}
if(v == -1) {
flag = false;
break;
}
ll p = -1;
rep(i, 0, n) {
if(cnt[i] < 2 and dep[i] == dep[v] - 2) {
p = i;
}
}
if(p == -1) {
bad[v] = true;
continue;
}
cnt[par[v]]--;
dep[v]--;
cnt[p]++;
par[v] = p;
sum--;
}
if(flag) {
cout << "YES" << '\n';
rep(i, 1, n) {
cout << par[i] + 1 << " \n"[i == n - 1];
}
} else {
cout << "NO" << '\n';
}
}
} | cpp |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n) — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111. | [
"dfs and similar",
"dsu",
"graphs"
] | #include<bits/stdc++.h>
#pragma GCC optimize ("Ofast")
using namespace std;
#define all(v) v.begin(), v.end()
#define F first
#define S second
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N=3e5+5;
int n, k, sz[2*N], p[2*N], st[N], val[N], ans;
string s;
vector<int>w[N];
int par(int u){
if(p[u]==u) return u;
return p[u]=par(p[u]);
}
void dsu(int u, int v){
p[u]=v;
sz[v]+=sz[u];
}
void opr(int u, int v){
u=par(u);v=par(v);
if(u==v)
return;
ans-=val[v>>1]+val[u>>1];
dsu(u, v);
dsu(u^1, v^1);
if(st[u>>1]!=-1)
st[v>>1]=(u&1)^(v&1)^st[u>>1];
if(st[v>>1]!=-1){
int vv=(v>>1)<<1;
val[v>>1]=sz[vv^st[v>>1]];
}
else
val[v>>1]=min(sz[v], sz[v^1]);
ans+=val[v>>1];
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>n>>k>>s;
for(int i=0;i<k;++i){
int c;
cin>>c;
for(int j=0;j<c;++j){
int x;
cin>>x;
w[--x].push_back(i);
}
}
iota(p, p+2*k, 0);
memset(st, -1, sizeof(st));
for(int i=0;i<k;++i)
sz[i<<1]=1;
for(int i=0;i<n;++i){
if(s[i]=='1'){
if((int)w[i].size()==2)
opr(w[i][0]<<1, w[i][1]<<1);
else if(!w[i].empty()){
int v=par(w[i][0]<<1);
ans-=val[v>>1];
st[v>>1]=(v&1)^1;
val[v>>1]=sz[v^1];
ans+=sz[v^1];
}
}
else{
if((int)w[i].size()==2)
opr(par(w[i][0]<<1)^1, w[i][1]<<1);
else{
int v=par(w[i][0]<<1);
ans-=val[v>>1];
st[v>>1]=v&1;
val[v>>1]=sz[v];
ans+=sz[v];
}
}
cout<<ans<<'\n';
}
}
| cpp |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
long long int s;
cin>>s;
while(s--)
{
long long int n;
cin>>n;
string a;
cin>>a;
long long int sum=0;
for(long long int i=0;i<n;i++)
{
sum+=a[i]-48;
}
if(sum%2!=0 || a[n-1]%2==0)
{
int sum1=0,flag=-1;
for(int i=0;i<n;i++)
{
sum1+=a[i]-48;
if(sum1%2==0 && a[i]%2!=0)
{
flag=i;
break;
}
}
if(flag==-1)
{
cout<<-1<<endl;
continue;
}
for(long long int i=0;i<=flag;i++)
cout<<a[i];
cout<<endl;
continue;
}
cout<<a<<endl;
}
return 0;
} | cpp |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template<class T> using oset =tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update> ;
typedef long long ll;
typedef vector<ll> vll;
typedef pair<ll,ll> pll;
typedef long double ld;
typedef map<ll,ll> mll;
typedef vector<int> vi;
typedef set<ll> sll;
typedef pair<int,int> ii;
typedef vector<ii> vii;
ll gcd(ll a, ll b) {return a == 0? b: gcd(b%a,a);}
ll lcm(ll a, ll b) {return a * (b / gcd(a,b));}
#define inf 1e17
#define pb(x) push_back(x)
#define rep(x,n) for (int i = x; i < n; i++)
#define all(x) (x).begin(), (x).end()
#define fo(x) find_by_order(x)
#define ok(x) order_of_key(x)
ll mod = 1e9 + 7;
const int MAXN = 1e5;
void solve(){
int a,b,c; cin >> a >> b >> c;
int op = INT_MAX, ra,rb,rc;
for (int i = 1; i <= MAXN; i++) {
for (int j = i; j <= MAXN; j+= i) {
int res = abs(i - a) + abs(j - b) + min(c % j, j - (c % j));
if (res < op) {
ra = i; rb = j;
op = res;
if (c % j < j - (c % j)) rc = c - (c % j);
else rc = c + (j - (c % j));
}
}
}
cout << op << "\n";
cout << ra << " " << rb << " " << rc << "\n";
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);
int t; cin >> t;
while (t--) solve();
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 ll long long
int main()
{
ll i,j,k,l,m,n,p,q,r,s,t,u,v,x,y,z;
cin>>t;
while(t--)
{
cin>>n;
unordered_map<ll,ll>mp;
for(i=0;i<n;i++)
{
cin>>k;
mp[k]++;
}
cout<<mp.size()<<endl;
}
// SUBMITTING AGAIN FOR SUBMISSIONS
} | 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: 102631276
#include <bits/stdc++.h>
constexpr int N = 1e5 + 10;
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n;
std::cin >> n;
std::vector<std::vector<int>> divs(N);
std::vector<int> mu(N);
for (int i = 1; i < N; ++i) {
mu[i] += i == 1;
divs[i].emplace_back(i);
for (int j = i * 2; j < N; j += i) {
divs[j].emplace_back(i);
mu[j] -= mu[i];
}
}
std::vector<int> a(N);
long long res = 0;
for (int i = 1; i <= n; ++i) {
int x;
std::cin >> x;
for (int j : divs[x]) {
a[j] = 1;
}
res = std::max(res, 1LL * x);
}
std::stack<int> sta;
std::vector<int> cnt(N);
for (int i = N - 1; i; --i) {
if (a[i]) {
int sum = 0;
for (int j : divs[i]) {
sum += mu[j] * cnt[j];
}
while (!sta.empty()) {
if (sum == 0) {
break;
}
int x = sta.top();
res = std::max(res, 1LL * i * x / std::__gcd(i, x));
for (int j : divs[x]) {
--cnt[j];
if (i % j == 0) {
sum -= mu[j];
}
}
sta.pop();
}
sta.push(i);
for (int j : divs[i]) {
++cnt[j];
}
}
}
std::cout << res << '\n';
} | 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;
#define ll long long
void slv(){
ll n,m,p;
cin>>n>>m>>p;
vector<ll> a(n),b(m);
for(ll i=0;i<n;i++)cin>>a[i];
for(ll i=0;i<m;i++)cin>>b[i];
ll ai=0,bi=0;
while(a[ai]%p==0)ai++;
while(b[bi]%p==0)bi++;
cout<<ai+bi<<'\n';
}
int main(){
ios::sync_with_stdio(0);cin.tie(0);
ll t=1;
//cin>>t;
while(t--)slv();
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"
] | // LUOGU_RID: 97402537
#include <bits/stdc++.h>
using namespace std;
using poly = vector <int>;
int n, a[150005];
poly g[150005];
bool vis[150005];
int f[150005], siz[150005], sum, rt = 0;
long long ans = 0;
void findrt(int u, int fa) {
f[u] = 0, siz[u] = 1;
for (auto v : g[u]) {
if (v != fa && !vis[v]) {
findrt(v, u);
f[u] = max(f[u], siz[v]);
siz[u] += siz[v];
}
}
f[u] = max(f[u], sum - siz[u]);
if (!rt or f[u] < f[rt]) {
rt = u;
}
}
struct LiChaoTree {
struct node {
int l, r;
long long k, b;
} t[600005];
void build(int p, int l, int r) {
t[p].l = l, t[p].r = r;
t[p].k = 0, t[p].b = -4e18;
if (l == r) {
return ;
}
int mid = (l + r) >> 1;
build(p << 1, l, mid);
build(p << 1 | 1, mid + 1, r);
}
void clear(int p) {
if (t[p].k == 0 && t[p].b == -4e18) {
return ;
}
else {
t[p].k = 0, t[p].b = -4e18;
}
if (t[p].l == t[p].r) {
return ;
}
int mid = (t[p].l + t[p].r) >> 1;
clear(p << 1), clear(p << 1 | 1);
}
void update(int p, long long k, long long b) {
if (t[p].l == t[p].r) {
if (t[p].k * t[p].l + t[p].b < k * t[p].l + b) {
t[p].k = k, t[p].b = b;
}
return ;
}
int mid = (t[p].l + t[p].r) >> 1;
if (k * t[p].l + b > t[p].k * t[p].l + t[p].b) {
if (k * mid + b > t[p].k * mid + b) {
update(p << 1 | 1, t[p].k, t[p].b);
t[p].k = k, t[p].b = b;
}
else update(p << 1, k, b);
}
else if (k * t[p].r + b > t[p].k * t[p].r + t[p].b) {
if (k * mid + b > t[p].k * mid + t[p].b) {
update(p << 1, t[p].k, t[p].b);
t[p].k = k, t[p].b = b;
}
else update(p << 1 | 1, k, b);
}
}
long long qry(int p, int x) {
if (t[p].l == t[p].r) {
return t[p].k * x + t[p].b;
}
int mid = (t[p].l + t[p].r) >> 1;
long long ans = t[p].k * x + t[p].b;
if (x <= mid) ans = max(ans, qry(p << 1, x));
else ans = max(ans, qry(p << 1 | 1, x));
return ans;
}
}tree;
long long pre_sum[150005], suc_sum[150005];
long long pre_rk_sum[150005], suc_rk_sum[150005];
void dfs(int u, int fa, int len) {
siz[u] = 1;
for (auto v : g[u]) {
if (v != fa && !vis[v]) {
pre_sum[v] = pre_sum[u] + a[v];
pre_rk_sum[v] = pre_rk_sum[u] + pre_sum[v];
suc_sum[v] = suc_sum[u] + a[v];
suc_rk_sum[v] = suc_rk_sum[u] + 1ll * len * a[v];
dfs(v, u, len + 1);
siz[u] += siz[v];
}
}
}
void calc_dfs(int u, int fa, int len) {
ans = max(ans, pre_rk_sum[u]);
ans = max(ans, suc_rk_sum[u] + suc_sum[u] + 1ll * a[rt]);
ans = max(ans, tree.qry(1, len) + suc_sum[u] * (len + 1) - suc_rk_sum[u]);
for (auto v : g[u]) {
if (v != fa && !vis[v]) {
calc_dfs(v, u, len + 1);
}
}
}
void add_dfs(int u, int fa, int len) {
tree.update(1, pre_sum[u], pre_sum[u] * (len + 1) - pre_rk_sum[u]);
for (auto v : g[u]) {
if (v != fa && !vis[v]) {
add_dfs(v, u, len + 1);
}
}
}
void solve(int u) {
vis[u] = true, rt = u;
pre_sum[u] = pre_rk_sum[u] = a[u];
suc_sum[u] = suc_rk_sum[u] = 0;
ans = max(ans, 1ll * a[u]), dfs(u, 0, 1);
tree.clear(1);
for (auto v : g[u]) {
if (!vis[v]) {
calc_dfs(v, u, 1);
add_dfs(v, u, 2);
}
}
reverse(g[u].begin(), g[u].end());
tree.clear(1);
for (auto v : g[u]) {
if (!vis[v]) {
calc_dfs(v, u, 1);
add_dfs(v, u, 2);
}
}
for (auto v : g[u]) {
if (!vis[v]) {
rt = 0, sum = siz[v];
findrt(v, u), solve(rt);
}
}
}
int main() {
ios :: sync_with_stdio(0), cin.tie(0);
cin >> n;
for (int i = 1; i < n; ++i) {
int u, v; cin >> u >> v;
g[u].push_back(v), g[v].push_back(u);
}
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
sum = n, findrt(1, 0), tree.build(1, 1, n);
solve(rt);
cout << ans << '\n';
return 0;
} | cpp |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#define enl '\n'
#define int long long
#define sz(s) (int)s.size()
#define all(v) (v).begin(),(v).end()
mt19937 rng (chrono::high_resolution_clock::now().time_since_epoch().count());
template <typename A, typename B> ostream& operator<< (ostream &cout, pair<A, B> const &p) { return cout << "(" << p.first << ", " << p.second << ")"; }
template <typename A, typename B> istream& operator>> (istream& cin, pair<A, B> &p) {cin >> p.first; return cin >> p.second;}
template <typename A> ostream& operator<< (ostream &cout, vector<A> const &v) {cout << "["; for(int i = 0; i < v.size(); i++) {if (i) cout << ", "; cout << v[i];} return cout << "]";}
template <typename A> istream& operator>> (istream& cin, vector<A> &x){for(int i = 0; i < x.size()-1; i++) cin >> x[i]; return cin >> x[x.size()-1];}
template <typename A, typename B> A amax (A &a, B b){ if (b > a) a = b ; return a; }
template <typename A, typename B> A amin (A &a, B b){ if (b < a) a = b ; return a; }
const long long mod = 1e9+7;
const long long inf = 1e18;
void solve() {
int n,k;
cin>>n>>k;
vector<vector<pair<int,int>>>adj(n+1);
vector<int>deg(n+1);
for(int i=1;i<n;i++) {
int x,y;
cin>>x>>y;
adj[x].push_back({y,i});
adj[y].push_back({x,i});
deg[x]++;
deg[y]++;
}
sort(all(deg),greater<int>());
vector<int>color(n+1);
int r = max(1LL,deg[k]);
function<void(int,int,int)>dfs = [&](int s,int p,int clr) {
for(auto [u,idx]:adj[s]) {
if(u == p) continue;
color[idx] = clr%r+1;
clr++;
dfs(u,s,clr%r);
}
};
dfs(1,-1,1);
cout<<r<<enl;
for(int i=1;i<n;i++) cout<<color[i]<<' ';
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);cout.tie(nullptr);
int testcases = 1;
//cin>>testcases;
while(testcases--) solve();
return 0;
} | cpp |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
#define int long long
#define ll long long
#define ff first
#define ss second
#define popf pop_front
#define popb pop_back
#define pb push_back
#define pf push_front
#define yes cout<<"YES"<<endl;
#define no cout<<"NO"<<endl;
#define go ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
const int N=2e5+10;
//int a[1000][1000];
int a[N];
map<char,vector<int> > m;
map<char,vector<int> > m2;
vector<pair<int,int>>v;
int32_t main( )
{
go
int t=1;
//cin>>t;
while(t--)
{
int n;
cin>>n;
string s,s2;
cin>>s>>s2;
for( int i=0; i<n; i++)
{
m[ s[i] ].pb(i+1);
m2[ s2[i] ].pb(i+1);
}
for(auto i:m)
{
if( i.ff=='?')continue;
if( m2[i.ff].size() )
{
while( m[i.ff].size() && m2[i.ff].size() )
{
v.pb( { m[i.ff].back(),m2[i.ff].back() } );
m[i.ff].popb();
m2[i.ff].popb();
}
}
if( m2['?'].size())
{
while( m[i.ff].size() && m2['?'].size() )
{
v.pb( { m[i.ff].back(),m2['?'].back() } );
m[i.ff].popb();
m2['?'].popb();
}
}
}
for(auto i:m2)
{
if( i.ff == '?')
{
for(auto j:m)
{
if( j.ss.size() )
{
while( m[ j.ff ].size() && m2['?'].size() )
{
v.pb( { m[j.ff].back(),m2['?'].back() } );
m2['?'].popb();
m[j.ff].popb();
}
}
}
}
if( i.ss.size())
{
while( m['?'].size() && m2[i.ff].size() )
{
v.pb( { m['?'].back(), m2[i.ff].back() } );
m['?'].popb();
m2[i.ff].popb();
}
}
}
cout<<v.size()<<endl;
for(auto i:v) cout<<i.ff<<" "<<i.ss<<endl;
}
}
/**
/// (a-b)%mod == ( (a-b)%mod+ mod)%mod
/// mod inverse n!/k!= n!*pow(k!,mod-2);
// count the number of numbers in range A , B that are divisible by M
int cnt( int A , int B , int M)
{
if(A%M == 0) return B/M - A/M +1 ;
else return B/M - A/M ;
}
// mod inverse :
int inv( int d)
{
return power(d,mod-2,mod);
}
bool isreg( string s)
{
vector<char>v;
for(int i=0; i<s.size(); i++)
{
if(s[i]=='(') v.push_back('(');
else if(s[i]==')'&&v.size()) v.pop_back();
else if( s[i]==')'&&v.size()==0 )return 0;
}
if(v.size())return 0;
return 1;
}
void seive()
{
for( int i=0; i<N; i++) prime[i]=1;
prime[1]=0;
prime[0]=0;
for( int i=2; i*i<=N; i++)
{
if( prime[ i ] )
{
for( int j=2; j*i<=N; j++)
{
prime[i*j]=0;
}
}
}
}
string numToString(long long n)
{
string s="";
while( n>0)
{
s+=n%10+48;
n/=10;
}
reverse(s.begin(),s.end());
return s;
}
int decToBinary( ll n , int arr[])
{
for(int i=0;i<100;i++)arr[i]=0;
int i=0;
while(n)
{
arr[i]=n%2;
n/=2;
i++;
}
// reverse( arr,arr+32);
return i;
}
int stn( string s )
{
int now=0;
for( auto i:s)
{
now+=i-48;
now*=10;
}
now/=10;
return now;
}
ll power(ll a,ll b )
{
if(b==0)return 1;
ll res=power(a,b/2 );
if(b%2)
return(((res * res) )*(a) );
else
return (res*res) ;
}
// power with mod
ll power(ll a ,ll b , ll m)
{
if(b==0)return 1;
ll res=power(a,b/2,m);
if(b%2)
return(((res * res)%m)*(a%m) )%m;
else
return (res*res)%m;
}
/// we have pair , and we want to sort it in ascending order by its first and in descending order by its second :
int now=v[0].ff;
int l=0,r=0;
sort(v.begin(),v.end());
for(int i=1;i<v.size();i++)
{
if( now==v[i].ff )
{
r++;
}
else
{
reverse( v.begin()+l,v.begin()+r+1 );
now=v[i].ff;
l=r=i;
}
if( i== v.size()-1)
{
reverse( v.begin()+l,v.begin()+r+1 );
}
}
*/
| cpp |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
| [
"dp",
"greedy",
"strings"
] | //Your worst fear owns this
#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<ll>())
#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 q,j=0;
cin>>q;
int arr[q];
while(j<q){
str s1,s2;
cin>>s1>>s2;
vector<int> ind(26,-1);
int vec[s1.sz][26];
for (int i = s1.sz - 1; i >= 0; i--)
{
int d = s1[i]-'a';
for (int ii = 0; ii < 26; ii++)
{
vec[i][ii]=ind[ii];
}
ind[d]=i;
}
int st=0;
int op=0;
while (st<s2.sz)
{
int beg=0;
int d = s2[st]-'a';
beg=ind[d];
if (beg==-1)
{
op=-1;
break;
}
st++;
while (st<s2.sz)
{
int dd = s2[st]-'a';
if (vec[beg][dd]==-1)
{
break;
}
else
{
beg = vec[beg][dd];
st++;
}
}
op++;
}
cout<<op<<endl;
j++;
}
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;
typedef long long ll;
#define endl '\n'
const int maxn=1e5+11;
const int Maxx=1e5+11;
const int mod=1e9+7;
int t;
int n,m;
ll k,now;
void solve()
{
cin>>n>>m>>k;
now=0;
if(k>4*n*m-2*n-2*m) {cout<<"NO"<<endl;return;}
cout<<"YES"<<endl;
vector<pair<int,string>>ans;
if(m!=1)
{
if(now+m-1<=k)
{
ans.emplace_back(m-1,"R");
now+=m-1;
}
else
{
ans.emplace_back(k,"R");
now+=k;
}
if(now+m-1<=k)
{
ans.emplace_back(m-1,"L");
now+=m-1;
}
else if(k-now)
{
ans.emplace_back(k-now,"L");
now=k;
}
}
for(int i=2;i<=n;++i)
{
if(now+1<=k&&n!=1)
{
ans.emplace_back(1,"D");
++now;
}
if(m!=1)
{
if(now+m-1<=k)
{
ans.emplace_back(m-1,"R");
now+=m-1;
}
else if(k-now)
{
ans.emplace_back(k-now,"R");
now=k;
}
if(now+3*(m-1)<=k)
{
ans.emplace_back(m-1,"UDL");
now+=3*(m-1);
}
else
{
ll num=(k-now)/3;
if(num) ans.emplace_back(num,"UDL");
ll res=(k-now)%3;
if(res==1) ans.emplace_back(1,"U");
else if(res==2) ans.emplace_back(1,"UD");
now=k;
}
}
}
if(now!=k&&n!=1)
{
ans.emplace_back(k-now,"U");
}
cout<<int(ans.size())<<endl;
for(auto p:ans) cout<<p.first<<" "<<p.second<<endl;
}
int main()
{
//scanf("%d",&t);
ios::sync_with_stdio(false);cin.tie(0);
//ios::sync_with_stdio(false);cin.tie(0);cin>>t;while(t--)
solve();
return 0;
} | cpp |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | #include <iostream>
#include <ranges>
#include <algorithm>
#include <numeric>
#include <vector>
#include <array>
#include <set>
#include <map>
#include <bit>
#include <sstream>
#include <list>
#include <stack>
#include <queue>
typedef long long integerType;
typedef integerType z;
typedef std::vector<integerType> v;
typedef std::vector<v> V;
typedef std::set<integerType> s;
typedef std::multiset<integerType> S;
typedef std::string r;
typedef std::vector<r> R;
typedef std::vector<bool> b;
struct RHEXAOCrocks {
RHEXAOCrocks() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); }
template<class T>
operator T() const { T n; std::cin >> n; return n; }
std::string operator()() { std::string s; std::cin >> s; return s; }
v operator()(integerType n) { v vec(n); for (auto& n : vec) std::cin >> n; return vec; }
R operator()(integerType n, char del) {
R vec(n); char ch; std::cin >> ch; vec[0].push_back(ch); int c;
for (integerType i{}; i < n;++i)
while ((c = std::cin.get()) != del)
vec[i].push_back(c);
return vec;
}
V operator()(integerType r, integerType c) { V tab(r, v(c)); for (auto& e : tab) for (auto& n : e) std::cin >> n; return tab; }
template<class T> RHEXAOCrocks& operator[](const T& t) { std::cout << t; return *this; }
RHEXAOCrocks& operator[](const R& a) { for (auto& e : a) std::cout << e << '\n'; return *this; }
template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const C<Ty>& c) {
for (auto Cc{ c.begin() }; Cc != c.end(); std::cout << *Cc << " \n"[++Cc == c.end()]); return *this;
}
template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const std::vector<C<Ty>>& c) {
for (auto& e : c) for (auto E{ e.begin() }; E != e.end(); )std::cout << *E << " \n"[++E == e.end()]; return *this;
}
}o;
#define i(b,e, ...) for(integerType i : std::views::iota(b,e) __VA_ARGS__)
#define _i(b,e, ...) for(integerType i : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define j(b,e, ...) for(integerType j : std::views::iota(b,e) __VA_ARGS__)
#define _j(b,e, ...) for(integerType j : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define k(b,e, ...) for(integerType k : std::views::iota(b,e) __VA_ARGS__)
#define _k(b,e, ...) for(integerType k : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define l(b,e, ...) for(integerType l : std::views::iota(b,e) __VA_ARGS__)
#define _l(b,e, ...) for(integerType l : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define Aa for(auto A{ a.begin() }, a_end{ a.end() }; A != a_end; ++A)
#define Bb for(auto B{ b.begin() }, b_end{ b.end() }; B != b_end; ++B)
#define Cc for(auto C{ c.begin() }, c_end{ c.end() }; C != c_end; ++C)
#define Dd for(auto D{ d.begin() }, d_end{ d.end() }; D != d_end; ++D)
#define z(a) (integerType)((a).size())
#define ff(...) auto f = [&](__VA_ARGS__, const auto& f)
#define f(...) f(__VA_ARGS__, f)
#define gg(...) auto g = [&](__VA_ARGS__, const auto& g)
#define g(...) g(__VA_ARGS__, g)
#define hh(...) auto h = [&](__VA_ARGS__, const auto& h)
#define h(...) h(__VA_ARGS__, h)
using namespace std;
namespace ra = ranges;
inline void nwmn(integerType nw, integerType& mn) { mn -= ((nw) < mn) * (mn - (nw)); }
inline void nwmx(integerType nw, integerType& mx) { mx += ((nw) > mx) * ((nw)-mx); }
z power(z a, z b, z M) { z r{ 1 }; do { if (b & 1) (r *= a) %= M; (a *= a) %= M; } while (b >>= 1); return r; }
#define w(...) if(__VA_ARGS__)
#define _ else
#define W(...) while(__VA_ARGS__)
#define A(...) for(auto __VA_ARGS__)
#define O while(true)
void solve_test_case()
{
z n{ o }, m{ o }, p{};
v a{ o(n) };
b b(n);
i(0, m)
b[(z)o - 1] = true;
i(0, n)
if (i == n - 1 || !b[i]) {
sort(a.begin() + p, a.begin() + i + 1);
p = i + 1;
}
o[ra::is_sorted(a) ? "YES\n" : "NO\n"];
}
int main()
{
z t{ o };
while (t--)
solve_test_case();
} | cpp |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | /* Code by Amaan Parvez (amaan0016) */
#include<bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL)
#define pb push_back
#define ppb pop_back
#define ff first
#define ss second
#define lb lower_bound
#define ub upper_bound
#define sz(x) ((int)(x).size())
#define vi vector<ll>
#define mkp make_pair
#define PI 3.141592653589793238462
#define all(v) v.begin(), v.end()
using namespace std;
const ll M = 1e9+7;
const ll MOD =1e18;
const ll N=100000000;
const ll mod=998244353;
#ifndef ONLINE_JUDGE
#define dbg(x) cerr<<#x<<" ";_print_(x);cerr<<endl;
#else
#define dbg(x)
#endif
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_(long double t) { cerr << t; }
void _print_(double t) { cerr << t; }
template <class T, class V> void _print_(pair <T, V> p);
template <class T, class V> void _print_(pair <T, V> p) { cerr << "{"; _print_(p.first); cerr << ","; _print_(p.second); cerr << "}"; }
template <class T> void _print_(set <T> v);
template <class T> void _print_(set <T> v) { cerr << "[ "; for (T i : v) { _print_(i); cerr << " "; } cerr << "]"; }
template <class T, class V> void _print_(map <T, V> v);
template <class T, class V> void _print_(map <T, V> v) { cerr << "[ "; for (auto i : v) { _print_(i); cerr << " "; } cerr << "]"; }
template <class T> void _print_(multiset <T> v);
template <class T> void _print_(multiset <T> v) { cerr << "[ "; for (T i : v) { _print_(i); cerr << " "; } cerr << "]"; }
template <class T> void _print_(vector <T> v);
template <class T> void _print_(vector <T> v) { cerr << "[ "; for (T i : v) { _print_(i); cerr << " "; } cerr << "]"; }
/*---------------------------------------------------------------------------------------------------------------------------*/
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
/*---------------------------------------------------------------------------------------------------------------------------*/
const int Number=10000005;
vector<bool> Prime(Number,true);
vector<int> spf(Number, Number);
void Sieve(){
Prime[0]=false;Prime[1] =false;
for (int i=2;i<Number;i++) {
if(Prime[i]){
spf[i]=i;
for (int j=i*2;j<Number;j+=i){
Prime[j]=false;
spf[j]=min(spf[j], i);
}
}
}
}
ll power(ll x,ll y,ll p){
ll res = 1;
x = x % p;
while (y>0){
if (y & 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return (res + p) % p;
}
ll modinv(ll x){
return power(x, M - 2, M);
}
ll sum(ll n){
// sum 1 to n = (n*(n+1))/2
return ((((n % M) * ((n + 1) %M)) % M) * modinv(2)) % M;
}
// divisors
vi div(ll n){
vi num;
for (ll i=1; i*i<=(n); i++){
if (n%i==0){
if (n/i == i)
num.pb(i);
else{
num.pb(i);
num.pb(n/i);
}
}
}
return num;
}
// TC --> O(sqrt(n))
// To calculate sum of divisors of a number
ll divisorSum(ll n){
ll l = 1;
ll ans = 0;
while (l <= n){
ll k = n / l;
ll r = n / k;
k %= M;
ans += ((sum(r) - sum(l - 1) %M) * k) % M;
ans %= M;
l = r + 1;
}
ans = ans % M;
if (ans < 0){
return ans+M;
}else{
return ans;
}
}
// Euler Totient
ll phi(ll n) {
ll result = n;
for (ll i=2;i*i<=n;i++) {
if (n%i==0) {
while(n % i == 0)
n/=i;
result-= result / i;
}
}
if (n>1)
result-=result / n;
return result;
}
// Factorial Calcultion
ll inverse(int n,int m){
if(n==1){
return 1;
}else{
return inverse(m%n,m)*(m-m/n)%m;
}
}
// Change Acc. to constraints
const ll fac_size=200005;
ll fac[fac_size+1],inv[fac_size+1];
void Cal_Factorial(){
fac[0]=1;
rep(i,1,fac_size+1){
fac[i]=mod_mul(fac[i-1],i,M);
}
inv[fac_size]=inverse(fac[fac_size],M);
for(int i=fac_size;i>0;i--){
inv[i-1]=mod_mul(inv[i],i,M);
}
}
ll C(ll n,ll r){
ll val=1LL*(fac[n]*inv[r]%M*inv[n-r]%M);
return val;
}
void solve(){
ll a,m;
cin >> a >> m;
ll val = gcd(a,m);
m /= val;
ll ans = phi(m);
cout << ans << endl;
}
int main(){
fast;
int t=1;
cin>>t;
while(t--){
#ifndef ONLINE_JUDGE
freopen("error.txt", "w", stderr);
#endif
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;
int output[t];
for (int i = 0; i < t; i++)
{
int s[3];
cin >> s[0] >> s[1] >> s[2];
if (s[0] > 3)
{
s[0] = 4;
}
if (s[1] > 3)
{
s[1] = 4;
}
if (s[2] > 3)
{
s[2] = 4;
}
int M, m, mid;
int iM, im;
if ((s[0] <= s[1]) && (s[0] <= s[2]))
{
m = s[0];
im = 0;
}
else if ((s[1] <= s[2]) && (s[1] <= s[0]))
{
m = s[1];
im = 1;
}
else
{
m = s[2];
im = 2;
}
if ((s[0] >= s[1]) && (s[0] >= s[2]))
{
M = s[0];
iM = 0;
}
else if ((s[1] >= s[2]) && (s[1] >= s[0]))
{
M = s[1];
iM = 1;
}
else
{
M = s[2];
iM = 2;
}
if ((im != 0) && (iM != 0))
{
mid = s[0];
}
else if ((im != 1) && (iM != 1))
{
mid = s[1];
}
else
{
mid = s[2];
}
if (m > 3)
{
output[i] = 7;
}
else
{
if (m == M)
{
if (m == 0)
{
output[i] = 0;
}
else if (m == 1)
{
output[i] = 3;
}
else if (m == 2)
{
output[i] = 4;
}
else
{
output[i] = 6;
}
}
else if (m == mid)
{
if (m == 0)
{
output[i] = 1;
}
if (m == 1)
{
output[i] = 3;
}
if (m == 2)
{
output[i] = 5;
}
if (m == 3)
{
output[i] = 6;
}
}
else if (mid == M)
{
if (mid == 1)
{
output[i] = 2;
}
else if (mid == 2)
{
if (m == 0)
{
output[i] = 3;
}
else if (m == 1)
{
output[i] = 4;
}
}
else if (mid == 3)
{
if (m == 0)
{
output[i] = 3;
}
else if (m == 1)
{
output[i] = 4;
}
else
{
output[i] = 5;
}
}
else
{
if (m == 0)
{
output[i] = 3;
}
if (m == 1)
{
output[i] = 4;
}
if (m == 2)
{
output[i] = 5;
}
if (m == 3)
{
output[i] = 6;
}
}
}
else
{
if (m == 0)
{
if (mid == 1)
{
output[i] = 2;
}
else if (mid == 2)
{
output[i] = 3;
}
else
{
output[i] = 3;
}
}
else if (m == 1)
{
output[i] = 4;
}
else if (m == 2)
{
output[i] = 5;
}
}
}
}
for (int i = 0; i < t; i++)
{
cout << output[i] << endl;
}
return 0;
} | cpp |
1313 | E | E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5]; | [
"data structures",
"hashing",
"strings",
"two pointers"
] | #include<bits/stdc++.h>
using namespace std;
long long n,m,nt[1000006],f[2][500005],sz[2][500005],ans;
vector<long long> vec[500005];
char a[500005],b[500005],c[1000006];
inline void add(long long op,long long u,long long w){for(long long i=u;i<=n;i+=(i&(-i))) sz[op][i]+=w;}
inline long long qry(long long op,long long u)
{
long long sum=0;
for(long long i=u;i>0;i-=(i&(-i))) sum+=sz[op][i];
return sum;
}
int main()
{
scanf("%lld%lld%s%s%s",&n,&m,a+1,b+1,c+1),a[n+1]=b[n+1]='$',c[m+1]='!';
for(long long i=1;i<=m+1;++i) if(c[i]!=c[i+1]){nt[2]=i-1;break;}
for(long long i=3,p=nt[2],p0=2;i<=m+1;++i)
{
if(i>p)
{
for(long long j=1;j<=m+1;++j) if(c[j]!=c[i+j-1]){nt[i]=j-1;break;}
p=i+nt[i]-1,p0=i;
}
else if(i+nt[i-p0+1]-1>=p)
{
for(long long j=p+1;j<=m+1;++j) if(c[j]!=c[j-i+1]){nt[i]=j-i;break;}
p=i+nt[i]-1,p0=i;
}
else nt[i]=nt[i-p0+1];
}
for(long long i=1;i<=n+1&&i<=m+1;++i) if(c[i]!=a[i]){f[0][1]=i-1;break;}
for(long long i=2,p=f[0][1],p0=1;i<=n;++i)
{
if(i>p)
{
for(long long j=1;j<=m+1&&i+j-1<=n+1;++j) if(c[j]!=a[i+j-1]){f[0][i]=j-1;break;}
p=i+f[0][i]-1,p0=i;
}
else if(i+nt[i-p0+1]-1>=p)
{
for(long long j=p+1;j<=n+1&&j-i+1<=m+1;++j) if(a[j]!=c[j-i+1]){f[0][i]=j-i;break;}
p=i+f[0][i]-1,p0=i;
}
else f[0][i]=nt[i-p0+1];
}
reverse(c+1,c+1+m),reverse(b+1,b+1+n);
for(long long i=1;i<=m+1;++i) if(c[i]!=c[i+1]){nt[2]=i-1;break;}
for(long long i=3,p=nt[2],p0=2;i<=m+1;++i)
{
if(i>p)
{
for(long long j=1;j<=m+1;++j) if(c[j]!=c[i+j-1]){nt[i]=j-1;break;}
p=i+nt[i]-1,p0=i;
}
else if(i+nt[i-p0+1]-1>=p)
{
for(long long j=p+1;j<=m+1;++j) if(c[j]!=c[j-i+1]){nt[i]=j-i;break;}
p=i+nt[i]-1,p0=i;
}
else nt[i]=nt[i-p0+1];
}//cout<<nt[3]<<endl;
for(long long i=1;i<=n+1&&i<=m+1;++i) if(c[i]!=b[i]){f[1][1]=i-1;break;}
for(long long i=2,p=f[1][1],p0=1;i<=n;++i)
{
if(i>p)
{
for(long long j=1;j<=m+1&&i+j-1<=n+1;++j) if(c[j]!=b[i+j-1]){f[1][i]=j-1;break;}
p=i+f[1][i]-1,p0=i;
}
else if(i+nt[i-p0+1]-1>=p)
{//cout<<i<<" "<<p<<endl;
for(long long j=p+1;j<=n+1&&j-i<=m;++j) if(b[j]!=c[j-i+1]){f[1][i]=j-i;break;}
p=i+f[1][i]-1,p0=i;
}
else f[1][i]=nt[i-p0+1];//cout<<i<<" "<<f[1][i]<<endl;
}
reverse(f[1]+1,f[1]+1+n);
for(long long i=1;i<=n;++i)
{//cout<<i<<" "<<f[0][i]<<endl;
vec[i-1].push_back(-max(m-f[0][i],1ll));
vec[min(n,i+m-2)].push_back(max(m-f[0][i],1ll));
}
for(long long i=1;i<=n;++i)
{//cout<<i<<" "<<f[1][i]<<endl;
long long len=vec[i].size();
add(0,n-f[1][i]+1,1),add(1,n-f[1][i]+1,min(f[1][i],m-1));//cout<<i<<endl;//cout<<qry(0,4)<<" "<<qry(0,3)<<endl;
for(long long j=0;j<len;++j)
{//cout<<vec[i][j]<<endl;
long long u=abs(vec[i][j]),tmp=qry(1,n-u+1)-(u-1)*qry(0,n-u+1);//cout<<i<<" "<<u<<" "<<qry(0,n-u+1)<<" "<<qry(1,n-u+1)<<endl;
if(vec[i][j]<0) ans-=tmp;
else ans+=tmp;
}//cout<<i<<" "<<ans<<endl;
}
printf("%lld",ans);
} | cpp |
1288 | C | C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1]. | [
"combinatorics",
"dp"
] | import java.io.*;
import java.util.StringTokenizer;
import java.util.*;
public class School {
static int mod=(int) 1e9+7;
static int [][] dp;
static boolean [][]vis;
static int ans=0;
static int solve (int n, int m){
if (n==0)return 0;
if (m==0)return 1;
if (vis[n][m])return dp[n][m];
vis[n][m]=true;
int take= solve(n-1,m);
int leave = solve(n,m-1);
return dp[n][m]= (take%mod+leave%mod)%mod;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int t= 1; // sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int m =sc.nextInt();
dp = new int [n+3][25];
vis= new boolean [n+3][25];
System.out.println(solve(n,2*m));
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | java |
1324 | E | E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good. | [
"dp",
"implementation"
] | import java.util.*;
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int mod = sc.nextInt();
int l = sc.nextInt();
int r = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println(sol.solutionn(l, r, arr, mod));
}
}
class Solution {
int l, r, mod;
int n;
int[] arr;
int[][] dp;
public int solutionn(int l_, int r_, int[] arr_, int mod_) {
n = arr_.length; l = l_; r = r_; arr = arr_; mod = mod_;
dp = new int[n][mod + 1];
for (int i = 0; i < n; i ++) Arrays.fill(dp[i], -1);
return dfs(0, 0);
}
private int dfs(int i, int sum) {
int ans = 0;
if (i > 0 && sum >= l && sum <= r) ans ++;
if (i == n) return ans;
if (dp[i][sum] != -1) return dp[i][sum];
ans += Math.max(dfs(i + 1, (sum + arr[i]) % mod), dfs(i + 1, (sum + arr[i] - 1) % mod));
dp[i][sum] = ans;
return ans;
}
} | java |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t > 0){
long n = sc.nextInt();long d = sc.nextInt();
if(d<=n){
System.out.println("YES");
}else{
if((n-1)*(n-1) - 4*(d-n) >=0){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
t--;
}
}
}
| java |
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"
] | import java.util.Scanner;
public class Lesson7ProductOf3Numbers {
public static boolean isPrime(int num)
{
if(num<=1)
{
return false;
}
for(int i=2;i<=num/2;i++)
{
if((num%i)==0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int TestCases = sc.nextInt();
while(TestCases -- > 0) {
int num = sc.nextInt();
int a = 0;
int b = 0;
int c = 0;
for(int i = 2; i * i < num; i++) {
if(num%i == 0) {
num /= i;
if(a == 0) {
a = i;
}else {
b = i;
break;
}
}else {
}
}
if(a!=0 && b!=0 && num>b) {
System.out.println("YES");
System.out.println(a+" "+b+" "+num+" ");
}else{
System.out.println("NO");
}
}
}
} | java |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | import java.util.Scanner;
public class _1288A {
static long f(long x, long d) {
return x + (long) Math.ceil((double) d / (x + 1));
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
for (int i = 0; i < t; i++) {
long n = input.nextLong();
long d = input.nextLong();
if (d <= n) {
System.out.println("YES");
} else {
long x = n / 2;
while (x > 0) {
if (f(x, d) <= n) {
break;
}
x /= 2;
}
if (f(x, d) <= n) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
}
| java |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] |
import java.io.InputStreamReader;
import static java.lang.Math.*;
import static java.lang.System.*;
import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
FastReader sc = new FastReader(new BufferedInputStream(System.in));
/* For Multiple Test Cases */
// int times = sc.nextInt();
// For single Test Case
int times = 1;
while (times-- > 0){
solve(sc);
}
}
public static void solve(FastReader sc) {
int n = sc.nextInt();
double ans = 0;
while (n>0){
ans+= (1.0/n);
n--;
}
out.println(ans);
}
/*---------------------------------------------------------------------------------------
Template Credit - MagentaCobra
--------------------------------------------------------------------------------------- */
public static void sort(int[] arr)
{
//because Arrays.sort() uses quicksort which is dumb
//Collections.sort() uses merge sort
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void sort(long[] arr)
{
//because Arrays.sort() uses quicksort which is dumb
//Collections.sort() uses merge sort
ArrayList<Long> ls = new ArrayList<Long>();
for(long x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void print(int[] arr)
{
//for debugging only
for(int x: arr)
out.print(x+" ");
out.println();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
/*-----------------------------------------------------------------------------------------------
End for MagentaCobra's Template
------------------------------------------------------------------------------------------------ */
static long maxSubArraySum(Deque<Long> a)
{
long size = a.size();
long tempMax = Integer.MIN_VALUE, maxEnd
= 0;
for (int i = 0; i < size; i++) {
maxEnd = maxEnd + a.pollFirst();
if (tempMax < maxEnd)
tempMax = maxEnd;
if (maxEnd < 0)
maxEnd = 0;
}
return tempMax;
}
/*-----------------------------------------------------------------------------------------------
Class For Fast I/O
------------------------------------------------------------------------------------------------ */
private static class FastReader {
public BufferedReader br;
public StringTokenizer st;
public FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | java |
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"
] | //Some of the methods are copied from GeeksforGeeks Website
import java.util.*;
import java.lang.*;
import java.io.*;
public class C_2_Skyscrapers_hard_version
{
//static Scanner sc=new Scanner(System.in);
//static Reader sc=new Reader();
static FastReader sc=new FastReader(System.in);
static long mod = (long)(1e9)+ 7;
static int max_num=(int)1e5+5;
public static void main (String[] args) throws java.lang.Exception
{
try{
/*
Collections.sort(al,(a,b)->a.x-b.x);
Collections.sort(al,Collections.reverseOrder());
StringBuilder sb=new StringBuilder(""); sb.append(cur); sb=sb.reverse(); String rev=sb.toString();
long n=sc.nextLong();
String s=sc.next();
char a[]=s.toCharArray();
StringBuilder sb=new StringBuilder();
map.put(a[i],map.getOrDefault(a[i],0)+1);
map.putIfAbsent(x,new ArrayList<>());
out.println("Case #"+tt+": "+ans );
*/
int t =1;// sc.nextInt();
for(int tt=1;tt<=t;tt++)
{
int n=sc.nextInt();
long a[]=new long[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextLong();
}
/* Easy version : (n^2), cal in every position i, (0<=i<=n-1)
long max=0;
int point=0;
long res[]=new long[n];
for(int i=0;i<n;i++)
{
long c[]=new long[n];
c[i]=a[i];
for(int j=i-1;j>=0;j--)
{
long cur=a[j];
long min=Math.min(cur,c[j+1]);
c[j]=min;
}
for(int j=i+1;j<n;j++)
{
long cur=a[j];
long min=Math.min(cur,c[j-1]);
c[j]=min;
}
long sum=sum_array(c);
if(sum>max)
{
max=sum;
point=i;
res=c;
}
}
print(res);
*/
// Hard version, can't cal for every positon going in both directions totally, use some suf,pref total(stack, p s e concept) in o(1) to reduce compl to o(n)
long l[]=new long[n];
Stack<Integer> st=new Stack<>();
for(int i=0;i<n;i++)
{
while(!st.isEmpty() && a[st.peek()]>a[i])
st.pop();
if(st.isEmpty())
l[i]=(i+1)*a[i];
else
l[i]=l[st.peek()]+(i-st.peek())*a[i];
st.push(i);
}
st.clear();
long r[]=new long[n];
for(int i=n-1;i>=0;i--)
{
while(!st.isEmpty() && a[st.peek()]>a[i])
st.pop();
if(st.isEmpty())
r[i]=(n-i)*a[i];
else
r[i]=r[st.peek()]+(st.peek()-i)*a[i];
st.push(i);
}
// print(l);
// print(r);
int point=0;
long max=0;
for(int i=0;i<n;i++)
{
long now=l[i]+r[i]-a[i];
if(now>max)
{
point=i;
max=now;
}
}
long ans[]=new long[n];
ans[point]=a[point];
for(int j=point-1;j>=0;j--)
{
long cur=a[j];
long min=Math.min(cur,ans[j+1]);
ans[j]=min;
}
for(int j=point+1;j<n;j++)
{
long cur=a[j];
long min=Math.min(cur,ans[j-1]);
ans[j]=min;
}
print(ans);
}
out.flush();
out.close();
}
catch(Exception e)
{}
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
/*
Map<Long,Long> map=new HashMap<>();
for(int i=0;i<n;i++)
{
if(!map.containsKey(a[i]))
map.put(a[i],1);
else
map.replace(a[i],map.get(a[i])+1);
}
Set<Map.Entry<Long,Long>> hmap=map.entrySet();
for(Map.Entry<Long,Long> data : hmap)
{
}
Iterator<Integer> itr = set.iterator();
while(itr.hasNext())
{
int val=itr.next();
}
*/
// static class Pair
// {
// int x,y;
// Pair(int x,int y)
// {
// this.x=x;
// this.y=y;
// }
// }
// Arrays.sort(p, new Comparator<Pair>()
// {
// @Override
// public int compare(Pair o1,Pair o2)
// {
// if(o1.x>o2.x) return 1;
// else if(o1.x==o2.x)
// {
// if(o1.y>o2.y) return 1;
// else return -1;
// }
// else return -1;
// }});
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void pn(int x)
{
out.println(x);
out.flush();
}
static void pn(long x)
{
out.println(x);
out.flush();
}
static void pn(String x)
{
out.println(x);
out.flush();
}
static int LowerBound(int a[], int x)
{
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u)
{
visited[u]=true;
int v=0;
for(int i=0;i<graph[u].size();i++)
{
v=graph[u].get(i);
if(!visited[v])
DFS(graph,visited,v);
}
}
static boolean[] prime(int num)
{
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long nCr(long a,long b,long mod)
{
return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod;
}
static long fact[]=new long[max_num];
static void fact_fill()
{
fact[0]=1l;
for(int i=1;i<max_num;i++)
{
fact[i]=(fact[i-1]*(long)i);
if(fact[i]>=mod)
fact[i]%=mod;
}
}
static long modInverse(long a, long m)
{
return power(a, m - 2, m);
}
static long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (long)((p * (long)p) % m);
if (y % 2 == 0)
return p;
else
return (long)((x * (long)p) % m);
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
// Thank You ! | java |
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"
] | import java.io.*;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.function.Predicate;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
public class CF1315B {
private void solveOne() {
int a = nextInt();
int b = nextInt();
int p = nextInt();
char[] s = nextString().toCharArray();
int n = s.length;
int[] stepsWeCanMoveFrom = new int[n];
stepsWeCanMoveFrom[n - 1] = 1;
for (int i = n - 2; i >= 0; i--) {
if (s[i] == s[i + 1]) {
stepsWeCanMoveFrom[i] = stepsWeCanMoveFrom[i + 1] + 1;
} else {
stepsWeCanMoveFrom[i] = 1;
}
}
System.out.println(lowerBound(
-1,
s.length,
ans -> ok(s.length, stepsWeCanMoveFrom, s, a, b, p, ans)
) + 1);
}
private boolean ok(int n, int[] stepsWeCanMoveFrom, char[] s, int a, int b, int p, int ans) {
for (int i = ans; i < n - 1; ) {
if (s[i] == 'B') {
if (p - b >= 0) {
p -= b;
} else {
return false;
}
}
if (s[i] == 'A') {
if (p - a >= 0) {
p -= a;
} else {
return false;
}
}
i += stepsWeCanMoveFrom[i];
}
return true;
}
private int lowerBound(int exclusiveLeft, int inclusiveRight, Predicate<Integer> predicate) {
while (inclusiveRight - exclusiveLeft > 1) {
int middle = exclusiveLeft + (inclusiveRight - exclusiveLeft) / 2;
if (predicate.test(middle)) {
inclusiveRight = middle;
} else {
exclusiveLeft = middle;
}
}
return inclusiveRight;
}
private void solve() {
int t = System.in.readInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(Object expected,
Object actual, Object... input) {
super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new CF1315B().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public void readLongArrays(long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readLong();
}
}
}
public void readDoubleArrays(double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readDouble();
}
}
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | java |
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"
] | import java.math.*;
import java.io.*;
import java.util.*;
import java.awt.*;
public class Main implements Runnable {
@Override
public void run() {
try {
new Solver().solve();
System.exit(0);
} catch (Exception | Error e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
//new Thread(null, new Main(), "Solver", 1l << 25).start();
new Main().run();
}
}
class Solver {
final Helper hp;
final int MAXN = 1000_006;
final long MOD = (long) 1e9 + 7;
final Timer timer;
final TimerTask task;
Solver() {
hp = new Helper(MOD, MAXN);
hp.initIO(System.in, System.out);
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
try {
hp.println(ans > MAXN ? -1 : ans);
hp.flush();
System.exit(0);
} catch (Exception e) {
}
}
};
timer.schedule(task, 2800);
}
int N;
ArrayList<Integer>[] graph;
void solve() throws Exception {
int i, j, k;
hp.setSieve();
int[] sieve = hp.sieve;
TreeSet<int[]> edges = new TreeSet<>((a, b) -> a[0] != b[0] ?
Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
HashSet<Integer> singles = new HashSet<>();
int n = hp.nextInt();
for (i = 0; i < n; ++i) {
int ele = hp.nextInt();
HashSet<Integer> primes = new HashSet<>();
while (ele > 1) {
int f = sieve[ele];
boolean flag = false;
while (ele % f == 0) {
ele /= f;
flag = !flag;
}
if (flag) {
if (primes.contains(f)) primes.remove(f);
else primes.add(f);
}
}
if (primes.isEmpty()) {
ans = Math.min(ans, 1);
} else if (primes.size() == 1) {
Iterator<Integer> itr = primes.iterator();
int a = 1, b = itr.next();
int[] e = new int[] {Math.min(a, b), Math.max(a, b)};
if (edges.contains(e)) ans = Math.min(ans, 2);
edges.add(e);
} else if (primes.size() == 2) {
Iterator<Integer> itr = primes.iterator();
int a = itr.next(), b = itr.next();
int[] e = new int[] {Math.min(a, b), Math.max(a, b)};
if (edges.contains(e)) ans = Math.min(ans, 2);
edges.add(e);
} else {
System.exit(7 / 0);
}
}
//System.err.println(singles);
//edges.forEach(a -> System.err.print(Arrays.toString(a)));
N = MAXN;
graph = new ArrayList[N];
for (i = 0; i < N; ++i) graph[i] = new ArrayList<>();
for (int[] e : edges) {
graph[e[0]].add(e[1]);
graph[e[1]].add(e[0]);
}
Integer[] list = new Integer[N];
for (i = 0; i < N; ++i) list[i] = i;
//hp.shuffle(list);
Arrays.sort(list, (a, b) -> Integer.compare(graph[a].size(), graph[b].size()));
for (int itr : list) if (graph[itr].size() > 1) {
//System.err.println("BFS from " + itr);
bfs(itr);
//System.err.println();
}
hp.println(ans > N ? -1 : ans);
timer.cancel();
hp.flush();
}
int ans = MAXN + 3;
void bfs(final int root) {
HashMap<Integer, Integer> vis = new HashMap<>();
ArrayDeque<Integer> deque = new ArrayDeque<>();
deque.addLast(root);
vis.put(root, 0);
for (int d = 1; 2 * d - 1 < ans && !deque.isEmpty(); ++d) {
ArrayDeque<Integer> nextLevel = new ArrayDeque<>();
while (!deque.isEmpty()) {
int node = deque.pollFirst();
//System.err.println(node + " = " + graph[node] + " " + vis);
for (int itr : graph[node]) {
if (vis.containsKey(itr)) {
int itrLvl = vis.get(itr), nodeLvl = d - 1;
if (itrLvl < nodeLvl) {
continue;
} else if (itrLvl > nodeLvl) {
ans = Math.min(ans, itrLvl * 2);
} else {
ans = Math.min(ans, nodeLvl * 2 + 1);
}
return;
}
nextLevel.addLast(itr);
vis.put(itr, d);
}
}
deque = nextLevel;
//System.err.println(deque);
}
}
}
class Helper {
final long MOD;
final int MAXN;
final Random rnd;
public Helper(long mod, int maxn) {
MOD = mod;
MAXN = maxn;
rnd = new Random();
}
public static int[] sieve;
public static ArrayList<Integer> primes;
public void setSieve() {
primes = new ArrayList<>();
sieve = new int[MAXN];
int i, j;
for (i = 2; i < MAXN; ++i)
if (sieve[i] == 0) {
primes.add(i);
for (j = i; j < MAXN; j += i) {
sieve[j] = i;
}
}
}
public static long[] factorial;
public void setFactorial() {
factorial = new long[MAXN];
factorial[0] = 1;
for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD;
}
public long getFactorial(int n) {
if (factorial == null) setFactorial();
return factorial[n];
}
public long ncr(int n, int r) {
if (r > n) return 0;
if (factorial == null) setFactorial();
long numerator = factorial[n];
long denominator = factorial[r] * factorial[n - r] % MOD;
return numerator * pow(denominator, MOD - 2, MOD) % MOD;
}
public long[] getLongArray(int size) throws Exception {
long[] ar = new long[size];
for (int i = 0; i < size; ++i) ar[i] = nextLong();
return ar;
}
public int[] getIntArray(int size) throws Exception {
int[] ar = new int[size];
for (int i = 0; i < size; ++i) ar[i] = nextInt();
return ar;
}
public String[] getStringArray(int size) throws Exception {
String[] ar = new String[size];
for (int i = 0; i < size; ++i) ar[i] = next();
return ar;
}
public String joinElements(long... ar) {
StringBuilder sb = new StringBuilder();
for (long itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(int... ar) {
StringBuilder sb = new StringBuilder();
for (int itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(String... ar) {
StringBuilder sb = new StringBuilder();
for (String itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(Object... ar) {
StringBuilder sb = new StringBuilder();
for (Object itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public long max(long... ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.max(ret, itr);
return ret;
}
public int max(int... ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.max(ret, itr);
return ret;
}
public long min(long... ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.min(ret, itr);
return ret;
}
public int min(int... ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.min(ret, itr);
return ret;
}
public long sum(long... ar) {
long sum = 0;
for (long itr : ar) sum += itr;
return sum;
}
public long sum(int... ar) {
long sum = 0;
for (int itr : ar) sum += itr;
return sum;
}
public void shuffle(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void shuffle(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void reverse(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = ar.length - 1 - i;
if (r > i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void reverse(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = ar.length - 1 - i;
if (r > i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public long pow(long base, long exp, long MOD) {
base %= MOD;
long ret = 1;
while (exp > 0) {
if ((exp & 1) == 1) ret = ret * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return ret;
}
static final int BUFSIZE = 1 << 20;
static byte[] buf;
static int index, total;
static InputStream in;
static BufferedWriter bw;
public void initIO(InputStream is, OutputStream os) {
try {
in = is;
bw = new BufferedWriter(new OutputStreamWriter(os));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
public void initIO(String inputFile, String outputFile) {
try {
in = new FileInputStream(inputFile);
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile)));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
private int scan() throws Exception {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public String next() throws Exception {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan())
sb.append((char) c);
return sb.toString();
}
public int nextInt() throws Exception {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long nextLong() throws Exception {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public void print(Object a) throws Exception {
bw.write(a.toString());
}
public void printsp(Object a) throws Exception {
print(a);
print(" ");
}
public void println() throws Exception {
bw.write("\n");
}
public void println(Object a) throws Exception {
print(a);
println();
}
public void flush() throws Exception {
bw.flush();
}
}
| java |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t-->0) {
int n=s.nextInt();
String str=s.next();
int count=0;
while(str.contains("AP")) {
str=str.replaceAll("AP","AA");
count++;
}
System.out.println(count);
}
}
}
| java |
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"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
BIrreducibleAnagrams solver = new BIrreducibleAnagrams();
solver.solve(1, in, out);
out.close();
}
static class BIrreducibleAnagrams {
public void solve(int testNumber, InputReader in, OutputWriter out) {
String s = in.nextString();
int[][] sum = new int[s.length() + 1][26];
for (int i = 0; i < s.length(); i++) {
System.arraycopy(sum[i], 0, sum[i + 1], 0, 26);
sum[i + 1][s.charAt(i) - 'a']++;
}
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int l = in.nextInt();
int r = in.nextInt();
int cnt = 0;
for (int j = 0; j < 26; j++) {
cnt += (sum[r][j] - sum[l - 1][j] > 0 ? 1 : 0);
}
if (l == r || cnt >= 3 || s.charAt(l - 1) != s.charAt(r - 1)) {
out.println("Yes");
} else {
out.println("No");
}
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| java |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
int num = cin.nextInt();
int radix = 2;
int div;
int res = 0;
int cur_res;
while(radix <= num-1){
div = num;
cur_res = 0;
while(div >= radix){
cur_res += div % radix;
div /= radix;
}
cur_res += div;
res += cur_res;
radix += 1;
}
int add = radix-(num%2);
while(radix <= num-1){
res += add;
add -= 1;
radix += 1;
}
int gcd = BigInteger.valueOf(res).gcd(BigInteger.valueOf(radix-2)).intValue();
System.out.println(res/gcd + "/" + (radix-2)/gcd);
}
}
| java |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | import java.util.*;
import java.io.*;
public class Main {
static Integer dp[][];
public static void main(String[] args) throws Exception {
//Code here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter wr = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
dp = new Integer[n][n];
String s = br.readLine();
System.out.println(dfs(s,0,n-1));
}
// m2 submitted below
private static int dfs(String s , int i , int j){
if(i>j) return 0;
if(dp[i][j]!=null) return dp[i][j];
int max = 0;
for(int k = i;k<=j;k++){
int left = dfs(s,i,k-1);
int right = dfs(s,k+1,j);
int currScore = left+right;
if(left==k-i&&right==j-k){
int counter = 0;
if(i-1>=0){
if((s.charAt(k)-s.charAt(i-1))==1) counter =1;
}
if(j+1<s.length()){
if((s.charAt(k)-s.charAt(j+1))==1) counter = 1;
}
currScore+=counter;
}
max = Math.max(max,currScore);
}
return dp[i][j] = max;
}
} | java |
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"
] | /*
ID: abdelra29
LANG: JAVA
PROG: zerosum
*/
/*
TO LEARN
2-euler tour
*/
/*
TO SOLVE
*/
/*
bit manipulation shit
1-Computer Systems: A Programmer's Perspective
2-hacker's delight
*/
/*
TO WATCH
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.text.DecimalFormat;
import java.util.stream.Collectors;
public class A{
static FastScanner scan=new FastScanner();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static int brute(int i,ArrayList<Integer>GG[],int ans)
{
if(i==idx){
// out.println("AHA");
return ans;
}
//out.println("FUCK");
int max=0;
if(GG[i].size()==0)
{
max=Math.max(max,brute(i+1,GG,ans));
}
for(int j:GG[i])
{
// out.println("AHA "+gcd(ans,j)+" "+i+" "+GG.length);
max=Math.max(max,brute(i+1,GG,gcd(ans,j)));
}
return max;
}
static int gcd(int x,int y)
{
if(x==0)
return y;
return gcd(y%x,x);
}
//static int gcdS[];
static boolean vis[];
static LinkedList<Pair>edges[];
static Set<Integer>GG[];
static int idx=0;
static void dfs(int x,int fi,int gcd)
{
vis[x]=true;
boolean is=false;
for(Pair v:edges[x])
{
if(!vis[(int)v.x])
{
// gcdS[x]=(int)v.y;
is=true;
dfs((int)v.x,fi,gcd(gcd,(int)(v.y)));
//gcdS[x]=gcd(gcdS[x],gcdS[(int)v.x]);
// out.println(gcdS[x]);
//if(x==fi)
// GG[idx].add(gcdS[x]);
// out.println(x+1);
}
}
if(!is){
//out.println(gcd);
GG[idx].add(gcd);
}
//out.println(x+1);
}
public static void main(String[] args) throws Exception
{
/*
very important tips
1-just fucking think backwards once in your shitty life
2-consider brute forcing and finding some patterns and observations
3-when you're in contest don't get out because you think there is no enough time
4-don't get stuck on one approach
*/
//scan=new FastScanner("D:\\usaco test data\\WW.txt");
//out = new PrintWriter("D:\\usaco test data\\WW.txt");
/*
READING
3-Introduction to DP with Bit-masking codeforces
4-Bit Manipulation hacker-earth
5-read more about mobious and inclusion-exclusion
6-read more about Fermat little theorem
*/
/*
-if the two persons are on the same line then it's not possible because that means the shortest path is either abs(x2-x1) or abs(y2-y1) and Manhattan will be abs(x2-x1)+abs(y2-y1) and it's obvious that it will be at least equal
-if the first person is on vertical and second is on horizontal then it's not possible
*/
int tt=1;
tt=scan.nextInt();
int T=1;
outer:while(tt-->0)
{
int n=scan.nextInt(),f=scan.nextInt(),s=scan.nextInt();
if(f+s<=n)
{
out.println(1+" "+(f+s-1));
}
else
{
out.println(Math.min(n,(f+s-n+1))+" "+n);
}
}
out.close();
}
static class special implements Comparable<special>{
int cnt,idx;
String s;
public special(int cnt,int idx,String s)
{
this.cnt=cnt;
this.idx=idx;
this.s=s;
}
@Override
public int hashCode() {
return (int)42;
}
@Override
public boolean equals(Object o){
// System.out.println("FUCK");
if (o == this) return true;
if (o.getClass() != getClass()) return false;
special t = (special)o;
return t.cnt == cnt && t.idx == idx;
}
public int compareTo(special o1)
{
if(o1.cnt==cnt)
{
return o1.idx-idx;
}
return o1.cnt-cnt;
}
}
static long binexp(long a,long n)
{
if(n==0)
return 1;
long res=binexp(a,n/2);
if(n%2==1)
return res*res*a;
else
return res*res;
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return (base % mod+mod)%mod;
long R = (powMod(base, exp/2, mod) % mod+mod)%mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return (base * R % mod+mod)%mod;
}
else return (R %mod+mod)%mod;
}
static double dis(double x1,double y1,double x2,double y2)
{
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int object : arr) list.add(object);
Collections.sort(list);
//Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private static void sort2(long[] arr) {
List<Long> list = new ArrayList<>();
for (Long object : arr) list.add(object);
Collections.sort(list);
Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
static class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static class Pair implements Comparable<Pair>{
public long x, y,z;
public Pair(long x1, long y1,long z1) {
x=x1;
y=y1;
z=z1;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y+" "+z;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
if(x==o.x)
return (int)(y-o.y);
return (int)(x-o.x);
}
}
}
| java |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | import java.util.Scanner;
public class ArrayWithOddSum {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while(t-- > 0){
int n = s.nextInt();
int arr[] = new int[n];
int count = 0;
int sum = 0;
for(int i = 0; i < n; i++){
arr[i] = s.nextInt();
sum += arr[i];
if(arr[i] % 2 != 0){
count++;
}
}
if(sum % 2 != 0){
System.out.println("YES");
}
else{
if(count != 0 && (n - count) != 0){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
}
| java |
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"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BIrreducibleAnagrams solver = new BIrreducibleAnagrams();
solver.solve(1, in, out);
out.close();
}
static class BIrreducibleAnagrams {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
char arr[] = in.scanString().toCharArray();
int[] pre[] = new int[26][arr.length + 1];
for (int i = 0; i < 26; i++) {
for (int j = 1; j <= arr.length; j++) {
pre[i][j] = pre[i][j - 1] + ((arr[j - 1] - 'a') == i ? 1 : 0);
}
}
int q = in.scanInt();
while (q-- > 0) {
int l = in.scanInt();
int r = in.scanInt();
int count = 0;
for (int i = 0; i < 26; i++) count += (pre[i][r] - pre[i][l - 1] > 0) ? 1 : 0;
if (l == r || arr[l - 1] != arr[r - 1] || count >= 3) {
out.println("Yes");
} else {
out.println("No");
}
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
public String scanString() {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder RESULT = new StringBuilder();
do {
RESULT.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return RESULT.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| java |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | import java.io.*;
import java.util.*;
public class E {
static int n;
static int[] di = { -1, 1, 0, 0 };
static int[] dj = { 0, 0, -1, 1 };
static boolean valid(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < n;
}
static char empty = '#';
static boolean eq(int[] a, int[] b) {
return a[0] == b[0] && a[1] == b[1];
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int[][][] a = new int[n][n][2];
char[][] ans = new char[n][n];
Queue<int[]> q = new LinkedList();
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
ans[i][j] = empty;
for (int k = 0; k < 2; k++)
a[i][j][k] = sc.nextInt() - 1;
if (a[i][j][0] == i && a[i][j][1] == j) {
q.add(new int[] { i, j });
ans[i][j] = 'X';
}
}
char[] dir = "UDLR".toCharArray();
while (!q.isEmpty()) {
int[] curr = q.poll();
int i = curr[0], j = curr[1];
for (int k = 0; k < 4; k++) {
int i2 = i + di[k], j2 = j + dj[k];
if (!valid(i2, j2) || ans[i2][j2] != empty)
continue;
if (eq(a[i2][j2], a[i][j])) {
ans[i2][j2] = dir[k ^ 1];
q.add(new int[] { i2, j2 });
}
}
}
boolean ok = true;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if (ans[i][j] != empty)
continue;
if (a[i][j][0] != -2) {
ok = false;
break;
}
int deg = 0;
for (int k = 0; k < 4; k++) {
int i2 = i + di[k], j2 = j + dj[k];
if (!valid(i2, j2) || !eq(a[i2][j2], a[i][j]))
continue;
deg++;
ans[i][j] = dir[k];
if (ans[i2][j2] == empty) {
ans[i2][j2] = dir[k ^ 1];
}
break;
}
ok&=deg>0;
}
if (!ok) {
System.out.println("INVALID");
return;
}
out.println("VALID");
for (char[] x : ans)
out.println(x);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
int[] nxtArr(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
} | java |
1141 | C | C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1
| [
"math"
] | //package javaapplication3;
import java.util.Scanner;
public class JavaApplication3 {
static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
int n = scan.nextInt();
int[] q = new int[n - 1];
int upper = 0, qSum = 0;
for (int i = 0; i < n - 1; i++) {
q[i] = scan.nextInt();
qSum += q[i];
if (qSum > 0)
upper++;
}
int[] p = new int[n];
int[] sorted = new int[n];
p[0] = n - upper;
try {
sorted[p[0] - 1] = p[0];
for (int i = 1; i < n; i++) {
p[i] = p[i - 1] + q[i - 1];
if (sorted[p[i] - 1] != 0) {
System.out.println(-1);
return;
}
sorted[p[i] - 1] = p[i];
}
} catch (Exception e) {
System.out.println(-1);
return;
}
for (int i = 0; i < n; i++) {
System.out.print(p[i] + " ");
}
}
}
| java |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
/**
*
* @author is2ac
*/
public class D_CF {
public static void main(String[] args) throws IOException {
FastScanner58 fs = new FastScanner58();
//Reader fs = new Reader();
PrintWriter pw = new PrintWriter(System.out);
//int t = fs.ni();
int t = 1;
for (int tc = 0; tc < t; tc++) {
int n = fs.ni();
long[] x = fs.longArray(n);
long[] v = fs.longArray(n);
BIT16 bit = new BIT16(200005);
BIT16 people = new BIT16(200005);
Set<Long> set = new HashSet();
List<Long> list = new ArrayList();
Map<Long,Integer> map = new HashMap();
for (int i = 0; i < n; i++) {
set.add(v[i]);
}
for (long val : set) {
list.add(val);
}
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
map.put(list.get(i),i+1);
}
long[][] matrix = new long[n][2];
for (int i = 0; i < n; i++) {
matrix[i][0] = x[i];
matrix[i][1] = v[i];
}
Arrays.sort(matrix,new Comparator<long[]>(){
public int compare(long[] a, long[] b) {
return Long.compare(a[0],b[0]);
}
});
long res = 0;
for (int i = 0; i < n; i++) {
long cx = matrix[i][0];
int cv = map.get(matrix[i][1]);
long cur = (long)people.sum(cv) * (long)cx;
cur -= (long)bit.sum(cv);
res += cur;
people.update(cv,1);
bit.update(cv,cx);
}
pw.println(res);
}
pw.close();
}
public static long gcd(long n1, long n2) {
if (n2 == 0) {
return n1;
}
return gcd(n2, n1 % n2);
}
}
class GFG {
// A utility function to get the
// middle index of given range.
static int getMid(int s, int e)
{
return s + (e - s) / 2;
}
/*
* A recursive function to get the sum
of values in given range of the array.
* The following are parameters
for this function.
*
* st -> Pointer to segment tree
* node -> Index of current node in
* the segment tree.
* ss & se -> Starting and ending indexes
* of the segment represented
* by current node, i.e., st[node]
* l & r -> Starting and ending indexes
* of range query
*/
static long MinUtil(long[] st, int ss,
int se, int l,
int r, int node)
{
// If segment of this node is completely
// part of given range, then return
// the max of segment
if (l <= ss && r >= se)
return st[node];
// If segment of this node does not
// belong to given range
if (se < l || ss > r)
return (long)(1e11);
// If segment of this node is partially
// the part of given range
int mid = getMid(ss, se);
return Math.min(
MinUtil(st, ss, mid, l, r,
2 * node + 1),
MinUtil(st, mid + 1, se, l, r,
2 * node + 2));
}
/*
* A recursive function to update the
nodes which have the given index in their
* range. The following are parameters
st, ss and se are same as defined above
* index -> index of the element to be updated.
*/
static void updateValue(long arr[], long[]
st, int ss,
int se, int index,
long value,
int node)
{
if (index < ss || index > se) {
//System.out.println("Invalid Input");
return;
}
if (ss == se) {
// update value in array and in
// segment tree
arr[index] = value;
st[node] = value;
}
else {
int mid = getMid(ss, se);
if (index >= ss && index <= mid)
updateValue(arr, st, ss, mid,
index, value,
2 * node + 1);
else
updateValue(arr, st, mid + 1, se, index,
value, 2 * node + 2);
st[node] = Math.min(st[2 * node + 1],
st[2 * node + 2]);
}
return;
}
// Return max of elements in range from
// index l (query start) to r (query end).
static long getMin(long[] st, int n, int l, int r)
{
// Check for erroneous input values
if (l < 0 || r > n - 1 || l > r) {
//System.out.printf("Invalid Input\n");
return (long)(1e11);
}
return MinUtil(st, 0, n - 1, l, r, 0);
}
// A recursive function that constructs Segment
// Tree for array[ss..se]. si is index of
// current node in segment tree st
static long constructSTUtil(long arr[],
int ss, int se,
long[] st, int si)
{
// If there is one element in array, store
// it in current node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then
// recur for left and right subtrees and
// store the max of values in this node
int mid = getMid(ss, se);
st[si] = Math.min(
constructSTUtil(arr, ss, mid,
st, si * 2 + 1),
constructSTUtil(arr, mid + 1,
se, st,
si * 2 + 2));
return st[si];
}
/*
* Function to construct segment tree from
given array. This function allocates
* memory for segment tree.
*/
static long[] constructST(long arr[], int n)
{
// Height of segment tree
int x = (int)Math.ceil(Math.log(n) / Math.log(2));
// Maximum size of segment tree
int max_size = 2 * (int)Math.pow(2, x) - 1;
// Allocate memory
long[] st = new long[max_size];
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, st, 0);
// Return the constructed segment tree
return st;
}
}
class BIT16 {
long[] bit;
public BIT16(int size) {
bit = new long[size];
}
public void update(int ind, long delta) {
while (ind < bit.length) {
bit[ind] += delta;
ind = ind + (ind & (-1 * ind));
}
}
public long sum(int ind) {
long s = 0;
while (ind > 0) {
s += bit[ind];
ind = ind - (ind & (-1 * ind));
}
return s;
}
public long query(int l, int r) {
return sum(r) - sum(l);
}
}
class UnionFind18 {
int[] id;
public UnionFind18(int size) {
id = new int[size];
for (int i = 0; i < size; i++) {
id[i] = i;
}
}
public int find(int p) {
int root = p;
while (root != id[root]) {
root = id[root];
}
while (p != root) {
int next = id[p];
id[p] = root;
p = next;
}
return root;
}
public void union(int p, int q) {
int a = find(p), b = find(q);
if (a == b) {
return;
}
id[b] = a;
}
}
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int ni() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) {
return;
}
din.close();
}
}
class FastScanner58 {
BufferedReader br;
StringTokenizer st;
public FastScanner58() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[] intArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++) {
ret[i] = ni();
}
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++) {
ret[i] = nl();
}
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
| java |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
int[] u = new int[n];
for(int i = 0;i < n;i++){
u[i] = a[i] - i;
}
int[][] ai = new int[n][];
for(int i = 0;i < n;i++){
ai[i] = new int[]{u[i], i};
}
Arrays.sort(ai, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
long max = 0;
for(int i = 0;i < n;){
int j = i;
while(j < n && ai[j][0] == ai[i][0])j++;
long val = 0;
for(int k = i;k < j;k++){
val += a[ai[k][1]];
}
max = Math.max(max, val);
i = j;
}
out.println(max);
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
} | java |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | [
"implementation",
"strings"
] | import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n,m;
n = scanner.nextInt();
m = scanner.nextInt();
String [] str1 = new String[n];
for (int i= 0;i< str1.length;i++){
str1[i] = scanner.next();
}
String [] str2 = new String[m];
for (int i= 0;i< str2.length;i++){
str2[i] = scanner.next();
}
int t = scanner.nextInt();
while (t-- > 0){
int l = scanner.nextInt();
String ans =str1[(l-1)%n] + str2[(l-1)%m];
System.out.println(ans);
}
}
} | java |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | import java.io.*;
import java.util.*;
public class cf {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void readArr(int[] ar, int n) {
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static boolean binary_search(long[] a, long k) {
long low = 0;
long high = a.length - 1;
long mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == k) {
return true;
} else if (a[(int) mid] < k) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
public static int bSearchDiff(long[] a, int low, int high) {
int mid = low + ((high - low) / 2);
int hight = high;
int lowt = low;
while (lowt < hight) {
mid = lowt + (hight - lowt) / 2;
if (a[high] - a[mid] <= 5) {
hight = mid;
} else {
lowt = mid + 1;
}
}
return lowt;
}
public static long lowerbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
// if (a[(int) mid] == ddp) {
// return mid;
// }
if (a[(int) mid] <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp && low != 0) {
low--;
}
return low;
}
public static long lowerbound(long a[], long ddp, long factor) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if ((a[(int) mid] + (mid * factor)) == ddp) {
return mid;
}
if ((a[(int) mid] + (mid * factor)) < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp - (low * factor) && low != 0) {
low--;
}
return low;
}
public static long lowerbound(List<Long> a, long ddp) {
long low = 0;
long high = a.size();
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
// if (a.get((int) mid) == ddp) {
// return mid;
// }
if (a.get((int) mid) < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if (low == a.size() && low != 0) {
// low--;
// return low;
// }
// if (a.get((int) low) >= ddp && low != 0) {
// low--;
// }
return low;
}
public static long lowerboundforpairs(pair a[], double pr) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid].w <= pr) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if(low == a.length && low != 0){
// low--;
// return low;
// }
// if(a[(int)low].w > pr && low != 0){
// low--;
// }
return low;
}
public static long upperbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
if (low == a.length) {
return a.length - 1;
}
return low;
}
public static long upperbound(ArrayList<Long> a, long ddp) {
long low = 0;
long high = a.size();
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a.get((int) mid) <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
// public static class pair implements Comparable<pair> {
// long w;
// long h;
// public pair(long w, long h) {
// this.w = w;
// this.h = h;
// }
// public int compareTo(pair b) {
// if (this.w != b.w)
// return (int) (this.w - b.w);
// else
// return (int) (this.h - b.h);
// }
// }
public static class pairs {
char w;
int h;
public pairs(char w, int h) {
this.w = w;
this.h = h;
}
}
public static class pair {
long w;
long h;
public pair(long w, long h) {
this.w = w;
this.h = h;
}
@Override
public int hashCode() {
return Objects.hash(w, h);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof pair)) {
return false;
}
pair c = (pair) o;
return Long.compare(this.w, c.w) == 0 && Long.compare(this.h, h) == 0;
}
}
public static class trinary {
long a;
long b;
long c;
public trinary(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public static pair[] sortpair(pair[] a) {
Arrays.sort(a, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
if (p1.w != p2.w) {
return (int) (p1.w - p2.w);
}
return (int) (p1.h - p2.h);
}
});
return a;
}
public static trinary[] sortpair(trinary[] a) {
Arrays.sort(a, new Comparator<trinary>() {
public int compare(trinary p1, trinary p2) {
if (p1.b != p2.b) {
return (int) (p1.b - p2.b);
} else if (p1.c != p2.c) {
return (int) (p1.c - p2.c);
}
return (int) (p1.a - p2.a);
}
});
return a;
}
public static void sort(long[] arr) {
ArrayList<Long> a = new ArrayList<>();
for (long i : arr) {
a.add(i);
}
Collections.sort(a);
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static void sortForObjecttypes(pair[] arr) {
ArrayList<pair> a = new ArrayList<>();
for (pair i : arr) {
a.add(i);
}
Collections.sort(a, new Comparator<pair>() {
@Override
public int compare(pair a, pair b) {
return (int) (a.h - b.h);
}
});
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static boolean ispalindrome(String s) {
long i = 0;
long j = s.length() - 1;
boolean is = false;
while (i < j) {
if (s.charAt((int) i) == s.charAt((int) j)) {
is = true;
i++;
j--;
} else {
is = false;
return is;
}
}
return is;
}
public static long power(long base, long pow, long mod) {
long result = base;
long temp = 1;
while (pow > 1) {
if (pow % 2 == 0) {
result = ((result % mod) * (result % mod)) % mod;
pow /= 2;
} else {
temp = temp * base;
pow--;
}
}
result = ((result % mod) * (temp % mod));
// System.out.println(result);
return result;
}
public static long sqrt(long n) {
long res = 1;
long l = 1, r = (long) 10e9;
while (l <= r) {
long mid = (l + r) / 2;
if (mid * mid <= n) {
res = mid;
l = mid + 1;
} else
r = mid - 1;
}
return res;
}
public static boolean is[] = new boolean[100001];
public static int a[] = new int[100001];
public static Vector<Integer> seiveOfEratosthenes() {
Vector<Integer> listA = new Vector<>();
for (int i = 2; i * i <= a.length; i++) {
if (a[i] != 1) {
for (long j = i * i; j < a.length; j += i) {
a[(int) j] = 1;
}
}
}
for (int i = 2; i < a.length; i++) {
if (a[i] == 0) {
is[i] = true;
listA.add(i);
}
}
return listA;
}
public static Vector<Integer> ans = seiveOfEratosthenes();
public static long sumOfDigits(long n) {
long ans = 0;
while (n != 0) {
ans += n % 10;
n /= 10;
}
return ans;
}
public static long gcdTotal(long a[]) {
long t = a[0];
for (int i = 1; i < a.length; i++) {
t = gcd(t, a[i]);
}
return t;
}
public static ArrayList<Long> al = new ArrayList<>();
public static void makeArr() {
long t = 1;
while (t <= 10e17) {
al.add(t);
t *= 2;
}
}
public static boolean isBalancedBrackets(String s) {
if (s.length() == 1) {
return false;
}
Stack<Character> sO = new Stack<>();
int id = 0;
while (id < s.length()) {
if (s.charAt(id) == '(') {
sO.add('(');
}
if (s.charAt(id) == ')') {
if (!sO.isEmpty()) {
sO.pop();
} else {
return false;
}
}
id++;
}
if (sO.isEmpty()) {
return true;
}
return false;
}
public static long kadanesAlgo(long a[], int start, int end) {
long maxSoFar = Long.MIN_VALUE;
long maxEndingHere = 0;
for (int i = start; i < end; i++) {
maxEndingHere += a[i];
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
}
if (maxEndingHere < 0) {
maxEndingHere = 0;
}
}
return maxSoFar;
}
public static Vector<Integer> prime = new Vector<>();
public static int components = 0;
public static void search(HashMap<Integer, Integer> hm, int max, int start, int high) {
if (start == 0) {
components++;
return;
}
int t = max;
boolean is = false;
for (int i = start; i < high; i++) {
if (hm.get(t) >= start) {
t--;
is = true;
} else {
// System.out.println(start + " " + high + " " + hm.get(t) + " " + hm.get(max));
is = false;
break;
}
}
// System.out.println(max + " " + is + " " + t);
if (is) {
search(hm, t, hm.get(t), start);
components++;
} else {
// System.out.println(t);
search(hm, max, hm.get(t), high);
}
}
public static void solve(FastReader sc, PrintWriter w, StringBuilder sb) throws Exception {
int n = sc.nextInt();
long a[] = new long[n];
long sumT = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
sumT += a[i];
}
long maxSub1 = kadanesAlgo(a, 0, n - 1);
long maxSub2 = kadanesAlgo(a, 1, n);
if (Math.max(maxSub1, maxSub2) < sumT) {
sb.append("YES\n");
} else {
sb.append("NO\n");
}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter w = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
// prime = seiveOfEratosthenes();
long o = sc.nextLong();
// makeArr();
while (o > 0) {
solve(sc, w, sb);
o--;
}
System.out.print(sb.toString());
w.close();
}
} | java |
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"
] | import java.util.*;
public class Solution {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int index = scan.nextInt();
String data = scan.next();
int[] nilai = new int[2];
for(int i=0;i<index;i++){
if(data.charAt(i)=='L'){
nilai[0] = nilai[0] - 1;
}
else{
nilai[1] = nilai[1] + 1;
}
}
int jumlah = 0;
for(int i=nilai[0];i<=nilai[1];i++){
jumlah++;
}
System.out.println(jumlah);
}
}
| java |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class B625 {
static BufferedReader br;
static long mod = 1000000000 + 7;
static HashSet<Integer> p = new HashSet<>();
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
int tc = 1;
// tc = cinI();
while (tc-- > 0) {
int[] nm = readArray(2,0,0);
HashSet<Integer>[] g = new HashSet[nm[0]+1];
HashSet<Integer>[] g1 = new HashSet[nm[0]+1];
long[] dist= new long[nm[0]+1];
HashSet<Integer>[] next = new HashSet[nm[0]+1];
for(int i=0;i<nm[1];i++){
int[]uv = readArray(2,0,0);
int u =uv[0];
int v = uv[1];
if(g[u]==null){
g[u]=new HashSet<Integer>();
}
if(g1[u]==null){
g[u]=new HashSet<Integer>();
}
if(g[v]==null){
g[v]=new HashSet<Integer>();
}
if(g1[v]==null){
g1[v]=new HashSet<Integer>();
}
g1[v].add(u);
g[u].add(v);
}
for(int i=0;i<=nm[0];i++){
next[i]=new HashSet<Integer>();
}
int n =cinI();
int[] arr =readArray(n,0,0);
Arrays.fill(dist,Long.MAX_VALUE);
dist[arr[n-1]]=0;
Queue<Integer> node = new LinkedList<>();
node.add(arr[n-1]);
while (node.isEmpty()==false){
int c = node.poll();
for(int cc : g1[c]){
if(dist[cc]==dist[c]+1){
next[cc].add(c);
continue;
}
if(dist[cc]>dist[c]+1){
dist[cc]=dist[c]+1;
next[cc].add(c);
node.add(cc);
}
}
}
long min=0;
long max=0;
for(int i=1;i<n;i++){
if(next[arr[i-1]].contains(arr[i])){
if(next[arr[i-1]].size()>1)
max+=1;
// System.out.println(arr[i]+" "+next[arr[i-1]]);
}
else{
// System.out.println(arr[i]+" elaee "+next[arr[i-1]]);
min+=1;
max+=1;
}
}
System.out.println(min +" "+max);
}
}
private static int dfs(TreeMap<Integer, HashSet<Integer>> graph, boolean[] vis, Integer key, Stack<Integer> st) {
if (st.size() == 0) {
return 0;
}
int par = st.pop();
HashSet<Integer> child = graph.get(par);
vis[par] = true;
int nodes = 1;
for (int c : child) {
if (vis[c] == false) {
st.add(c);
nodes += dfs(graph, vis, c, st);
}
}
return nodes;
}
public static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
private static long gcd(long a, long b) {
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a % b, b);
return gcd(a, b % a);
}
public static long min(long a, long b) {
return Math.min(a, b);
}
public static int min(int a, int b) {
return Math.min(a, b);
}
public static void sieve() {
int[] pf = new int[100000000 + 1];
//0 prime //1 not prime
pf[0] = 1;
pf[1] = 1;
for (int j = 2; j <= 10000; j++) {
if (pf[j] == 0) {
p.add(j);
for (int k = j * j; k < pf.length; k += j) {
pf[k] = 1;
}
}
}
}
public static int[] readArray(int n, int x, int z) throws Exception {
int[] arr = new int[n];
String[] ar = cinA();
for (int i = x; i < n + x; i++) {
arr[i] = getI(ar[i - x]);
}
return arr;
}
public static long[] readArray(int n, int x) throws Exception {
long[] arr = new long[n];
String[] ar = cinA();
for (int i = x; i < n + x; i++) {
arr[i] = getL(ar[i - x]);
}
return arr;
}
public static void arrinit(String[] a, long[] b) throws Exception {
for (int i = 0; i < a.length; i++) {
b[i] = Long.parseLong(a[i]);
}
}
public static HashSet<Integer>[] Graph(int n, int edge, int directed) throws Exception {
HashSet<Integer>[] tree = new HashSet[n];
for (int j = 0; j < edge; j++) {
String[] uv = cinA();
int u = getI(uv[0]);
int v = getI(uv[1]);
if (directed == 0) {
tree[v].add(u);
}
tree[u].add(v);
}
return tree;
}
public static void arrinit(String[] a, int[] b) throws Exception {
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
}
static double findRoots(int a, int b, int c) {
// If a is 0, then equation is not
//quadratic, but linear
int d = b * b - 4 * a * c;
double sqrt_val = Math.sqrt(Math.abs(d));
// System.out.println("Roots are real and different \n");
return Math.max((double) (-b + sqrt_val) / (2 * a),
(double) (-b - sqrt_val) / (2 * a));
}
public static String cin() throws Exception {
return br.readLine();
}
public static String[] cinA() throws Exception {
return br.readLine().split(" ");
}
public static String[] cinA(int x) throws Exception {
return br.readLine().split("");
}
public static String ToString(Long x) {
return Long.toBinaryString(x);
}
public static void cout(String s) {
System.out.println(s);
}
public static Integer cinI() throws Exception {
return Integer.parseInt(br.readLine());
}
public static int getI(String s) throws Exception {
return Integer.parseInt(s);
}
public static long getL(String s) throws Exception {
return Long.parseLong(s);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static void coutI(int x) {
System.out.println(String.valueOf(x));
}
public static void coutI(long x) {
System.out.println(String.valueOf(x));
}
public static Long cinL() throws Exception {
return Long.parseLong(br.readLine());
}
public static void arrInit(String[] arr, int[] arr1) throws Exception {
for (int i = 0; i < arr.length; i++) {
arr1[i] = getI(arr[i]);
}
}
} | java |
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"
] | import java.util.*;
import java.util.Map.Entry;
import javax.swing.ToolTipManager;
import org.xml.sax.HandlerBase;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.*;
import java.sql.Array;
public class Simple{
public static class Node{
int v;
int val;
public Node(int v,int val){
this.val = val;
this.v = v;
}
}
static final Random random=new Random();
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static void ruffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
long oi=random.nextInt(n), temp=a[(int)oi];
a[(int)oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
public static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair other){
return this.y - other.y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
// public boolean equals(Pair other){
// if(this.x == other.x && this.y == other.y)return true;
// return false;
// }
// public int hashCode(){
// return 31*x + y;
// }
// @Override
// public int compareTo(Simple.Pair o) {
// // TODO Auto-generated method stub
// return 0;
// }
}
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(long n, long r,
long p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
long[] fac = new long[(int)n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[(int)n] * modInverse(fac[(int)r], p)
% p * modInverse(fac[(int)n - (int)r], p)
% p)
% p;
}
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcd_long(long a, long b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd_long(a-b, b);
return gcd_long(a, b-a);
}
// public static int helper(int arr[],int n ,int i,int j,int dp[][]){
// if(i==0 || j==0)return 0;
// if(dp[i][j]!=-1){
// return dp[i][j];
// }
// if(helper(arr, n, i-1, j-1, dp)>=0){
// return dp[i][j]=Math.max(helper(arr, n, i-1, j-1,dp)+arr[i-1], helper(arr, n, i-1, j,dp));
// }
// return dp[i][j] = helper(arr, n, i-1, j,dp);
// }
// public static void dfs(ArrayList<ArrayList<Integer>> al,int levelcount[],int node,int count){
// levelcount[count]++;
// for(Integer x : al.get(node)){
// dfs(al, levelcount, x, count+1);
// }
// }
public static long __gcd(long a, long b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static class DSU{
int n;
int par[];
int rank[];
public DSU(int n){
this.n = n;
par = new int[n+1];
rank = new int[n+1];
for(int i=1;i<=n;i++){
par[i] = i ;
rank[i] = 0;
}
}
public int findPar(int node){
if(node==par[node]){
return node;
}
return par[node] = findPar(par[node]);//path compression
}
public void union(int u,int v){
u = findPar(u);
v = findPar(v);
if(rank[u]<rank[v]){
par[u] = v;
}
else if(rank[u]>rank[v]){
par[v] = u;
}
else{
par[v] = u;
rank[u]++;
}
}
}
public static boolean isPallindrome(char[] arr,int n,boolean vis[]){
int i=0;
int j= n-1;
while(i<j){
if(vis[i])i++;
else if(vis[j])j--;
else{
if(arr[i]!=arr[j])return false;
i++;
j--;
}
}
return true;
}
public static List<List<Integer>> permute(int[] nums) {
List<Integer> list = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
helper(ans,list,nums,nums.length);
return ans;
}
public static void helper(List<List<Integer>> ans,List<Integer> list,int nums[],int n){
if(list.size()==n){
ans.add(new ArrayList<>(list));
return;
}
for(int i=0;i<n;i++){
if(!list.contains(nums[i])){
list.add(nums[i]);
helper(ans,list,nums,n);
list.remove(list.size()-1);
}
}
}
static int level = 0;
static ArrayList<Integer> nodes;
public static int printShortestPath(Map<Integer,Integer> par, int s, int d)
{
level = 0;
// If we reached root of shortest path tree
if (par.get(s) == -1)
{
System.out.printf("Shortest Path between"+
"%d and %d is %s ", s, d, s);
return level;
}
printShortestPath(par, par.get(s), d);
level++;
// if (s < this.V)
// System.out.printf("%d ", s);
return level;
}
// finds shortest path from source vertex 's' to
// destination vertex 'd'.
// This function mainly does BFS and prints the
// shortest path from src to dest. It is assumed
// that weight of every edge is 1
public static void swap(char arr[],int i){
char c = arr[i];
arr[i] = arr[i+1];
arr[i+1] = c;
}
public static String mul(String str,int n){
int carry = 0;
StringBuilder muli = new StringBuilder();
for(int i=n-1;i>=0;i--){
int val = str.charAt(i) - '0';
int ans = val*2 + carry;
carry = ans/10;
ans = ans%10;
char c = (char)(ans + '0');
muli.append(c);
}
if(carry!=0){
muli.append((char)(carry + '0'));
}
muli.reverse();
return muli.toString();
}
static boolean isSmaller(String str1, String str2)
{
// Calculate lengths of both string
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true;
if (n2 < n1)
return false;
for (int i = 0; i < n1; i++)
if (str1.charAt(i) < str2.charAt(i))
return true;
else if (str1.charAt(i) > str2.charAt(i))
return false;
return false;
}
// Function for find difference of larger numbers
static String findDiff(String str1, String str2)
{
// Before proceeding further, make sure str1
// is not smaller
if (isSmaller(str1, str2)) {
String t = str1;
str1 = str2;
str2 = t;
}
// Take an empty string for storing result
String str = "";
// Calculate length of both string
int n1 = str1.length(), n2 = str2.length();
// Reverse both of strings
str1 = new StringBuilder(str1).reverse().toString();
str2 = new StringBuilder(str2).reverse().toString();
int carry = 0;
// Run loop till small string length
// and subtract digit of str1 to str2
for (int i = 0; i < n2; i++) {
// Do school mathematics, compute difference of
// current digits
int sub
= ((int)(str1.charAt(i) - '0')
- (int)(str2.charAt(i) - '0') - carry);
// If subtraction is less then zero
// we add then we add 10 into sub and
// take carry as 1 for calculating next step
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += (char)(sub + '0');
}
// subtract remaining digits of larger number
for (int i = n2; i < n1; i++) {
int sub = ((int)(str1.charAt(i) - '0') - carry);
// if the sub value is -ve, then make it
// positive
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += (char)(sub + '0');
}
// reverse resultant string
return new StringBuilder(str).reverse().toString();
}
public static double cal1(double x1,double x2,double y1,double y2){
double x = Math.abs(x1 - x2);
double y = Math.abs(y1 - y2);
double ans = x*x + y*y;
return Math.sqrt(ans);
}
public static void main(String args[]){
try {
FastReader s=new FastReader();
FastWriter out = new FastWriter();
// Scanner s = new Scanner(System.in);
// int testCases=s.nextInt();
int testCases = 1;
int counter = 0;
// int something = 0;
while(testCases-- > 0){
// counter++;
// x0, y0, ax, ay, bx, by
long x0 = s.nextLong();
long y0 = s.nextLong();
long ax = s.nextLong();
long ay = s.nextLong();
long bx = s.nextLong();
long by = s.nextLong();
long xs = s.nextLong();
long ys = s.nextLong();
long time = s.nextLong();
ArrayList<Long> x = new ArrayList<>();
ArrayList<Long> y = new ArrayList<>();
x.add(x0);
y.add(y0);
long max = (long)Math.pow(10, 18);
while(true){
long x00 = x0;
long y00 = y0;
x0 = ax*x0 + bx;
y0 = ay*y0 + by;
if(x00>=x0 || y00>=y0)break;
if(x0>=max || y0>=max || x0< 0 || y0<0)break;
x.add(x0);
y.add(y0);
}
int size = x.size();
// System.out.println(x.toString());
// System.out.println(y.toString());
long ans = 0;
for(int i=0;i<size;i++){
long temp = time;
long cover = 0;
temp-= (Math.abs(xs - x.get(i)) + Math.abs(ys - y.get(i)));
if(temp>=0)cover++;
for(int j =i -1;j>=0 && temp>=0;j--){
temp-= (Math.abs(x.get(j) - x.get(j+1)) + Math.abs(y.get(j) - y.get(j+1)));
if(temp>=0 || temp>time)cover++;
else break;
}
ans = Math.max(ans,cover);
temp = time;
cover =0 ;
temp-= (Math.abs(xs - x.get(i)) + Math.abs(ys - y.get(i)));
if(temp>=0)cover++;
for(int j =i +1;j<size && temp>=0;j++){
temp-= (Math.abs(x.get(j) - x.get(j-1)) + Math.abs(y.get(j) - y.get(j-1)));
if(temp>=0 || temp > time)cover++;
else break;
}
ans = Math.max(ans, cover);
}
System.out.println(ans);
}
}
catch (Exception e) {
System.out.println(e.toString());
// System.out.println("Eh");
return;
}
}
}
/*
1 3 4 5 2
2 4 3 5 1
*/ | java |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.in;
import static java.lang.System.out;
public class Kuroni_and_Simple_Strings {
public static void main(String[] args) {
try {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
//Your Code Here
String s = in.next();
calc(s);
out.close();
} catch (Exception e) {
return;
}
}
private static void calc(String s) {
ArrayList<Integer> left = new ArrayList<>();
ArrayList<Integer> right = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left.add(i + 1);
}
if (s.charAt(s.length() - 1 - i) == ')') {
right.add(s.length() - i);
}
}
// Collections.reverse(right);
int count = 0;
for (int i = 0; i < Math.min(left.size(), right.size()); i++) {
if (left.get(i) < right.get(i)) {
count++;
} else {
break;
}
}
// out.println(count);
// out.println(right);
if (count == 0) {
out.println(0);
} else {
out.println(1);
out.println(2 * count);
for (int i = 0; i < count; i++) {
out.print(left.get((i)) + " ");
}
for (int i = count-1; i >= 0; i--) {
out.print(right.get(i) + " ");
}
out.println("");
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return parseInt(next());
}
long nextLong() {
return parseLong(next());
}
double nextDouble() {
return parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
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"
] | //package com.example.practice.codeforces.below2000;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
//A. Recommendations
public class Solution16 {
public static void main (String [] args) throws IOException {
// Use BufferedReader rather than RandomAccessFile; it's much faster
final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// input file name goes above
//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("inflate.out")));
int n = Integer.parseInt(input.readLine());
int[][] ns = new int[n][];
StringTokenizer st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i] = new int[]{Integer.parseInt(st.nextToken()), 0};
}
st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i][1] = Integer.parseInt(st.nextToken());
}
out.println(calc(n, ns));
out.close(); // close the output file
}
private static long calc(final int n, final int[][] ns) {
if (n<2)return 0;
Arrays.sort(ns, Comparator.comparingInt(a -> a[0]));
int pre = ns[0][0];
long res = 0;
for (int i=0,j=1;j<n;++j){
pre++;
if (ns[j][0] >= pre){
res += calcGroup(ns, i, j-1);
pre = ns[j][0];
i = j;
}else if (j+1==n){
res += calcGroup(ns, i, j);
}
}
return res;
}
private static long calcGroup(final int[][] ns, int l, int r){
if (l>=r)return 0;
long res = 0;
PriorityQueue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return ns[o2][1] - ns[o1][1];
}
});
int p = l;
for (int i=ns[l][0],j=i+(r-l);i<=j;++i){
while (p<=r && ns[p][0]<=i){
heap.offer(p++);
}
int t = heap.poll();
res += ((long)(i-ns[t][0])) * ns[t][1];
}
return res;
}
}
| java |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | import java.util.*;
import java.io.*;
public class dsu {
static int n;
static long memo[][];
static int p;
static int pl[][];
static pair[] a;
static int k;
public static long dp(int msk, int idx) {
if (idx == n)
return 0;
if (memo[msk][idx] != -1)
return memo[msk][idx];
long max = k - (idx - Integer.bitCount(msk)) > 0 ? dp(msk, idx + 1) + a[idx].x : dp(msk, idx + 1);
for (int i = 0; i < p; i++) {
if (((msk >> i) & 1) == 0) {
max = Math.max(max, pl[a[idx].y][i] + dp(msk | 1 << i, idx + 1));
}
}
return memo[msk][idx] = max;
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
p = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
a = new pair[n];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < a.length; i++) {
a[i] = new pair(Integer.parseInt(st.nextToken()), i);
}
Arrays.sort(a, (x, y) -> y.x-x.x);
pl = new int[n][p];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < pl[i].length; j++) {
pl[i][j] = Integer.parseInt(st.nextToken());
}
}
memo=new long[1<<p][n];
for (int i = 0; i < memo.length; i++) {
Arrays.fill(memo[i],-1);
}
System.out.println(dp(0,0));
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class pair {
int x;
int y;
pair(int r, int t) {
x = r;
y = t;
}
@Override
public String toString() {
return "("+ x+","+y+")" ;
}
}
} | java |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] |
/*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
import java.util.function.Consumer;
import java.util.*;
import java.math.*;
import java.io.*;
import java.lang.Math.*;
public class KickStart2020 {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static class Pair implements Comparable<Pair> {
public int index;
public int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
// multiplied to -1 as the author need descending sort order
return -1 * Integer.valueOf(this.value).compareTo(other.value);
}
}
static boolean isPrime(long d) {
if (d == 1)
return true;
for (int i = 2; i <= (long) Math.sqrt(d); i++) {
if (d % i == 0)
return false;
}
return true;
}
static String decimalTob(int n, int b, String g) {
int z = n % b;
g = String.valueOf(z) + g;
n /= b;
if (n > 0) {
g = decimalTob(n, b, g);
}
return g;
}
static long powermod(long x, long y, long mod) {
long ans = 1;
x = x % mod;
if (x == 0)
return 0;
int i = 1;
while (y > 0) {
if ((y & 1) != 0)
ans = (ans * x) % mod;
y = y >> 1;
x = (x * x) % mod;
}
return ans;
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
while(t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int arr[] = new int[n];
int brr[] = new int[m];
for(int i = 0; i < n; i++) arr[i] = sc.nextInt();
for(int i = 0; i < m; i++) brr[i] = sc.nextInt();
int crr[] = new int[n + 1];
int drr[] = new int[m + 1];
int i = 0;
while(i < n) {
int temp = arr[i];
int count = 0;
while(i < n && temp == arr[i]) {i++; count++; if(temp == 1) crr[count]++;}
}
i = 0;
while(i < m) {
int temp = brr[i];
int count = 0;
while(i < m && temp == brr[i]) {i++; count++; if(temp == 1) drr[count]++;}
}
for(int j = n - 1; j >= 0; j--) {
crr[j] += crr[j + 1];
}
for(int j = m - 1; j >= 0; j--) {
drr[j] += drr[j + 1];
}
long count = 0;
for(int j = 1; j * j <= k; j++) {
if(k % j != 0)
continue;
int d = k / j;
if(j <= n && d <= m) count += (long)crr[j] * drr[d];
if(j <= m && d <= n && j != d) count += (long)crr[d] * drr[j];
}
out.println(count);
}
out.close();
}
} | java |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | // Program Code
// Problem A:
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
static int N = 1000000;
static int M = 1000000007;
static String res = "";
public static void main(String[] args) throws Exception{
fileConnect();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long ab = 0;
long t = Long.parseLong(st.nextToken());
while(++ab <= t){
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
String str = st.nextToken();
char[] arr = str.toCharArray();
int max = 0;
int temp = 0;
int i=0;
while(i<n){
if(arr[i] != 'A'){
i++;
}else break;
}
while(i<n){
int cnt = 0;
while(i < n && arr[i] == 'P'){
i++;
cnt++;
}
i++;
max = Math.max(max, cnt);
}
System.out.println(max);
} // end of while loop
}
static boolean check(int a, int b, int c, int d)
{
if(a < b && c < d && a < c && b < d) return true;
else return false;
}
static int value(char c){
if(c == 'X') return 1;
else if(c == 'S') return 2;
else if(c == 'M') return 3;
else if(c == 'L') return 4;
else return -1;
}
static boolean check(int[] arr, int[] brr){
for(int i=0; i<26; i++){
if(2*arr[i] != brr[i]) return false;
}
return true;
}
// gcd
static long gcd(long a, long b){
if(b == 0) return a;
return gcd(b, a%b);
}
// read array
static int[] readArr(int N, BufferedReader br, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(br.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
static long[] readArr2(int N, BufferedReader br, StringTokenizer st) throws Exception
{
long[] arr = new long[N];
st = new StringTokenizer(br.readLine());
for(int i=0; i < N; i++)
arr[i] = Long.parseLong(st.nextToken());
return arr;
}
// print array
static void printArr(int[] arr, int n){
for(int i=0; i<n; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
// FileInputOutput
static void fileConnect(){
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {
System.err.println("Error");
}
}
} | java |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | import java.io.*;
import java.util.*;
public class Main {
private static FastScanner fs;
public static void main(String[] args) throws IOException {
fs = new FastScanner();
int nTest = 1;
nTest = fs.nextInt();
for (int testcase = 1; testcase <= nTest; ++testcase) {
solve();
}
}
static void solve() throws IOException {
String s = fs.nextLine();
String t = fs.nextLine();
int n = s.length();
int m = t.length();
int[][] nxt = getNxt(s, n);
for (int i = 0; i < m; ++i) {
if (ok(s, t.substring(0, i + 1), t.substring(i + 1), nxt)) {
System.out.println("YES");
return;
}
}
System.out.println("NO");
}
static int[][] getNxt(String s, int n) {
int[][] nxt = new int[n][26];
for (int ch = 0; ch < 26; ++ch) {
for (int i = n - 1; i >= 0; --i) {
if (s.charAt(i) - 'a' == ch) {
nxt[i][ch] = 1;
} else {
if (i < n - 1 && nxt[i + 1][ch] != -1) {
nxt[i][ch] = 1 + nxt[i + 1][ch];
} else {
nxt[i][ch] = -1;
}
}
}
}
return nxt;
}
static boolean ok (String s, String t1, String t2, int[][] nxt) {
int[][] dp = new int[t1.length() + 1][t2.length() + 1];
int n = s.length();
for (int i = 0; i <= t1.length(); ++i) {
for (int j = 0; j <= t2.length(); ++j) {
dp[i][j] = n + 1;
}
}
dp[0][0] = 0;
for (int i = 1; i <= t1.length(); ++i) {
if (dp[i - 1][0] < n && nxt[dp[i - 1][0]][t1.charAt(i - 1) - 'a'] != -1) {
dp[i][0] = dp[i - 1][0] + nxt[dp[i - 1][0]][t1.charAt(i - 1) - 'a'];
} else {
break;
}
}
for (int i = 1; i <= t2.length(); ++i) {
if (dp[0][i - 1] < n && nxt[dp[0][i - 1]][t2.charAt(i - 1) - 'a'] != -1) {
dp[0][i] = dp[0][i - 1] + nxt[dp[0][i - 1]][t2.charAt(i - 1) - 'a'];
} else {
break;
}
}
for (int i = 1; i <= t1.length(); ++i) {
for (int j = 1; j <= t2.length(); ++j) {
if (dp[i - 1][j] < n && nxt[dp[i - 1][j]][t1.charAt(i - 1) - 'a'] != -1) {
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + nxt[dp[i - 1][j]][t1.charAt(i - 1) - 'a']);
}
if (dp[i][j - 1] < n && nxt[dp[i][j - 1]][t2.charAt(j - 1) - 'a'] != -1) {
dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + nxt[dp[i][j - 1]][t2.charAt(j - 1) - 'a']);
}
}
}
return dp[t1.length()][t2.length()] <= n;
}
static void sort(int[] a) {
ArrayList<Integer> arr = new ArrayList<>();
for (int val : a) {
arr.add(val);
}
Collections.sort(arr);
for (int i = 0; i < a.length; ++i) {
a[i] = arr.get(i);
}
}
static class FastScanner {
private static BufferedReader br;
private static StringTokenizer st;
FastScanner() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
br = new BufferedReader(new FileReader("input.txt"));
PrintStream o = new PrintStream("output.txt");
System.setOut(o);
} else {
br = new BufferedReader(new InputStreamReader(System.in));
}
st = new StringTokenizer("");
}
String nextLine() throws IOException {
return br.readLine();
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
} | java |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | import java.io.*;
import java.util.*;
public class NashMatrix {
private static final int[] DX = {-1, 1, 0, 0}, DY = {0, 0, -1, 1},
REMAP = {1, 0, 3, 2};
private static final char[] MAP = {'U', 'D', 'L', 'R'};
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(in.readLine());
Coordinate[][] board = new Coordinate[n][n];
String[] line;
for (int i = 0; i < n; i++) {
line = in.readLine().split(" ");
for (int j = 0; j < n; j++)
board[i][j] = new Coordinate(Integer.parseInt(line[2 * j]) - 1, Integer.parseInt(line[2 * j + 1]) - 1);
}
char[][] ans = new char[n][n];
// Finds the answer for all squares with value (-1, -1):
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j].x >= 0) continue;
for (int k = 0; k < DX.length; k++) {
int x = i + DX[k], y = j + DY[k];
if (x < 0 || y < 0 || x >= n || y >= n || board[x][y].x >= 0) continue;
ans[i][j] = MAP[k];
break;
}
// If the square is not adjacent to any square with value (-1, -1), then a cycle is impossible.
// Therefore, our answer is "INVALID":
if (ans[i][j] == '\u0000') {
out.println("INVALID");
out.close();
return;
}
}
}
// Finds the answer for all squares with value not (-1, -1):
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (ans[i][j] != '\u0000') continue;
Coordinate cd = board[i][j];
Coordinate cd2 = board[cd.x][cd.y];
// Outputs "INVALID" if the value of the square at (cd) is not (cd):
if (!cd.equals(cd2)) {
out.println("INVALID");
out.close();
return;
}
// Floods all squares with value (cd) starting from (cd).
floodFill(board, ans, cd);
// Outputs "INVALID" if the flood doesn't reach (i, j):
if (ans[i][j] == '\u0000') {
out.println("INVALID");
out.close();
return;
}
}
}
// Output:
out.println("VALID");
for (char[] row : ans) {
for (char ch : row) out.print(ch);
out.println();
}
out.close();
}
private static void floodFill(Coordinate[][] board, char[][] ans, Coordinate cur) {
ans[cur.x][cur.y] = 'X';
Queue<Coordinate> queue = new LinkedList<>();
queue.add(cur);
while (!queue.isEmpty()) {
cur = queue.poll();
for (int i = 0; i < DX.length; i++) {
int x = cur.x + DX[i], y = cur.y + DY[i];
if (x < 0 || y < 0 || x >= board.length || y >= board[x].length ||
!board[x][y].equals(board[cur.x][cur.y]) || ans[x][y] != '\u0000') continue;
ans[x][y] = MAP[REMAP[i]];
queue.add(new Coordinate(x, y));
}
}
}
private static class Coordinate {
private final int x, y;
private Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (other == null || other.getClass() != Coordinate.class) return false;
Coordinate cd = (Coordinate) other;
return cd.x == x && cd.y == y;
}
}
}
| java |
1299 | A | A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer. | [
"brute force",
"greedy",
"math"
] | import java.util.*;
public class C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
String[] a = new String[n];
for(int i=0;i<n;i++) {
arr[i] = sc.nextInt();
a[i] = Integer.toString(arr[i], 2);
int len = a[i].length();
while(len<30) {
a[i] = "0"+a[i];
len++;
}
}
int idx = 0;
for(int i=0;i<30;i++) {
int zero = 0;
for(int j=0;j<n;j++) {
if(a[j].charAt(i)=='0')
zero++;
else
idx = j;
}
if(zero==n-1)
break;
}
int tmp = arr[0];
arr[0] = arr[idx];
arr[idx] = tmp;
for(int i=0;i<n;i++) {
System.out.print(i==0 ? arr[i] : " "+arr[i]);
}
}
}
| java |
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"
] | import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
long n = sc.nextLong();
long a=1,b=1,c;
long rootN = (long)Math.sqrt(n);
for(long i=2; i<=rootN; i++)
{
if(n%i==0)
{
a = i;
break;
}
}
if(a==1 || n==1)
{
System.out.println("NO");
continue;
}
long temp = n/a;
rootN = (long)Math.sqrt(temp);
for(long i=a+1; i<=rootN; i++)
{
if(temp%i==0)
{
b = i;
break;
}
}
if(b==a || b==1)
{
System.out.println("NO");
continue;
}
c = n/(b*a);
if(c!=1 && c!=a && c!=b)
{
System.out.println("YES");
System.out.println(a + " " + b + " " + c);
}
else
System.out.println("NO");
}
}
}
| java |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class B_Cow_and_Friend {
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = f.nextInt();
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
int x = f.nextInt();
int arr[] = f.nextArray(n);
HashSet<Integer> hs = new HashSet<>();
for(int i: arr) {
hs.add(i);
}
int ans = Integer.MAX_VALUE;
for(int i = 0; i < n; i++) {
if(arr[i] > x) {
ans = min(ans, 2);
} else {
ans = min(ans, (x+arr[i]-1)/arr[i]);
}
}
out.println(ans);
}
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
public static int gcd(int a, int b) {
int dividend = a > b ? a : b;
int divisor = a < b ? a : b;
while(divisor > 0) {
int reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
public static int lcm(int a, int b) {
int lcm = gcd(a, b);
int hcf = (a * b) / lcm;
return hcf;
}
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
| java |
1299 | A | A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer. | [
"brute force",
"greedy",
"math"
] | import java.io.*;
import java.util.*;
public class Anu_Has_a_Function {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};
private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100);
private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100);
private static final int mod1 = (int) (1e9 + 7);
private static final int mod2 = 998244353;
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
//t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
int n = fs.nextInt();
int[] arr = readIntArray(n);
int[] no_of_set_bits = new int[30];
for (int x : arr) {
for (int bit = 0; bit < 30; bit++) {
if (((x >> bit) & 1) == 0) no_of_set_bits[bit]++;
}
}
int max = -1;
int idx = -1;
for (int i = 0; i < n; i++) {
int x = arr[i];
int curr = 0;
for (int bit = 0; bit < 30; bit++) {
if (((x >> bit) & 1) == 1 && no_of_set_bits[bit] == n - 1) {
curr |= (1 << bit);
}
}
if (curr > max) {
max = curr;
idx = i;
}
}
fw.out.print(arr[idx] + " ");
for (int i = 0; i < n; i++) {
if (i == idx) continue;
fw.out.print(arr[i] + " ");
}
}
private static class UnionFind {
private final int[] parent;
private final int[] rank;
UnionFind(int n) {
parent = new int[n + 5];
rank = new int[n + 5];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
private int find(int i) {
if (parent[i] == i)
return i;
return parent[i] = find(parent[i]);
}
private void union(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b]) {
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
if (rank[a] == rank[b])
rank[a]++;
}
}
}
private static class Calc_nCr {
private final long[] fact;
private final long[] invfact;
private final int p;
Calc_nCr(int n, int prime) {
fact = new long[n + 5];
invfact = new long[n + 5];
p = prime;
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (i * fact[i - 1]) % p;
}
invfact[n] = pow(fact[n], p - 2, p);
for (int i = n - 1; i >= 0; i--) {
invfact[i] = (invfact[i + 1] * (i + 1)) % p;
}
}
private long nCr(int n, int r) {
if (r > n || n < 0 || r < 0) return 0;
return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;
}
}
private static long gcd(long a, long b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long lcm(long a, long b) {
return ((a * b) / gcd(a, b));
}
private static long pow(long a, long b, int mod) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long ceilDiv(long a, long b) {
return ((a + b - 1) / b);
}
private static long getMin(long... args) {
long min = lMax;
for (long arg : args)
min = Math.min(min, arg);
return min;
}
private static long getMax(long... args) {
long max = lMin;
for (long arg : args)
max = Math.max(max, arg);
return max;
}
private static boolean isPalindrome(String s, int l, int r) {
int i = l, j = r;
while (j - i >= 1) {
if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
private static List<Integer> primes(int n) {
boolean[] primeArr = new boolean[n + 5];
Arrays.fill(primeArr, true);
for (int i = 2; (i * i) <= n; i++) {
if (primeArr[i]) {
for (int j = i * i; j <= n; j += i) {
primeArr[j] = false;
}
}
}
List<Integer> primeList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (primeArr[i])
primeList.add(i);
}
return primeList;
}
private static int noOfSetBits(long x) {
int cnt = 0;
while (x != 0) {
x = x & (x - 1);
cnt++;
}
return cnt;
}
private static boolean isPerfectSquare(long num) {
long sqrt = (long) Math.sqrt(num);
return ((sqrt * sqrt) == num);
}
private static class Pair<U, V> {
private final U first;
private final V second;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
private Pair(U ff, V ss) {
this.first = ff;
this.second = ss;
}
}
private static void randomizeIntArr(int[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swapInIntArr(arr, i, j);
}
}
private static void randomizeLongArr(long[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swapInLongArr(arr, i, j);
}
}
private static void swapInIntArr(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static void swapInLongArr(long[] arr, int a, int b) {
long temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static int[] readIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextInt();
return arr;
}
private static long[] readLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextLong();
return arr;
}
private static List<Integer> readIntList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextInt());
return list;
}
private static List<Long> readLongList(int n) {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextLong());
return list;
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws IOException {
if (checkOnlineJudge)
this.br = new BufferedReader(new FileReader("src/input.txt"));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.st = new StringTokenizer("");
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException err) {
err.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st.hasMoreTokens()) {
return st.nextToken("").trim();
}
try {
return br.readLine().trim();
} catch (IOException err) {
err.printStackTrace();
}
return "";
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static class FastWriter {
PrintWriter out;
FastWriter() throws IOException {
if (checkOnlineJudge)
out = new PrintWriter(new FileWriter("src/output.txt"));
else
out = new PrintWriter(System.out);
}
}
}
| java |
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"
] | import java.io.*;
import java.nio.file.FileStore;
import java.util.*;
public class zia
{
static void BFS(ArrayList<ArrayList<Integer>> adj,int s, boolean[] visited)
{
Queue<Integer> q=new LinkedList<>();
visited[s] = true;
q.add(s);
while(q.isEmpty()==false)
{
int u = q.poll();
for(int v:adj.get(u)){
if(visited[v]==false){
visited[v]=true;
q.add(v);
}
}
}
}
// static int BFS(ArrayList<ArrayList<Integer>> adj,pair s, boolean[] visited,int ar[],int m)
// {
// Queue<pair> q=new LinkedList<>();
// visited[s.a] = true;
// q.add(s);
// int count=0;
// while(q.isEmpty()==false)
// {
// pair u = q.poll();
// // if(adj.get(u.a).size()==0)
// // count++;
// boolean end=true;
// for(int v:adj.get(u.a)){
// if(visited[v]==false){
// visited[v]=true;
// end=false;
// int cat=ar[v]==0?0:ar[v]+u.b;
// if(cat>m)
// continue;
// q.add(new pair(v, cat));
// // System.out.print("--"+v+" "+cat+"--");
// }
// }
// if(end)
// count++;
// // System.out.println(u.a+" "+adj.get(u.a).size()+" count "+count);
// }
// return count;
// }
static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
static void ruffleSort(long[] a) {
int n=a.length;
Random random = new Random();
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n=a.length;
Random random = new Random();
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
public static int Lcm(int a,int b)
{ int max=Math.max(a,b);
for(int i=1;;i++)
{
if((max*i)%a==0&&(max*i)%b==0)
return (max*i);
}
}
static void sieve(int n,boolean prime[])
{
// boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i =i+ p)
prime[i] = false;
}
}
}
// public static String run(int ar[],int n)
// {
// }
public static int upperbound(int s,int e, long ar[],long x)
{
int res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;res=mid;}
else if(ar[mid]<x)
{s=mid+1;}
else
{e=mid-1;res=mid;
if(mid>0&&ar[mid]==ar[mid-1])
e=mid-1;
else
break;
}
}
return res;
}
public static long lowerbound(int s,int e, long ar[],long x)
{
long res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;}
else if(ar[mid]<x)
{s=mid+1;res=mid;}
else
{res=mid;
if(mid+1<ar.length&&ar[mid]==ar[mid+1])
s=mid+1;
else
break;}
}
return res;
}
static long modulo=1000000007;
public static long power(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2)%modulo;
if((b&1)==0)
return (temp*temp)%modulo;
else
return (((temp*temp)%modulo)*a)%modulo;
}
public static long powerwithoutmod(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2);
if((b&1)==0)
return (temp*temp);
else
return ((temp*temp)*a);
}
public static double log2(long a)
{ double d=Math.log(a)/Math.log(2);
return d;
}
public static int log10(long a)
{ double d=Math.log(a)/Math.log(10);
return (int)d;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static void tree(int s,int e,int ar[],int c)
{
if(s<=e)
{
int max=s;
for(int i=s;i<=e;i++)
if(ar[i]>ar[max])
max=i;
ar[max]=c++;
tree(s,max-1,ar,c);
tree(max+1,e,ar,c);
}
}
static int resturant=0;
static void DFS(ArrayList<ArrayList<Integer>> al,boolean visited[],int s,int max,int curr,int ar[])
{
visited[s]=true;
if(al.get(s).size()==1&&visited[al.get(s).get(0)]==true)
{resturant++;return;}
// System.out.println(s+" "+curr);
for(int x:al.get(s))
{
if(visited[x]==false)
{
if(ar[x]==0)
DFS(al, visited, x, max, 0, ar);
else if(curr+ar[x]<=max)
DFS(al, visited, x, max, curr+ar[x], ar);
}
}
}
public static void main(String[] args) throws Exception
{
FastIO sc = new FastIO();
//sc.println();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
int test=sc.nextInt();
// // double c=Math.log(10);
// boolean prime[]=new boolean[233334];
// sieve(233334, prime);
// HashMap<Character,Integer> hm=new HashMap<>(9);
// char c='1';
// for(int i=1;i<=9;i++)
// hm.put(c++,i);
while(test-->0)
{
int n=sc.nextInt();
int ar[]=new int[n];
for (int i = 0; i < n; i++) {
ar[i]=sc.nextInt();
}
HashSet<Integer> hs=new HashSet<>();
int d=0;
for (int i = 0; i < n; i++) {
if(ar[i]==-1)
{
if(i-1>=0&&ar[i-1]!=-1)
hs.add(ar[i-1]);
if(i+1<n&&ar[i+1]!=-1)
hs.add(ar[i+1]);
}
else
{
if(i-1>=0&&ar[i-1]!=-1)
d=Math.max(d,Math.abs(ar[i-1]-ar[i]));
if(i+1<n&&ar[i+1]!=-1)
d=Math.max(d,Math.abs(ar[i+1]-ar[i]));
}
}
if(hs.size()==0)
{
sc.println("0 0");
continue;
}
int max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
for(int i:hs)
{
min=Math.min(min,i);
max=Math.max(max,i);
}
int mean=(min+max)/2;
d=Math.max(d,mean-min);
d=Math.max(d,max-mean);
sc.println(d+" "+mean);
}
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sc.close();
}
}
class pair implements Comparable<pair>{
int a;
int b;
pair(int a,int b)
{this.a=a;
this.b=b;
}
public int compareTo(pair p)
{
if(this.a-p.a==0)
return this.b-p.b;
return (this.a-p.a);
}
}
class triplet implements Comparable<triplet>{
long first,second,third;
triplet(long first,long second,long third)
{this.first=first;
this.second=second;
this.third=third;
}
public int compareTo(triplet p)
{
return (int)(this.first-p.first);
}
}
// class triplet
// {
// int x1,x2,i;
// triplet(int a,int b,int c)
// {x1=a;x2=b;i=c;}
// }
class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastIO() { this(System.in,System.out); }
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
public String nextLine() {
int c; do { c = nextByte(); } while (c <= '\n');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n');
return res.toString();
}
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nextInt() {
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c; do { c = nextByte(); } while (c <= ' ');
long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() { return Double.parseDouble(next()); }
} | java |
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"
] |
import java.util.Scanner;
public class anagram {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.next();
int q = s.nextInt();
int n = str.length();
int [][] dp = new int[n+1][26];
for(int i = 1 ;i <= n ; i++) {
for(int j = 0 ; j < 26 ;j++) {
dp[i][j] = dp[i-1][j];
}
dp[i][str.charAt(i-1)-'a']++;
}
while(q-->0) {
int l = s.nextInt();
int r = s.nextInt();
int total_unique = 0 ;
for(int j = 0 ; j < 26 ;j++) {
if( dp[r][j] - dp[l-1][j] >0) {
total_unique++;
}
}
if(r==l || (total_unique==2 && str.charAt(l-1) != str.charAt(r-1) ) || (total_unique>=3)) {
System.out.println("Yes");
}else {
System.out.println("No");
}
}
}
}
| java |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
| [
"dp",
"greedy",
"strings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.TreeSet;
public class ObtainTheString {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine());
while(t!=0){
solve(br,pr);
t--;
}
pr.flush();
pr.close();
}
public static void solve(BufferedReader br,PrintWriter pr) throws IOException{
char[] s=br.readLine().toCharArray();
char[] t=br.readLine().toCharArray();
TreeSet<Integer>[] indexes=new TreeSet[26];
for(int i=0;i<26;i++){
indexes[i]=new TreeSet<>();
}
for(int i=0;i<s.length;i++){
char letter=s[i];
indexes[letter-'a'].add(i);
}
int lastIndex=-1;
int res=1;
for(int i=0;i<t.length;i++){
char letter=t[i];
if(indexes[letter-'a'].size()==0){
pr.println(-1);
return;
}
var next=indexes[letter-'a'].ceiling(lastIndex+1);
if(next!=null){
lastIndex=next;
}
else if(next==null){
lastIndex=indexes[letter-'a'].first();
res++;
}
}
pr.println(res);
}
}
| java |
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"
] | import java.util.*;
public class p1290A {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
int t=scn.nextInt();
for(int i1=0;i1<t;i1++){
int n=scn.nextInt();
int m=scn.nextInt();
int k=scn.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=scn.nextInt();
}
if(m<=k+1){
k=m-1;
}
Integer val1=Integer.MIN_VALUE;
for(int i=0;i<=k;i++){
int val=Integer.MAX_VALUE;
for(int j=0;j<=m-k-1;j++){
int a=j+i;
int b=n-(-i+m-j);
val=Math.min(Math.max(arr[a],arr[b]),val);
}
if(val>val1){
val1=val;
}
}
System.out.println(val1);
}
}
}
| java |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | // Hydro submission #632f16e3ea0e1b063193825e@1664030435801
import java.util.*;
public class Main {
static class Person{
long t, l, h;
Person(long t, long l, long h){
this.t = t;
this.l = l;
this.h = h;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int q = scanner.nextInt();
g:for(int i=0;i<q;i++){
int n = scanner.nextInt(), m = scanner.nextInt();
Person[] p = new Person[n];
for(int j=0;j<n;j++) p[j] = new Person(scanner.nextLong(), scanner.nextLong(), scanner.nextLong());
long left = m - p[0].t, right = m + p[0].t;
for(int j=0;j<n;j++){
Person cur = p[j];
if(cur.h < left || cur.l > right){
System.out.println("NO");
continue g;
}else if(j == n - 1){
System.out.println("YES");
continue g;
}
if(cur.l >= left && cur.h <= right){ //包含
left = cur.l;
right = cur.h;
}else if(cur.l >= left) left = cur.l; //右侧有区间重叠
else if(cur.h <= right) right = cur.h;
left -= p[j + 1].t - cur.t;
right += p[j + 1].t - cur.t;
}
}
}
} | java |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
| [
"math"
] | // Source: https://usaco.guide/general/io
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(r.readLine());
int count = Integer.parseInt(st.nextToken());
int m;
for(int i = 0; i < count; i++) {
st = new StringTokenizer(r.readLine());
m = Integer.parseInt(st.nextToken());
pw.println(findMax(m));
}
pw.close();
}
public static int findMax(int s)
{
if(s < 10)
return s;
return (s - s%10) + findMax(s%10 + ((s - s%10) / 10));
}
}
| java |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | import java.util.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int testcases = in.nextInt();
while (testcases-- > 0) {
int n = in.nextInt();
int a[][] = new int[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = in.nextInt();
a[i][1] = in.nextInt();
}
Arrays.sort(a, (x, y) -> x[0] == y[0] ? Integer.compare(x[1], y[1]) : Integer.compare(x[0], y[0]));
// System.out.println(Arrays.toString(a));
StringBuilder ans = new StringBuilder();
int x = 0, y = 0;
boolean flag = true;
for (int i = 0; i < n; i++) {
if (a[i][0] < x) {
flag = false;
break;
}
for (int j = 0; j < a[i][0] - x; j++)
ans.append("R");
x = a[i][0];
if (a[i][1] < y) {
flag = false;
break;
}
for (int j = 0; j < a[i][1] - y; j++)
ans.append("U");
y = a[i][1];
}
if (flag) {
System.out.println("YES");
System.out.println(ans);
} else
System.out.println("NO");
}
in.close();
}
} | java |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | //package com.company;
import com.sun.source.tree.ArrayAccessTree;
import javax.swing.*;
import java.beans.IntrospectionException;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Main {
static class pair implements Comparable<pair> {
long a = 0;
long b = 0;
// int cnt;
pair(long b, long a) {
this.a = b;
this.b = a;
// cnt = x;
}
@Override
public int compareTo(pair o) {
if(this.a != o.a)
return (int) (this.a - o.a);
else
return (int) (this.b - o.b);
}
// public boolean equals(Object o) {
// if (o instanceof pair) {
// pair p = (pair) o;
// return p.a == a && p.b == b;
// }
// return false;
// }
//
// public int hashCode() {
// return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());
// }
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void prlong(Object object) throws IOException {
bw.append("" + object);
}
public void prlongln(Object object) throws IOException {
prlong(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
//HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS
// HashSet<Long> set = new HashSet<>();
// for(int i = 0; i < s.length(); i++){
// int b = 0;
// long h = 1;
// for(int j=i; j<s.length(); j++){
// h = 131*h + (int)s.charAt(j);
// b += bad[(int)(s.charAt(j)-'a')];
// if(b<=k){
// set.add(h);
// }
// }
// }
// System.out.println(set.size());
//dsu
static int[] par, rank;
public static void dsu(int n) {
par = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
par[i] = i;
rank[i] = 1;
}
}
static int find(int u) {
return par[u] == -1 ? -1 : par[u] == u ? u : (par[u] = find(par[u]));
}
static void union(int u, int v) {
int a = find(u), b = find(v);
if (a != b && a != -1 && b != -1) {
par[b] = a;
rank[a] += rank[b];
}
}
static void disunion(int u, int v) {
int a = find(u), b = find(v);
if (a != -1 && a == b) {
par[a] = -1;
}
}
static class Calc_nCr {
private final long[] fact;
private final long[] invfact;
private final int p;
Calc_nCr(int n, int prime) {
fact = new long[n + 5];
invfact = new long[n + 5];
p = prime;
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (i * fact[i - 1]) % p;
}
invfact[n] = pow(fact[n], p - 2, p);
for (int i = n - 1; i >= 0; i--) {
invfact[i] = (invfact[i + 1] * (i + 1)) % p;
}
}
private long nCr(int n, int r) {
if (r > n || n < 0 || r < 0) return 0;
return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;
}
private static long pow(long a, long b, int mod) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
}
static void sort(long[] a ) {
ArrayList<Long> l = new ArrayList<>();
for(long i: a) {
l.add(i);
}
Collections.sort(l);
for(int i =0;i<a.length;++i) {
a[i] = l.get(i);
}
}
public static void main(String[] args) {
try {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
int mx=10000000;
boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5];
for (int i = 0; i <= mx; i++) {
isPrime[i] = true;
}
for(int i =0;i<primeDiv.length;i++)
primeDiv[i]=i;
isPrime[0] = isPrime[1] = false;
for (long i = 2; i <= mx; i++) {
if (isPrime[(int)i]) {
for (long j = i*i; j <= mx; j += i) {
if (primeDiv[(int)j] == j) {
primeDiv[(int)j] = (int)i;
}
isPrime[(int)j] = false;
}
}
}
// System.out.println(
// String.format("%.12f", x));
int testCases=in.nextInt();
// int n =in.nextInt();
// long arr[]=new long[n];
// ArrayList<Long>ans=new ArrayList<>();
// for(int i =0;i<n;i++)
//
//
// } ans.add(in.nextLong());
// Collections.sort(ans);
// for(int i =0;i<n;i++)
// arr[i]=ans.get(i);
fl:
while (testCases-- > 0) {
int n =in.nextInt();
long k =in.nextLong();
long arr[]=new long[n];
for(int i =0;i<n;i++)
arr[i]=in.nextLong();
int c[]=new int[60];
for(int i =0;i<n;i++)
{
int j=0;
while(arr[i]!=0) {
c[j]+=arr[i]%k;
++j;
arr[i]/=k;
}
}
for(int i :c)
{
if(i>1)
{
System.out.println("NO");
continue fl;
}
}
System.out.println("YES");
}
out.close();
} catch (Exception e) {
return;
}
}
static long comb(int r,int n)
{
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
static long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
static void LongestPalindromicPrefix(String str,int lps[]){
// String temp = str + '/';
// str = reverse(str);
// temp += str;
String temp =str;
int n = temp.length();
for(int i = 1; i < n; i++)
{
int len = lps[i - 1];
while (len > 0 && temp.charAt(len) !=
temp.charAt(i))
{
len = lps[len - 1];
}
if (temp.charAt(i) == temp.charAt(len))
{
len++;
}
lps[i] = len;
}
// return temp.substring(0, lps[n - 1]);
}
static String reverse(String input)
{
char[] a = input.toCharArray();
int l, r = a.length - 1;
for(l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.valueOf(a);
}
}
/*
*
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ JACKS PET FROM ANOTHER WORLD
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓-------
* ┃ ┏┛-------
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
//RULES
//TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array
//Always use stringbuilder of out.println for strinof out.println for string or high level output
// IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN
//Read minute details if coming wrong for no idea questions | java |
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"
] | import java.io.*;
import java.util.*;
public class A {
static int n;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int p[] = new int[n], c[] = new int[n + 1];
for (int i = 0; i < n; i++)
p[i] = sc.nextInt();
for (int i = 0; i < n; i++)
c[p[i]] = sc.nextInt();
SegmentTree st = new SegmentTree();
for (int i = 1; i <= n; i++)
st.update(i, n, c[i]);
long ans = Long.MAX_VALUE;
for (int k = 0; k + 1 < n; k++) {
st.update(0, p[k] - 1, c[p[k]]);
st.update(p[k], n, -c[p[k]]);
ans = Math.min(ans, st.query(0, n));
}
System.out.println(ans);
out.close();
}
static class SegmentTree {
long[] min, lazy;
SegmentTree() {
min = new long[4 * n];
lazy = new long[4 * n];
}
void update(int l, int r, int v) {
update(1, 0, n, l, r, v);
}
void update(int node, int tl, int tr, int l, int r, int v) {
if (tr < l || r < tl)
return;
if (tl >= l && tr <= r) {
lazy[node] += v;
min[node] += v;
return;
}
int mid = tl + tr >> 1, left = node << 1, right = left | 1;
propagate(node);
update(left, tl, mid, l, r, v);
update(right, mid + 1, tr, l, r, v);
min[node] = Math.min(min[left], min[right]);
}
long query(int l, int r) {
return query(1, 0, n, l, r);
}
long query(int node, int tl, int tr, int l, int r) {
if (r < tl || tr < l)
return Long.MAX_VALUE;
if (tl >= l && tr <= r)
return min[node];
int mid = tl + tr >> 1, left = node << 1, right = left | 1;
propagate(node);
return Math.min(query(left, tl, mid, l, r), query(right, mid + 1, tr, l, r));
}
private void propagate(int node) {
// TODO Auto-generated method stub
int child = node << 1;
lazy[child] += lazy[node];
min[child] += lazy[node];
child++;
lazy[child] += lazy[node];
min[child] += lazy[node];
lazy[node] = 0;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
} | java |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | //package aerodynamic;
import java.util.*;
import java.io.*;
public class aerodynamic {
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(fin.readLine());
if(n % 2 == 1) {
System.out.println("NO");
}
else {
int[][] points = new int[n][2];
for(int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(fin.readLine());
points[i][0] = Integer.parseInt(st.nextToken()) * 10;
points[i][1] = Integer.parseInt(st.nextToken()) * 10;
}
int midX = 0;
int midY = 0;
boolean isValid = true;
for(int i = 0; i < n / 2; i++) {
int curMidX = (points[i][0] + points[i + n / 2][0]) / 2;
int curMidY = (points[i][1] + points[i + n / 2][1]) / 2;
if(i == 0) {
midX = curMidX;
midY = curMidY;
}
else if(midX != curMidX || midY != curMidY){
isValid = false;
break;
}
}
System.out.print(isValid? "YES" : "NO");
}
}
}
| java |
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"
] | import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class FastFoodRestaurent {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for ( int i = 0; i < t; i++){
ArrayList <Integer> list = new ArrayList<>(1);
for ( int j = 0; j < 3; j++){
list.add(in.nextInt());
}
Collections.sort(list);
int sum = 0;
if(list.get(0) > 0){
list.set(0,list.get(0)-1);
sum+=1;
}
if(list.get(1) > 0){
list.set(1,list.get(1)-1);
sum+=1;
}
if(list.get(2)>0){
list.set(2,list.get(2)-1);
sum+=1;
}
if(list.get(0) > 0 && list.get(2) > 0){
list.set(2,list.get(2)-1);
list.set(0,list.get(0)-1);
sum+=1;
}
if(list.get(2) > 0 && list.get(1) > 0){
list.set(2, list.get(2)-1);
list.set(1,list.get(1)-1);
sum+=1;
}
if(list.get(0) > 0 && list.get(1) > 0){
list.set(0, list.get(0)-1);
list.set(1, list.get(1)-1);
sum+=1;
}
if(list.get(0) > 0 && list.get(1) > 0 && list.get(2) > 0){
sum+=1;
}
System.out.println(sum);
}
}
} | java |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Objects;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
}
static class FMovingPoints {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] x = in.nextIntArray(n);
int[] s = in.nextIntArray(n);
int mx = Integer.MAX_VALUE;
int ms = Integer.MAX_VALUE;
for (int a : x) mx = Math.min(mx, a);
s = compress(s);
ArrayList<Pair> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
x[i] -= mx;
list.add(new Pair(x[i], s[i]));
}
Collections.sort(list);
for (int i = 0; i < n; i++) {
x[i] = list.get(i).a;
s[i] = list.get(i).b;
}
// out.println(x);
// out.println(s);
long ans = 0;
FenwickTree f = new FenwickTree(200005);
FenwickTree freq = new FenwickTree(200005);
for (int i = n - 1; i >= 0; i--) {
ans += f.find(s[i], 200002);
long count = freq.find(s[i], 200002);
ans -= (long) x[i] * count;
// d.dbg(ans,f.find(s[i],100002),freq.find(s[i],100002));
// d.dbg(ans,i,s[i],f.find(s[i]+1,100002));
if (i == 0) break;
// d.dbg(i,f.find(s[i]),x[i],s[i]);
f.add(s[i], x[i]);
freq.add(s[i], 1);
// d.dbg(freq.find(s[i],s[i]),s[i]);
}
out.println(ans);
}
int[] compress(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int boof = 1; //min value
for (int x : ls)
if (!map.containsKey(x))
map.put(x, boof++);
int[] brr = new int[arr.length];
for (int i = 0; i < arr.length; i++)
brr[i] = map.get(arr[i]);
return brr;
}
class Pair implements Comparable<Pair> {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int hashCode() {
return Objects.hash(a, b);
}
public boolean equals(Object obj) {
Pair that = (Pair) obj;
return a == that.a && b == that.b;
}
public String toString() {
return "[" + a + ", " + b + "]";
}
public int compareTo(Pair v) {
return a - v.a;
}
}
class FenwickTree {
public long[] tree;
public int size;
public FenwickTree(int size) {
this.size = size;
tree = new long[size + 5];
}
public void add(int i, long v) {
while (i <= size) {
tree[i] += v;
i += i & -i;
}
}
public long find(int i) {
long res = 0;
while (i >= 1) {
res += tree[i];
i -= i & -i;
}
return res;
}
public long find(int l, int r) {
return find(r) - find(l - 1);
}
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| java |
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"
] | // package c1294;
//
// Codeforces Round #615 (Div. 3) 2020-01-22 06:35
// D. MEX maximizing
// https://codeforces.com/contest/1294/problem/D
// time limit per test 3 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// Recall that of an array is a that does not belong to the array. Examples:
// * for the array [0, 0, 1, 0, 2] MEX equals to 3 because numbers 0, 1 and 2 are presented in the
// array and 3 is the minimum non-negative integer not presented in the array;
// * for the array [1, 2, 3, 4] MEX equals to 0 because 0 is the minimum non-negative integer not
// presented in the array;
// * for the array [0, 1, 4, 3] MEX equals to 2 because 2 is the minimum non-negative integer not
// presented in the array.
//
// You are given an empty array a=[] (in other words, a zero-length array). You are also given a
// positive integer x.
//
// You are also given q queries. The j-th query consists of one integer y_j and means that you have
// to append one element y_j to the array. The array length increases by 1 after a query.
//
// In one move, you can choose any index i and set a_i := a_i + x or a_i := a_i - x (i.e. increase
// or decrease any element of the array by x). The only restriction is that . Since initially the
// array is empty, you can perform moves only after the first query.
//
// You have to maximize the (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 q queries (i.e. the j-th answer corresponds to the
// array of length j).
//
// Input
//
// The first line of the input contains two integers q, x (1 <= q, x <= 4 * 10^5) -- the number of
// queries and the value of x.
//
// The next q lines describe queries. The j-th query consists of one integer y_j (0 <= y_j <= 10^9)
// and means that you have to append one element y_j to the array.
//
// Output
//
// Print the answer to the initial problem after each query -- for the query j print the maximum
// value of after first j queries. Note that queries are dependent (the array changes after each
// query) but operations are independent between queries.
//
// Example
/*
input:
7 3
0
1
2
2
0
0
10
output:
1
2
3
3
4
4
7
input:
4 3
1
2
1
2
output:
0
0
0
0
*/
// Note
//
// In the first example:
// * After the first query, the array is a=[0]: you don't need to perform any operations, maximum
// possible MEX is 1.
// * After the second query, the array is a=[0, 1]: you don't need to perform any operations,
// maximum possible MEX is 2.
// * After the third query, the array is a=[0, 1, 2]: you don't need to perform any operations,
// maximum possible MEX is 3.
// * After the fourth query, the array is a=[0, 1, 2, 2]: you don't need to perform any operations,
// maximum possible MEX is 3 (you can't make it greater with operations).
// * After the fifth query, the array is a=[0, 1, 2, 2, 0]: you can perform a[4] := a[4] + 3 = 3.
// The array changes to be a=[0, 1, 2, 2, 3]. Now MEX is maximum possible and equals to 4.
// * After the sixth query, the array is a=[0, 1, 2, 2, 0, 0]: you can perform a[4] := a[4] + 3 = 0
// + 3 = 3. The array changes to be a=[0, 1, 2, 2, 3, 0]. Now MEX is maximum possible and equals
// to 4.
// * After the seventh query, the array is a=[0, 1, 2, 2, 0, 0, 10]. You can perform the following
// operations:
// * a[3] := a[3] + 3 = 2 + 3 = 5,
// * a[4] := a[4] + 3 = 0 + 3 = 3,
// * a[5] := a[5] + 3 = 0 + 3 = 3,
// * a[5] := a[5] + 3 = 3 + 3 = 6,
// * a[6] := a[6] - 3 = 10 - 3 = 7,
// * a[6] := a[6] - 3 = 7 - 3 = 4. The resulting array will be a=[0, 1, 2, 5, 3, 6, 4]. Now MEX is
// maximum possible and equals to 7.
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class C1294D {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] solve(int[] ya, int x) {
int q = ya.length;
int[] ans = new int[q];
int[] min = new int[q+1];
for (int i = 0; i <= q; i++) {
min[i] = i;
}
boolean[] ok = new boolean[q+1];
int mex = 0;
for (int i = 0; i < q; i++) {
int y = ya[i] % x;
if (y < q) {
if (min[y] <= q) {
ok[min[y]] = true;
min[y] += x;
}
}
while(ok[mex]) {
mex++;
}
ans[i] = mex;
}
return ans;
}
// TLE
static int[] solveA(int[] ya, int x) {
int q = ya.length;
int[] ct = new int[q + 1];
int[] ans = new int[q];
int mex = 0;
for (int i = 0; i < q; i++) {
int y = ya[i];
// increase y to the minimal value >= mex
if (y < mex) {
int k = (mex - y + x - 1) / x;
y += k * x;
}
myAssert(y >= mex);
// decrease y to the minimal value >= mex
{
int k = (y - mex) / x;
y -= k * x;
}
// Increase y if there is already a count
while (y <= q && ct[y] != 0) {
y += x;
}
if (test) System.out.format(" i:%2d y:%d\n", i, y);
if (y <= q) {
ct[y]++;
}
while (ct[mex] > 0) {
mex++;
}
ans[i] = mex;
}
return ans;
}
static String trace(int[][] a) {
return Arrays.deepToString(a).replace(" ", "").replace('[', '{').replace(']', '}');
}
static String trace(int[] a) {
return Arrays.toString(a).replace(" ", "").replace('[', '{').replace(']', '}');
}
static void test(int[] exp, int[] y, int x) {
System.out.format("%s %d\n", trace(y), x);
int[] ans = solve(y, x);
boolean ok = true;
if (exp != null) {
for (int i = 0; i < ans.length; i++) {
if (ans[i] != exp[i]) {
ok = false;
break;
}
}
}
System.out.format(" => %s %s\n", trace(ans), ok ? "":"Expected " + trace(exp));
myAssert(ok);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(new int[] {0,2,3,3,3,5,5,7,9,10,10,10,12,14,14,14,14,16,16,18,18,18,20,20,22,22,22,22,24,26,26,
28,30,30,30,32,34,36,38,40,41,42,42,44,45,45,45,45,47,49,49},
new int[] {630874911, 734875554, 732780376, 761466396, 543967336, 727295757, 142396288,
900137307, 707426025, 179546151, 26986631, 549687, 778668574, 62916138, 98303405,
884297679, 765856475, 981943572, 659643629, 881357320, 951014691, 422536531, 299232258,
85228941, 305055348, 88611335, 243438099, 736398145, 741925046, 55318966, 587721649,
299573818, 10356092, 975743365, 864911753, 206516024, 423602150, 715941614, 393849704,
889427616, 881407230, 261023741, 768345063, 158178032, 20771974, 922787326}, 2);
int q = 1 + RAND.nextInt(30);
int x = 1 + RAND.nextInt(30);
int[] y = new int[q];
for (int i = 0; i < q; i++) {
y[i] = RAND.nextInt(1000);
}
test(null, y, x);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int q = in.nextInt();
int x = in.nextInt();
int[] y = new int[q];
for (int i = 0; i < q; i++) {
y[i] = in.nextInt();
}
int[] ans = solve(y, x);
output(ans);
}
static void output(int[] a) {
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append('\n');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.print(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
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"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
List<Integer> maximums = new ArrayList<>();
List<Integer> minimums = new ArrayList<>();
for (int i = 0; i < n; i++) {
boolean alreadyHasAscent = false;
int totalElements = sc.nextInt();
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int j = 0; j < totalElements; j++) {
int value = sc.nextInt();
if (value > min) {
alreadyHasAscent = true;
}
min = Math.min(min, value);
max = Math.max(max, value);
}
if (alreadyHasAscent) {
min = Integer.MIN_VALUE;
max = Integer.MAX_VALUE;
}
minimums.add(min);
maximums.add(max);
}
Collections.sort(minimums);
Collections.sort(maximums);
//out.println(maximums);
long totalPairs = 0;
for (int i = 0; i < minimums.size(); i++) {
totalPairs += binarySearch(maximums, minimums.get(i));
}
out.println(totalPairs);
}
private static long binarySearch(List<Integer> maximums, int minValue) {
int n = maximums.size();
int lo = 0, hi = n - 1;
int res = n;
while (lo <= hi) {
int mid = (lo + hi) >> 1;
if (maximums.get(mid) > minValue) {
//out.println("ok");
res = Math.min(res, mid);
hi = mid - 1;
}else {
lo = mid + 1;
}
}
return n - res;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException end)
{
end.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException end)
{
end.printStackTrace();
}
return str;
}
}
} | java |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
FastReader sc=new FastReader();
int t=sc.nextInt();
while (t-->0){
long n=sc.nextLong();
int m=sc.nextInt();
int bit[]=new int[61];
long sum=0;
for (int i=0;i<m;i++){
int temp=sc.nextInt();
sum+=temp;
int j=0;
while ((temp&(1<<j))==0)j++;
bit[j]++;
}
if (sum<n) {
System.out.print("-1\n");
continue;
}
int res=0;
for (int i=0;i<60;i++){
if ((n&(1L<<i))!=0){
if (bit[i]==0){
int j=i+1;
while (bit[j]==0)j++;
while (j!=i){
bit[j]--;
j--;
bit[j]+=2;
res++;
}
}
bit[i]--;
}
bit[i+1]+=bit[i]/2;
}
System.out.println(res);
}
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
} | java |
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"
] | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
new Main().solve(new InputReader(System.in), new PrintWriter(System.out));
}
private void solve(InputReader in, PrintWriter pw) {
// int tt = 1;
int tt = in.nextInt();
int x = in.nextInt();
int mex = 0;
int[] cnt = new int[x];
while (tt-- > 0) {
int y = in.nextInt();
y = (y + x) % x;
cnt[y]++;
// 枚举mex,如果cnt[mex%x]>mex/x,则代表可以通过mex%x+nx构造出mex,此时mex++
while (cnt[mex % x] > mex / x) {
mex++;
}
pw.println(mex);
}
pw.close();
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
private int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
}
class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str;
try {
str = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return str;
}
public boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String nextLine = null;
try {
nextLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (nextLine == null)
return false;
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
return a;
}
} | java |
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"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
public class coding {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try {
String str = br.readLine();
if(str == null)
throw new InputMismatchException();
st = new StringTokenizer(str);
} catch(IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch(IOException e) {
e.printStackTrace();
}
if(str == null)
throw new InputMismatchException();
return str;
}
public BigInteger nextBigInteger() {
// TODO Auto-generated method stub
return null;
}
}
public static <K, V> K getKey(Map<K, V> map, V value)
{
for (Map.Entry<K, V> entry: map.entrySet())
{
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
public static void main(String args[] ) throws Exception {
// FastReader sc = new FastReader();
// PrintWriter out = new PrintWriter(System.out);
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
Integer n=sc.nextInt();
int arr[]=new int[n];
int s=0;
int c=0;
int x=0;
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
s=s+arr[i];
if(arr[i]==0)
{
c++;
}
}
Arrays.sort(arr);
if(s==0 && c==0)
{
x=1;
}
if(s==0 && c>0)
{
x=c;
}
if(s!=0 && c==0)
{
x=0;
}
if(s!=0 && c>0)
{
x=c;
s=s+c;
if(s==0)
{
x++;
}
}
System.out.println(x);
}
}
} | java |
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"
] | public class AddOddorSubtractEven {
public static void main(String[] args) throws Exception {
java.util.Scanner sc=new java.util.Scanner(System.in);
int t=sc.nextInt();
StringBuilder sb=new StringBuilder();
while (t>0){
int a=sc.nextInt(),b=sc.nextInt();
if (a==b) sb.append(0+"\n");
else if (a-b<0){
if ((b-a)%2==1){
sb.append(1+"\n");
}else sb.append(2+"\n");
}else {
if ((a-b)%2==0){
sb.append(1+"\n");
}else sb.append(2+"\n");
}
t--;
}
System.out.println(sb);
}
} | java |
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"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DTimeToRun solver = new DTimeToRun();
solver.solve(1, in, out);
out.close();
}
static class DTimeToRun {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
if (k > 4 * n * m - 2 * n - 2 * m) {
out.println("NO");
return;
}
out.println("YES");
if (m == 1) {
out.println(k);
int min = Math.min(k, n - 1);
k -= min;
for (int i = 0; i < min; i++) {
out.println("1 D");
}
min = Math.min(k, n - 1);
if (k != 0) {
for (int i = 0; i < min; i++) {
out.println("1 U");
}
}
return;
}
ArrayList<String> ans = new ArrayList<>();
int id = -1;
for (int i = 0; i < n - 1; i++) {
int val = 4 * (m - 1) + 1;
if (val <= k) {
id = i;
k -= val;
ans.add("" + (m - 1) + " RDU");
ans.add("" + (m - 1) + " L");
ans.add("1 D");
} else {
break;
}
}
if (k != 0) {
int min = Math.min(k, m - 1);
ans.add("" + min + " R");
k -= min;
}
id++;
if (k != 0) {
int min = Math.min(k, m - 1);
ans.add("" + min + " L");
k -= min;
}
if (id != n - 1) {
if (k > 0) {
k -= 1;
ans.add("1 D");
}
if (k != 0) {
int min = Math.min(k, m - 1);
ans.add("" + min + " R");
k -= min;
}
if (k != 0) {
int min = Math.min(k, m - 1);
ans.add("" + min + " L");
k -= min;
}
}
if (k > 0) {
int min = Math.min(k, n - 1);
ans.add("" + min + " U");
}
out.println(ans.size());
for (String s : ans) out.println(s);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| java |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* @author Mubtasim Shahriar
*/
public class FillTheBag {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
int t = sc.nextInt();
// int t = 1;
while (t-- != 0) {
solver.solve(sc, out);
}
out.close();
}
static class Solver {
public void solve(InputReader sc, PrintWriter out) {
long n = sc.nextLong();
int m = sc.nextInt();
int bitl = 60;
int[] cnt = new int[bitl];
int[] boxes = sc.nextIntArray(m);
long sum = 0;
for(long l : boxes) {
sum += l;
int pow = 0;
while(l>1) {
pow++;
l /= 2;
}
cnt[pow]++;
}
if(sum<n) {
out.println(-1);
return;
}
long ans = 0;
for (int bit = 0; bit < bitl; bit++) {
if(((1l<<bit)&n)!=0) {
if(cnt[bit]==0) {
int bigat = -1;
for(int i = bit+1; i < bitl; i++){
if(cnt[i]!=0) {
bigat = i;
break;
}
}
if(bigat==-1) throw new RuntimeException();
while(bigat>bit) {
cnt[bigat]--;
ans++;
cnt[bigat-1] += 2;
bigat--;
}
}
cnt[bit]--;
}
if(bit+1<bitl) {
int nowcnt = cnt[bit];
cnt[bit+1] += nowcnt/2;
}
}
out.println(ans);
}
}
static void sort(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sort(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sortDec(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static void sortDec(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
}
}
| java |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | import java.io.*;
import java.util.*;
public class KuroniGifts
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine().trim());
int t=Integer.parseInt(st.nextToken());
for(int e=1;e<=t;e++)
{
int n=Integer.parseInt(br.readLine());
int[] arr=new int[n];
int[] arr2=new int[n];
st=new StringTokenizer(br.readLine());
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(st.nextToken());
st=new StringTokenizer(br.readLine());
for(int i=0;i<n;i++)
arr2[i]=Integer.parseInt(st.nextToken());
Arrays.sort(arr);
Arrays.sort(arr2);
for(int i=0;i<n;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
for(int i=0;i<n;i++)
{
System.out.print(arr2[i]+" ");
}
System.out.println();
}
}
}
| java |
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"
] | import java.util.*;
import java.io.*;
public class Main {
static long mod = 1000000007;
static long max ;
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
/*
* check for increasing and decreasing
* if increasing add 2*n - 1 and if decreasing add 1
* update n on the way
* make two array one for the minimum and one for the maximum and if decreasing
*/
int n = sc.nextInt();
long ans = 0;
int temp = n;
ArrayList<Integer> min = new ArrayList<>();
ArrayList<Integer> max = new ArrayList<>();
for( int i = 0 ;i < n ;i++) {
boolean incr = false;
boolean dec = false;
int mi = Integer.MAX_VALUE;
int ma = Integer.MIN_VALUE;
int size = sc.nextInt();
int arr[] = new int[size];
arr[0] = sc.nextInt();
mi = Math.min(mi , arr[0]);
ma = Math.max(ma, arr[0]);
for( int j = 1 ;j < size ;j++) {
arr[j] = sc.nextInt();
mi = Math.min(mi , arr[j]);
ma = Math.max(ma, arr[j]);
int t = arr[j];
if( t > arr[j-1]) {
incr = true;
}
if( t < arr[j-1]) {
dec = true;
}
}
if( incr) {
ans+=2*temp - 1;
temp--;
}
else {
// if( dec) {
// ans++;
// }
min.add(mi);
max.add(ma);
}
}
int size = min.size();
if( size != 0) {
Collections.sort(max);
// out.println(min);
// out.println(max);
int ma = max.get(size - 1);
for( int i = 0 ;i < size ;i++) {
if( min.get(i) >= ma) {
continue;
}
else {
ans+=solve( max , min.get(i) , size );
}
}
}
out.println(ans);
out.flush();
}
private static long solve(ArrayList<Integer> max, int min, int size) {
int i = 0;
int j = size - 1;
int ans = Integer.MAX_VALUE;
int mid = (i+1)/2;
while( i <= j) {
if( max.get(mid) <= min){
i = mid+1;
}
else {
ans = Math.min(ans, mid);
j = mid - 1;
}
mid = (i+j)/2;
}
return size - ans;
}
public static boolean ifpowof2(long n ) {
return ((n&(n-1)) == 0);
}
public static int[] nextLargerElement(int[] arr, int n) {
Stack<Integer> stack = new Stack<>();
int rtrn[] = new int[n];
rtrn[n-1] = -1;
stack.push( n-1);
for( int i = n-2 ;i >= 0 ; i--){
int temp = arr[i];
int lol = -1;
while( !stack.isEmpty() && arr[stack.peek()] <= temp){
if(arr[stack.peek()] == temp ) {
lol = stack.peek();
}
stack.pop();
}
if( stack.isEmpty()){
if( lol != -1) {
rtrn[i] = lol;
}
else {
rtrn[i] = -1;
}
}
else{
rtrn[i] = stack.peek();
}
stack.push( i);
}
return rtrn;
}
@SuppressWarnings("unused")
private static void mysort(int[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
int loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
@SuppressWarnings("unused")
private static void mySort(long[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
long loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
static long rightmostsetbit(long n) {
return n&-n;
}
static long leftmostsetbit(long n)
{
long k = (long)(Math.log(n) / Math.log(2));
return 1 << k;
}
static HashMap<Long,Long> primefactor( long n){
HashMap<Long ,Long> hm = new HashMap<>();
long temp = 0;
while( n%2 == 0) {
temp++;
n/=2;
}
if( temp!= 0) {
hm.put( 2L, temp);
}
long c = (long)Math.sqrt(n);
for( long i = 3 ; i <= c ; i+=2) {
temp = 0;
while( n% i == 0) {
temp++;
n/=i;
}
if( temp!= 0) {
hm.put( i, temp);
}
}
if( n!= 1) {
hm.put( n , 1L);
}
return hm;
}
@SuppressWarnings("unused")
private static ArrayList<Integer> allfactors(int abs) {
HashMap<Integer,Integer> hm = new HashMap<>();
ArrayList<Integer> rtrn = new ArrayList<>();
for( int i = 2 ;i*i <= abs; i++) {
if( abs% i == 0) {
hm.put( i , 0);
hm.put(abs/i, 0);
}
}
for( int x : hm.keySet()) {
rtrn.add(x);
}
if( abs != 0) {
rtrn.add(abs);
}
return rtrn;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
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"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.min;
import static java.lang.Math.sqrt;
public class SolutionF extends Thread {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static final FastReader scanner = new FastReader();
private static final PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
solve();
out.close();
}
private static void solve() {
int n = scanner.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextLong();
}
long minOps = Long.MAX_VALUE;
for (int it = 0; it < 20; it++) {
int index = (int) (Math.random() * n);
long ai = a[index];
for (long x = Math.max(2, ai-1); x <= ai+1; x++) {
List<PowerPair> primeFactors = getPrimeFactorsOfNumber(x);
for (PowerPair p: primeFactors) {
long ops = 0;
for (int i = 0; i < n; i++) {
if (a[i] < p.base) {
ops += p.base - a[i];
} else {
ops += Math.min(a[i] % p.base, p.base - (a[i] % p.base));
}
}
minOps = Math.min(minOps, ops);
}
}
}
out.println(minOps);
}
static class PowerPair {
public long base;
int exp;
public PowerPair(long base, int exp) {
this.base = base;
this.exp = exp;
}
@Override
public String toString() {
return base + "^" + exp;
}
}
public static List<PowerPair> getPrimeFactorsOfNumber(long n) {
List<PowerPair> result = new ArrayList<>();
for (int i = 2; i <= sqrt(n); i++) {
PowerPair pair = new PowerPair(i, 0);
while (n % i == 0) {
pair.exp++;
n /= i;
}
if (pair.exp > 0) {
result.add(pair);
}
}
if (n != 1) {
result.add(new PowerPair(n, 1));
}
return result;
}
//REMINDERS:
//- CHECK FOR INTEGER-OVERFLOW BEFORE SUBMITTING
//- CAN U BRUTEFORCE OVER SOMETHING, TO MAKE IT EASIER TO CALCULATE THE SOLUTION
} | java |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | import java.io.*;
import java.util.*;
public class Matrix {
static boolean works;
static Pair[][] dest;
static boolean[][] visited;
static char[][] ans;
static int n, size;
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
n = in.nextInt();
works = true;
dest = new Pair[n][n];
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
dest[i][j] = new Pair(x, y);
}
}
visited = new boolean[n][n];
ans = new char[n][n];
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
if (dest[i][j].x==-2 && !visited[i][j]) {
size = 0;
floodfill1(i, j);
if (size==1) {
works = false;
// System.out.println("failed "+i+" "+j+" "+dest[i][j].x+" "+dest[i][j].y);
break;
}
}
if (dest[i][j].x==i && dest[i][j].y==j && !visited[i][j]) {
ans[i][j] = 'X';
floodfill2(i, j);
}
}
}
for (int i=0; i<n; i++) {
if (!works) break;
for (int j=0; j<n; j++) {
if (!visited[i][j]) {
// System.out.println(i+" "+j+" unvisited");
works = false;
break;
}
}
}
if (!works) in.pr.println("INVALID");
else {
in.pr.println("VALID");
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
in.pr.print(ans[i][j]);
}
in.pr.println();
}
}
in.pr.close();
}
public static void floodfill1(int x, int y) {
if (visited[x][y]) return;
visited[x][y] = true;
// System.out.println(x+" "+y);
size++;
if (x<n-1 && dest[x+1][y].x==-2) {
floodfill1(x+1, y);
if (ans[x][y]==0) ans[x][y] = 'D';
}
if (x>0 && dest[x-1][y].x==-2) {
floodfill1(x-1, y);
if (ans[x][y]==0) ans[x][y] = 'U';
}
if (y<n-1 && dest[x][y+1].x==-2) {
// System.out.println("going to "+ x+" "+(y+1));
floodfill1(x, y+1);
if (ans[x][y]==0) ans[x][y] = 'R';
}
if (y>0 && dest[x][y-1].x==-2) {
floodfill1(x, y-1);
if (ans[x][y]==0) ans[x][y] = 'L';
}
}
public static void floodfill2(int x, int y) {
if (visited[x][y]) return;
visited[x][y] = true;
// System.out.println(x+" "+y);
if (x<n-1 && dest[x+1][y].equals(dest[x][y])) {
if (ans[x+1][y]==0) ans[x+1][y] = 'U';
floodfill2(x+1, y);
}
if (x>0 && dest[x-1][y].equals(dest[x][y])) {
if (ans[x-1][y]==0) ans[x-1][y] = 'D';
floodfill2(x-1, y);
}
if (y<n-1 && dest[x][y+1].equals(dest[x][y])) {
if (ans[x][y+1]==0) ans[x][y+1] = 'L';
floodfill2(x, y+1);
}
if (y>0 && dest[x][y-1].equals(dest[x][y])) {
if (ans[x][y-1]==0) ans[x][y-1] = 'R';
floodfill2(x, y-1);
}
}
static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object other) {
Pair p = (Pair)other;
return x==p.x && y==p.y;
}
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
PrintWriter pr;
public FastIO() throws IOException
{
br = new BufferedReader(
new InputStreamReader(System.in));
pr = new PrintWriter(System.out);
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
return str;
}
}
}
| java |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
/*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
static class Pair{
int f,l;
public Pair(int first,int last)
{
this.f=first;
this.l=last;
}
}
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
int tes=sc.nextInt();
while(tes-->0)
{
int n=sc.nextInt();
String s=sc.next();
int i,x=0,y=0,step=0;
HashMap<String,Integer> map=new HashMap<>();
map.put(x+" "+y,step);
step++;
TreeMap<Integer,String> ans=new TreeMap<>();
for(i=0;i<n;i++)
{
if(s.charAt(i)=='U')
y++;
if(s.charAt(i)=='D')
y--;
if(s.charAt(i)=='L')
x++;
if(s.charAt(i)=='R')
x--;
String ns=x+" "+y;
if(map.containsKey(ns))
{
int dis=step+1-map.get(ns);
ans.put(dis,(map.get(ns)+1)+" "+step);
}
map.put(ns,step);
step++;
}
if(ans.size()==0)
{
System.out.println(-1);
continue;
}
for(Integer it:ans.keySet())
{
System.out.println(ans.get(it));
break;
}
}
}
public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)
return mid;
else if (x > arr.get(mid))
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid - 1), x, n);
}
return -1;
}
public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)
return mid;
else if (x < arr.get(mid))
return last(arr, low, (mid - 1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get((int)mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long mod=1000000007;
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while(t-->0){
int n = Integer.parseInt(br.readLine().trim());
String[] in = br.readLine().trim().split(" ");
if(n==1){
int num = Integer.parseInt(in[0]);
if((num & 1) != 0){
System.out.println(-1);
}else{
System.out.println(n+"\n"+1);
}
}else{
int num1 = Integer.parseInt(in[0]);
int num2 = Integer.parseInt(in[1]);
if((num1 & 1) == 0){
System.out.println(1);
System.out.println(1);
}else if((num2 & 1) == 0){
System.out.println(1);
System.out.println(2);
}else{
System.out.println(2);
System.out.println(1+" "+2);
}
}
}
}
} | java |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | import java.util.*;
import java.io.*;
public class Main {
static long mod = 1000000007;
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
int t = sc.nextInt();
while( t-- > 0) {
int n =sc.nextInt();
boolean check = false;
double x= sc.nextDouble();
boolean equal = false;
double max = Double.MIN_VALUE;
for( int i = 0 ;i < n; i++) {
double temp =sc.nextDouble();
if( temp >= x/2 ) {
check = true;
}
if( temp == x) {
equal = true;
}
max = Math.max(max, temp);
}
if( equal) {
out.println(1);
}
else if( check) {
out.println(2);
}
else {
double temp = (x-2*max)/max;
//out.println(temp);
long ans = find( temp);
out.println(ans+2);
}
}
out.flush();
}
private static long find(double temp) {
if( (long) temp == temp) {
return (long)temp;
}
else {
return (long)temp + 1;
}
}
public static int[] nextLargerElement(int[] arr, int n) {
Stack<Integer> stack = new Stack<>();
int rtrn[] = new int[n];
rtrn[n-1] = -1;
stack.push( n-1);
for( int i = n-2 ;i >= 0 ; i--){
int temp = arr[i];
int lol = -1;
while( !stack.isEmpty() && arr[stack.peek()] <= temp){
if(arr[stack.peek()] == temp ) {
lol = stack.peek();
}
stack.pop();
}
if( stack.isEmpty()){
if( lol != -1) {
rtrn[i] = lol;
}
else {
rtrn[i] = -1;
}
}
else{
rtrn[i] = stack.peek();
}
stack.push( i);
}
return rtrn;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static HashMap<Long,Long> primefactor( long n){
HashMap<Long ,Long> hm = new HashMap<>();
long temp = 0;
while( n%2 == 0) {
temp++;
n/=2;
}
if( temp!= 0) {
hm.put( 2L, temp);
}
long c = (long)Math.sqrt(n);
for( long i = 3 ; i <= c ; i+=2) {
temp = 0;
while( n% i == 0) {
temp++;
n/=i;
}
if( temp!= 0) {
hm.put( i, temp);
}
}
if( n!= 1) {
hm.put( n , 1L);
}
return hm;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | java |
1304 | F2 | F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp",
"greedy"
] | //package round620;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.InputMismatchException;
public class F2 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), K = ni();
int[][] a = new int[n][];
for(int i = 0;i < n;i++){
a[i] = na(m);
}
long[][] cum = new long[n][m+1];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
cum[i][j+1] = cum[i][j] + a[i][j];
}
}
long[][] rcum = new long[n][m+1];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
rcum[i][j+1] = rcum[i][j] + a[i][m-1-j];
}
}
long[] dp = new long[m-K+1];
for(int i = 0;i < m-K+1;i++){
dp[i] = cum[0][i+K] - cum[0][i];
}
for(int i = 1;i < n;i++){
dp = trans(dp, cum[i], rcum[i] ,K);
}
long ans = 0;
for(long v : dp){
ans = Math.max(ans, v);
}
out.println(ans);
}
long[] trans(long[] dp, long[] cum, long[] rcum, int K)
{
int n = cum.length-1;
for(int i = 0;i < n-K+1;i++){
dp[i] += cum[i+K] - cum[i];
}
// tr(dp, cum, rcum);
long[] ndp = new long[n-K+1];
Arrays.fill(ndp, Long.MIN_VALUE / 2);
// 2321
// 000346
go(ndp, dp, cum, K);
rev_(ndp);
rev_(dp);
go(ndp, dp, rcum, K);
rev_(ndp);
// tr(ndp);
return ndp;
}
public static long[] rev_(long[] a)
{
for(int i = 0, j = a.length-1;i < j;i++,j--){
long c = a[i]; a[i] = a[j]; a[j] = c;
}
return a;
}
void go(long[] ndp, long[] dp, long[] cum, int K)
{
int n = cum.length-1;
long flatmax = Long.MIN_VALUE / 2;
Deque<long[]> nonflat = new ArrayDeque<>();
for(int i = 0;i < n-K+1;i++){
while(!nonflat.isEmpty() && nonflat.peekLast()[1] < dp[i]-cum[i+K]){
nonflat.pollLast();
}
nonflat.add(new long[]{i, dp[i]-cum[i+K]});
while(!nonflat.isEmpty() && nonflat.peekFirst()[0] < i-K){
nonflat.pollFirst();
}
if(i-K >= 0){
flatmax = Math.max(flatmax, dp[i-K]);
}
// tr(flatmax, nonflat.peekFirst());
ndp[i] = Math.max(ndp[i], flatmax + cum[i+K] - cum[i]);
if(!nonflat.isEmpty()){
ndp[i] = Math.max(ndp[i], nonflat.peekFirst()[1] + cum[i] + cum[i+K] - cum[i]);
}
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F2().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| java |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
r.init(System.in);
int n = r.nextInt();
double res = 1;
double i = n;
while (i != 1){
res += 1 / i;
i--;
}
System.out.println(res);
}
}
class r {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer
= new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
| java |
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"
] | import static java.lang.Math.*;
import java.awt.Point;
import java.io.*;
import java.util.*;
public class Exercise {
static StringTokenizer st;
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static int N;
public static int[] size;
public static void readLine() {
try {
st = new StringTokenizer(in.readLine());
} catch(Exception e) {}
}
public static int nextInt() {
return Integer.parseInt(st.nextToken());
}
public static void init() {
size = new int[N + 1];
}
public static void main(String args[]) {
readLine(); N = nextInt(); init();
List<Point> vertex = new ArrayList<>();
for(int i = 1; i < N; i++) {
readLine();
int v = nextInt(); int u = nextInt();
size[v]++; size[u]++;
vertex.add(new Point(v, u));
}
int start = 0; int end = N - 2;
for(int i = 0; i < vertex.size(); i++) {
Point p = vertex.get(i);
if(size[p.x] == 1 || size[p.y] == 1) System.out.println(start++);
else System.out.println(end--);
}
}
}
| java |
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"
] | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
var scan = new Scanner(System.in);
int n = scan.nextInt();
var Robo = new byte[n];
var Bionic = new byte [n];
var index = new byte[n];
for (int i = 0;i < n;i++) Robo[i] = scan.nextByte();
for (int i = 0;i < n;i++) Bionic[i] = scan.nextByte();
int p = 1;
while(true){
Index(p, n , Robo, index);
if(Arrays.toString(Robo).equals(Arrays.toString(Bionic)) || p == 200 ) {
System.out.println(-1);
return;
}
else if(Sum(p,n,Robo,index) <= Sum(p,n,Bionic,index)){
p++;
continue;
}
break;
}
System.out.println(p);
}
public static int Sum(int p,int n,byte[] arr,byte [] index){
int sum = 0;
for (int i = 0;i < n;i++) sum += (index[i] * arr[i]);
return sum;
}
public static void Index(int p,int n , byte [] arr, byte [] index){
for (int i = 0;i < n;i++){
if (arr[i] == 0) index[i] = 1;
else index[i] = (byte)p;
}
}
} | java |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5. | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] |
import java.util.*;
import javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static void rvrs(int[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void rvrs(long[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long mod_mul( long mod , long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum(long mod , long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2, m);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y, long m){
if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
public Combinations(long N , long mod) {
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R, long mod)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.max(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.max(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
// tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
}
static void TEST_CASE() {
int n = sc.nextInt();
// int[] arr = new int[n];
ArrayList<Integer> al = new ArrayList<>();
for(int i =0 ; i<n ; i++) {
// arr[i] = sc.nextInt();
al.add(sc.nextInt());
}
System.out.println(bit(al, 30));
}
static int bit(ArrayList<Integer> al , int bit) {
if(bit == -1) return 0;
ArrayList<Integer> one = new ArrayList<>();
ArrayList<Integer> zero = new ArrayList<>();
for(int e:al) {
int on = 1<<bit;
if( (on&e)!=0) one.add(e);
else zero.add(e);
}
if(one.size() == 0) return bit(zero , bit-1);
if(zero.size() == 0) return bit(one , bit-1);
return min(bit(one ,bit -1) , bit(zero , bit-1)) + (1<<bit);
}
}
/*******************************************************************************************************************************************************/
/**
4 2 1
0 1 0
0 1 1
0 0 1
1 0 0 1 0 1 1
0 1 0 1 1 0 1
1 0 0 1 1 0 0
1 0 1 0 0 1 0
1 0 1 1 1 0 0
*/
| java |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102. | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | import java.io.*;
import java.util.*;
public class Main{
static int solveLower(int i,int[]in,int left,int right) {
int lo=0,hi=i-1;
int ans=-1;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int sum=in[i]+in[mid];
if(sum<left) {
lo=mid+1;
}
else {
if(sum>right)
hi=mid-1;
else{
ans=mid;
hi=mid-1;
}
}
}
return ans;
}
static int solveUpper(int i,int[]in,int left,int right) {
int lo=0,hi=i-1;
int ans=-1;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int sum=in[i]+in[mid];
if(sum<left) {
lo=mid+1;
}
else {
if(sum>right)
hi=mid-1;
else{
ans=mid;
lo=mid+1;
}
}
}
return ans;
}
public static void main(String[] args) throws Exception{
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int[]in=sc.takearr(n);
int ans=0;
for(int b=0;b<26;b++) {
int tmp[]=new int[n];
for(int i=0;i<n;i++) {
tmp[i]=in[i]%(1<<(b+1));
}
Arrays.sort(tmp);
int left=1<<b,right=(1<<(b+1))-1;
long cnt=0;
for(int i=1;i<n;i++) {
int lower=solveLower(i, tmp, left, right);
if(lower==-1)continue;
int upper=solveUpper(i, tmp, left, right);
cnt+=upper-lower+1;
}
left=(1<<b)+(1<<(b+1));right=(1<<(b+2))-2;
for(int i=1;i<n;i++) {
int lower=solveLower(i, tmp, left, right);
if(lower==-1)continue;
int upper=solveUpper(i, tmp, left, right);
cnt+=upper-lower+1;
}
if(cnt%2==1) {
ans+=1<<b;
}
}
pw.println(ans);
pw.flush();
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] takearr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] takearrl(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public Integer[] takearrobj(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] takearrlobj(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | java |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
public class Round12 {
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
while (t-- > 0) {
int n = fastReader.nextInt();
int pow1 = fastReader.nextInt();
int pow2 = fastReader.nextInt();
int k = fastReader.nextInt();
int a[] = fastReader.ria(n);
long ans = 0;
ArrayList<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int low = 1, high = a[i];
int req = 1;
while (low <= high) {
int mid = (low + high) / 2;
if (isPossible(mid, pow1, pow2, a[i])) {
req = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
if (req % 2 == 0) {
long add = rep(pow1, pow2, req, a[i]);
list.add(add);
} else {
ans++;
}
}
Collections.sort(list);
for (int i = 0 ; i < list.size() ; i++){
if (list.get(i) <= k){
ans++;
k-=list.get(i);
}
}
out.println(ans);
}
out.close();
}
private static long rep(int pow1, int pow2, int req, int i) {
long t = ((req + 1) / 2);
long tot = t * pow1;
long tot2 = pow2 * ((req - t) - 1);
long total = (long) tot + tot2;
// System.out.println(total);
long diff = i - total;
long ans = diff / pow1;
if (diff % pow1 != 0) ans++;
return ans;
}
private static boolean isPossible(int mid, long pow1, long pow2, int i) {
long tot1 = ((mid + 1) / 2) * pow1;
long tot2 = ((mid) / 2) * pow2;
return tot1 + tot2 >= i;
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 92233720368547L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0) return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0) return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0) return new int[]{1, 0};
int[] y = exgcd(b, a % b);
return new int[]{y[1], y[0] - y[1] * (a / b)};
}
static long[] exgcd(long a, long b) {
if (b == 0) return new long[]{1, 0};
long[] y = exgcd(b, a % b);
return new long[]{y[1], y[0] - y[1] * (a / b)};
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i]) continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j) nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.