input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Aiz Onsen has a bathhouse and a pool. To use the bathhouse, you need to buy a bathing ticket, and to use the pool, you need to buy a pool ticket. Prices for these tickets may vary from day to day. In addition, Aiz Onsen has the following rules.
* Tickets are valid only once on the day of purchase.
* If you buy 5 or mo... | #include <stdio.h>
int main(void){
int n,i,x,y,b,p;
int q,w;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d %d %d %d",&x,&y,&b,&p);
q=x*b+y*p;
if(b<5)b=5;
if(p<2)p=2;
w=(x*b+y*p)*0.8;
if(q<w){
printf("%d\n",q);
}else{
printf("%d\n",w);
}
}
return 0;
} |
problem
For the integer n (1 ≤ n), let Pn be a string of n + 1 I's and n O's starting with I and alternating, where I and O are the uppercase Ai and O, respectively. is there.
P1 | IOI
--- | ---
P2 | IOIOI
P3 | IOIOIOI
|. |
|. |
|. |
Pn | IOIOIO ... OI (n O)
Figure 1-1 Character string considered in this question... | #include <iostream>
#include <string>
using namespace std;
int main(){
int ans = 0;
int n;
cin >> n;
while(n != 0){
int m;
cin >> m;
string s;
cin >> s;
string see = "I";
for(int i = 0; i < n; i++){
string temp = "OI";
see = see+temp;
}
int ans = 0;
string sn =... |
In Storia Kingdom, there is an artifact called "Perfect Sphere" made by a great meister Es. This is handed down for generations in the royal palace as a treasure. Es left a memo and filled mysterious values in it. Within achievements of researches, it has been revealed that the values denote coordinate values. However ... | #include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloa... |
William Robinson was completely puzzled in the music room; he could not find his triangle in his bag. He was sure that he had prepared it the night before. He remembered its clank when he had stepped on the school bus early that morning. No, not in his dream. His triangle was quite unique: no two sides had the same len... | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class Main{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
double[] d;
P[] ps;
int n;
void run(){
d=new double[3];
for(int t=sc.next... |
Example
Input
100 1 0
50 100
Output
14.57738 | #include <algorithm>
#include <cmath>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#include <cassert>
#include <func... |
Problem
Uniqlo Uzuki and Rin Meguro are coming to SEARIGHT LIVE FES for sale. As shown in the figure below, the product sales line consists of two lines, with W people in the horizontal direction and H people in the vertical direction, forming a U-shape. The person at the top of the line is removed from the line after... | #include <bits/stdc++.h>
#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=int(a);i<int(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)
#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i)
#define r... |
Once upon a time, there lived a dumb king. He always messes things up based on his whimsical ideas. This time, he decided to renew the kingdom’s coin system. Currently the kingdom has three types of coins of values 1, 5, and 25. He is thinking of replacing these with another set of coins.
Yesterday, he suggested a coi... | import java.util.Arrays;
import java.util.Scanner;
//Greedy, Greedy.
public class Main{
int n, INF = 1<<29;
int[] c;
int f(int x){
int res = 0, k = n-1;
while(x>0&&k>=0){
res += x/c[k];
x%=c[k--];
}
return x==0?res:INF;
}
void run(){
Scanner sc = new Scanner(System.in);
for(int T=1;;T++){
... |
Kitamasa is studying various transformations at university. Recently, the transformations that Kitamasa is interested in are as follows. N + 1 integers a0, ..., aN are fixed, and the integer z is used as an input. Also, let P be a prime number.
> t = (aNzN + aN-1zN-1 + ... + a2z2 + a1z + a0) mod P
Kitamasa noticed th... | #include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <numeric>
#include <utility>
#include <iomanip>... |
A browser-based puzzle game called "Bubble Puzzle" is now popular on the Internet.
The puzzle is played on a 4 × 4 grid, and initially there are several bubbles in the grid squares. Each bubble has a state expressed by a positive integer, and the state changes when the bubble gets stimulated. You can stimulate a bubbl... | #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <tuple>
#include <cassert>
const int wmax=4;
const int hmax=4;
const int rmax=5;
const int vx[]={0,1,0,-1};
const int vy[]={-1,0,1,0};
bool simul(std::vector<std::vector<int>> &m,int h,int w){//ある盤面で(h,w)をクリックした結果を上書きし、全消ししているかを返す
... |
A - Everlasting Zero
Problem Statement
You are very absorbed in a famous role-playing game (RPG), "Everlasting -Zero-". An RPG is a game in which players assume the roles of characters in a fictional setting. While you play the game, you can forget your "real life" and become a different person.
To play the game mor... | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<iomanip>
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<list>
using namespace std;
typedef long long LL;
t... |
prison
There are an infinite number of prisoners. Initially, the prisoners are numbered 0, 1, 2, ....
Do the following N times:
* Release the 0th prisoner and execute the k, 2k, 3k, ... th prisoners.
* Then renumber the remaining prisoners. At this time, the prisoners with the smallest original numbers are numbered ... | #include<iostream>
using namespace std;
typedef unsigned long long ull;
typedef unsigned __int128 ui128;
signed main(){
ui128 ans = 0, b = 0;
ull N, k;
cin>>N>>k;
for(ui128 i = 1; i < N; i++){
ans = (k*b+k-1)/(k-1);
// cout<<i<<" "<<ans<<endl;
b = ans;
}
cout<<(ull)ans<<endl;
return 0;
}
|
You are given a string $S$, which is balanced parentheses with a star symbol '*' inserted.
Any balanced parentheses can be constructed using the following rules:
* An empty string is balanced.
* Concatenation of two balanced parentheses is balanced.
* If $T$ is balanced parentheses, concatenation of '(', $T$, and ')'... | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define MOD ((int)1e9+7)
signed main(){
string s;
stack<int> sta;
cin>>s;
for(int i = 0; i < s.size(); i++){
if(s[i] == '*'){
cout<<sta.size()<<endl;
} else if(s[i] == '('){
sta.push(1);
}else {
sta.pop();
... |
G: Toss Cut Tree
Problem Statement
You are given two trees T, U. Each tree has N vertices that are numbered 1 through N. The i-th edge (1 \leq i \leq N-1) of tree T connects vertices a_i and b_i. The i-th edge (1 \leq i \leq N-1) of tree U connects vertices c_i and d_i.
The operation described below will be performe... | #include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0; i<(n); i++)
#define FOR(i,a,b) for(int i=(a); i<(b); i++)
#define FORR(i,a,b) for(int i=(b)-1; i>=(a); i--)
#define DEBUG(x) cerr << #x << ": " << (x) << endl;
using ll = long long;
using vi = vector<int>;
using pii = pair<int,int>;
const l... |
UnionFind(ランダム生成)
Example
Input
Output | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <limits>
#include <random>
#include <utility>
#include <vector>
namespace procon {
class UnionFind {
private:
struct nodeinfo {
int par;
int rank;
nodeinfo(int par) : par(par), rank(0) {}
};
std::ve... |
A bipartite graph G = (V, E) is a graph in which the vertex set V can be divided into two disjoint subsets X and Y such that every edge e ∈ E has one end point in X and the other end point in Y.
A matching M is a subset of edges such that each node in V appears in at most one edge in M.
Given a bipartite graph, find ... | #include <iostream>
#include <vector>
#include <algorithm>
#define REP(i,n) for (int i=0;i<(n);i++)
using namespace std;
const int INF = 1e9;
const int MAX_V = 210;
struct edge{
int to, cap, rev;
edge(int to,int cap, int rev):to(to),cap(cap),rev(rev){}
};
vector<vector<edge> > G(MAX_V); //??°???????????£??\????????... |
From the FAQ:
What am I allowed to post as a comment for a problem?
Do NOT post code.
Do NOT post a comment asking why your solution is wrong.
Do NOT post a comment asking if you can be given the test case your program fails on.
Do NOT post a comment asking how your solution can be improved.
Do NOT post a comment g... | a=int(raw_input())
ans=[]
for i in range(0,a):
q=0
b=int(raw_input())
c=raw_input()
if b==2 and c[0]=='?':
if c.find('0')>0 and c.find('1')>0:
if c.find('1') < c.find('0') and c.find('1')%2==0:
c='1'+c[1:]
elif c.find('1') > c.find('0') and c.find('0')%2==... |
POINTS - 30
Given an integer N, output the number of zeroes at the end of N! (factorial).
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
Output
For each test case... | import sys
t=int(sys.stdin.readline())
while t!=0:
n=int(sys.stdin.readline())
f=1
for i in range (1,n+1):
f=f*i
f=str(f)
c=0
l=len(f)-1
while l>=0:
if f[l]=='0':
c+=1
l-=1
else:
break
print c
t-=1 |
Problem Description:
A pyramid has been constructed using bricks. All these bricks are made of gold. However the quality of gold varies from brick to brick. The value of the bricks has been marked equivalent to nCr. Where n is the nth row of the pyramid from the top, and r is the number of the brick in that row (Both n... | from math import sqrt
def disp(A):
j = 0
for i in A:
print j, i
j += 1
print
def Asum(A):
s = 0L
for i in A:
s += sum(i)
return long(s)
def solve(N):
N = sqrt(1 + 8*N) - 1
N /= 2
N = int(N)
# print N
A = [[0] * (i + 1) for i in xrange(N)]
A... |
Chef Po has given an online advertisement to provide Event organizing services. Chef got a huge response for his advertisement. He got various orders to conduct the events from different organizations. In turn, Chef will receive a compensation depend upon the type of event and the total numbers of persons in the event.... | from sys import stdin
from collections import defaultdict
class Event(object):
def __init__(self, start, end, value):
self.start = start
self.end = end
self.value = value
T = int(stdin.readline())
for _ in range(T):
number_of_events = int(stdin.readline())
events = defaultdict(list)
for _ in range(number_o... |
Chef loves arrays. But he really loves a specific kind of them - Rainbow Arrays.
The array is a Rainbow Array if it has such a structure:
The first a1 elements equal to 1.
The next a2 elements equal to 2.
The next a3 elements equal to 3.
The next a4 elements equal to 4.
The next a5 elements equal to 5.
The n... | import sys
f=sys.stdin
mod=1000000007
n=int(f.readline())
if n<13:
print 0
else :
n+=1
n/=2
n-=1
ans=n*(n-1)*(n-2)*(n-3)*(n-4)*(n-5)
ans/=720
ans%=mod
print ans |
Damon was captured by almighty Ni’klaus.
Ni’klaus was 1000 years old and have spent his life hunting innocents, so he didn’t had time to study math.
Damon, a sharp minded vampire, came across a very interesting idea. He wanted to tell his friends the address of the house he is being held captive in, so he called one o... | t=input()
for x in range(0,t):
n=input()
s=bin(n)
cnt=s.count('1')
print cnt |
There are n houses in a row. They are numbered from 1 to n in order from left to right. Initially you are in the house 1.
You have to perform k moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current h... | import math
def main():
n, k, s = [int(x) for x in input().split()]
if (n - 1) * k < s:
print('NO')
return
if k > s:
print('NO')
return
curr = 1
print('YES')
while s > 0:
d = min(n - 1, s - k + 1)
s -= d
k -= 1
if curr + d <= n... |
This is an interactive problem.
In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontr... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
srand(time(0));
long long n;
int k;
cin >> n >> k;
long long L = 1, r = n;
while (true) {
if (r - L < 6 * k) {
long long rnd =
L + (r - L + 1) * (long long)rand() / (long long)(RAND_MAX + 1);
... |
There are n TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The i-th of the shows is going from l_i-th to r_i-th minute, both ends inclusive.
You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you... | #include <bits/stdc++.h>
using namespace std;
const long long int mod = 1e9 + 7;
int main() {
long long int n, x, y;
cin >> n >> x >> y;
vector<pair<long long int, long long int> > V;
for (long long int i = 0; i < n; ++i) {
long long int a, b;
cin >> a >> b;
V.push_back(make_pair(a, 0));
V.push_... |
Once Grisha found a tree (connected graph without cycles) with a root in node 1.
But this tree was not just a tree. A permutation p of integers from 0 to n - 1 is written in nodes, a number p_i is written in node i.
As Grisha likes to invent some strange and interesting problems for himself, but not always can solve ... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
struct Segtree {
int n;
T e;
vector<T> dat;
typedef function<T(T a, T b)> Func;
Func f;
Segtree() {}
Segtree(int n_input, Func f_input, T e_input) {
initialize(n_input, f_input, e_input);
}
void initialize(int n_input, Func f_inpu... |
You are given an array a consisting of n integers. Let's denote monotonic renumeration of array a as an array b consisting of n integers such that all of the following conditions are met:
* b_1 = 0;
* for every pair of indices i and j such that 1 ≤ i, j ≤ n, if a_i = a_j, then b_i = b_j (note that if a_i ≠ a_j, i... | import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
# sys.setrecursionlimit(100000)
# ^^^TAKE CARE FOR MEMORY LIMIT^^^
import random
def main():
pass
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
de... |
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit afte... | #include <bits/stdc++.h>
using namespace std;
char getc() {
char c = getchar();
while ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9'))
c = getchar();
return c;
}
int gcd(int n, int m) { return m == 0 ? n : gcd(m, n % m); }
int read() {
int x = 0, f = 1;
char c = getchar();
while (c... |
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of a... | Answer = 'ACTG'
MIN = 10 ** 6
input()
X = input()
for i in range(0, len(X) - 3):
Temp = X[i:i + 4]
Index, Count = 0, 0
for j in Temp:
tmp = 0
if ord(j) > ord(Answer[Index]):
tmp += 26 + ord(Answer[Index]) - ord(j)
else:
tmp += 26 + ord(j) - ord(Answer[Index])
... |
Nauuo is a girl who loves coding.
One day she was solving a problem which requires to calculate a sum of some numbers modulo p.
She wrote the following code and got the verdict "Wrong answer".
<image>
She soon discovered the bug — the ModAdd function only worked for numbers in the range [0,p), but the numbers in th... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 5;
const long long inf = 1e18;
char buf[1 << 12], *pp1 = buf, *pp2 = buf, nc;
int ny;
inline char gc() {
return pp1 == pp2 &&
(pp2 = (pp1 = buf) + fread(buf, 1, 1 << 12, stdin), pp1 == pp2)
? EOF
: *pp1++;
... |
"Duel!"
Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.
There are n cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping card... | #include <bits/stdc++.h>
const int maxn = 1e5 + 5;
using namespace std;
char a[maxn];
int n, k, L[2][2];
int main() {
scanf("%d%d", &n, &k);
getchar();
for (int i = 1; i <= n; i++) {
scanf("%c", &a[i]);
int k = a[i] - '0';
if (L[k][0] == 0) {
L[k][0] = i;
}
L[k][1] = i;
}
int len0 = ... |
Koala Land consists of m bidirectional roads connecting n cities. The roads are numbered from 1 to m by order in input. It is guaranteed, that one can reach any city from every other city.
Koala starts traveling from city 1. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put space... | import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.max;
import static java.lang.System.arraycopy;
import static java.lang.System.exit;
import static java.util.Arrays.copyOf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream... |
You have an integer n. Let's define following tree generation as McDic's generation:
1. Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactl... | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
using DO = double;
using pii = pair<int, int>;
using VI = vector<int>;
const int NN = (1 << 17) + 10, inf = 1e9;
VI adj[NN];
int deg[NN];
int n, m;
void check(int u, int fa = 0, int deep = 0) {
if (deep >= n) {
puts("0");
exit(0);
}
int d... |
Let's call a binary string s awesome, if it has at least 1 symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are awesome, but 0, 110, 01010 aren't.
You are given a binary string s. Count the number of its awesome substrings.
A string a is a substring of a string b if... | #include <bits/stdc++.h>
using namespace std;
const long long inf = (long long)1e18;
const long long mod = (long long)1e9 + 7;
const double eps = (double)1e-9;
const double pi = acos(-1.0);
const int dx[] = {0, 0, 1, 0, -1};
const int dy[] = {0, 1, 0, -1, 0};
const int N = 200005;
const int BL = 300;
long long ans;
cha... |
[THE SxPLAY & KIVΛ - 漂流](https://soundcloud.com/kivawu/hyouryu)
[KIVΛ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With 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,... | #include <bits/stdc++.h>
using namespace std;
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(0);
long long x[100];
long long y[100];
long long ax, ay, bx, by;
cin >> x[0] >> y[0] >> ax >> ay >> bx >> by;
long long sx, sy, t;
cin >> sx >> sy >> t;
long long i;
for (i = 1; i <= 100; i++) {
... |
This is a harder version of the problem. In this version n ≤ 500 000
The 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 compan... | #include <bits/stdc++.h>
using namespace std;
const int inf = int(1e9) + 7;
int main() {
ios::sync_with_stdio(false);
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vector<long long> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
vector<long long> minl(n);
vector<long long> minr(n);
vector<long lo... |
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the ki... | #include <bits/stdc++.h>
using namespace std;
vector<int> g[210000];
int size[210000];
int depth[210000];
int n, k;
void init() {
int x, y;
cin >> n >> k;
for (int i = 1; i < n; i++) {
scanf("%d%d", &x, &y);
g[x].push_back(y);
g[y].push_back(x);
}
}
vector<int> ans;
void dfs(int pos, int f) {
size... |
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.
You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of d... | def sm(a, b):
val = (a + b) * (b - a + 1) // 2
return (val)
n, x = [int(x) for x in input().split()]
d = [int(x) for x in input().split()] * 2
mx, i, j, day, hug = 0, 0, 0, 0, 0
while(i < n):
if day + d[j] <= x:
day += d[j]
hug += sm(1, d[j])
j += 1
else:
mx = max(mx, h... |
A cubic lattice L in 3-dimensional euclidean space is a set of points defined in the following way: $$$L=\\{u ⋅ \vec r_1 + v ⋅ \vec r_2 + w ⋅ \vec r_3\}_{u, v, w ∈ \mathbb Z} Where \vec r_1, \vec r_2, \vec r_3 \in \mathbb{Z}^3$$$ are some integer vectors such that:
* \vec r_1, \vec r_2 and \vec r_3 are pairwise ort... | #include <bits/stdc++.h>
using namespace std;
const int N = 10003;
const long double eps = 1e-9;
int n, x[N], y[N], z[N];
template <typename T>
inline void read(T &x) {
int ch = getchar();
x = 0;
bool f = false;
for (; ch < '0' || ch > '9'; ch = getchar()) f |= ch == '-';
for (; ch >= '0' && ch <= '9'; ch = g... |
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.
You are given a weighted rooted tree, vertex 1 is the root of this tree.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last differ... | import java.io.*;
import java.math.*;
import java.util.*;
/**
*
* @author Saju
*
*/
public class Main {
private static int dx[] = { 1, 0, -1, 0 };
private static int dy[] = { 0, -1, 0, 1 };
private static final long INF = Long.MAX_VALUE;
private static final int INT_INF = Integer.MAX_VALUE;
... |
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
... | #include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f3f3f3f3f;
long long dx[] = {0, 1, 1, 1, 0, -1, -1, -1};
long long dy[] = {1, 1, 0, -1, -1, -1, 0, 1};
struct BipartiteMatcher {
vector<vector<long long>> G;
vector<long long> L, R, Viz;
BipartiteMatcher(long long n, long long m)
:... |
You are given an array a of n positive integers.
You can use the following operation as many times as you like: select any integer 1 ≤ k ≤ n and do one of two things:
* decrement by one k of the first elements of the array.
* decrement by one k of the last elements of the array.
For example, if n=5 and a=[3... | t = int(input())
for case in range(t):
n = int(input())
a = list(map(int, input().split()))
x = 0
low = a[0]
works = True
for i in range(1, n):
if a[i] < x:
print("NO")
works = False
break
next_low = low
if a[i] - x < low:
... |
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. W... | #include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
int main()
{
IOS;
int q;
cin >> q;
int id = 0;
map<int, queue<int> > m;
set<int> have;
while(q--)
{
int type;
cin >> type;
if(type == 1)
{
id++;
have.insert(id);
int ... |
You have a deck of n cards, and you'd like to reorder it to a new one.
Each card has a value between 1 and n equal to p_i. All p_i are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. p_1 stands for the bottom card, p_n is the top card.
In each step you pick some integer k > 0, take the top ... | for t in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
look = [0] * n
look[0] = a[0]
for i in range(1, n):
look[i] = max(look[i - 1], a[i])
j = n
ans = []
for i in range(n - 1, -1, -1):
if look[i] == a[i]:
ans.extend(a[i:j])
j = i
print(*ans) |
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
P... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Solve {
static int mod = 1000000000 + 7;
static long fact[... |
There is an infinite set generated as follows:
* 1 is in this set.
* If x is in this set, x ⋅ a and x+b both are in this set.
For example, when a=3 and b=6, the five smallest elements of the set are:
* 1,
* 3 (1 is in this set, so 1⋅ a=3 is in this set),
* 7 (1 is in this set, so 1+b=7 is in this set... | import sys
input=sys.stdin.readline
t=int(input())
for i in range(t):
n,a,b=map(int,input().split())
if(a==1):
if((n-1)%b==0):
print('YES')
else:
print('NO')
continue;
t=1
flag=0
while(t<=n):
if((n-t)%b==0):
flag=1
b... |
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task i... | import java.util.*;
/**
*
*
* @author Mustafa Arinmis
* @since 05.11.2020
* */
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
TreeMap<Integer, Integer> containers = new Tr... |
According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set:
* In each row at most two different colours can be used.
* No two adjacent squares can be painted the same c... | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zyf... |
Rubik is very keen on number permutations.
A permutation a with length n is a sequence, consisting of n different numbers from 1 to n. Element number i (1 ≤ i ≤ n) of this permutation will be denoted as ai.
Furik decided to make a present to Rubik and came up with a new problem on permutations. Furik tells Rubik two... | #include <bits/stdc++.h>
using namespace std;
const unsigned long long P = 1037159;
unsigned long long degs[200001];
struct TNode {
TNode *left, *right;
int x, y;
int key, size;
int leftmost, rightmost;
unsigned long long hash;
TNode(int _x, int _key);
};
TNode *null;
TNode::TNode(int _x, int _key)
: le... |
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that:
1. choose any non-empty string from strings s1, s2, ..., sn;
2. ch... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 10;
struct Edge {
int from, to, cap, flow, cost;
Edge() {}
Edge(int f, int t, int c, int fl, int co)
: from(f), to(t), cap(c), flow(fl), cost(co) {}
};
struct MCMF {
int n, m, s, t;
vector<Edge> edges;
vector<int> G[maxn];
bool in... |
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.
There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the term... | #include <bits/stdc++.h>
using namespace std;
long long int mod = 1e9 + 7;
long long int fexpo(long long int a, long long int b) {
if (b == 0) return 1LL;
if (b == 1) return a;
if (b == 2) return ((a) * (a));
if (b % 2 == 0)
return fexpo(fexpo(a, b / 2), 2);
else
return ((a) * (fexpo(fexpo(a, (b - 1) ... |
As you know, Vova has recently become a new shaman in the city of Ultima Thule. So, he has received the shaman knowledge about the correct bracket sequences. The shamans of Ultima Thule have been using lots of different types of brackets since prehistoric times. A bracket type is a positive integer. The shamans define ... | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int M = 1000010;
const int mod = 1e9;
const double eps = 1e-8;
const double Pi = 2 * acos(0.0);
int n, p[M], t, tmp, stk[M];
bool q[M];
int main() {
ios::sync_with_stdio(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> p[i];
... |
Rainbow built h cells in a row that are numbered from 1 to h from left to right. There are n cells with treasure. We call each of these n cells "Treasure Cell". The i-th "Treasure Cell" is the ai-th cell and the value of treasure in it is ci dollars.
Then, Freda went in the first cell. For now, she can go just k cells... | #include <bits/stdc++.h>
using namespace std;
struct pkt {
long long x, c;
bool jest;
};
const long long INF = 1000000000000000000;
void Dijkstra(long long k, vector<long long>& skoki,
set<pair<long long, long long> >& S, vector<pkt>& a) {
vector<long long> D(k, INF);
D[0] = 0;
set<pair<long lon... |
Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies.
Help him give n bags of candies to each brother so th... | import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int v[]=new int[n*n];
for (int i = 0; i < v.length; i++) {
v[i]=i+1;
}
for (int i = 0; i < v.length/2; i++) {
System.out.println(v[i]+" "+v[((n*n)-1)-i]);
... |
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c1 schoolchildren got 1 po... | m=int(input())
l=list(map(int,input().split()))
x,y=map(int,input().split())
theI=0
for i in range(len(l)):
first_sum=sum(l[0:i])
second_sum=sum(l[i:])
if (first_sum>=x and first_sum<=y) and (second_sum>=x and second_sum<=y):
theI=i+1
print(theI) |
Having unraveled the Berland Dictionary, the scientists managed to read the notes of the chroniclers of that time. For example, they learned how the chief of the ancient Berland tribe was chosen.
As soon as enough pretenders was picked, the following test took place among them: the chief of the tribe took a slab divid... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int N;
char a[51][51];
int c[51][51];
vector<vector<int> > g;
int mt[51 * 51][51 * 51];
int used[51 * 51];
int d[51 * 51];
int color[51 * 51];
void dfs(int first, int second) {
c[first][second] = N;
if (first > 0 && c[first - 1][second] == 0 &&
a[first -... |
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals ci. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type ci are nu... | #include <bits/stdc++.h>
int add(int a, int b) { return a == INT_MAX || b == INT_MAX ? INT_MAX : a + b; }
int dsu[100000];
int find(int i) { return dsu[i] < 0 ? i : (dsu[i] = find(dsu[i])); }
void join(int i, int j) {
i = find(i);
j = find(j);
if (i == j) return;
if (dsu[i] <= dsu[j]) {
dsu[i] += dsu[j];
... |
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new pol... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
long long p[n];
for (int q = 0; q < n; q++) cin >> p[q];
long long prefsum[n];
long long prefct[n];
long long suffsum[n];
long long suffct[n];
prefsum[0] = 0;
prefct[0] = 0;
... |
Jzzhu has a big rectangular chocolate bar that consists of n × m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements:
* each cut should be straight (horizontal or vertical);
* each cut should go along edges of unit squares (it is prohibited to divide any unit choc... | import java.util.Scanner;
public class Enter {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
long n = scanner.nextInt();
long m = scanner.nextInt();
long k = scanner.nextInt();
if (((n - 1) + (m - 1)) < k) {
System.out.print(... |
There is an easy way to obtain a new task from an old one called "Inverse the problem": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example.
Now ... | #include <bits/stdc++.h>
using namespace std;
int n;
struct node {
int t, nxt;
} edge[2000000];
int headline[2100], E;
inline void add(int f, int t) {
edge[E].t = t;
edge[E].nxt = headline[f];
headline[f] = E++;
}
int puzzle[2100][2100];
int lca[2100][2100];
bool visit[2100], flag;
int fsu[2100];
int ans[2100][... |
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.
First, each actor... | #include <bits/stdc++.h>
using namespace std;
const int MN = 100001;
int n, m, lo[2 * MN], hi[2 * MN], ans[MN], k[2 * MN], p[2 * MN];
set<pair<int, int> > actors;
set<pair<int, int> >::iterator lb;
bool lexLess(int i, int j) { return (lo[i] == lo[j]) ? i > j : lo[i] < lo[j]; }
int main() {
scanf("%d", &n);
for (int... |
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | n, m = [int(x) for x in input().split()]
s = 0
while(n < m):
s += 1 + (m % 2)
m = (m + m % 2) // 2
print(s + n - m)
|
As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish.
<image>
He has marked n distinct points in the plane. i-th point is point (xi, yi). He wants to put exactly one fish in each of these points such tha... | #include <bits/stdc++.h>
using namespace std;
const int M = 4e5 + 7;
const int N = 2e5 + 1;
vector<int> adj[M];
set<int> d[2];
int first[M];
map<pair<int, int>, bool> Hash;
void del(int u, int p) {
d[p].erase(u);
d[p ^ 1].insert(u);
}
void dfs(int v, int p) {
int i, u;
while (adj[v].size() > 0) {
u = adj[v]... |
Limak is a grizzly bear who desires power and adoration. He wants to win in upcoming elections and rule over the Bearland.
There are n candidates, including Limak. We know how many citizens are going to vote for each candidate. Now i-th candidate would get ai votes. Limak is candidate number 1. To win in elections, he... | #include <bits/stdc++.h>
using namespace std;
int n, has;
int a[113];
int main() {
scanf("%d%d", &n, &has);
n -= 1;
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int ans = 0;
while (true) {
sort(a, a + n, greater<int>());
if (has > a[0]) return printf("%d\n", ans), 0;
a[0] -= 1;
has += 1;
... |
For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions.
He knows that this year n competitions will take place. During the i-th competition the participant must as quickly as possible complete a ride along a straight lin... | #include <bits/stdc++.h>
using namespace std;
int Q, r, v, x, y;
const double eps = 1e-7;
bool check(double x, double L) {
double tmp = x / r;
return (x + 2 * r * fabs(sin(tmp / 2)) - L > eps);
}
int main() {
scanf("%d%d%d", &Q, &r, &v);
while (Q--) {
scanf("%d%d", &x, &y);
double L = 0, R = y - x, ans ... |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... |
if __name__ == '__main__':
c = int(input())
x = [5,4,3,2,1]
count = 0
while x!=[]:
m = max(x)
while c>=max(x):
c=c-m
count+=1
x.pop(0)
print (count)
|
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
string a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
map<string, long long> D;
vector<string> ans;
for (long long i = n - 1; i >= 0; i--) {
D[a[i]]++;
if (D[a[i]] == 1) {
ans.push_back(a[i]);
}
... |
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online.
The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order.
Due to the... | /*
* Code Author: Akshay Miterani
* DA-IICT
*/
import java.io.*;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
public class MainC {
static double eps=(double)1e-6;
static long mod=(int)1e9+7;
public... |
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that <image>). You are given two integers n and k and n closed intervals [li, ri] on OX axis an... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const double pi = acos(-1.0), eps = 1e-6;
void File() {
freopen("D:\\in.txt", "r", stdin);
freopen("D:\\out.txt", "w", stdout);
}
template <class T>
inline void read(T &x) {
char c = getchar();
x = 0;
while (... |
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m dif... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
//parameters: number of trees, number of groups <--- minimize cost
//T[t][g][c] - minimum cost if i color t-th tree with color c, and form g groups
//T[t][g][c] = min(cost[c] + T[t-1][g][c'] ... |
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation!
Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes ho... | mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
a,b,c=sorted(il(),reverse=True)
sm=0
if a!=b:
sm+=max(0,(a-b-1))+max(0,(a-c-1))
else:
sm+=max(... |
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".
The testtube is divided into n consecutive re... | #include <bits/stdc++.h>
using namespace std;
const long long N = 5e3 + 10, K = 30, MOD = 1e9 + 7;
long long fac[N + 1], inv[N + 1], dp[N][N], ps[N], R[K];
long long mul(long long a, long long b) {
a %= MOD, b %= MOD;
return (a * b) % MOD;
}
long long Pow(long long a, long long b) {
long long r = 1;
for (; b; b... |
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strang... | #include <bits/stdc++.h>
using namespace std;
const int INFTY = 20000000;
const int MAX = 500100;
const int MOD = 10000000;
void coutTab(long long* tab, int n) {
for (int i = 0; i < n; i++) {
cout << tab[i] << " ";
}
cout << "\n";
}
struct el {
long long a, b, h;
};
el me(long long a, long long b, long long... |
The good times at Heidi's library are over. Marmots finally got their internet connections and stopped coming to the library altogether. Not only that, but the bookstore has begun charging extortionate prices for some books. Namely, whereas in the previous versions each book could be bought for 1 CHF, now the price of ... | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
template <typename T>
inline void read(T &x) {
int ch = getchar();
x = 0;
bool f = false;
double d = 1;
for (; ch != '-' && (ch < '0' || ch > '9'); ch = getchar())
;
if (ch == '-') {
f = true;
ch = getchar();
}
for (; ... |
The first semester ended. You know, after the end of the first semester the holidays begin. On holidays Noora decided to return to Vičkopolis. As a modest souvenir for Leha, she brought a sausage of length m from Pavlopolis. Everyone knows that any sausage can be represented as a string of lowercase English letters, th... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000009;
int N, M, K, dp[100005][35];
char s[100005], t[100005];
long long hsh1[100005], hsh2[100005], power[100005];
inline long long substrHash(int l, int r, long long hsh[]) {
return (hsh[r] - (hsh[l - 1] * power[r - l + 1] % MOD) + MOD) % MOD;
}
inl... |
Soon the first year students will be initiated into students at the University of Berland. The organizers of the initiation come up with a program for this holiday. In their opinion, it would be good if the first-year students presented small souvenirs to each other. When they voiced this idea to the first-year student... | #include <bits/stdc++.h>
using namespace std;
pair<int, int> p[5005];
vector<int> v[5005];
int vis[5005];
int ans;
bool check(int a, int b) {
vis[a] = 1;
if (v[a].size() < ans) {
v[a].push_back(b);
return true;
}
for (vector<int>::iterator it = v[a].begin(); it != v[a].end(); it++) {
if (!vis[*it] &... |
Adieu l'ami.
Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.
The space is represented by a rectangular grid of n × m cells, arranged into n rows and m columns. The c-th cell in the r-th row is denoted by (r,... | #include <bits/stdc++.h>
using namespace std;
long long T[2510][2510][2];
long long base[2] = {2000000011, 1000000003};
long long p[2] = {10047, 10091};
long long pw[100010][2];
int val[2510][2510];
const int limit = 2;
void update(int u, int v, int id, int val) {
int cur = v;
for (; u < 2510; u += u & (-u)) {
... |
At the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.
Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but h... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long N = 1e6 + 11;
long long num[28];
long long num2[28];
char s[N], lm[N];
long long len;
long long fac[N];
long long inv[N];
long long finv[N];
long long powmod(long long a, long long b, long long mod) {
long long ans = 1;
whi... |
To your surprise, Jamie is the final boss! Ehehehe.
Jamie has given you a tree with n vertices, numbered from 1 to n. Initially, the root of the tree is the vertex with number 1. Also, each vertex has a value on it.
Jamie also gives you three types of queries on the tree:
1 v — Change the tree's root to vertex with ... | #include <bits/stdc++.h>
const int N = 100050;
long long addv[N * 4], sumv[N * 4];
inline void upd(int o, int l, int r) {
if (l != r)
sumv[o] = sumv[o << 1] + sumv[o << 1 | 1] + addv[o] * (r - l + 1);
else
sumv[o] = addv[o];
}
void add(int o, int l, int r, int L, int R, int x) {
if (r < L || R < l) return... |
Arkady wants to have a dinner. He has just returned from a shop where he has bought a semifinished cutlet. He only needs to fry it. The cutlet should be fried for 2n seconds, in particular, it should be fried for n seconds on one side and n seconds on the other side. Arkady has already got a frying pan and turn on fire... | #include <bits/stdc++.h>
using namespace std;
class MyQueue {
vector<pair<int, int> > a1, a2;
void clear_a1_stack() {
while (a1.size()) {
a2.push_back(a1.back());
if (a2.size() > 1)
a2.back().second = min(a2.back().first, a2[a2.size() - 2].second);
else
a2.back().second = a2.ba... |
k people want to split n candies between them. Each candy should be given to exactly one of them or be thrown away.
The people are numbered from 1 to k, and Arkady is the first of them. To split the candies, Arkady will choose an integer x and then give the first x candies to himself, the next x candies to the second ... |
(n, k, M, D) = map(int, raw_input().split())
p = n / M
ans = M * ((p-1)/k + 1)
for i in xrange(1,D+1):
split = (i-1)*k + 1
per = n / split
if per > M:
continue
ans = max(ans, i*per)
#print ans, i, i*per
print ans |
Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).
Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with ... | #include <bits/stdc++.h>
using namespace std;
using lli = long long int;
using pii = pair<int, int>;
using vi = vector<int>;
using vb = vector<bool>;
using vvi = vector<vector<int>>;
using vlli = vector<long long int>;
using vpii = vector<pair<int, int>>;
lli fast_exp(lli base, lli exp) {
lli res = 1;
while (exp > ... |
Arya Stark a headstrong, fiercely independent, disdains traditional women's pursuits, the younger daughter of Lord Eddard Stark and his wife Lady Catelyn Starkand who is often mistaken for a boy, becomes increasingly hardened and brutalized, and personally kills a number of men after the execution of her father. She co... | def path(a,x,y,goal):
c=0
if(x==goal and y==goal):return 1
if(x==n-1 and a[x][y+1]==1):c= path(a,x,y+1,goal)
if(c==0 and y==n-1 and a[x+1][y]==1):c= path(a,x+1,y,goal)
if(c==0 and x<n-1 and a[x+1][y]==1):c= path(a,x+1,y,goal)
if(c==0 and y<n-1 and a[x][y+1]==1):c= path(a,x,y+1,goal)
return c
t=input(... |
View Russian Translation
A wild chemist wants to prepare his mysterious mixture.
The recipe is very simple, he has already mixed all the necessary powders and the only remaining thing is to add exactly m nanoliters of any liquids.
In his lab he has n_1 bottles full of liquid called amulus of various capacities and... | import itertools
def valid(m,S):
W = []
for k in S:
if (m >= k):
m -= k
W.append(k)
return (m==0,W)
def solve():
m,n,N = map(int,raw_input().split())
S = map(int,raw_input().split()); S.sort(); S.reverse()
T = map(int,raw_input().split())
val = -1
for r in range(len(T)):
for z in itertools.co... |
Omar loves problem solving very much and today he faces the following problem.
Given a multiset A of N integers {a_1, a_2, \ldots, a_N} and an integer L, his task is to perform L operations indexed from 1 to L in the ascending order of their indices.
Let's consider the operation with index i. Moreover, for i > 1, le... | from sys import stdin
import math
n,l = map(int,stdin.readline().split())
a = [0]*(l+5)
b = [0] * (l+5)
x = map(int,stdin.readline().split())
x.sort()
y = [0]*n
for i in xrange(2,l+1):
if a[i]==0:
cur = i
while cur<=l:
tm = cur
co = 0
while tm%i==0:
tm/=i
co+=1
if co > b[cur]:
b[cur] = co
... |
More Unsullied army are joining Daenerys Stormborn of the House Targaryen, the First of Her Name, the Unburnt, Queen of Meereen,
Queen of the Andals and the Rhoynar and the First Men, Khaleesi of the Great Grass Sea, Breaker of Chains, and Mother of Dragons.
We know Grey Worm is the Commander of Unsullied and needs h... | from sys import stdin
t = int(stdin.readline())
for _ in xrange(t):
n = int(stdin.readline())
a = []
for __ in xrange(n):
m = int(stdin.readline())
b = map(int,stdin.readline().split())
for i in b:
a.append(i)
a.sort()
for i in a:
print i,
print "" |
"Not every love story has a happy ending!"- Little Jhool was certainly a con man, fooling people by telling them about their future, [The first problem!] but he loved his girl - truly! But, Big Jhool, his girlfriend, was shocked and had broken up with him after getting to know that Little Jhool was a con man. Now, our ... | noOfFlowers = input()
flowers = sorted(map(int, raw_input().split()))
petals = sum(flowers)
if petals % 2 == 1:
print petals
else:
for flower in flowers:
if flower % 2 == 1:
print petals - flower
exit()
print ":(" |
Students of Computer Science Department of SKIT have designed a basic Notepad for the purpose of studying the functioning and advance features in many other text editors.
It is a simple text editor that supports only the following two commands:
"type c" where c is a character: Append character c to the end of the curr... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
import sys
T = int(sys.stdin.readline())
for i in xrange(T):
N = int(sys.stdin.readline())
stack=[]
for j in xrange(N):
line = sys.stdin.readline().split()
tup = (int(line[0]),li... |
You are given two string S and T. Find the maximal length of some prefix of the string S which occurs in strings T as subsequence.
Input
The first line contains string S.
The second line contains string T.
Both strings consist of lowecase Latin letters.
Output
Output one integer - answer to the question.
Constraints... | first = raw_input()
second = raw_input()
length=0
pos=0
while(length < len(first) and pos < len(second)):
if (first[length] == second[pos]):
length += 1
pos += 1
print length |
Samu had come up with new type of numbers, she named them Special Coprime numbers. Special Coprime numbers follow a property : A number N is said to be Special Coprime if sum of its digits as well as the sum of the squares of its digits are coprime to each other.
Now she started counting numbers that are Special Cop... | from fractions import gcd
def solveDP(pos, sumD, sumSq, check):
if pos == -1:
return 1 if gcd(sumD, sumSq) == 1 else 0
if not check and dp[pos][sumD][sumSq] != -1:
return dp[pos][sumD][sumSq]
ans, endDig = 0, 0
endDig = digits[pos] if check else 9
for curDig in xrange(0, endDig +... |
Two letter strings are the strings consisting of only two letters "X" and "Y". A string is "super two letter string" if
a) It does not have leading "X" letters.
b) It does not contain P consecutive "X" letters.
Your task is to find total number of Super two letter strings of length N.
Input :
The first line contai... | mod = 1000000007
for tc in xrange(input()):
N, P = map(int, raw_input().split())
X = [0] * N
Y = [0] * N
if P >= N:
print 1 << N - 1
continue
Y[0] = 1
for i in xrange(1, P): # until P length no consecutive X
X[i] = X[i - 1] + Y[i - 1]
Y[i] = X[i - 1] + Y[i - 1]
for i in xrange(P, N):
X[i] = (X[i - ... |
Given the time shown by a wall clock, you have to output the internal angle between the minute and hour hand of the clock.
(Wall Clock displays a 12 hour format.)
For instance, if the time shown is 01:00 , the angle between the hands is 30 degrees.
Input : Time in HH:MM format
Output: The angle in degrees, correct u... | [h,m]=[int(i) for i in raw_input().split(':')];
mangle=6.0*m;
hangle=(h%12.0)*30+0.5*m;
deg=mangle-hangle;
if deg<0:
deg*=(-1);
print "%.6f"%min(deg,360-deg); |
For a positive integer X, let f(X) be the number of positive divisors of X.
Given a positive integer N, find \sum_{K=1}^N K\times f(K).
Constraints
* 1 \leq N \leq 10^7
Input
Input is given from Standard Input in the following format:
N
Output
Print the value \sum_{K=1}^N K\times f(K).
Examples
Input
4
O... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, ans = 0; cin >> n;
for(long long i = 1; i <= n; ++i) for(long long j = 1; i*j <= n; ++j) ans += i*j;
cout << ans << "\n";
return 0;
} |
Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)
Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded d... | A,B=map(int,input().split());v=max(A*25+1>>1,B*10);print(v if v<min(A*25+26>>1,B*10+10)else-1) |
Takahashi has N cards. The i-th of these cards has an integer A_i written on it.
Takahashi will choose an integer K, and then repeat the following operation some number of times:
* Choose exactly K cards such that the integers written on them are all different, and eat those cards. (The eaten cards disappear.)
For... | #include<bits/stdc++.h>
using namespace std;
int a[300001],b[300001]={0},c[300001]={0};
int u=0;
int n;
int k;
int judge(int q,int k)
{
int l=1,r=n,mid,ans;
while(l<=r)
{
mid=(l+r)/2;
if(b[mid]<q&&(mid==n||b[mid+1]>=q))
{
ans=mid;
break;
}
else if(b[mid]<q) l=mid+1;
else r=mid-1;
}
if((n-ans)*q+c... |
Takahashi and Aoki will play a game. They will repeatedly play it until one of them have N wins in total.
When they play the game once, Takahashi wins with probability A %, Aoki wins with probability B %, and the game ends in a draw (that is, nobody wins) with probability C %. Find the expected number of games that wi... | M=10**9+7
N,A,B,C=map(int,input().split())
f=[1]
for i in range(1,2*N):
f.append(f[-1]*i%M)
t=pow(A+B,M-2,M)
A*=t
B*=t
a=pow(A,N,M)
b=pow(B,N,M)
z=0
for i in range(N):
z+=(N+i)*100*pow(100-C,M-2,M)*f[N+i-1]*pow(f[N-1]*f[i],M-2,M)*(a+b)
z%=M
a=a*B%M
b=b*A%M
print(z)
|
There is a directed graph G with N vertices and M edges. The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i. G does not contain directed cycles.
Find the length of the longest directed path in G. Here, the length of a directed path is the num... | #include <bits/stdc++.h>
using namespace std;
#define ll int
const ll N = 1e5 + 5;
vector<ll> a[N];
ll n, m, u, v, ans[N];
ll dfs(ll x)
{
if (ans[x])
return ans[x];
for (ll e : a[x])
ans[x] = max(ans[x], dfs(e) + 1);
return ans[x];
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0);
... |
Snuke has an integer sequence A of length N.
He will freely choose an integer b. Here, he will get sad if A_i and b+i are far from each other. More specifically, the sadness of Snuke is calculated as follows:
* abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))
Here, abs(x) is a function that returns the... | n=int(input())
a=list(map(int,input().split()))
for i in range(n):
a[i]-=i+1
a.sort()
m=a[n//2]
sum=0
for x in a:
sum+=abs(x-m)
print(sum)
|
You have a circle of length C, and you are placing N arcs on it. Arc i has length L_i.
Every arc i is placed on the circle uniformly at random: a random real point on the circle is chosen, then an arc of length L_i centered at this point appears.
Note that the arcs are placed independently. For example, they may inte... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double ld;
#define mp make_pair
#define PI pair<int,int>
#define poly vector<int>
#define For(i,l,r) for(int i=(int)(l);i<=(int)(r);i++)
#define Rep(i,r,l) for(int i=(int)(r);i>=(int)(l);i--)
#define pb push_back
... |
We have a board with an H \times W grid. Each square in the grid is painted in black or white. The square at the i-th row from the top and j-th column from the left is black if the j-th character in S_i is `#`, and white if that character is `.`.
Snuke can perform the following operation on the grid any number of time... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper p... |
Takahashi has a lot of peculiar devices. These cylindrical devices receive balls from left and right. Each device is in one of the two states A and B, and for each state, the device operates as follows:
* When a device in state A receives a ball from either side (left or right), the device throws out the ball from the... | #include<bits/stdc++.h>
using namespace std;
#define RI register int
const int N=200005;
int n,K,tag,l,r,a[N*3];char S[N];
void print() {for(RI i=l;i<=r;++i) putchar(a[i]^tag?'A':'B');}
int main()
{
scanf("%d%d",&n,&K);
scanf("%s",S+1);
for(RI i=1;i<=n;++i) a[i]=(S[i]=='A');
l=1,r=n,tag=0;
for(RI i=1;i<=n+n;++i) {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.