input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Takahashi and Aoki will take N exams numbered 1 to N. They have decided to compete in these exams. The winner will be determined as follows:
* For each exam i, Takahashi decides its importance c_i, which must be an integer between l_i and u_i (inclusive).
* Let A be \sum_{i=1}^{N} c_i \times (Takahashi's score on Exa... | import sys,heapq,time
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
DBG = True and False
def ddprint(x):
if DBG:
print(x)
n,x = inm()
blu = []
pt = 0
for ... |
The server in company A has a structure where N devices numbered 1, 2, ..., N are connected with N - 1 cables. The i-th cable connects Device U_i and Device V_i. Any two different devices are connected through some number of cables.
Each device v (1 \leq v \leq N) has a non-zero integer A_v, which represents the follo... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1e16;
const int MAXN = 5050;
using Arr = array<ll, 2>;
int N;
int A[MAXN];
vector<int> adj[MAXN];
vector<Arr> dfs(int v, int p) {
vector<Arr> dp(1);
dp[0][0] = A[v];
if (A[v] > 0) dp[0][1] = A[v];
else dp[0][1] = INF;
... |
You are given two integers a and b. Determine if a+b=15 or a\times b=15 or neither holds.
Note that a+b=15 and a\times b=15 do not hold at the same time.
Constraints
* 1 \leq a,b \leq 15
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
a b
Output
If a+b=15,... |
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
int a=gi();
int b=gi();
//System.out.print();
if (a+b==15) {
System.out.print("+");
}else if(a*b==15) {
... |
There are N white balls arranged in a row, numbered 1,2,..,N from left to right. AtCoDeer the deer is thinking of painting some of these balls red and blue, while leaving some of them white.
You are given a string s of length K. AtCoDeer performs the following operation for each i from 1 through K in order:
* The i-t... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
#define fi first
#define se second
#define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define rep(i,n) repl(i,0,n)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#defi... |
You have two strings A = A_1 A_2 ... A_n and B = B_1 B_2 ... B_n of the same length consisting of 0 and 1. The number of 1's in A and B is equal.
You've decided to transform A using the following algorithm:
* Let a_1, a_2, ..., a_k be the indices of 1's in A.
* Let b_1, b_2, ..., b_k be the indices of 1's in B.
* Rep... | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define REP(i,a,b) for(int i=(a),_end_=(b);i<=_end_;i++)
#define DREP(i,a,b) for(int i=(a),_end_=(b);i>=_end_;i--)
#define EREP(i,u) for(int i=start[u];i;i=e[i].next)
#define fi first
#define se second
#define mkr(a,b) make_pair(a,b)
#define SZ(A) ((int)... |
AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i. Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater.
Then, for each card i, he judges whether it is unnecessary... | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a.at(i);
sort(a.begin(), a.end());
int l = -1, r = n;
while (r - l > 1) {
int mid = (l + r) / 2;
vector... |
There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.
Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) po... | #include<cstdio>
#include<algorithm>
#define ls p<<1,l,m
#define rs p<<1|1,m+1,r
using namespace std;
const int N=3e5+5,P=4*N;
int nn,mm,n,i,x,y,k;
struct arr{int x,y;}a[N];
bool operator < (arr A,arr B){return A.x<B.x;}
int read(){
char c=getchar();int k=0;for (;c<48||c>57;c=getchar());
for (;c>47&&c<58;c=getchar())... |
One of the simple ciphers is the affine cipher. First, replace the letters a to z with the numbers a = 0, b = 1, c = 2, ..., x = 23, y = 24, z = 25 and 0 to 25. Then replace the original alphabet with the following formula.
$ F (\ gamma) = (\ alpha \ cdot \ gamma + \ beta) $ mod $ 26 $
However, mod 26 represents the ... | z='abcdefghijklmnopqrstuvwxyz'
for _ in[0]*int(input()):
e=input()
for i in range(1,26,2):
for j in range(26):
a=''
for c in e:
if c in z:a+=z[(z.index(c)*i+j)%26]
else:a+=c
if'that'in a or'this'in a:print(a);break
|
Dr. Tsuruga of the University of Aizu is famous for his enthusiastic research. There are several students in his lab, but he works late into the night every day, so he always comes home last. His lab has multiple rooms connected by doors, and the last person to leave the lab is supposed to turn off the lights in all th... | #include<iostream>
#include<map>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
typedef pair<int,int> P;
int dp[15][1<<15];
P prv[15][1<<15];
bool g[15][15];
int n,m,s,t,k[15],l;
vector<int> r[15];
int INF = (1<<10);
string itos(int a){
if(!a)return "0";
string res;
while(a){
res... |
University A will hold a programming contest this year as well. As a member of the writing team, you will be responsible for creating the input data for computational geometry problems. The input data you want to create is a set of line segments that are parallel to the x-axis or y-axis and do not touch each other. You... | #include <bits/stdc++.h>
using namespace std;
struct SegmentTree
{
vector< set< int > > seg, lazy;
int sz;
SegmentTree(int n)
{
sz = 1;
while(sz < n) sz <<= 1;
seg.resize(2 * sz - 1);
lazy.resize(2 * sz - 1);
}
bool query(int a, int b, int low, int high, int k, int l, int r)
{
if(a... |
problem
JOI decided to make a signboard for the store.
There are N old signboards with letters written at equal intervals. JOI makes a sign by erasing some letters from the old sign. I want the remaining characters to be the name of the store, and the remaining characters to be evenly spaced. Signs must be made from ... | import java.util.Scanner;
public class Main {
char[] target;
int cnt=0;
void check(char[] o){
int space, work;
boolean flag;
for(int j=0; j<o.length; j++){
flag=true;
if(target[0]==o[j]){//??????????????????????????£??????
for(int k=j+1; k<o.length; k++){
if(target[1]==o[k]){//?????... |
You have to organize a wedding party. The program of the party will include a concentration game played by the bride and groom. The arrangement of the concentration game should be easy since this game will be played to make the party fun.
We have a 4x4 board and 8 pairs of cards (denoted by `A' to `H') for the concent... | #include <iostream>
using namespace std;
// 入力
int dx[4], dy[4];
// used[y][x] := (y,x) にカードをおいたかどうか
bool used[4][4];
int solve(int n){
if(n == 0) return 1;
int res = 0;
// 1 枚目のカードを置く
int x1, y1;
for( y1 = 0 ; y1 < 4 ; y1++ ){
for( x1 = 0 ; x1 < 4 ; x1++ ){
if( !used[y1][x1] ) break;
}
if( x1 != 4 ... |
Ms. Iyo Kiffa-Australis has a balance and only two kinds of weights to measure a dose of medicine.
For example, to measure 200mg of aspirin using 300mg weights and 700mg weights, she can put one 700mg weight on the side of the medicine and three 300mg weights on the opposite side (Figure 1). Although she could put fou... | #include <cstdio>
#include <cmath>
int abs(int x){
if(x<0)return -x;
return x;
}
#define INF 5e4
int extgcd(int a,int b,int &x,int &y){
int d=a;
if(b!=0){
d=extgcd(b,a%b,y,x);
y-=(a/b)*x;
}else{
x=1;
y=0;
}
return d;
}
int a,b,d;
int main(void){
while(1){
scanf("%d %d %d",&a,&b,&d);
if(a+b+d==0)... |
Problem B Parallel Lines
Given an even number of distinct planar points, consider coupling all of the points into pairs. All the possible couplings are to be considered as long as all the given points are coupled to one and only one other point.
When lines are drawn connecting the two points of all the coupled point ... | #include<bits/stdc++.h>
using namespace std;
int vis[200],m,ans=0;
double k[30000];
struct sc
{
int x,y;
} s[200];
bool flag=true;
void update(int cnt)
{
int sum=0;
for(int i=0; i<cnt; i++)
for(int j=i+1; j<cnt; j++)
if(k[j]==k[i])sum++;
ans=max(sum,ans);
flag=false;
}
void dfs(i... |
Complex Paper Folding
Dr. G, an authority in paper folding and one of the directors of Intercultural Consortium on Paper Crafts, believes complexity gives figures beauty. As one of his assistants, your job is to find the way to fold a paper to obtain the most complex figure. Dr. G defines the complexity of a figure by... | #include<bits/stdc++.h>
#define f first
#define s second
#define mp make_pair
#define pi M_PI
#define inf 1<<30
#define eps (1e-6)
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
Point operator+(Point p){ return Point(x+p.x,y... |
This is a story in a depopulated area. In this area, houses are sparsely built along a straight road called Country Road. Until now, there was no electricity in this area, but this time the government will give us some generators. You can install the generators wherever you like, but in order for electricity to be supp... | #include <algorithm>
#include <cstdio>
#include <iostream>
using namespace std;
const long N=100000;
int main(){
int t;
scanf(" %d", &t);
for(int times=0; times<t; ++times){
long n, k, x[N];
scanf(" %ld %ld", &n, &k);
for(long i=0; i<n; ++i) scanf(" %ld", &x[i]);
long bet[N];
//bet[i]=distance betw... |
The cave, called "Mass of Darkness", had been a agitating point of the evil, but the devil king and all of his soldiers were destroyed by the hero and the peace is there now.
One day, however, the hero was worrying about the rebirth of the devil king, so he decided to ask security agency to patrol inside the cave.
Th... | #include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define chmax(a,b) (a = max(a,b))
using namespace std;
typedef vector<int> vi;
const string dir = "URDL";
const int dy[] = {-1,0,1,0}, dx[] = {0,1,0,-1};
int main(){
cin.tie(0); ios::sync_with_stdio(0);
int Hini, Hmax;
while(cin >> Hini >> Hma... |
Taro is an elementary school student and has graffiti on the back of the leaflet. At one point, Taro came up with the next game.
* Write n × n grid-like squares.
* The initial state of each square is either marked or unmarked.
* Erase or write these circles so that there is always exactly one circle no matter which co... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
#define REP(i, n) for (ll (i) = 0 ; (i) < (ll)(n) ; ++(i))
#define REPN(i, m, n) for (int (i) = m ; (i) < (int)(n) ; ++(i))
#define REP_REV(i, n) for (int (i) = (int)(n) - 1 ; (i) >= 0 ; --(i... |
Elevator hall number
JAG (Japanese Alumni Group) is a mysterious organization headquartered in a skyscraper somewhere in Tokyo. There are $ N $ elevators in operation in this building, and the $ i $ elevators stop on each floor from the $ low_i $ floor to the $ high_i $ floor ($ 1 \ le i \ le N $).
Mr. X, a new staff... | #include <bits/stdc++.h>
using namespace std;
#define DEBUG(x) cerr<<#x<<": "<<x<<endl;
#define DEBUG_VEC(v) cerr<<#v<<":";for(int i=0;i<v.size();i++) cerr<<" "<<v[i]; cerr<<endl;
#define DEBUG_MAT(v) cerr<<#v<<endl;for(int i=0;i<v.size();i++){for(int j=0;j<v[i].size();j++) {cerr<<v[i][j]<<" ";}cerr<<endl;}
typedef... |
E-Election campaign
Problem Statement
You are a supporter of Mr. X, a candidate for the next election. Mr. X is planning a street speech in front of the station and intends to give a speech in a place that can be seen by as many voters as possible.
The front of the station is given as a two-dimensional plane with $ ... | #include<bits/stdc++.h>
using namespace std;
const double EPS = 1e-8, PI = acos(-1);
inline bool eq(double a, double b)
{
return abs(b - a) < EPS;
}
#define curr(P, i) P[i]
#define next(P, i) P[(i+1)%P.size()]
#define prev(P, i) P[(i+P.size()-1) % P.size()]
enum { OUT, ON, IN };
namespace Geometory
{
struct... |
problem
AOR Ika-chan, who loves feasts, defined "the number of feasts". A feast number is a natural number that includes "$ 51-3 $" in $ 10 $ decimal notation.
$? $ Can be any number from $ 0 $ to $ 9 $.
Find the number of feasts out of the natural numbers below $ N $.
input
$ N $
output
Output the number of fe... | #include <bits/stdc++.h>
using namespace std;
#define rep(i, m, n) for (int i = m; i < n; ++i)
typedef long long ll;
ll dp[20][2][1000][2];
int main() {
string S;
cin >> S;
int N = S.size();
dp[0][0][0][0] = 1;
rep(i, 0, N) rep(j, 0, 2) rep(k, 0, 1000) rep(l, 0, 2) {
int x = j ? 9 : S[i] - '0';
rep(d... |
Problem
Let $ f (x) $ be the sum of each digit when the non-negative integer $ x $ is expressed in binary.
Given a positive integer $ N $, output the largest of $ f (0) $, $ f (1) $, ..., $ f (N) $.
Example of calculating the function $ f (5) $:
When 5 is expressed in binary, it is 101 and the sum of each digit is 1... | #include <bits/stdc++.h>
using namespace std;
int main(){
long long n,mon=1,ans=0;
cin>>n;
while(1){
if(n>=mon*2-1){++ans;}
else{break;}
mon*=2;
}
cout<<ans<<endl;
}
|
Your task is to implement a double linked list.
Write a program which performs the following operations:
* insert x: insert an element with key x into the front of the list.
* delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.
* deleteFirst... | #include <bits/stdc++.h>
using namespace std;
int main(){
int n, c; cin >> n;
string s;
list<int> l;
for(int i=0; i<n; i++){
cin >> s;
if(s =="insert"){
cin >> c;
l.push_front(c);
}else if(s=="delete"){
cin >> c;
for (list<int>::it... |
Your task is to perform a simple table calculation.
Write a program which reads the number of rows r, columns c and a table of r × c elements, and prints a new table, which includes the total sum for each row and column.
Constraints
* 1 ≤ r, c ≤ 100
* 0 ≤ an element of the table ≤ 100
Input
In the first line, two ... | r,c = map(int,input().split())
a =[]
for i in range(r) :
a.append(list(map(int,input().split())))
a[i].append(sum(a[i]))
b = list(map(sum,zip(*a)))
for i in range(r) :
print(*a[i])
print(*b)
|
WonderKing himself is a very genius in mathematics. One day when he was thinking, king got a wonderful idea – circular prime. A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will be a prime. Simply if all the rotatio... | arr = [2,3,5,7,11,13,17,31,37,71,73,79,97,113,131,197,199,311,337,373,719,733,919,971,991,1193,1931,3119,3779,7793,7937,9311,9377,11939,19391,19937,37199,39119,71993,91193,93719,93911,99371,193939,199933,319993,331999,391939,393919,919393,933199,939193,939391,993319,999331]
n=input()
for i in range(n):
a=input()
if a... |
It's finally summer in Chefland! So our chef is looking forward to prepare some of the best "beat-the-heat" dishes to attract more customers. He summons the Wizard of Dessert to help him with one such dish.
The wizard provides the chef with a sequence of N ingredients where the i^th ingredient has a delish value of D[... | # Property 1:
#j and k cannot have gap
#because if have gap > 0, one side will eat it up
# hence for each middle position j or k
# calculate the min/max values for each section, one to the left
# and one to the right of j/k
# then calculate the largest absolute difference between each
# pair of left/right sections
i... |
You are given a sequence of N integers, a[1], a[2], , , , a[N].
Find out the maximum possible average value of sub-sequences of array a.
Input
First line of the input contains a single integer T denoting number of test cases
For each test case, first line contains a single integer denoting N, the number of eleme... | t=int(input())
for i in range(t):
n=int(input())
ar=map(int,raw_input().split())
print max(ar) |
For Turbo C++ Users : Read the following document before attempting the question :
Problem Description
First question is easy to set you up with the online judge. You are given a number 'N'. You need to find the sum of first N terms of the series: 1 - 2 + 3 - 4 + 5 - 6 ...
Input
First line contains T, the number ... | for i in range(input()):
n=input()
r=n%2
if r==0:
print (-1)*n/2
else:
print (-1)*(n-1)/2+n |
In every contest there should be an easy problem about matrices. December Cook-Off is not an exception.
Given a matrix A which consists of n rows and m columns, and contains integer numbers.
Consider every possible vector v of m elements, such that every 1 ≤ vi ≤ n.
Let value of the vector be product of all Avi, i (1 ... | z=map(int,raw_input().split())
n=z[0]
m=z[1]
a=[0]*m
for i in range(n):
x=map(int,raw_input().split())
for j in range(m):
a[j]=a[j]+x[j]
ans=1
for i in range(m):
ans=ans*a[i]
print ans%(10**7+7) |
Some of the secret doors contain a very interesting word puzzle. The team of
archaeologists has to solve it to open that doors. Because there is no
other way to open the doors, the puzzle is very important for us.
There is a large number of magnetic plates on every door. Every plate has one
word written on it. The p... | """
Solution to the 'Play on Words' puzzle.
The idea is to view the problem as determining the existence
of an Eulerian path in a graph: each word is taken to be
a directed edge, from the node corresponding to the first
character in the word to the node corresponding to the last
character. The words can be arranged in... |
Sergey just turned five years old! When he was one year old, his parents gave him a number; when he was two years old, his parents gave him an array of integers. On his third birthday he received a string. When he was four, his mother woke him up in a quiet voice, wished him to be a good boy and gave him a rooted tree.... | #include <bits/stdc++.h>
using namespace std;
bool bit(int n, int i) { return (n >> i) & 1; }
int ceil(int a, int b) { return ceil(((long double)a) / b); }
int faltu;
const int mod = 1e9 + 7;
const long long inf = 4e18;
const long long ninf = -inf;
const int imax = 2e9 + 100;
const int maxn = 1e6 + 100;
int n, m;
vecto... |
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Ever... | n,m=[int(x) for x in input().split()]
v=[]
h=[]
for i in range(n):
x=int(input())
v.append(x)
for i in range(m):
x,y,z=[int(x) for x in input().split()]
if x==1:
h.append(y)
h.sort()
v.sort()
m=len(h)
n=len(v)
if n==0 or v[n-1]!=1000000000:
v.append(1000000000)
n+=1
mina=9999999999999
j=... |
Maksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move:
* (1, 0);
* (0, 1);
* (-1, 0);
* (0, -... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 2 * 1e5 + 5;
const long long INF = 1e15;
struct pt {
long long x, y;
};
bool operator<(const pt& A, const pt& B) {
if (A.x == B.x) return A.y > B.y;
return A.x < B.x;
}
long long N;
long long DP[MAXN][2];
vector<long long> LEVEL;
map<long long, set<pt... |
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them qu... | #include <bits/stdc++.h>
using namespace std;
int n;
set<long long> s;
string vs[3300];
int vn = 0;
char sp[3300];
int sn;
int su[3300], ml[3300][3300], ty[3300][3300];
pair<int, int> hz[3300];
bool gg[3300];
bool ad[3300][3300], ag[3300][3300];
bool go[3300][3300];
long long hsh(const string& w) {
long long t = 3;
... |
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan... | #include <bits/stdc++.h>
using namespace std;
int st[200010];
int main() {
int i, j, c = 0, t, n;
char s[200010];
cin >> n;
scanf("%s", s);
for (i = 0; i < n - 1; i++) {
if (s[i] == s[i + 1] && st[i] == 0) {
st[i + 1] = 1, c++;
}
}
cout << c << endl;
for (i = 0; i < n; i++) {
if (i == ... |
Lena is playing with matches. The natural question arising in the head of any child playing with matches is whether it's possible to set a tree on fire with a matches, or not.
Let's say, that the tree is a connected graph without cycles and the vertices are labeled with integers 1, 2, …, n. Also every vertex v has som... | #include <bits/stdc++.h>
using namespace std;
inline void read(int &tar) {
tar = 0;
char ch = getchar();
while ((ch < '0' || ch > '9') && (ch < 'a' || ch > 'z')) ch = getchar();
while (ch >= 'a' && ch <= 'z') {
if (ch == 'u') tar = 1;
if (ch == 'w') tar = 2;
if (ch == 'c') tar = 3;
ch = getchar(... |
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) — "ab" and (2, 3) — "ba". Letters 'a' and 'z' aren't considered neighbou... | T = int(input())
for _ in range(T):
s = input()
d = {}
for i in s:
d[i] = d.get(i, 0) + 1
k = sorted(list(d.keys()))
n = len(k)
if n == 2:
if abs(ord(k[0]) - ord(k[1])) == 1:
ans = "No answer"
else:
ans = s
elif n == 3:
if abs(ord(k[0])... |
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?
The book contains a single string of characters "a", "... | s=input()
n=len(s)
b=[]
for j in s:
b.append(j)
x=[]
y=[]
j=0
i=n-1
while(j<i):
if b[j]==b[i]:
if i!=j:
x.append(b[j])
y.append(b[i])
else:
x.append(b[j])
i+=-1
j+=1
elif b[j]==b[i-1]:
if (i-1) != j:
x.append(b[j])
... |
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be ... | import java.util.*;
import java.io.*;
public class Solution{
static class pair /*implements Comparable<pair>*/{
long a,b;
pair(long x,long y){
a=x;b=y;
}
// public long compareTo(pair t){
// if(t.a==this.a)
// return this.b-t.b;
// return ... |
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the followi... | import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
from copy import deepcopy
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline()... |
Consider a tunnel on a one-way road. During a particular day, n cars numbered from 1 to n entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.
A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel ex... | /***
* ██████╗=====███████╗====███████╗====██████╗=
* ██╔══██╗====██╔════╝====██╔════╝====██╔══██╗
* ██║==██║====█████╗======█████╗======██████╔╝
* ██║==██║====██╔══╝======██╔══╝======██╔═══╝=
* ██████╔╝====███████╗====███████╗====██║=====
* ╚═════╝=====╚══════╝====╚══════╝====╚═╝=====
* ===... |
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume.
There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea... | // package com.company;
import java.util.*;
import java.lang.*;
import java.io.*;
//****Use Integer Wrapper Class for Arrays.sort()****
public class AZ1 {
public static void main(String[] Args){
FastReader scan=new FastReader();
int t=scan.nextInt();
while(t-->0){
long a=scan.nex... |
Consider the following experiment. You have a deck of m cards, and exactly one card is a joker. n times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck.
Let x be the number of times you have taken the joker out of the deck during this experiment. Assuming ... | #include <bits/stdc++.h>
using namespace std;
inline void read(long long &x, long long f = 1) {
x = 0;
char ch = getchar();
while (!isdigit(ch)) f = ch == '-' ? -1 : 1, ch = getchar();
while (isdigit(ch)) x = (x << 3) + (x << 1) + ch - '0', ch = getchar();
x *= f;
}
long long n, m, k, ans;
long long s2[5050][... |
There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right.
You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1},... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T, class U>
using Pa = pair<T, U>;
template <class T>
using vec = vector<T>;
template <class T>
using vvec = vector<vec<T>>;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N;
cin >> N;
vec<ll> A(N);
for (int i = 0... |
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task — she asked every student... | #include <bits/stdc++.h>
using namespace std;
const int N = 500005, mod = 1000000007;
long long int a, b, c, d, e, f, g, h[N], arr[N];
string s;
vector<long long int> v;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> a >> s;
long long int say = 0, ans = 0;
for (long lon... |
Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it?
A string s is given. It consists of k kind... | #include <bits/stdc++.h>
using namespace std;
const pair<int, int> MOD = make_pair(1e9 + 7, 1e9 + 9);
const int base = 1e6 + 3;
const int N = 1e5 + 100, B = 600;
pair<int, int> operator+(pair<int, int> a, pair<int, int> b) {
a.first += b.first;
if (a.first >= MOD.first) a.first -= MOD.first;
a.second += b.second;... |
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace — do it yourself!". It contains many necklace parts and some magic glue.
The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magi... | #include <bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
using namespace std;
int n, m;
pair<int, int> a[3000005];
int deg[3000005];
set<int> e[3000005];
vector<int> res;
void eu(int cn) {
while (!e[cn].empty()) {
int nn = *e[cn].begin();
e[nn... |
Koa the Koala and her best friend want to play a game.
The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts.
Let's describe a move in the game:
* During his move, a player chooses any element of... | import java.util.*;
import java.io.*;
public class A {
public static void main(String[] args) throws Exception {
// int t = i();
// for (int tt = 0; tt < t; tt++) {
// int n = i();
// int[] f = new int[26];
// for (int i = 0; i < n; i++) {
// String s = s();
// for (int j = 0; j < s.length(); j++... |
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov... |
import java.util.*;
import java.io.*;
/**
* Made by egor https://github.com/chermehdi/egor.
*
* @author Azuz
*
*/
public class Main {
private Scanner in;
private PrintWriter out;
int d = -1;
int dv = -1;
int dab = -1;
public Main(Scanner in, PrintWriter out) {
this.in = in;
... |
Chaneka has a hobby of playing with animal toys. Every toy has a different fun value, a real number. Chaneka has four boxes to store the toys with specification:
* The first box stores toys with fun values in range of (-∞,-1].
* The second box stores toys with fun values in range of (-1, 0).
* The third box s... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int a, b, c, d;
cin >> a >> b >> c >> d;
string ans[4];
if ((a + b) % 2) {
ans[3] = "Tidak";
ans[2] = "Tidak";
if (a > 0 || d > 0)
ans[0] = "Ya";
else
ans[0] = "Tidak";... |
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 ≤ j ≤ k, j≠ i), for which (b_i ⊕ b_j) is the smallest among all such j,... | // Don't place your source in a package
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
// Please name your class Main
public class Main {
//static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
/*static int read() throw... |
Polycarp has invited n friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.
Each friend is characterized by two values h_i (their height) and w_i (their width). On the photo the i-th friend will occupy a rectangle h_i ... | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {... |
Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has n nodes (numbered 1 to n, with some node r as its root). There are a_i presents are hanging from the i-th node.
Before beginning the game, a special integer k is chosen. The game proceeds as follows:
* Alice begin... | #include <bits/stdc++.h>
#define ll long long
#define ls id << 1
#define rs id << 1 | 1
#define mem(array, value, size, type) memset(array, value, ((size) + 5) * sizeof(type))
#define memarray(array, value) memset(array, value, sizeof(array))
#define fillarray(array, value, begin, end) fill((array) + (begin), (array) +... |
You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length n, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the co... | import java.util.*;
import java.io.*;
public class Arranging_The_Sheeps {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
... |
You have been offered a job in a company developing a large social network. Your first task is connected with searching profiles that most probably belong to the same user.
The social network contains n registered profiles, numbered from 1 to n. Some pairs there are friends (the "friendship" relationship is mutual, th... | #include <bits/stdc++.h>
using namespace std;
long long p[1000005], h[1000005];
unordered_map<long long, long long> m1, m2;
int main() {
long long ans = 0, n, m, B = 37, x, y;
m1.reserve(1 << 12), m2.reserve(1 << 12);
m1.max_load_factor(0.25), m2.max_load_factor(0.25);
scanf("%lld%lld", &n, &m), p[0] = 1;
for... |
To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the sellin... | #include <bits/stdc++.h>
int x4[4] = {0, 0, -1, 1};
int y4[4] = {-1, 1, 0, 0};
int x8[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
int y8[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
using namespace std;
int n, m, k;
char dummy[15];
int a[15][105], b[15][105], c[15][105];
int ans = 0;
bool f(pair<int, int> x, pair<int, int> y) { return x.se... |
You are given a tree with n vertexes and n points on a plane, no three points lie on one straight line.
Your task is to paint the given tree on a plane, using the given points as vertexes.
That is, you should correspond each vertex of the tree to exactly one point and each point should correspond to a vertex. If two... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline bool chkmin(T& x, T y) {
return y < x ? x = y, 1 : 0;
}
template <class T>
inline bool chkmax(T& x, T y) {
return x < y ? x = y, 1 : 0;
}
inline long long Max(long long x, long long y) { return x > y ? x : y; }
inline long long Min(long long x,... |
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece,... | #include <bits/stdc++.h>
using namespace std;
int n, cnt, sum, now, a[100000];
long long ans;
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", a + i);
sum += a[i];
}
if (sum % 3) return puts("0");
for (int i = 0; i < n - 1; i++) {
now += a[i];
if (now == sum / 3 * 2) ans... |
Let's consider an n × n square matrix, consisting of digits one and zero.
We'll consider a matrix good, if it meets the following condition: in each row of the matrix all ones go in one group. That is, each row of the matrix looks like that 00...0011...1100...00 (or simply consists of zeroes if it has no ones).
You a... | #include <bits/stdc++.h>
using namespace std;
const int N = 2005;
int n, tot, root, cur;
int pq[N * N], value[N * N], num[N * N][3], order[N];
vector<int> edge[N * N];
char ch[N][N];
void Init() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%s", ch[i] + 1);
tot = root = n + 1;
for (int i = 1; i <= n; i... |
Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.
However, his... | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;;
public class Main {
// AltSTU1
public static void main(String[] args) {
try {
long timeStamp1 = System.currentTimeMillis(... |
A rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of n vertices, numbered from 1 to n. In this problem the tree root is the vertex number 1.
Let's represent the length of the shortest by t... | #include <bits/stdc++.h>
const long double eps = 1e-9;
using namespace std;
template <class T>
inline T MAX(const T &_a, const T &_b) {
return ((_a > _b) ? _a : _b);
}
template <class T>
inline T MIN(const T &_a, const T &_b) {
return ((_a < _b) ? _a : _b);
}
template <class T>
inline T MAX3(const T &_a, const T &_... |
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:
You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type:
1. For given numbers xi and vi assign value vi to element axi.... | import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
long mod = 1000000000;
class FenwickTree {
int n;
long[] t;
public FenwickTree(int n) {
this.n = n;
this.t = new long[n];
}
long ... |
Learn, learn and learn again — Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite th... | #include <bits/stdc++.h>
using namespace std;
static const double EPS = 1e-8;
int main() {
int n;
scanf("%d", &n);
vector<int> a(n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
long long pref[100010], suff[100010];
memset(pref, -127, sizeof(pref));
memset(suff, -127, sizeof(suff));
long lo... |
A little boy Petya dreams of growing up and becoming the Head Berland Plumber. He is thinking of the problems he will have to solve in the future. Unfortunately, Petya is too inexperienced, so you are about to solve one of such problems for Petya, the one he's the most interested in.
The Berland capital has n water ta... | #include <bits/stdc++.h>
using namespace std;
struct edge {
int b;
int cap, f, cost;
int rev_id;
};
vector<edge> E[55];
int dist[55];
int from[55];
int from_edge[55];
int res[55];
struct cmp {
bool operator()(int &a, int &b) { return dist[a] > dist[b]; }
};
int find_aug(int s, int t) {
for (int n = s; n <= t;... |
String diversity is the number of symbols that occur in the string at least once. Diversity of s will be denoted by d(s). For example , d("aaa")=1, d("abacaba")=3.
Given a string s, consisting of lowercase Latin letters. Consider all its substrings. Obviously, any substring diversity is a number from 1 to d(s). Find s... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using vi = vector<int>;
using vl = vector<long>;
using vll = vector<ll>;
using vb = vector<bool>;
using vvb = vector<vb>;
using vvi = vector<vector<int> >;
using ii = pair<int, int>;
using vii = vector<ii>;
using vs = ve... |
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.
The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (... | #include <bits/stdc++.h>
using namespace std;
const int inf = 1e9, maxn = 2e5 + 5, mod = 1e9 + 7;
int n, a[maxn], dp[maxn];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
dp[1] = 0;
for (int i = 2; i <= n + 1; i++)
dp[i] = (dp[i - 1] * 2ll % mod + mod - dp[a[i - 1]] + 2) % mo... |
Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu.
Each piece of tofu in the canteen is given a m-based number, all numbers are in the range [l, r] (l and r being m-based numbers), and for ev... | #include <bits/stdc++.h>
using namespace std;
auto SEED = chrono::steady_clock::now().time_since_epoch().count();
mt19937 rng(SEED);
const int mod = 1e9 + 7, x = 864197532, N = 1001, logN = 18, K = 500, C = 1e9;
struct AC {
vector<vector<int>> ch;
vector<int> cnt, f;
AC() { extend(); }
void extend() {
ch.pu... |
Andrew plays a game called "Civilization". Dima helps him.
The game has n cities and m bidirectional roads. The cities are numbered from 1 to n. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities v1, v2, ..., vk, that there is a r... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 10;
int n, m, q;
int par[maxn], L[maxn];
int cnt[maxn];
void merge(int, int);
pair<int, int> root(int);
vector<int> adj[maxn];
void input() {
scanf("%d%d%d", &n, &m, &q);
int v, u;
for (int i = 0; i < n; i++) par[i] = -1;
for (int i = 0; i < m... |
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a stud... | import sys
if __name__ == '__main__':
n = int(sys.stdin.readline())
times = []
for _ in xrange(n):
a, b = map(int, sys.stdin.readline().strip().split())
times.append((a, b))
times.sort()
current_day = 0
for a, b in times:
current_day = b if b >= current_day else a
print current_day
|
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the secon... | import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class C {
class E implements Comparable<E>{
int id, deg, xor;
public E(int id, int deg, int xor) {
this.id = id;
this.deg = deg;
... |
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting t... | import operator as op
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from functools import reduce
from itertools import (
accumulate, combinations, combinations_with_replacemen... |
Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
Input
The first line contains integer ... | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Competencia3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] X = new int[n];
int[] Y = new int[n];
for(int i = 0; i < n; i++) {
X[i] = scan.nextInt();
... |
You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make <image> as large as possible, where <image> denotes the bitwise OR.
Find the maximum possible value of <image> after performing at most k operations optimally.
I... | import java.util.Scanner;
public class D
{
public void solve()
{
Scanner cin = new Scanner(System.in);
int N = cin.nextInt();
int K = cin.nextInt();
int x = cin.nextInt();
int[] a = new int[N];
long[] b = new long[N];
long[] sumA = new long[N + 1];
... |
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in th... | #include <bits/stdc++.h>
using namespace std;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
const long long NLINF = 0xf7f7f7f7f7f7f7f7;
const int INF = 0x3f3f3f3f, NINF = 0xf7f7f7f7;
const int MOD1 = 1e9 + 7, MOD2 = 1e9 + 9;
const int N = 2e5 + 10;
int n, freq[30], mark[30];
vector<char> odd, ch;
char s[N], r[N];
int main... |
There are well-known formulas: <image>, <image>, <image>. Also mathematicians found similar formulas for higher degrees.
Find the value of the sum <image> modulo 109 + 7 (so you should find the remainder after dividing the answer by the value 109 + 7).
Input
The only line contains two integers n, k (1 ≤ n ≤ 109, 0 ≤... | #include <bits/stdc++.h>
using namespace std;
const int N = 100000;
const int inf = (int)1e9 + 1;
const long long big = (long long)1e18 + 1;
const int P = 239;
const int MOD = (int)1e9 + 7;
const int MOD1 = (int)1e9 + 9;
const double eps = 1e-9;
const double pi = atan2(0, -1);
long long bin_pow(long long a, long long p... |
In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.
When a query appears server may react in three possible ways:
1. If server is free and... | 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.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Lin... |
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.
There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to t... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:500000000")
using namespace std;
int main() {
int n, k, i;
scanf("%d %d", &n, &k);
vector<int> a(n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
sort(a.begin(), a.end());
int L, R;
L = 0, R = a.back();
int RR = R;
while (L <= R) {
int c = (L... |
Barney is searching for his dream girl. He lives in NYC. NYC has n junctions numbered from 1 to n and n - 1 roads connecting them. We will consider the NYC as a rooted tree with root being junction 1. m girls live in NYC, i-th of them lives along junction ci and her weight initially equals i pounds.
<image>
Barney co... | #include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
inline T1 max(T1 a, T2 b) {
return a < b ? b : a;
}
template <typename T1, typename T2>
inline T1 min(T1 a, T2 b) {
return a < b ? a : b;
}
const char lf = '\n';
namespace ae86 {
const int bufl = 1 << 15;
char buf[bufl], *s = buf, *t ... |
I’m strolling on sunshine, yeah-ah! And doesn’t it feel good! Well, it certainly feels good for our Heroes of Making Magic, who are casually walking on a one-directional road, fighting imps. Imps are weak and feeble creatures and they are not good at much. However, Heroes enjoy fighting them. For fun, if nothing else. ... | #include <bits/stdc++.h>
using namespace std;
long long oo = 2e15;
const int maxn = 4e5, maxm = 1e6;
long long z0[maxm], z1[maxm], m0[maxm], m1[maxm];
int c[maxn];
int L, R, x, n, i, q;
void update(int o) {
m0[o] = min(z0[2 * o] + m0[2 * o], z0[2 * o + 1] + m0[2 * o + 1]);
m1[o] = min(z1[2 * o] + m1[2 * o], z1[2 * ... |
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the inte... | #include <bits/stdc++.h>
const int N = 2e5 + 2;
long long dep[N];
int lj[N], nxt[N], len[N], fir[N], f[N][19], a[N], s[N];
int n, i, bs, c, x, y;
inline void read(int &x) {
c = getchar();
while ((c < 48) || (c > 57)) c = getchar();
x = c ^ 48;
c = getchar();
while ((c >= 48) && (c <= 57)) {
x = x * 10 + (... |
You are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn't exist.
Divisor of n is any such natural number, that n can be divided by it without remainder.
Input
The first line contains two integers n and k (1 ≤ n ≤ 1015, 1 ≤ k ≤ 109).
Output
If n has less than k divisors, output ... | //I AM THE CREED
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class HelloWorld{
public static void main(String[] args) throws IOException
{
... |
Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.
Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th v... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
T getint() {
T x = 0, p = 1;
char ch;
do {
ch = getchar();
} while (ch <= ' ');
if (ch == '-') p = -1, ch = getchar();
while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
return p == 1 ? x : -x;
}
template <typename ... |
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.
Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place p.
Now the elimination rou... | #include <bits/stdc++.h>
using namespace std;
int p, x, y;
bool check(int a) {
a /= 50;
a %= 475;
for (int i = 0; i < 25; ++i) {
a = (a * 96 + 42) % 475;
if (a + 26 == p) return true;
}
return false;
}
int solve() {
int a = x;
a = (y / 50) * 50 + x % 50;
if (a < y) a += 50;
while (a < x) {
... |
Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.
P... | #include <bits/stdc++.h>
using namespace std;
map<int, int> mp;
set<int> s;
int a[2345];
int b[2345];
int sum[2345];
int main() {
mp.clear();
s.clear();
int k, n, h = 0, flag = 1;
scanf("%d %d", &k, &n);
for (int i = 0; i < k; i++) {
scanf("%d", &a[i]);
if (i) {
sum[i] = a[i] + sum[i - 1];
... |
The competitors of Bubble Cup X gathered after the competition and discussed what is the best way to get to know the host country and its cities.
After exploring the map of Serbia for a while, the competitors came up with the following facts: the country has V cities which are indexed with numbers from 1 to V, and the... | #include <bits/stdc++.h>
using namespace std;
const int N = 605, INF = 1e9;
int w[N][N], a[N], b[N];
bool used[N];
vector<int> v[N], t[N];
int g = 0;
bool dfs(int node) {
if (used[node]) return false;
used[node] = 1;
for (int to : t[node]) {
if (b[to] == -1 || dfs(b[to])) {
b[to] = node;
a[node] =... |
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large ve... | import java.util.*;
import java.io.*;
import java.math.*;
public class c {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
... |
One Martian boy called Zorg wants to present a string of beads to his friend from the Earth — Masha. He knows that Masha likes two colours: blue and red, — and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if on... | #include <bits/stdc++.h>
using namespace std;
long long f[55][2][2], K, d;
int a[55], n;
long long C(int l, int r, int x, int y) {
if (l > r) return 1;
long long& F = f[l][x][y];
if (~F) return F;
F = 0;
for (int i = 0; i <= 1; ++i)
for (int j = 0; j <= 1; ++j)
if (a[l] - !i && a[r] - !j && (l < r |... |
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of strin... | #include <bits/stdc++.h>
using namespace std;
long long n, k, i, j, sum, sm[2000000], cnt1, cnt2, ans;
pair<pair<long long, long long>, long long> p[2000000];
string s[2000000], S;
bool cmp(pair<pair<long long, long long>, long long> a,
pair<pair<long long, long long>, long long> b) {
if (a.first.second == 0... |
After the Search Ultimate program that searched for strings in a text failed, Igor K. got to think: "Why on Earth does my program work so slowly?" As he double-checked his code, he said: "My code contains no errors, yet I know how we will improve Search Ultimate!" and took a large book from the shelves. The book read "... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
using namespace std;
int n;
int a[300][300];
vector<pair<pair<int, int>, int> > from[300];
int bild[300000];
int sum = 0;
vector<pair<pair<int, int>, pair<int, int> > > bd;
vector<pair<pair<int, int>, pair<int, int> > > ans;
void punch() {
if (((int)... |
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.
A postman delivers letters. Sometimes there is no specific dormitory and room number in it o... | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
# aa = [sum(a[:i+1]) for i in range(len(a))]
j = 0
s = a[0]
for i in range(len(b)):
while b[i] > s: # aa[j]:
j += 1
s += a[j]
print(j+1, b[i]- (s-a[j]) if j > 0 else b[i])
|
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers.
There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulti... | #include <bits/stdc++.h>
using namespace std;
int n, m, x, y, z, taka;
int ara[30000];
vector<int> cut;
int main() {
cin >> n >> taka;
int odd = 0, even = 0;
for (int i = 1; i <= n; i++) cin >> ara[i];
for (int i = 1; i <= n; i++) {
x = ara[i];
if (x % 2)
odd++;
else
even++;
if (odd ... |
Mid semesters are nearly here. In order to pass the time waiting for the question paper malfunctions, the students have organized a betting pool on students that will pass the semester and the students that will fail.
Students place their bets on the sum of the students that will pass and students that will fail, or ... | for tc in range(int(raw_input())):
a,b=map(int,raw_input().split())
if (a+b)%2!=0 or a<=b:
print "impossible"
else:
print (a+b)/2,(a-b)/2 |
Given an amount A, we want you to compute the number of ways in which you
can gather A rupees if you have an infinite supply of each of C = {1, 3, 5} valued rupee coins.
Input:
First line contains T, the number of test-cases. This is followed by T lines, where each line consists of the amount A.
Output:
For each t... | for tc in range(int(raw_input())):
n=int(raw_input())
count=0
for c5 in range(n/5+1):
for c3 in range((n-(c5*5))/3+1):
for c1 in range((n-(c5*5)-(c3*3))/1+1):
#print c1
if ((c5)*5)+((c3)*3)+((c1)*1)==n:
count+=1
print count |
Kate has finally calmed down and decides to forgive Little Deepu, but she won't forgive him just like that. She agrees to forgive him on the grounds that he can solve a mathematical question for her.
She gives Deepu a large number N and a prime number P and asks him to calculate ((3*N)! / (3!^N) )%P.Your task is to he... | from sys import stdin
import math
t = int(stdin.readline())
fa = [1]
for i in xrange(1,100):
fa.append(i*fa[i-1])
for _ in xrange(t):
n,p = map(int,stdin.readline().split())
if p==2:
num = fa[3*n]
den = pow(6,n,p)
print (num*den)%2
else:
den = pow(6,n,p)
den = pow(den,p-2,p)
num = 0
if 3*n <p:
num ... |
This is a fact for almost all the students out there that Mathematics subject is a very fearful subject for them.
And no wonder this fact is also true for our friend Primo. But to challenge his fear he went to the Mathe-Matica Town for his summer vacations.
In Mathe-Matica town every person is assigned a Friend Score... | limit = 1000000
prime = [0] * (limit + 1)
def seive():
global limit
global prime
prime[0] = 1
prime[1] = 1
p = 2
while p * p <= limit:
if prime[p] == 0:
i = p * 2
while i <= limit:
prime[i] = 1
i += p
p+=1
... |
I and my flatmate ,Sayan, went to see the magnificient fountains in the Jubilee park on 3rd March.It was the eve of the 184rd Bithday of the late Mr. J.N.Tata and the fountains were set to blow at regular intervals.
I sat down praising the scenic beauty of the fountains.But Sayan, who is a bit wierd, came up with a cha... | def gcd(a,b):
if(a<b):
return gcd(b,a)
if(a%b == 0):
return b
else:
return gcd(b,a%b)
def lcm(a,b):
return a*b/(gcd(a,b))
test = input()
for i in range(test):
n = input()
arr = map(int,raw_input().split())
lcm_result= arr[0]
for i in range(1,n):
lcm... |
Nikhil got to know about what is a matrice. He made several patterns using 1-d and 2-d matrices. One of which was his favorite pattern. Your task is to right a code for his favorite pattern.
NOTE :- To understand his favorite pattern see the sample output
Input:-
First line of code takes number of test cases 'N' as ... | def spiral(n):
dx,dy = 1,0 # Starting increments
x,y = 0,0 # Starting location
myarray = [[None]* n for j in range(n)]
for i in xrange(n**2):
myarray[x][y] = i
nx,ny = x+dx, y+dy
if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
x,y = nx,ny
... |
Puchi hates to carry luggage, but unfortunately he got a job to carry the luggage of his N friends in office. Each day, one of his N friends, gives him the luggage of a particular weight to carry. You will be given the weight of luggage of each friend in the array Weight, where Weighti is the weight of luggage of i^th... | M_SIZE = 1000001
def update(bitree, idx, val):
while idx < M_SIZE:
bitree[idx] += val
idx += (idx & -idx)
def query(bitree, idx):
res = 0
while idx > 0:
res += bitree[idx]
idx -= (idx & -idx)
return res
def magic():
"""
1 <= test_cases <= 30
1 <= n <= 10000... |
During his interview, Shil came across a very difficult problem. The problem is as follows:
A matrix V consisting of N rows and M columns is called beautiful if and only if it satisfies the following two conditions:
1) Every cell of the matrix contains distinct natural number less or equal to N*M.
2) For any two... | from math import factorial
MOD=1000000007
n,m=map(int,raw_input().split())
cnt=[0]*(1<<20)
for i in range(1,n+1):
for j in range(1,m+1):
cnt[i^j]+=1
prod=1
for c in cnt:
if c>1:
prod=prod*factorial(c)%MOD
print prod |
PandeyG, a brilliant tennis player, decided to start a tournament in his colony. Now, since PandeyG is overly optimistic and ambitious - he tries to lure in as many people as he can from his colony for them to participate in his very own knockout type tennis tournament. What he fails to realize that, to have a knockout... | name=int(raw_input( ))
while(name>0):
n=int(raw_input())
if(n!=0):
print n-1
else:
print 0
name=name-1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.