input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Points:10
The Indian Heights School believes that learning with the aid of technology is the fastest way to do so. It is a pioneer in innovation and virtual classrooms in the country. Keeping in accordance with its practices, the school wants to integrate software and automate various functions at the classroom level. ... | import sys
t=int(sys.stdin.readline())
for _ in range(0,t):
s=sys.stdin.readline().split()
n,r=int(s[0]),int(s[1])
x=1
if r>(n//2):
r=n-r
for i in range(1,r+1):
x=n*x
n-=1
x=x//i
print(x) |
The Head Chef is interested in studying interactions between his chefs . There are N chefs with ids 1 to N . Each chef trusts some of the other chefs . The relation of trust is one way . Also , a chef may trust chefs only with ids strictly greater than his/her id .A chef with id = i , trusts the chefs with next ni id... | n,b = map(int,raw_input().split())
a = [0]
for i in range(n):
a.append(int(raw_input()))
dp = []
ss = []
for i in range(n+2):
dp.append(0)
ss.append(0)
dp[b] = 1
ss[b] = 1
M = 1000000007
for i in range(b-1,0,-1):
dp[i] = (ss[i+1]-ss[i+a[i]+1])%M
ss[i] = (dp[i] + ss[i+1])%M
q = int(raw_input())
for i in rang... |
Problem Statement
Given a number , find whether it is a power of 2 or not
NOTE There is a limit in Source code.
Input
The first Line contains T , the no of test cases followed by T lines.
Each line has a integer X
Output
Output has T lines , with each line indicating whethet the number is a power of 2 or not(... | # Konrad Talik
T=input()
while T:
n=input()
while ((n%2)==0)and n>1:
n/=2
print int(n==1);T-=1 |
Sonya has an array a_1, a_2, …, a_n consisting of n integers and also one non-negative integer x. She has to perform m queries of two types:
* 1 i y: replace i-th element by value y, i.e. to perform an operation a_{i} := y;
* 2 l r: find the number of pairs (L, R) that l≤ L≤ R≤ r and bitwise OR of all integers in... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7, N = 1e5 + 7;
int n, m, x;
struct T {
long long ans;
vector<pair<int, int> > l, r;
T() {}
T(int val) {
l = r = {{val, 1}};
ans = val >= x;
}
};
vector<pair<int, int> > cmb(vector<pair<int, int> > a,
vecto... |
Consider a set of points A, initially it is empty. There are three types of queries:
1. Insert a point (x_i, y_i) to A. It is guaranteed that this point does not belong to A at this moment.
2. Remove a point (x_i, y_i) from A. It is guaranteed that this point belongs to A at this moment.
3. Given a point (x_i... | #include <bits/stdc++.h>
using namespace std;
map<long long, set<pair<long long, long long>>> points;
long long size_ = 0;
map<pair<long long, long long>, long long> cnt_dirs, on_line;
long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); }
void norm(pair<long long, long long>& p) {
long long d = g... |
There are n points on the plane, (x_1,y_1), (x_2,y_2), …, (x_n,y_n).
You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
I... | n = input()
points = []
for i in range(n):
x, y = map(int, raw_input().split())
points.append((x, y))
def possible(m):
for point in points:
# y = mid - x
if mid - point[0] <= point[1]:
return False
return True
low = 1
high = 2* (10**9)
ans = 1
while low <= high:
mid = (... |
Polycarp took n videos, the duration of the i-th video is a_i seconds. The videos are listed in the chronological order, i.e. the 1-st video is the earliest, the 2-nd video is the next, ..., the n-th video is the last.
Now Polycarp wants to publish exactly k (1 ≤ k ≤ n) posts in Instabram. Each video should be a part ... | #include <bits/stdc++.h>
using namespace std;
int n;
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, k;
cin >> n >> k;
vector<int> v(n);
long long sum = 0;
for (int i = 0; i < n; i++) {
cin >> v[i];
sum += v[i];
}
if (sum % k != 0)
cout << "No\n";
else {
int ... |
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
... | #include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
long long int lcm(long long int a, long long int b) {
return a * b / gcd(a, b);
}
long long int fexp(long long int a, long long int b) {
long long int ans = 1;
whil... |
You are given a tree with n nodes and q queries.
Every query starts with three integers k, m and r, followed by k nodes of the tree a_1, a_2, …, a_k. To answer a query, assume that the tree is rooted at r. We want to divide the k given nodes into at most m groups such that the following conditions are met:
* Each ... | #include <bits/stdc++.h>
using namespace std;
class FenwickTree {
public:
FenwickTree(int _n = 10) : n(_n), data(_n, 0) {}
void reset(int _n) {
n = _n;
data.resize(n);
data.assign(n, 0);
}
void put(int x, int v) {
for (; x < n; x |= x + 1) {
data[x] += v;
}
}
int get(int x) {
... |
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool p... | if __name__ == '__main__':
n = input()
a = list(map(int, input().split()))
b = [0]
for ai in a:
b.append(b[-1] + ai)
b.sort()
for i in range(1, len(b)):
if b[i - 1] + 1 != b[i]:
print(-1)
break
else:
zero_idx = b.index(0)
x = zero_... |
You have a garden consisting entirely of grass and weeds. Your garden is described by an n × m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either gras... | #include <bits/stdc++.h>
using namespace std;
int n, m, i = 0, y;
pair<int, int> take() {
char a;
int maxi = INT_MIN, mini = INT_MAX;
for (int j = 0; j < n; j++) {
cin >> a;
if (a == 'W' && mini == INT_MAX) {
mini = j;
y = i + 1;
}
if (a == 'W' && maxi < j) {
maxi = j;
y = ... |
You have a given picture with size w × h. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:
* A "+" shape has one center nonempty cell.
* There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other ... | def check(pic,row,col,h,w):
for i in range(row+1,h):
for j in range(w):
if j != col:
if pic[i][j] == '*':
return False
for i in range(row-1,-1,-1):
for j in range(w):
if j != col:
if pic[i][j] == '*':
... |
Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point x. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or righ... | from math import sqrt
x = abs(int(input()))
n = int((sqrt(1 + 8 * x) - 1) / 2)
k = (n * (n + 1)) // 2
if k == x: print(n)
else:
n += 1
k += n
if (k - x) % 2:
n += 1
k += n
print(n + (k - x) % 2)
else: print(n) |
Let's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that ho... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
int n, m;
struct NODE {
long long m1[10], m2[10];
NODE() {
for (int i = 0; i <= 9; i++) m1[i] = m2[i] = 2e10;
}
NODE operator+(const NODE& b) const {
NODE res;
for (int i = 0; i <= 9; i++) {
res.m1[i]... |
You are given a sequence a_1, a_2, ..., a_n, consisting of integers.
You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation.
For example,... | #include <bits/stdc++.h>
using namespace std;
long long dp[300005];
long long n, a[300005];
vector<long long> v;
long long maxm;
long long lft[300005], rgt[300005];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long t;
cin >> t;
while (t--) {
cin >> n;
v.clear();... |
You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.
You must paint a fence which consists of 10^{100} planks in two colors in the following way (suppose planks are numbered from ... |
import java.util.*;import java.io.*;import java.math.*;
public class Main
{
public static void process()throws IOException
{
long r=nl(),b=nl(),k=nl();
long a=Math.min(r, b);b=Math.max(r, b);long lcm=a*b/gcd(a,b);
long large_pt=lcm/b,small_pt=lcm/a-1;
long adj=(long)Math.ceil(small_pt/(lar... |
Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.
The exam consists of n problems that can be solved in T minutes. Thus, the exam begins at time 0 and ends at time T. Petya can leave the exam at any integer time from 0... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T>
inline bool chmax(T& a, T b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <class T>
inline bool chmin(T& a, T b) {
if (a > b) {
a = b;
return 1;
}
return 0;
}
const ll INF = 1e9;
const ll MOD = 1... |
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the fol... | mod=998244353
#import resource
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#import threading
#threading.stack_size(2**27)
import sys
#sys.setrecursionlimit(10**6)
#fact=[1]
#for i in range(1,100001):
# fact.append((fact[-1]*i)%mod)
#ifact=[0]*100001
#ifact[100000]=pow(fact[10000... |
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,... | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
in... |
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m... | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 19:21:12 2020
@author: user
"""
def solve(n,l):
c1=0
c2=0
for i in range(n):
if(i%2==0 and l[i]%2!=0):
c1+=1
elif(i%2!=0 and l[i]%2==0):
c2+=1
if(c1==c2):
print(c1)
else:
print(-1)
... |
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | #code
t=int(input())
while t>0:
n=int(input())
k=n/4
l=int(k)
if k==l:
for i in range(n-l):
print("9",end="")
for i in range(l):
print("8",end="")
print("")
else:
l+=1
for i in range(n-l):
print("9",end="")
for i in... |
You are given a positive integer k and an array a_1, a_2, …, a_n of non-negative distinct integers not smaller than k and not greater than 2^c-1.
In each of the next k seconds, one element is chosen randomly equiprobably out of all n elements and decreased by 1.
For each integer x, 0 ≤ x ≤ 2^c - 1, you need to find t... | #include <bits/stdc++.h>
using namespace std;
int const p = 998244353;
int pw(int x, int y) {
int res = 1;
while (y) {
if (y & 1) res = 1ll * res * x % p;
x = 1ll * x * x % p;
y >>= 1;
}
return res;
}
int a[65537], iv[65537], b[65537], sum[195], inv[65537], cnt[131075], st[195],
top, tmp[20], tm... |
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.
He's got problems wi... | #include <bits/stdc++.h>
using namespace std;
int n, m, ch[13][13], a[13][13], ans = 0;
char s99[] =
"AAABCCCD.\n.A.B.C.D.\nEABBBCDDD\nEEE.FG...\nEHFFFGGGI\n.HHHFGIII\nJH."
"KLLLMI\nJJJK.L.M.\nJ.KKKLMMM\n";
int w[4][3][3] = {{{1, 1, 1}, {0, 1, 0}, {0, 1, 0}},
{{1, 0, 0}, {1, 1, 1}, {1, 0, 0}},... |
Alice and Bob are playing a game. They have a tree consisting of n vertices. Initially, Bob has k chips, the i-th chip is located in the vertex a_i (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree.
The game consists of turns. Each turn, the following... | #include<bits/stdc++.h>
using namespace std;
const int maxn=3e5+5;
const int mod=1e9+7;
const int inf=1e9;
#define pb push_back
#define fi first
#define se second
#define all(x) (x).begin(),(x).end()
#define rep(i,a,n) for (int i=a;i<=n;i++)
#define per(i,a,n) for (int i=n;i>=a;i--)
typedef long long ll;
typedef double... |
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches ... | #include <bits/stdc++.h>
#include <ostream>
using namespace std;
using ll = long long;
#define SZ(x) (int)((x).size())
#define ALL(x) (x).begin(), (x).end()
#define RALL(x) (x).rbegin(), (x).rend()
#define TMAX(type) numeric_limits<type>::max()
#define TMIN(type) numeric_limits<type>::min()
#ifdef LOCAL
#define a... |
This is an interactive problem.
Alice and Bob are playing a game. There is n× n grid, initially empty. We refer to the cell in row i and column j by (i, j) for 1≤ i, j≤ n. There is an infinite supply of tokens that come in 3 colors labelled 1, 2, and 3.
The game proceeds with turns as follows. Each turn begins with A... | #include<bits/stdc++.h>
using namespace std;
#define ll long long
signed main(){
ll n, i, j, x, y;
cin >> n;
ll a[n+1][n+1];
vector<pair<ll,ll>> v1, v2;
bool f = 1;
for( i = 1 ; i <= n ; i++ ){
for( j = 1 ; j <= n ; j++ ){
if( f )
v1.push_back( { i, j } );
else
v2.push_back( { i, j } );
f ... |
This is an interactive problem.
There is a secret permutation p (1-indexed) of numbers from 1 to n. More formally, for 1 ≤ i ≤ n, 1 ≤ p[i] ≤ n and for 1 ≤ i < j ≤ n, p[i] ≠ p[j]. It is known that p[1]<p[2].
In 1 query, you give 3 distinct integers a,b,c (1 ≤ a,b,c ≤ n), and receive the median of \{|p[a]-p[b]|,|p[b]-p... | //#pragma GCC optimize ("Ofast")
//#pragma GCC target("avx2")
//#pragma GCC optimize("unroll-loops")
//#include <x86intrin.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
#include <bits/stdc++.h>
#define PI 3.141592653589793L
#define FAST ios::sync_with_stdio(false); cin.tie(NULL);... |
The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they f... | #include <bits/stdc++.h>
int count(int);
int n, deg[1000000];
int main(void) {
int i, maxsum = -1000000000;
scanf("%d\n", &n);
for (i = 0; i < n; i++) scanf("%d", °[i]);
for (i = 1; i * 3 <= n; i++) {
if (n % i) continue;
maxsum = (maxsum > count(i)) ? maxsum : count(i);
}
printf("%d\n", maxsum);... |
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.
We assume that the hash table consists of h cells numb... | #include <bits/stdc++.h>
using namespace std;
const int oo = 1 << 20;
const double PI = M_PI;
const double EPS = 1e-15;
const int MaxH = 200005;
int H, M, N;
int row[MaxH];
int col[MaxH];
int size[MaxH];
vector<set<int> > second;
map<int, pair<int, int> > pos;
set<int>::iterator k;
int main() {
scanf("%d%d%d", &H, &M... |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | import sys
def main():
n = float(sys.stdin.readline().strip())
juices = map(float, sys.stdin.readline().strip().split())
print "{0:.5f}\n".format(sum(juices) / n)
if __name__ == "__main__":
main() |
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).
<imag... | q=int(input())
w=int(input())
k=0
for i in range(q):
e=list(map(int,input().split()))
if (w in e) or ((7-w) in e):
print('NO')
k=1
break
if k==0:
print('YES') |
In the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 100000;
const double Epsilon = 1e-7;
inline int sign(const double &a) {
if (a < -Epsilon)
return -1;
else if (a > Epsilon)
return 1;
else
return 0;
}
inline int dblcmp(const double &a, const double &b) { return sign(a - b); }
struct point ... |
Dima and Anya love playing different games. Now Dima has imagined a new game that he wants to play with Anya.
Dima writes n pairs of integers on a piece of paper (li, ri) (1 ≤ li < ri ≤ p). Then players take turns. On his turn the player can do the following actions:
1. choose the number of the pair i (1 ≤ i ≤ n), ... | #include <bits/stdc++.h>
using namespace std;
int sg[1000 + 5], n, p, a[1000 + 5], tot = 0, s[1000 + 5], dp[1000 + 5][4];
void add(int &a, int b) { a += b, a %= 1000000007; }
int cal(int l, int r) {
return (p + p - l - r - 1) * 1ll * (r - l) / 2 % 1000000007;
}
int main() {
scanf("%d%d", &n, &p);
a[tot = 1] = ((2... |
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds.
Polar bears Alice and Bob each have caught some fish, and they are g... | #include <bits/stdc++.h>
using namespace std;
int a[110000];
int b[110000];
int main() {
vector<int> v;
int i, n, m, k;
cin >> n >> m >> k;
for (i = 0; i < n; ++i) cin >> a[i];
for (i = 0; i < m; ++i) cin >> b[i];
sort(a, a + n);
sort(b, b + m);
bool answer = false;
int it1 = 0, it2 = 0;
while (1) {... |
There is a new TV game on BerTV. In this game two players get a number A consisting of 2n digits. Before each turn players determine who will make the next move. Each player should make exactly n moves. On it's turn i-th player takes the leftmost digit of A and appends it to his or her number Si. After that this leftmo... | #include <bits/stdc++.h>
using namespace std;
int n;
string s;
long long w[20], dp[20][20];
int main() {
cin >> n >> s;
w[0] = 1;
for (int i = 1; i <= n; i++) w[i] = w[i - 1] * 10;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++) {
int x = s[2 * n - (i + j)] - '0';
if (i > 0) dp[i][j] =... |
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel.
When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the... | #include <bits/stdc++.h>
using namespace std;
long n, m, pos;
long long h[100005], r[100005];
char s[1200000];
long long i, j, mij;
long long getLongLong() {
long long ans = 0;
while (s[pos] == ' ') pos++;
while ((s[pos] >= '0') && (s[pos] <= '9')) {
ans = ans * 10 + s[pos] - '0';
pos++;
}
return (ans... |
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ...... | n, m = map(int, input().split())
l = list(map(int, input().split()))
els = []
for i in range(m):
els.append(int(input()))
b = set()
aux = [0]*n
cont = 0
for i in range(n-1, -1, -1):
if l[i] not in b:
b.add(l[i])
cont += 1
aux[i] = cont
for i in els:
print(aux[i-1]) |
Inna loves sweets very much. She has n closed present boxes lines up in a row in front of her. Each of these boxes contains either a candy (Dima's work) or nothing (Sereja's work). Let's assume that the boxes are numbered from 1 to n, from left to right.
As the boxes are closed, Inna doesn't know which boxes contain c... | #include <bits/stdc++.h>
using namespace std;
int s[100001][11];
int main() {
ios_base::sync_with_stdio(false);
memset((s), (0), sizeof(s));
int n, k, w;
cin >> n >> k >> w;
string str;
cin >> str;
for (int _n(min(k, n)), r(0); r < _n; r++) {
for (int i = r; i < n; i += k) {
s[i][r] = str[i] == ... |
The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessar... | import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Codeforces412B {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Integer[] a = new Integer[n];
int k = in.nextInt();
for (int i =... |
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother.
As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the ma... | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is ... |
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:
* Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.
* Each time Applema... | #include <bits/stdc++.h>
using namespace std;
const int M = 300010;
int n, p, a[M];
long long sum, ans;
int main() {
while (scanf("%d", &n) != EOF) {
sum = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
sum += a[i];
}
sort(a, a + n);
ans = sum;
p = 0;
while (p != n - 1) {... |
Bizon the Champion has recently finished painting his wood fence. The fence consists of a sequence of n panels of 1 meter width and of arbitrary height. The i-th panel's height is hi meters. The adjacent planks follow without a gap between them.
After Bizon painted the fence he decided to put a "for sale" sign on it. ... | #include <bits/stdc++.h>
using namespace std;
struct event {
int y, i, type;
event() {}
event(int y, int i, int type) : y(y), i(i), type(type) {}
bool operator<(const event &e) const {
if (y != e.y) return y > e.y;
return type < e.type;
}
};
struct seg {
int mx, l, r, f;
seg() {}
seg(int mx, int... |
Notice that the memory limit is non-standard.
Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline bool read(T &x) {
int c = getchar();
int sgn = 1;
while (~c && c<'0' | c> '9') {
if (c == '-') sgn = -1;
c = getchar();
}
for (x = 0; ~c && '0' <= c && c <= '9'; c = getchar()) x = x * 10 + c - '0';
x *= sgn;
return ~c;
}
stru... |
One Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.
We will call person a a subordinates of another person b, if either b is an immediate... | #include <bits/stdc++.h>
using namespace std;
const double inf = 1e15;
const int maxn = 2e5 + 0.5;
int n, a[maxn + 10];
vector<int> G[maxn + 10];
long long dp[maxn + 5][2];
void update(long long& x, long long val) {
if (val > x) x = val;
}
void dfs(int x) {
int siz = G[x].size();
dp[x][0] = 0;
dp[x][1] = -inf;
... |
Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.
Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple tre... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MAX = 100010;
const double eps = 1e-9;
long long int modexpo(long long int a, long long int b) {
long long int x = 1, y = a;
while (b > 0) {
if (b & 1) x = (x * y) % MOD;
y = (y * y) % MOD;
b >>= 1;
}
return x;
}
long l... |
You are given an array of positive integers a1, a2, ..., an × T of length n × T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array.
Input
The first line contains two space-separated integers: n, T (1 ≤ n ≤ 100, 1 ≤ T ≤ 107). The second li... | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new Main().run(in, out);
out.close();
}
public static long mod =... |
You are playing a board card game. In this game the player has two characteristics, x and y — the white magic skill and the black magic skill, respectively. There are n spell cards lying on the table, each of them has four characteristics, ai, bi, ci and di. In one move a player can pick one of the cards and cast the s... | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF605D extends PrintWriter {
CF605D() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF605D o = new CF605D(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
int[] tr;... |
Paul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3010;
int n, k, r, c;
vector<int> G[maxn];
struct point {
int x, y;
point() {}
} p[maxn];
vector<int> q;
bool cmp(int A, int B) {
if (p[A].x == p[B].x) return p[A].y < p[B].y;
return p[A].x < p[B].x;
}
int pre[maxn], nex[maxn], nexk[maxn];
int calc(... |
Little Petya is now fond of data compression algorithms. He has already studied gz, bz, zip algorithms and many others. Inspired by the new knowledge, Petya is now developing the new compression algorithm which he wants to name dis.
Petya decided to compress tables. He is given a table a consisting of n rows and m col... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int INF = 0x3f3f3f3f;
const long long INFF = 0x3f3f;
const double pi = acos(-1.0);
const double inf = 1e18;
const long long mod = 1e9 + 7;
const unsigned long long mx = 133333331;
inline void RI(int &x) {
char c;... |
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bit... |
import java.util.Scanner;
/**
* Created by user on 01.06.2016.
*/
public class C {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
long ans = 1;
for (int i = 0; i < s.length(); i++) {
int a = 0;
... |
Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with... | import java.util.Scanner;
public class Driver
{
public static int[][] ranges;
public static void main(String args[])
{
try
{
Scanner scanner = new Scanner(System.in);
int count = scanner.nextInt();
int[] bars = new int[count];
for(int i = 0;... |
Once Danil the student was returning home from tram stop lately by straight road of length L. The stop is located at the point x = 0, but the Danil's home — at the point x = L. Danil goes from x = 0 to x = L with a constant speed and does not change direction of movement.
There are n street lights at the road, each of... | #include <bits/stdc++.h>
using namespace std;
pair<int, int> a[200500];
pair<int, int> b[200500];
int main() {
int shit, n, p, t;
ios_base::sync_with_stdio(false);
cin >> shit >> n >> p >> t;
int pos = 0;
a[0] = {-t - 1, 0};
int tot = 1;
while (n--) {
int l, r;
cin >> l >> r;
while (pos + 1 < ... |
Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction <image> as a sum of three distinct positive fractions in form <image>.
Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that <image... | import java.io.*;
import java.util.*;
public class Main {
List<Long> divs(long n){
long half = n / 2 + (n % 2 == 0 ? 1 : 0);
List<Long> div = new ArrayList<Long>();
for(long i = 2; i < half; i++){
if(n % i == 0){
div.add(i);
div.add(n / i);
break;
}
}
ret... |
Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by n - 1 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it.
We define the distance from city x to city y as the xor of numbers attached to the citie... | #include <bits/stdc++.h>
using namespace std;
const int MOD = (int)1e9 + 7;
const int INF = (int)1e9;
const long long LINF = (long long)1e18;
const long double PI = acos((long double)-1);
const long double EPS = 1e-9;
inline long long gcd(long long a, long long b) {
long long r;
while (b) {
r = a % b;
a = b... |
A breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them.
The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playin... | import java.util.Scanner;
public class D78 {
static double R;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
R = sc.nextInt();
long ans = 0;
for (int i = 1; 1+1.5*i <= R; i++) {
double t = 0;
if (i % 2==0)
... |
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.
More formally, the guys take turns giving each ot... | import math
[a,b] = map(float,raw_input().split())
n = 1
while True:
if(a < (2*n-1)):
print "Vladik"
break
a -= (2*n-1)
if(b < 2*n):
print "Valera"
break
b -= 2*n
n += 1
|
One very important person has a piece of paper in the form of a rectangle a × b.
Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi × yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).
A very importa... | n,A,B=map(int,input().split())
arr=[]
for x in range(n):
i,j=map(int,input().split())
arr.append([i,j])
ans=int(0)
i=int(0)
j=int(0)
for i in range(n):
for j in range(i+1,n):
a=arr[i][0]
b=arr[i][1]
c=arr[j][0]
d=arr[j][1]
temp=a*b+c*d
if(temp<=ans):
... |
Real Cosmic Communications is the largest telecommunication company on a far far away planet, located at the very edge of the universe. RCC launches communication satellites.
The planet is at the very edge of the universe, so its form is half of a circle. Its radius is r, the ends of its diameter are points A and B. T... | #include <bits/stdc++.h>
using namespace std;
struct vec {
int x, y;
friend long long operator/(const vec& a, const vec& b) {
return 1LL * a.x * b.y - 1LL * a.y * b.x;
}
friend long long operator*(const vec& a, const vec& b) {
return 1LL * a.x * b.x + 1LL * a.y * b.y;
}
};
struct meg {
int g, x, y;
... |
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.
The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 5;
const int inf = 1e9 + 5;
int n, m;
string s;
vector<string> v;
bool check(string g) {
for (int i = 0; i < n; ++i) {
if (s[i] != '*') {
if (s[i] != g[i]) {
return false;
}
for (int j = 0; j < n; ++j) {
if (g[j... |
Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing mini... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n;
char mde[N];
char mde1[N >> 1];
char mde2[N >> 1];
struct nod {
int v;
int fr;
friend bool operator<(nod a, nod b) {
return (a.v == b.v) ? a.fr < b.fr : a.v < b.v;
}
} dp[N], g[N];
struct data {
int s;
int d;
int siz;
inlin... |
A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets.
Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouqu... | import java.util.*;
import java.lang.*;
import java.io.*;
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count1 = 0;
int count2 = 0;
for( int i = 0; i < n; ++i ) {
int tmp = sc.nextInt();
if( tm... |
Andrew's favourite Krakozyabra has recenly fled away and now he's eager to bring it back!
At the moment the refugee is inside an icy cave with n icicles dangling from the ceiling located in integer coordinates numbered from 1 to n. The distance between floor and the i-th icicle is equal to ai.
Andrew is free to choos... | #include <bits/stdc++.h>
using namespace std;
const int infinito = 1000000000;
void minimiza(int &a, int b) { a = min(a, b); }
const int tope = 1 << 19;
const int primero = 1 << 18;
void reset(int minimo[tope]) {
for (int i = tope - 1; i >= 0; i--) minimo[i] = infinito;
}
void insertar(int minimo[tope], int pos, int ... |
In the School of Magic in Dirtpolis a lot of interesting objects are studied on Computer Science lessons.
Consider, for example, the magic multiset. If you try to add an integer to it that is already presented in the multiset, each element in the multiset duplicates. For example, if you try to add the integer 2 to the... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeSet;
/*
3... |
Scooby is stuck in a cave in barren islands. Shaggy decided to play a prank on scooby.
in his ghostly voice shaggy asks a question to the scared scooby.
the ghost(shaggy) will make scooby's way out only if he answers the following problem.
since scooby is not a nerd help him get out of the cave. the question is as fo... | t = input();
while(t > 0):
n = input(); a = [int(i) for i in raw_input().split()]; s = 0;
for i in range(0, n): s += a[i];
print (pow(2, n - 1) * s) % 1000000007;
t -= 1; |
Aarav has just graduated from the university. Now he is going to travel along his country. More precisely: there are N cities with integer coordinates. His plan is to travel between each pair of the cities.
The distance between city A with coordinates (x1, y1) and city B with coordinates (x2, y2) is equal to |x1 - x2... | sum=0
q=1000000007
n = int(raw_input())
a1 = []
a2 = []
for i in range(n):
n1,n2 = raw_input().split()
a1.append(int(n1))
a2.append(int(n2))
a1.sort()
a2.sort()
for i in range(n-1,-1,-1):
sum=(sum+(n-1-2*(n-1-i))*a1[i])%q;
sum=(sum+(n-1-2*(n-1-i))*a2[i])%q;
print (sum)%q |
Each digit of a number is represented by a cluster of adjacent X, with spaces between neighboring clusters. The digit is determined by the number of X in the cluster. For example, the number 243 would be represented by the following pattern
-XX-XXXX-XXX-
So to represent 0 the pattern will be -- (2 dashes without a... | t=int(raw_input())
for _ in range(t):
arr=raw_input()
for i in range(len(arr)-1):
if arr[i]=='-' and arr[i+1]=='-':
arr=arr[0:i+1]+"0"+arr[i+1:]
arr=arr[1:-1]
arr=arr.split("-")
res=""
for word in arr:
if word == "0":
res+="0"
else:
res+=str(len(word))
print(res) |
Given an array A of N numbers, find the number of distinct pairs (i, j) such that j ≥i and A[i] = A[j].
First line of the input contains number of test cases T. Each test case has two lines, first line is the number N, followed by a line consisting of N integers which are the elements of array A.
For each test case p... | T = input()
for i in range(T):
N = input()
inparr = map(int, raw_input().split())
d = {}
for j in inparr:
if(j in d):
d[j]+=1
else:
d[j]=1
tot = 0
for k,v in d.items():
tot += v*(v+1)/2
print tot |
There are many ways to order a list of integers from 1 to n. For example, if n = 3, the list could be : [3\; 1\; 2].
But there is a special way to create another list from the given list of integers. In this list, position of integer i is the i-th number in the given list. So following this rule, the given list will ... | n=int(raw_input())
while n:
n=n-1
size=int(raw_input())
a=raw_input().split()
a=[int(i) for i in a]
b=list(xrange(size))
for i in list(xrange(size)):
b[a[i]-1]=i+1
if a==b:
print "inverse"
else:
print "not inverse" |
You are given a N x N square matrix of integers where each cell represents the amount of gold in it. You need to travel from the top left cell to the bottom right cell, and back, maximizing the amount of gold you collect as you pass by the cell following some constraints given below
You cannot use squares on the lead... | def main():
n = input()
l = []
m = []
for i in range(n):
str = raw_input()
spl = str.split()
l.append([])
m.append([])
for j in range(n):
l[i].append(int(spl[j]))
m[i].append(-999999999)
q = []
s = 0
q.append((0,... |
CodeswarBala found various ornaments in Btyeland. Each ornament is made up of various items, and each item is represented by a letter from 'a' to 'z'. An item can be present multiple times in a ornament . An item is called special item if it occurs at least once in each of the ornament.
Given the list of N ornaments... | noOfOrn = int(raw_input())
m = {}
count = 0
for c in range(1, noOfOrn + 1):
inp = raw_input()
count += 1
for k in inp:
if(m.has_key(k) == False):
m[k]= []
if(count not in m[k]):
m[k].append(count)
c = 0
for key in m.keys():
if(len(m[key]) == noOfOrn):
c += 1
print c |
Rani works at sweet shop and is currently arranging sweets i.e. putting sweets in boxes. There are some boxes which contains sweets initially but they are not full. Rani have to fill boxes completely thereby minimizing the total no. of boxes.
You are given N no. of boxes, their initial amount and total capacity in gram... | t=input()
while t:
t-=1
n=int(input())
ini=[]
tot=[]
ini=map(int, raw_input().split())
tot=map(int, raw_input().split())
c=0
for i in range(0,n):
c+=ini[i]
tot.sort()
tot=tot[::-1]
i=0
d=0
while i<n:
d+=tot[i]
if (d>=c):
break
i+=1
print (i+1) |
Our smart travel agent, Mr. X's current assignment is to show a group of tourists a distant city. As in all countries, certain pairs of cities are connected by two-way roads. Each pair of neighboring cities has a bus service that runs only between those two cities and uses the road that directly connects them. Each bus... | n,m=map(int,raw_input().split())
INF=-10000000
adj=[[INF for i in xrange(n+1)] for j in xrange(n+1)]
adj1=[[INF for i in xrange(n+1)] for j in xrange(n+1)]
for j in xrange(m):
a,b,c=map(int,raw_input().split())
adj[a][b]=int(c)
adj[b][a]=int(c)
adj1[a][b]=b
soruce,dest,num_ppl=map(int,raw_input().split(... |
There was a power value associated with each soldier of Ram’s troop. It was a known belief that if two soldiers could be paired such that their total power can be divided by 3 perfectly, the pairing becomes ultra-powerful. Ram was curious as to see how many such pairings were possible.
Help Ram find out the number of p... | t = int(raw_input())
while t:
n = int(raw_input())
arr = [int(i) for i in raw_input().split()]
cnt =0;
for i in range(n-1):
for j in range(i+1,n):
if not (arr[i]+arr[j])%3:
cnt+=1
print cnt
t-=1 |
There are N points on the 2D plane, i-th of which is located on (x_i, y_i). There can be multiple points that share the same coordinate. What is the maximum possible Manhattan distance between two distinct points?
Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-... | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<long long> u,v;
int main(){
int i,n; cin >> n;
for(i=0;i<n;i++){
long long x,y; cin >> x >> y;
u.push_back(x + y),v.push_back(x - y);
}
sort(u.begin(),u.end()); sort(v.begin(),v.end());
long long a... |
AtCoder Inc. holds a contest every Saturday.
There are two types of contests called ABC and ARC, and just one of them is held at a time.
The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.
Given a string S representing the type of the contest held last week, print the str... | #include<iostream>
using namespace std;
int main()
{
string s;
cin>>s;
if(s[1]=='B')cout<<"ARC";
if(s[1]=='R')cout<<"ABC";
} |
Given are two sequences a=\\{a_0,\ldots,a_{N-1}\\} and b=\\{b_0,\ldots,b_{N-1}\\} of N non-negative integers each.
Snuke will choose an integer k such that 0 \leq k < N and an integer x not less than 0, to make a new sequence of length N, a'=\\{a_0',\ldots,a_{N-1}'\\}, as follows:
* a_i'= a_{i+k \mod N}\ XOR \ x
F... | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = a + a[:-1]
da = [a[i] ^ a[i+1] for i in range(len(a) - 1)]
db = [b[i] ^ b[i+1] for i in range(len(b) - 1)]
fail = [0 for i in range(len(da))]
fail[0] = -1
p = 0
for q in range(2, len(da)):
while p >= 0 and da[q-1] != da[... |
Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).
Constraints
* 1 \leq N \leq 10^5
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of positive integers less than ... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
int r = 0;
for(int i = 1; i <= N; i++) {
int l = String.valueOf(i).length();
if(l % 2 != 0) r++;
}
System.out.println(r);
}
}
|
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent chara... | N = int(input())
memo = [{} for i in range(N + 1)]
MOD = 10 ** 9 + 7
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i], t[i - 1] = t[i - 1], t[i]
if "".join(t).count("AGC") >= 1:
return False
return True
def dfs(cur, l... |
We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i.
In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y).
We will consider a directed cycle in thi... | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N=1e6;
const LL INF=1e16;
int n;
LL now[N+10],sum[N+10],f[N+10];
struct data {
LL x,y;
}a[N+10];
bool cmp1(data p,data q) {
return p.x<q.x;
}
bool cmp2(data p,data ... |
Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process:
First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation:
* If p_i = 1, do nothing.
* If p_i \neq 1, let j' be the largest j such that p_j < p_i. S... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n; scanf("%d", &n);
vector<vector<int>> g(n);
for (int i = 0; i < n - 1; ++i) {
int u, v; scanf("%d%d", &u, &v);
u--, v--;
g[u].push_back(v);
g[v].push_back(u);
}
vector<int> dep(n), fa(n);
function<... |
We have a long seat of width X centimeters. There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length Y centimeters.
We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least Z centimeters between two... | x,y,z=map(int,input().split())
x-=z
print(x//(z+y)) |
For a positive integer n, we denote the integer obtained by reversing the decimal notation of n (without leading zeroes) by rev(n). For example, rev(123) = 321 and rev(4000) = 4.
You are given a positive integer D. How many positive integers N satisfy rev(N) = N + D?
Constraints
* D is an integer.
* 1 ≤ D < 10^9
In... | #include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <string>
using namespace std;
typedef long long int ll;
typedef pair <int,int> P;
ll rt[30];
int main()
{
ll D;
scanf("%lld",... |
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i i... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3010,mod = 1e9 + 7;
int n,m,sum[maxn],R[maxn],f[maxn][maxn];
char s[maxn];
int main()
{
scanf("%d%d",&n,&m);
scanf("%s",s + 1);
for (int i = 1; i <= n; i++)
{
sum[i] = sum[i - 1] + s[i] - '0';
R[i] = i;
}
R[n + 1] ... |
Snuke got a grid from his mother, as a birthday present. The grid has H rows and W columns. Each cell is painted black or white. All black cells are 4-connected, that is, it is possible to traverse from any black cell to any other black cell by just visiting black cells, where it is only allowed to move horizontally or... | #include <bits/stdc++.h>
using namespace std;
#define int long long
const int P = 1e9 + 7;
int h, w, cnt, s1, s2, f1, f2, k;
char s[2050][2050];
long long quickpow(long long base,long long to)
{
if(to<=0)return 1;
if(to==1)return base;
long long mid=quickpow(base,to>>1);
if(to&1)return mid*mid%P*base%P;... |
There is a frequency operation in the conversion operation of a finite number sequence. The conversion result of the sequence $ S = \\ {s_1, s_2, ... s_n \\} $ is a sequence of the same length. If the result is $ C = \\ {c_1, c_2, ..., c_n \\} $, then $ c_i $ represents the number of $ s_i $ in the sequence $ S $.
For... | #include <iostream>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#define loop(i,a,b) for(int i=a; i<b; i++)
#define rep(i,b) loop(i,0,b)
#define all(c) (c).begin(), (c).end()
using namespace std;
typedef vector<int> vi;
int main(){
int ... |
Mobile phones are equipped with a function that displays input candidates in order to efficiently input texts such as emails. This records frequently used words and presents words that have the entered letters as initial letters as input candidates. For example, if you usually enter the word "computer" a lot, just ente... | #include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
using namespace std;
#define foreach(i,c) for(__typeof__((c).begin()) i=(c).begin();i!=(c).end();++i)
int main()
{
for(int n;cin>>n,n;){
cin.ignore();
vector<string> words;
while(n--){
string line; g... |
Two players, A and B, play the game using cards with numbers from 0 to 9. First, the two arrange the given n cards face down in a horizontal row. After that, the two players turn their cards face up one by one from the left, and the owner of the card with the larger number takes the two cards. At this time, the sum of ... | while True:
n = int(input())
if n == 0:
break
pointA, pointB = 0, 0
for i in range(n):
cardA, cardB = map(int, input().split())
if cardA == cardB:
pointA += cardA
pointB += cardB
elif cardA > cardB:
pointA += cardA + cardB
else:... |
The University of Aizu started a new system for taking classes in 2009. Under the new system, compulsory subjects have been abolished, and subjects can be freely selected in consideration of each course.
However, not all courses can be taken unconditionally, and in order to take a specific course, it is necessary to m... | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
#define LET(name, value) __typeof(value) name = value
#define REP(i, n) for (int i = 0; i < (int)(n); ++i)
#define FOR(i, a, b) for (int i = (a); i < (int)(b); ++i)... |
Professor Random, known for his research on randomized algorithms, is now conducting an experiment on biased dice. His experiment consists of dropping a number of dice onto a plane, one after another from a fixed position above the plane. The dice fall onto the plane or dice already there, without rotating, and may rol... | #include <bits/stdc++.h>
#define chmin(a, b) ((a)=min((a), (b)))
#define chmax(a, b) ((a)=max((a), (b)))
#define fs first
#define sc second
#define eb emplace_back
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef tuple<int, int, int> T;
const ll MOD=1e9+7;
const ll INF=1e18;
int dx[]={... |
The goddess of programming is reviewing a thick logbook, which is a yearly record of visitors to her holy altar of programming. The logbook also records her visits at the altar.
The altar attracts programmers from all over the world because one visitor is chosen every year and endowed with a gift of miracle programmin... | #include <bits/stdc++.h>
using namespace std;
#define REP(i,a,b) for(int i=a;i<(int)b;i++)
#define rep(i,n) REP(i,0,n)
struct data {
int m1,d1,h,m;
int time() const { return h*60+m; }
bool operator < (data const& d) const {
if(m1!=d.m1) return m1<d.m1;
if(d1!=d.d1) return d1<d.d1;
return h != d.h ?... |
Problem
In 19XX, the Allied Forces were formed in n countries. Each country belonging to the Allied Forces has set up one or more bases in the country to protect itself from the invasion of enemy forces and is on the alert. Figure 1 shows an example of an Allied country, where the rectangle represents each country and... | #define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <queue>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <cctype>
#include <cassert>
#define rep(i,n) f... |
You were the master craftsman in the stone age, and you devoted your life to carving many varieties of tools out of natural stones. Your works have ever been displayed respectfully in many museums, even in 2006 A.D. However, most people visiting the museums do not spend so much time to look at your works. Seeing the si... | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
//Rock Man
public class Main{
int n, COUNT, INF = 1<<29, res;
List<E>[] edge, rev;
Map<String, Integer> ref;
int get(String s){
if(ref.containsKey(s))return ref.get(s);
ref.put(s, COU... |
Nathan O. Davis is challenging a kind of shooter game. In this game, enemies emit laser beams from outside of the screen. A laser beam is a straight line with a certain thickness. Nathan moves a circular-shaped machine within the screen, in such a way it does not overlap a laser beam. As in many shooters, the machine i... | #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-10)
#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,... |
Kita_masa is planning a trip around the world. This world has N countries and the country i has M_i cities. Kita_masa wants to visit every city exactly once, and return back to the starting city.
In this world, people can travel only by airplane. There are two kinds of airlines: domestic and international lines. Since... | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const do... |
As a proud hero, you are finally about to reach the Demon King. However, in order to reach the throne where the Demon King is, you must clear the final map prepared by the Demon King.
In this map, everything changes like a two-dimensional plan view from the sky. Humans transform into just points on this map. The map i... | #include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <deque>
#include <complex>
#include <stack>
#include ... |
G: Dungeon of Cards
story
This is a wonderland hydrangea. It is said that gold and silver treasures sleep in the labyrinth of cards located in the remote area of Ajifurai. As soon as the curious Aizu Nyan heard this legend, he decided to take his friend Wi and go on a journey to the Labyrinth of Cards.
The next da... | #include <bits/stdc++.h>
#define MAX_V 40
#define INF 1e5
using namespace std;
/*テヲツ慊?・ツーツ湘ィツイツサテァツ板ィテヲツオツ?テ」ツδッテ」ツδシテ」ツつキテ」ツδ」テ」ツδォテ」ツδ陛」ツδュテ」ツつ、テ」ツδ嘉、ツスツソテァツ板ィ) O(F|V||E|)*/
//ティツセツコテ」ツつ津ィツ。ツィテ」ツ?凖ヲツァツ凝ゥツ??、ツスツ?ティツ。ツ古」ツ?催・ツ?暗」ツ??・ツョツケテゥツ?湘」ツ??」ツつウテ」ツつケテ」ツδ暗」ツ??ゥツ??ィツセツコ)
struct edge{int to, cap,cost,rev;};
int V; ... |
problem
A dance party with $ N $ people is held at a dance hall. The dance hall is divided into $ H $ vertical and $ W $ horizontal grids, with $ (0,0) $ in the upper left, $ r $ squares from the top, and $ c $ squares from the left. The coordinates of the grid of the eyes are expressed as $ (r, c) $. The initial posi... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
#define EACH(i,a) for (auto& i : a)
#define FOR(i,a,b) for (ll i = (a); i < (b); ++i)
#define RFOR(i,a,b) for (ll i=(b)-1; i>=a;i--)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) RFOR(i,0,n)
#define pb push_back
#define ALL(a... |
Mysterious button
You decide to earn coins in a dungeon on the outskirts of town. There are N rooms in this dungeon, numbered from 1 to N. In addition, there are mysterious buttons called "coin button", "escape button", and "warp button" in the dungeon. The details of each button are as follows.
* There is exactly on... | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
template<typename T,T MOD = 1000000007>
struct Mint{
static constexpr T mod = MOD;
T v;
... |
Range Min of Max Query
Given a sequence of integer pairs (a_1, b_1), (a_2, b_2), .., (a_N, b_N).
Handle two types of queries.
The first type of query adds X to a_L, a_ {L + 1}, .., a_R.
The second type of query finds the minimum values of max (a_L, b_L), max (a_ {L + 1}, b_ {L + 1}), .., max (a_R, b_R).
input
... | #include <iostream>
#include <vector>
#include <array>
#include <list>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <memory>
#include <cmath>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <numeri... |
The range search problem consists of a set of attributed records S to determine which records from S intersect with a given range.
For n points on a plane, report a set of points which are within in a given range. Note that you do not need to consider insert and delete operations for the set.
Constraints
* 0 ≤ n ≤ 5... | #include <iostream>
#include <iomanip>
#include <vector>
#include <set>
#include <string>
#include <queue>
#include <algorithm>
#include <map>
#include <cmath>
#include <list>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define rep(i, n) for (int i = 0; i < n; i++)
using namespace std;
ty... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.