input
stringlengths
29
13k
output
stringlengths
9
73.4k
Problem Aizu decided to play a game using a prime number $ P $, a set of natural numbers $ G $, and a natural number $ A $. First, Aizu writes $ 1 $ on the paper at hand. After that, perform the following series of operations any number of times. * Select one element from $ G $. Let this be $ g $. * Write a new prod...
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<pair<long long, long long> > prime_factorize(long long n) { vector<pair<long long, long long> > res; for (long long p = 2; p * p <= n; ++p) { if (n % p != 0) continue; int num = 0; while (n % p == 0) ...
Find the diameter of a convex polygon g. In other words, find a pair of points that have maximum distance between them. Constraints * 3 ≤ n ≤ 80000 * -100 ≤ xi, yi ≤ 100 * No point in the g will occur more than once. Input n x1 y1 x2 y2 : xn yn The first integer n is the number of points in g. In the following ...
#include <bits/stdc++.h> #define rep(i, a, b) for(int i = (a); i <= (b); ++i) #define per(i, a, b) for(int i = (a); i >= (b); --i) #define debug(x) cerr << #x << ' ' << x << endl; using namespace std; typedef long long ll; const int mod = 1e9+7; const int MAXN = 2e5 + 7; const double EPS=1e-8; inline int sign(double a...
Write a program which reads $n$ items and sorts them. Each item has attributes $\\{value, weight, type, date, name\\}$ and they are represented by $\\{$ integer, integer, upper-case letter, integer, string $\\}$ respectively. Sort the items based on the following priorities. 1. first by value (ascending) 2. in case of...
#include<iostream> #include<tuple> #include<algorithm> using namespace std; int main(){ int n, v, w; char t; long long d; string s; cin >> n; tuple<int, int, char, long long, string> goods[n]; for(int i = 0;i < n;i++){ cin >> v >> w >> t >> d >> s; goods[i] = make_tuple(v, w, t, d, s); } ...
There's an array A consisting of N non-zero integers A1..N. A subarray of A is called alternating if any two adjacent elements in it have different signs (i.e. one of them should be negative and the other should be positive). For each x from 1 to N, compute the length of the longest alternating subarray that starts at...
def opposite(a,b): if(a<0): return b>=0 else: return b<0 def func(a): a2 = [1]*len(a) count = 1 for i in range(len(a)): if(count>1): count = count-1 a2[i] = count else: j = i while(j<len(a)-1 and opposite(a[j],a[j+1])):...
The chef is fond of triangles. He has a task for you. You are given n point out of which only k are collinear. Find the number of triangles that can be formed from these n points. You have to perform the above task for a number of test cases.   Input The first line of input contains the number of test cases, t. Then ...
T = (int)(raw_input()) while T: n,k=map(int,raw_input().split()) print n*(n-1)*(n-2)/6-k*(k-1)*(k-2)/6 T-=1
One of the most fundamental concepts learnt by a novice programmer is generation of Fibonacci Series. The Fibonacci Series is known to be of the form 0 1 1 2 3 5 8 13... etc. Usually a recursive approach to solve the problems is applied. The problem with the usual recursive approach is that multiple calls are made to c...
import sys t=int(sys.stdin.readline()) while t!=0: x=raw_input().split() f1=int(x[0]) f2=int(x[1]) n=int(x[2]) if n==1: print f1 else: if n==2: print f2 else: for i in range (2,n): f=f1+f2 f1=f2 f2=f ...
Eugene loves sequences, especially arithmetic progressions. One day he was asked to solve a difficult problem. If a sequence of numbers A1, A2, ... , AN form an arithmetic progression A, he was asked to calculate sum of F(Ai), for L ≤ i ≤ R. F(X) is defined as: If X < 10 then F(X) = X. Else F(X) = F(sum_of_digits(X))....
''' Created on 21-Nov-2015 @author: Lenovo ''' def F(x): return (x-1)%9+1 T =input() for t in range(T): A, D, L, R = map(int, raw_input().split()) L-=1;R-=1; sum_per9 =0; for i in range(1,10): sum_per9 +=F(A+D*i) ans =0 while (R-L+1)%9 != 0: ans +=F(A+D*R) R -=1 ans ...
Given a sequence of numbers, find the absolute difference between the number of odd numbers and number of even numbers in a given sequence. Input The first line will contain the number of numbers in the sequence. And the second line will contain the sequence itself i.e. a series of integers separated by a space Ou...
#!/usr/bin/python count = int(raw_input()) nums = raw_input().split() odd = 0 even = 0 for n in nums: if int(n) % 2 == 0: even = even + 1 else: odd = odd + 1 print abs(odd - even)
For Turbo C++ Users : Read the following document before attempting the question : Problem description. HM has a tree-cutting facility. He also paint logs to sell them for treehouse-making. His assistant Deepsaggas is a student of IIIT-Delhi. He loves competitive programming very much. He has been working hard and...
#Enter your code here a=raw_input().split() n=int(a[0]) q=int(a[1]) a=raw_input().split() for i in xrange(n): a[i]=int(a[i]) hola=[0] hola.append(a[0]) for i in range(1,n): a[i]+=a[i-1] hola.append(a[i]) #print hola for i in xrange(q): ra=raw_input().split() l=int(ra[0]) r=int(ra[1]) #print ...
A sequence a_1, a_2, ..., a_n is called good if, for each element a_i, there exists an element a_j (i ≠ j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d). For example, the following sequences are good: * [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum ...
#include <bits/stdc++.h> using namespace std; vector<long long> b; void solve() { b.push_back(1); b.push_back(2); long long val = 4; for (int i = 2; i < 33; i++) { b.push_back(val); val = val * 2; } return; } int main() { int n; cin >> n; vector<int> a(n); solve(); map<int, int> mp; for ...
You are given a string t consisting of n lowercase Latin letters and an integer number k. Let's define a substring of some string s with indices from l to r as s[l ... r]. Your task is to construct such string s of minimum possible length that there are exactly k positions i such that s[i ... i + n - 1] = t. In other...
n, k = map(int, input().split()) s = input() ans = None for i in range(1, n): prefix = s[0:n-i] suffix = s[i:n] if prefix == suffix: ans = prefix ans += s[n-i:n] * k break if ans is None: ans = s * k print (ans)
There are n cities in the Kingdom of Autumn, numbered from 1 to n. People can travel between any two cities using n-1 two-directional roads. This year, the government decides to separate the kingdom. There will be regions of different levels. The whole kingdom will be the region of level 1. Each region of i-th level s...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, fu = 0; char ch = getchar(); for (; ch < 48 || ch > 57; ch = getchar()) fu |= (ch == '-'); for (; ch > 47 && ch < 58; ch = getchar()) x = x * 10 + ch - '0'; return fu ? -x : x; } inline void add(int &x, const int &y) { x += y; x ...
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely. Lesha knows that today he can study for at most a hours, and he will have b hours to study tomorro...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); int a, b; vector<int> ansa, ansb; void solve() { int cnt = 0; int k = 0; while (cnt + k + 1 <= a + b) { k++; cnt += k; } ansa.clear(); ansb.clear(); for (int i = k; i >= 1; i--) { if (i <= a) { a -= i; ansa...
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left. There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative inte...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int maxn = 1000000; long long b[maxn]; long long ans[maxn]; int main() { int n; cin >> n; for (int i = 0; i < n / 2; i++) cin >> b[i]; long long l, r; l = 0, r = b[0]; ans[0] = l; ans[n - 1] = r; for (int i = 1; i < n / 2; i...
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
#include <bits/stdc++.h> using namespace std; long long int counter[2][((long long int)(1 << 20) + 2)]; int main() { counter[1][0] = 1; long long int n; cin >> n; long long int x = 0; long long int ans = 0; for (long long int i = 0; i < n; i++) { long long int f; cin >> f; x ^= f; ans += cou...
This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a...
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ impor...
You are a car race organizer and would like to arrange some races in Linear Kingdom. Linear Kingdom has n consecutive roads spanning from left to right. The roads are numbered from 1 to n from left to right, thus the roads follow in the order of their numbers' increasing. There will be several races that may be held o...
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; const int MX = 200010; const int N = MX + 10; const long long oo = 2e18; long long seg[4 * N], lazy[4 * N], dp[N]; int n, m, a, b, p, cost[N]; vector<pair<int, int> > ed[N]; void push(int n, int s, int e) { seg[n] += lazy[n]; if (s != e) { l...
Let f_{x} = c^{2x-6} ⋅ f_{x-1} ⋅ f_{x-2} ⋅ f_{x-3} for x ≥ 4. You have given integers n, f_{1}, f_{2}, f_{3}, and c. Find f_{n} mod (10^{9}+7). Input The only line contains five integers n, f_{1}, f_{2}, f_{3}, and c (4 ≤ n ≤ 10^{18}, 1 ≤ f_{1}, f_{2}, f_{3}, c ≤ 10^{9}). Output Print f_{n} mod (10^{9} + 7). Exam...
import java.util.*; import java.io.*; public class codeforces { public static long M = 1000000007; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); long n = in.nextLong(); long f1 = in.nex...
Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, i...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-9; const int mod = (int)1e+9 + 7; const double pi = acos(-1.); const int maxn = 100100; string s, t; long double check(string s) { int g = 0, t = 0, f = 0, c = 0; for (unsigned int i = 0; i < s.length(); i++) { if (s[i] == 'X') t++; e...
Bob Bubblestrong just got a new job as security guard. Bob is now responsible for safety of a collection of warehouses, each containing the most valuable Bubble Cup assets - the high-quality bubbles. His task is to detect thieves inside the warehouses and call the police. Looking from the sky, each warehouse has a sha...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; const long double PI = acosl(-1); mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); struct point { long double x, y; bool zin = false; long double val = 0; point() {} point(long double x, long double y) : x(x), y(y)...
Suppose you are stuck on a desert island. The only way to save yourself is to craft a wooden raft and go to the sea. Fortunately, you have a hand-made saw and a forest nearby. Moreover, you've already cut several trees and prepared it to the point that now you have n logs and the i-th log has length a_i. The wooden ra...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; const int maxN = 5 * (int)1e5 + 100; int pref[maxN]; int n; int a[maxN]; int get(int l, int r) { r = min(r, maxN - 1); if (l > r) return 0; if (l == 0) return pref[r]; return pref[r] - pref[l - 1]; } long long cnt = 0; bool can(int x, int ...
You're given a tree with n vertices. The color of the i-th vertex is h_{i}. The value of the tree is defined as ∑_{h_{i} = h_{j}, 1 ≤ i < j ≤ n}{dis(i,j)}, where dis(i,j) is the number of edges on the shortest path between i and j. The color of each vertex is lost, you only remember that h_{i} can be any integer fro...
#include <bits/stdc++.h> using namespace std; const int Mod = 1e9 + 7; int n, Link[100010], sum[100010], dep[100010], F[100010], son[100010], T = 0, dfn[100010], top[100010], cnt = 0; int inv[100010]; struct das { int v, nex; } e[200010]; struct dsa { int L, R, id, len; } a[100010]; struct SubTree { int l, r,...
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format! Your task is to find the number of minutes before the New Year. You know that New Year comes when the...
for _ in range(int(input())): h,m = map(int,input().split()) print((24*60)-(h*60+m))
This is the easy version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved. n wise men live in a beautiful city. Some of them know each other. For each of the n! possible permutations p_1, p_2, …, p_n of the wise...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") using namespace std; using ll = long long int; const int MOD = 998244353; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; vector<bitset<15>> G(n); vector<ll> ans(1 << (n - 1)); for (int i = 0; i < n; ++i) { string x; cin >> ...
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you ha...
#include <bits/stdc++.h> using namespace std; const int maxn = 100005; const long long mod = 1e9 + 7; int n; long long a[maxn], sol[maxn], aux[maxn]; long long delta(int i, long long x) { return a[i] - 3 * x * x + 3 * x - 1; } long long bb(long long d, int id) { if (a[id] - 1 <= d) return 0; long long ini = 0, fin ...
The store sells n beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them. A necklace is a set of beads connected in a circle. For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemb...
#include <bits/stdc++.h> using namespace std; const long long INF = 1e9 + 7; const int N = 2e2 + 10; int cnt[N]; int gcd(int n, int m) { return m == 0 ? n : gcd(m, n % m); } int main() { int ncase; scanf("%d", &ncase); while (ncase--) { int n, k; scanf("%d%d", &n, &k); string str; cin >> str; ...
After returning to shore, uncle Bogdan usually visits the computer club "The Rock", to solve tasks in a pleasant company. One day, uncle Bogdan met his good old friend who told him one unusual task... There are n non-intersecting horizontal segments with ends in integers points on the plane with the standard cartesian...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Objects; import java.util.List; import java.util.TreeMap; import java.util....
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: * The array consists of n distinct positive (greater than 0) integers. * The array contains two elements x and y (these elements are known for you) such that x < y. * If you sort the arr...
T = int(input()) for t in range(T): n, x, y = [int(i) for i in input().split()] found_flag = False for d in range(1,51): if (y-x) % d == 0: for a in range(1, x+1): if (x-a) % d == 0 and (y-a) % d == 0 and a + (n-1)* d >= y: ans = [a+i*d for i in range(...
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apar...
for _ in range(int(input())): n = int(input()) if n%3==0:print(n//3,0,0) elif n%5==0:print(0,n//5,0) elif n%7==0:print(0,0,n//7) elif n%3==1 and n>7:print((n-7)//3,0,1) elif n%3==2 and n>7:print((n-5)//3,1,0) else:print(-1)
Gildong has a square board consisting of n rows and n columns of square cells, each consisting of a single digit (from 0 to 9). The cell at the j-th column of the i-th row can be represented as (i, j), and the length of the side of each cell is 1. Gildong likes big things, so for each digit d, he wants to find a triang...
#include<bits/stdc++.h> long long res[10],n,i,j,h,k,t[10],d[10],m,l[10],r[10],test,mt[10][2002],md[10][2002],mr[10][2002],ml[10][2002]; int a[2005][2005]; char c; using namespace std; int main() { cin>>test; for(h=1;h<=test;h++) { cin>>n; for(i=0;i<=9;i++) { res[i]=0; ...
n distinct integers x_1,x_2,…,x_n are written on the board. Nezzar can perform the following operation multiple times. * Select two integers x,y (not necessarily distinct) on the board, and write down 2x-y. Note that you don't remove selected numbers. Now, Nezzar wonders if it is possible to have his favorite nu...
import os import sys from io import BytesIO, IOBase from math import gcd BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in ...
There is a grid with n rows and m columns. Every cell of the grid should be colored either blue or yellow. A coloring of the grid is called stupid if every row has exactly one segment of blue cells and every column has exactly one segment of yellow cells. In other words, every row must have at least one blue cell, an...
#include <bits/stdc++.h> #define rep(i, a, b) for(int i = a; i < b; i ++) using namespace std; #define mx 4100 #define mn 2050 #define endl '\n' typedef long long LL; #define mod 998244353 int n, m; LL H[mn][mn], C[mx][mx]; void init(){ C[0][0] = 1; rep(i, 1, 4100){ C[i][0] = 1; rep(j, 1, i + 1) C[i][j] = (C[i...
The weight of a sequence is defined as the number of unordered pairs of indexes (i,j) (here i < j) with same value (a_{i} = a_{j}). For example, the weight of sequence a = [1, 1, 2, 2, 1] is 4. The set of unordered pairs of indexes with same value are (1, 2), (1, 5), (2, 5), and (3, 4). You are given a sequence a of n...
from sys import stdin from itertools import repeat from collections import defaultdict def solve(): n = int(stdin.readline()) a = map(int, stdin.readline().split(), repeat(10, n)) s = defaultdict(int) ans = 0 for i, x in enumerate(a): ans += s[x] * (n - i) s[x] += i + 1 print ans...
Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a m...
#include <bits/stdc++.h> using namespace std; int main() { int cap_first[1010], marker_first[1010]; int n, m; memset(cap_first, 0, sizeof(cap_first)); memset(marker_first, 0, sizeof(marker_first)); vector<vector<int> > cap_sec(1010, vector<int>(0)); vector<vector<int> > marker_sec(1010, vector<int>(0)); c...
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants. The magic square is a matrix of size n × n. The elements of this matrix are integers....
#include <bits/stdc++.h> using namespace std; const int MAXN = 25; int n, N, A[MAXN], s, T[MAXN][MAXN], F[MAXN], C[MAXN], D[2], FN[MAXN], CN[MAXN], DN[2]; bool used[MAXN], solved; int WF[MAXN], WC[MAXN]; bool tenta(int i, int x, int y) { if (used[i]) return false; int fn = FN[x] + 1; int cn = CN[y] + 1; int...
While most students still sit their exams, the tractor college has completed the summer exam session. In fact, students study only one subject at this college — the Art of Operating a Tractor. Therefore, at the end of a term a student gets only one mark, a three (satisfactory), a four (good) or a five (excellent). Thos...
#include<bits/stdc++.h> /* #include <ext/pb_ds/assoc_container.hpp> // Common file #include <ext/pb_ds/tree_policy.hpp> // Including */ using namespace std; //using namespace __gnu_pbds; //typedefs typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vi> vvi; typedef vector<vl> vvl; typ...
Let us remind you the rules of a very popular game called "Snake" (or sometimes "Boa", "Python" or "Worm"). The game field is represented by an n × m rectangular table. Some squares of the field are considered impassable (walls), all other squares of the fields are passable. You control a snake, the snake consists of...
#include <bits/stdc++.h> using namespace std; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, -1, 1}; int n, m; int len; int sum = 0; int vis[20][20]; char ma[20][20]; int aimx, aimy, sx, sy; struct point { int x, y; }; struct snake { int x, y, dep; int ex, ey; point s[10]; }; int BFS(snake start) { queue<snake...
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the cha...
#include <bits/stdc++.h> using namespace std; template <class a, class b> ostream &operator<<(ostream &tout, const pair<a, b> &c) { return (tout << '(' << c.first << ',' << c.second << ')'); } template <class t> ostream &operator<<(ostream &tout, const vector<t> &s) { tout << '['; for (int i = 0; i < s.size(); i+...
Luyi has n circles on the plane. The i-th circle is centered at (xi, yi). At the time zero circles start to grow simultaneously. In other words, the radius of each circle at time t (t > 0) is equal to t. The circles are drawn as black discs on an infinite white plane. So at each moment the plane consists of several bla...
#include <bits/stdc++.h> using namespace std; const int mod = (int)1e9 + 7; const double eps = 1e-8; int n, m, k; struct node { double x, y; node(double xx = 0, double yy = 0) : x(xx), y(yy) {} bool operator<(node b) const { return fabs(x - b.x) < eps ? y < b.y : x < b.x; } node operator-(node b) { no...
The polar bears have discovered a gigantic circular piece of floating ice with some mystic carvings on it. There are n lines carved on the ice. Each line connects two points on the boundary of the ice (we call these points endpoints). The endpoints are numbered 1, 2, ..., 2n counter-clockwise along the circumference. N...
#include <bits/stdc++.h> using namespace std; int INP, AM, REACHEOF; const int BUFSIZE = (1 << 12) + 17; char BUF[BUFSIZE + 1], *inp = BUF; const int MN = 200111; int n, p[MN], bit[MN]; void update(int u) { for (int x = u; x <= n + n; x += ((x) & (-(x)))) bit[x]++; } int get(int u) { int res = 0; for (int x = u; ...
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member o...
#include <bits/stdc++.h> using namespace std; const int N = 100 + 9; char c[N]; long long Xpow(long long b, long long p) { if (!p) return 1; long long h = Xpow(b, p >> 1); long long ret = h * h % 1000000007; if (p & 1) ret *= b; ret %= 1000000007; return ret; } long long to_B10(int b, int n) { long long r...
Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property: * consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a; * for each pair x, y must exist some position j (1 ≤ j < n), such that at leas...
#include <bits/stdc++.h> using namespace std; long long n, m; long long a[2000007]; void input(); void solve(); int main() { input(); solve(); return 0; } void input() { scanf("%I64d%I64d", &n, &m); int i; int x; for (i = 1; i <= m; i++) { scanf("%d%I64d", &x, &a[i]); } sort(a + 1, a + m + 1); r...
You will receive 3 points for solving this problem. Manao is designing the genetic code for a new type of algae to efficiently produce fuel. Specifically, Manao is focusing on a stretch of DNA that encodes one protein. The stretch of DNA is represented by a string containing only the characters 'A', 'T', 'G' and 'C'. ...
#include <bits/stdc++.h> using namespace std; int main() { string s; int a, c = 0, x; cin >> s; a = s.size(); x = 0; for (int i = 0; i < a; i++) { if (s[i] == s[i + 1]) { x++; } else { if (x % 2 == 1) { c++; } x = 0; } } cout << c; return 0; }
One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day. Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume ...
#include <bits/stdc++.h> using namespace std; string s; int main() { cin >> s; long long int size = s.size(), sum = 0, vaild = 0, tsum = 0; for (int i = 0; i < size; i++) { if (s[i] == '@') { int j = i - 1; while (j > -1 && s[j] != '@' && s[j] != '.') { if (s[j] >= 'a' && s[j] <= 'z') tsum...
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him;...
s1 = ''.join(input().split()) s2 = ''.join(input().split()) for i in s2: if s2.count(i) > s1.count(i): print("NO") exit(0) print("YES")
Toastman came up with a very complicated task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him? Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o', or nothing. How many ways to fill all the empty cells with 'x' or 'o' (each cell must conta...
#include <bits/stdc++.h> using namespace std; const int MAX_N = int(1e5) + 10; const int MOD = int(1e9) + 7; struct Edge { int t, c; Edge(int t, int c) : t(t), c(c) {} }; vector<Edge> E[MAX_N]; int n, k; void addEdge(int u, int v, int c) { E[u].push_back(Edge(v, c)); E[v].push_back(Edge(u, c)); } bool bad; int ...
Let's denote as <image> the number of bits set ('1' bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and <image> is maximum possible. If there are multiple such numbers find the sma...
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer tb; for (int i = 0; i < n; i++) { tb = new StringTokenizer(br...
Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi. Vasya wonders what the numbers ai could be like. Of all the possibl...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1000; int n, b[999]; int a[999][MAXN]; int len[999]; int comp(int idxa, int idxb) { for (int i = 0; i < MAXN; ++i) { if (a[idxa][i] > a[idxb][i]) return 1; if (a[idxa][i] < a[idxb][i]) return -1; } return 0; } void gen(int idx, int num) { le...
Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics. Polycarp needed to write a code that could, given two words, check whether t...
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class E { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(...
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the nodes of the tree such tha...
#include <bits/stdc++.h> using namespace std; set<pair<long long, long long> > S; set<pair<long long, long long> >::iterator it; set<pair<long long, long long> >::iterator it2; pair<long long, long long> temp; void intersect_yes(long long s, long long e) { if (S.empty()) return; for (it = S.begin(); it != S.end();)...
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle. More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the ci...
n = int(input()) print((27 ** n - 7 ** n) % (10 ** 9 + 7))
The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0, y0) of a rectangular squared field of size x × y, after that a mine will be i...
#include <bits/stdc++.h> using namespace std; char ins[123456]; int n = 0; bool vis[501][501]; int h, w, y, x; void step(int i) { if (ins[i] == 'L') x = max(x - 1, 0); if (ins[i] == 'R') x = min(x + 1, w - 1); if (ins[i] == 'U') y = max(y - 1, 0); if (ins[i] == 'D') y = min(y + 1, h - 1); } int main() { scanf...
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which...
#include <bits/stdc++.h> using namespace std; long long cnt = 0; string str = ""; int change(string a) { stringstream ss; int number; ss << a; ss >> number; ss.clear(); return number; } void dp(long long i) { string temp; temp = str[i]; if (change(temp) % 4 == 0) cnt++; if (i > 0) { temp = ""; ...
You are given a permutation p of length n. Also you are given m foe pairs (ai, bi) (1 ≤ ai, bi ≤ n, ai ≠ bi). Your task is to count the number of different intervals (x, y) (1 ≤ x ≤ y ≤ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the position...
#include <bits/stdc++.h> using namespace std; const int MAX = 300009; int n, m; int P[MAX]; vector<int> v[MAX]; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { int a; scanf("%d", &a); P[a] = i; } for (int i = 0; i < m; i++) { int a, b; scanf("%d%d", &a, &b); a = P[a]; ...
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k. Input The only line contains two integers n and k (1 ≤ n, k ≤ 109). Output Print the smallest integer x > n, so it is divisible by the number k. Examples Input 5 3 Output 6...
import java.util.*; public class helloWorld { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int ans = 0; ans = m * (int) Math.ceil( 1.0 * (n+1) / m); System.out.println(ans); in.close(); } }
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k pe...
n,l,v1,v2,k=(map(int, raw_input().split())) n = (n+k-1)/k print float(l) * (v2*(2*n-1) + v1) / (v2 * (v2 + (v1*(2*n-1))))
You are given an array consisting of n non-negative integers a1, a2, ..., an. You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed. After each element is destroyed you have to find out the segment ...
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { FastScanner in; PrintWriter out; static final String FILE = ""; long pack(int a, int b) { return (((long)(a)) << 32) + b; } int getA(long v) { return (int)(v >> 32); } int getB...
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries. The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world. There is at most one...
class Union: def __init__(self, n): self.ancestors = [i for i in range(n+1)] self.size = [0]*(n+1) def get_root(self, node): if self.ancestors[node] == node: return node self.ancestors[node] = self.get_root(self.ancestors[node]) return self.ancestors[node] ...
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the nu...
#include <bits/stdc++.h> using namespace std; int n, nh[1000005], sum[1000005], t[1000005], p, root; pair<int, int> kq; vector<pair<int, int> > a[1000005]; void home() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); } void dfs(int u, int p) { sum[u] += t[u]; if (a[u].size()) for (int j = (0...
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that membe...
import sys import threading countV = 0 countE = 0 n, m = map(int, raw_input().strip().split(' ')) f = {i: set() for i in xrange(n)} for i in xrange(m): a,b = map(int, raw_input().strip().split(' ')) f[a-1].add(b-1) f[b-1].add(a-1) res = True visited = [False for i in xrange(n)] def dfs(node): glo...
This is an interactive problem. Vladik has favorite game, in which he plays all his free time. Game field could be represented as n × m matrix which consists of cells of three types: * «.» — normal cell, player can visit it. * «F» — finish cell, player has to finish his way there to win. There is exactly one c...
#include <bits/stdc++.h> using namespace std; template <class T, class S> ostream& operator<<(ostream& os, const pair<T, S>& v) { return os << "(" << v.first << ", " << v.second << ")"; } template <class T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "["; for (int i = int(0); i <= int((static_cas...
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m). You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Als...
import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.math.BigDecimal; import java.util.Map; import java.util.TreeMap; /** * Created by dalt on 2017/9/10. */ public class BruteForcePrefixSums { int n; long threshold; l...
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are o...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static...
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits. He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, s...
#include <bits/stdc++.h> using namespace std; int cnt[100]; int f(char ch) { if (ch <= 'z' && ch >= 'a') return ch - 'a'; if (ch <= 'Z' && ch >= 'A') return ch - 'A' + 30; return ch - '0' + 60; } char fi(int n) { if (n < 30) return n + 'a'; if (n < 60) return (n - 30) + 'A'; return (n - 60) + '0'; } void so...
Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for eac...
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; impo...
There is a straight line colored in white. n black segments are added on it one by one. After each segment is added, determine the number of connected components of black segments (i. e. the number of black segments in the union of the black segments). In particular, if one segment ends in a point x, and another seg...
#include <bits/stdc++.h> using namespace std; int read() { int w = 0, f = 1; char c = ' '; while (c < '0' || c > '9') c = getchar(), f = c == '-' ? -1 : f; while (c >= '0' && c <= '9') w = w * 10 + c - 48, c = getchar(); return w * f; } struct node { int l, r; bool operator<(const node& o) const { return ...
There is a rectangular grid of n rows of m initially-white cells each. Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and...
#include <bits/stdc++.h> using namespace std; int main() { int N, M; cin >> N >> M; vector<string> vv(N); for (int i = 0; i < N; i++) cin >> vv[i]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (vv[i][j] == '#') { for (int k = 0; k < N; k++) { if (vv[k][j] == '#' &...
In the Bus of Characters there are n rows of seat, each having 2 seats. The width of both seats in the i-th row is w_i centimeters. All integers w_i are distinct. Initially the bus is empty. On each of 2n stops one passenger enters the bus. There are two types of passengers: * an introvert always chooses a row whe...
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String[] args) throws java.lang.Exception { //Reader pm =new Reader(); Scanner pm = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int t = 1; while(t-- ...
Rahul and Rashi are bored with playing the game of Nim, particularly after Rahul gained a thorough understanding of game theory, and would always win. Now, they are going to play on a variation. There are only 2 piles of coins. Each player can make the following move: Pick K ( ≥ 1) coins from pile 1. Pick K ( ≥ 1) co...
maxn = 10**6 cold_pos = {} def gen_cold(): d = 0 i = 0 while (i < maxn): if not (cold_pos.has_key(i)): cold_pos[i] = i + d cold_pos[i + d] = i d += 1 i += 1 if __name__ == "__main__": gen_cold() t = int(raw_input()) for i in range(t): n = map(int, raw_input().split(" ")) if n[1] == cold_pos[n[0...
Let us define F(N,K) be number of subsets of K distinct elements of S where N is the size of S. Given a P( ≤ N), let Sum = F(N,0) + F(N,1) + ... + F(N,P). You have to print Sum modulo 1000000007. Input: First line contains, T, the number of testcases. Each testcase consists of N and P in one line. Output: Pri...
dp=[[0 for i in range(1001)] for j in range(1001)] for i in range(1,1001): dp[i][0]=1 dp[i][1]=i for i in range(2,1001): for j in range(2,i+1): if j==i: dp[i][j]=1 else: dp[i][j]=dp[i-1][j-1]+dp[i-1][j] t=int(raw_input()) for k in range(t): n,r = [int(i) for i in raw_input().split()] if r==0: pri...
You are given n triangles. You are required to find how many triangles are unique out of given triangles. For each triangle you are given three integers a,b,c , the sides of a triangle. A triangle is said to be unique if there is no other triangle with same set of sides. Note : It is always possible to form triangl...
from collections import Counter if __name__ == "__main__": print Counter([" ".join(sorted(raw_input().rstrip().split(" "))) for i in range(input())]).values().count(1)
Consider a Deterministic Finite Automaton(DFA) which takes N states numbered from 0 to N-1, with alphabets 0 and 1. Now consider a string of 0s and 1s, let the decimal value of this string as M. For e.g., if string be "010" then the decimal value or M is 2. The speciality in our DFA is that when we simulate the string ...
n=input() cnt=0 for i in range(0,n): print i, print (cnt)%n,(cnt+1)%n cnt=cnt+2
Manku has still not learnt from KK's hard problem and continues bragging about himself. He claims that he can code problems even in his sleep. So one day Shark wakes him from sleep and asks him to solve a problem. Shark gives him a number x and another number m and asks him to check whether any power of x is divisibl...
from sys import stdin import math def gcd(a,b): while a%b: t = a%b;a=b;b=t return b t = int(stdin.readline()) for _ in xrange(t): n,m = map(int,stdin.readline().split()) u = n v = m ans = 'YES' g = gcd(m,n) if pow(n,g*n*n,m): ans = 'NO' print ans
N coders decided to go for a trip for the upcoming weekend. They chose Crater Lake National Park in Oregon, USA as their destination, because they all like to take a lot of photos and the beautiful nature gives them a chance to do so. In order to capture some memories from the trip, they wanted to take the greatest nu...
import itertools t=input() while t: t-=1 n,p=map(int,raw_input().split()) c=0 c+=n mat=[] arr=range(1,n+1) for i in range(p): mat.append(map(int,raw_input().split())) for l in range(2,len(arr)+1): for subset in itertools.combinations(arr,l): temp=p for pair in mat: if not (pair[0] in subset and pa...
Today Oz is playing with his game-board. He has N coins of type-1 and M coins of type-2. Also the game-board has N squares of type-1 and M squares of type-2. In this game Oz must place one coin into each square. After placing all coins Oz will get a score based on his coin placement strategy . His score calculation i...
diff=0 def ABS(a): if(a<0):return -a return a def MIN(one,two): if(one < two): return one return two test=input() for t in range(0,test): N,M,A,B,C=map(int,raw_input().split()) first=N*A + M*B second= MIN(N,M) if(N>M): diff=A *ABS(N-M) else: diff=B * ABS(N-M) second=2*C*second + diff if(first>secon...
A Darie is a special circle. Numbers 1, 2, ..., n are written clockwise around this circle in order. You can stand on a number! Initially Rasta is on number 1. In each step, he jumps exactly p numbers clockwise. For example if n = 3 and he is standing on number 1: If p = 1 then he jumps to number 2. Or if p = 2 he ju...
def gcd(a,b): if b==0: return a else: return gcd(b,a%b) t=int(input()) while t>0: n,p,k=raw_input().split(' ') a=[1,1] n=int(n) p=int(p) k=int(k) if gcd(n,p)==1: if k>n: res=-1 else: res=k else: temp=gcd(n,p) i...
It's the rainy season again, and the city experiences frequent showers throughout the day. The weather report says that there is a P probability of rainfalls today. Raj has to step out for a meeting at the office, and would like to know the probability that it rains during the time he is on the way. Input: The first...
t = int(raw_input()) for i in range(t): p,t = map(float,raw_input().split(" ")) a = round(1 - (1 - p) ** (t / 1440.0),4) l = len(str(a)[2:]) if(l != 4): a = str(a) + "0" * (4 - l) print(a)
Tic-Tac-Toe are three cousins. They love to send emails to each other. Tic is a naughty boy. He sends similar email to Tac multiple times. Now Tac needs your help to filter out the emails and delete the emails with similar subjects. Input: First line of the input contains T, followed by T lines, each containing an ar...
n = int(raw_input()) for i in xrange(n): s = raw_input().split() dic = {} for i in s: dic[i] = 0 for i in s: dic[i] = dic[i] + 1 if dic[i] == 1: print i,#dic[i], print
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types. * `0 p x`: a_p \gets a_p + x * `1 l r`: Print \sum_{i = l}^{r - 1}{a_i}. Constraints * 1 \leq N, Q \leq 500,000 * 0 \leq a_i, x \leq 10^9 * 0 \leq p < N * 0 \leq l_i < r_i \leq N * All values in Input are integer. I...
class BinaryIndexedTree: # a[i] = [0] * n def __init__(self, n): self.size = n self.data = [0] * (n+1) # return sum(a[0:i]) def cumulative_sum(self, i): ans = 0 while i > 0: ans += self.data[i] i -= i & -i return ans # a[i] += x d...
Give a pair of integers (A, B) such that A^5-B^5 = X. It is guaranteed that there exists such a pair for the given integer X. Constraints * 1 \leq X \leq 10^9 * X is an integer. * There exists a pair of integers (A, B) satisfying the condition in Problem Statement. Input Input is given from Standard Input in the fo...
import java.util.*; import java.lang.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long X = sc.nextLong(); long[] five = new long[1001]; long A = 0; for( int i=1; i<=1000; i++ ){ A++; five[i] = A*A*A*A*A; } loop:for( int i=0; i<=1000; i++ ){ ...
Find the minimum prime number greater than or equal to X. Constraints * 2 \le X \le 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: X Output Print the minimum prime number greater than or equal to X. Examples Input 20 Output 23 Input 2 Outpu...
#include<bits/stdc++.h> using namespace std; typedef long long ll; bool hoge(int a){ for(ll i=2;i*i <= a;i++){ if(a%i == 0)return false; } return true; } int main(){ int x; cin >> x; while(!hoge(x)){x++;} cout << x << endl; }
We have a sequence of N integers: A_1, A_2, \cdots, A_N. You can perform the following operation between 0 and K times (inclusive): * Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element. Compute the maximum possible pos...
#include <bits/stdc++.h> using namespace std; int main() { int N, K; cin >> N >> K; vector<int> A(N), B(N); for (int i=0; i<N; i++) cin >> A[i]; int S = accumulate(A.begin(), A.end(), 0); vector<int> divisors; for (int i=1; i*i<=S; i++) { if (S % i == 0) { divisors.push_back...
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. Edge i connects Vertex a_i and b_i bidirectionally. Determine if three circuits (see Notes) can be formed using each of the edges exactly once. Constraints * A...
#include <bits/stdc++.h> using namespace std; const int MX = 100000; multiset<int> G[MX]; int loops = 0; void remove(int v) { int a = *G[v].begin(); int b = *G[v].rbegin(); G[v].clear(); G[a].erase(v); G[b].erase(v); if (a == b) { loops++; if (G[a].size() == 2) remove(a); if (G[b].size() == 2) ...
Problem F and F2 are the same problem, but with different constraints and time limits. We have a board divided into N horizontal rows and N vertical columns of square cells. The cell at the i-th row from the top and the j-th column from the left is called Cell (i,j). Each cell is either empty or occupied by an obstacl...
#include <bits/stdc++.h> using namespace std; typedef long long ll; int sumv[505][505],rpos[505][505]; int minn[2][505][505],maxn[2][505][505]; char str[505][505]; int main() { int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%s",str[i]+1); int cur=0; ll ans=0; for(int i=n;i>0;i--) { cur^=1; f...
10^{10^{10}} participants, including Takahashi, competed in two programming contests. In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th. The score of a participant is the product of his/her ranks in the two contests. Process the following Q queries: * In the i-th query, you are ...
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) #define rep1(i,n) for(int i=1;i<=n;i++) #define per(i,n) for(int i=n-1;i>=0;i--) #define per1(i,n) for(int i=n;i>0;i--) #define all(v) v.begin(), v.end() typedef long long ll; typedef pair<ll,ll> P; typedef vector<ll> vec; typedef vector...
We have N gemstones labeled 1 through N. You can perform the following operation any number of times (possibly zero). * Select a positive integer x, and smash all the gems labeled with multiples of x. Then, for each i, if the gem labeled i remains without getting smashed, you will receive a_i yen (the currency of ...
#include<set> #include<map> #include<deque> #include<queue> #include<stack> #include<cmath> #include<ctime> #include<bitset> #include<string> #include<vector> #include<cstdio> #include<cstdlib> #include<cstring> #include<climits> #include<complex> #include<iostream> #include<algorithm> #define ll long long #define inf ...
Nukes has an integer that can be represented as the bitwise OR of one or more integers between A and B (inclusive). How many possible candidates of the value of Nukes's integer there are? Constraints * 1 ≤ A ≤ B < 2^{60} * A and B are integers. Input The input is given from Standard Input in the following format: ...
import sys def solve(): a = int(input()) b = int(input()) if a == b: print(1) return t = a ^ b N = len(bin(t)) - 2 t = 1 << N a = a & (t - 1) b = b & (t - 1) blen = len(bin(b)) - 2 sb = b & (2**(blen - 1) - 1) if sb == 0: sblen = 0 else: ...
There are N boxes arranged in a row. Initially, the i-th box from the left contains a_i candies. Snuke can perform the following operation any number of times: * Choose a box containing at least one candy, and eat one of the candies in the chosen box. His objective is as follows: * Any two neighboring boxes conta...
#include<iostream> using namespace std; int main(){ long n,x; long c=0; cin>>n>>x; long arr[n]; for(int i=0;i<n;i++)cin>>arr[i]; if(arr[0]>x){ c = arr[0]-x; arr[0]=x; } for(int i=1; i <n; i++){ int a; a = arr[i] + arr[i-1]; if(a > x){ c+=a-x; arr[i] -=a-x; } } cou...
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the `0` key, the `1` key and the backspace key. To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this stri...
#include<bits/stdc++.h> using namespace std; typedef long long LL; const LL mod = 1e9+7; #define MAXN 5000 LL ksm(LL p, LL q) { LL ret = 1LL; while(q != 0){ if (q & 1) ret = ret * p % mod; p = p * p % mod; q >>= 1; } return ret; } LL dp[MAXN+5][MAXN+5]; int main() { LL N, le...
Hiroshi:? D-C'KOPUA Peter: What's wrong, Dr. David? I'm used to shouting something I don't understand, but I'm not even writing it today. Hiroshi: Here. <image> Peter: What? This table ... oh, there was something like this in the qualifying question. Replacing characters using a table reduces the number of charact...
#include <iostream> #include <string> #include <map> using namespace std; map<char, string> encode_table; map<string, char> decode_table; char decode(string s) { // cout << s << endl; return decode_table[s]; } string encode(string s) { string tmp; for (string::iterator si = s.begin(); si != s.end(); s...
Better things, cheaper. There is a fierce battle at the time sale held in some supermarkets today. "LL-do" here in Aizu is one such supermarket, and we are holding a slightly unusual time sale to compete with other chain stores. In a general time sale, multiple products are cheaper at the same time, but at LL-do, the t...
#include <iostream> #include <stdio.h> #include <sstream> #include <string> #include <vector> #include <map> #include <queue> #include <algorithm> #include <set> #include <math.h> #include <utility> #include <stack> #include <string.h> #include <complex> using namespace std; const int INF = 1<<29; const double EPS = 1e...
There are n cups of different sizes and three trays (bon festivals) A, B, and C, and these cups are placed on top of each of the three trays in a pile. However, in any tray, the smallest cup in the tray is on the bottom, the second smallest cup is on top, and the third smallest cup is on top, in ascending order. .. For...
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define i_7 (ll)(1E9+7) #define i_5 (ll)(1E9+5) ll mod(ll a){ ll c=a%i_7; if(c>=0)return c; else return c+i_7; } typedef pair<int,int> i_i; typedef pair<ll,ll> l_l; ll inf=(ll)1E12; #define rep(i,l,r) for(ll i=l;i<=r;i++) #define pb push_...
Jack loved his house very much, because his lovely cats take a nap on the wall of his house almost every day. Jack loved cats very much. Jack decided to keep an observation diary of the cats as a free study during the summer vacation. After observing for a while, he noticed an interesting feature of the cats. The fen...
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<cassert> #include<iostream> #include<sstream> #include<string> #include<vector> #include<queue> #include<set> #include<map> #include<utility> #include<numeric> #include<algorithm> #include<bitset> #include<complex> using namespace std; type...
You have a deck of N × M cards. Each card in the deck has a rank. The range of ranks is 1 through M, and the deck includes N cards of each rank. We denote a card with rank m by m here. You can draw a hand of L cards at random from the deck. If the hand matches the given pattern, some bonus will be rewarded. A pattern...
//copied from http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=1635223#1 //my source code is http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=3712456#1 #include<stdio.h> #include<algorithm> using namespace std; char in[10][10]; int pl[10]; int u[10][10]; int t3[10]; int q[10]; int used[10]; int L; int dfs(int ...
A taxi driver, Nakamura, was so delighted because he got a passenger who wanted to go to a city thousands of kilometers away. However, he had a problem. As you may know, most taxis in Japan run on liquefied petroleum gas (LPG) because it is cheaper than gasoline. There are more than 50,000 gas stations in the country, ...
#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 dou...
Background Mr. A and Mr. B are enthusiastic about the game "Changing Grids". This game is for two players, with player 1 forming the stage and player 2 challenging the stage and aiming for the goal. Now, A and B have played this game several times, but B has never won because of A's winning streak. So you decided to ...
#include<bits/stdc++.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define HUGE_NUM 99999999999999999 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; struct Loc{ void set(int arg_row,int arg_col){ row = arg_row; col = arg_col; } int row,col; };...
You are a resident of Kyoot (oh, well, it’s not a misspelling!) city. All streets there are neatly built on a grid; some streets run in a meridional (north-south) direction and others in a zonal (east-west) direction. The streets that run from north to south are called avenues, whereas those which run from east to west...
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<string> #include<vector> #include<map> #include<set> #include<list> #include<queue> #include<deque> #include<algorithm> #include<numeric> #include<utility> #include<complex> #include<functional> using namespace std; /* c...
Edward Leven loves multiples of eleven very much. When he sees a number, he always tries to find consecutive subsequences (or substrings) forming multiples of eleven. He calls such subsequences as 11-sequences. For example, he can find an 11-sequence 781 in a number 17819. He thinks a number which has many 11-sequence...
#include <iostream> using namespace std; int main(){ string str; while( cin >> str && str != "0" ){ int ele[12] = {}; ele[0] = 1; int s=0; long long ans = 0; for(int i = str.size() - 1 ; i >= 0 ; i--){ int d = str[i] - '0'; int c = i % 2 ? 10 : 1; s += c * d; s %= 11; if( d != 0 ){ ans +...
Problem statement There is a positive integer sequence $ X_1, X_2, ..., X_N $. Select the subsequence $ S $ from the sequence $ \\ {1,2, ..., N \\} $. However, $ S $ must meet the following conditions. * $ T = \\ {X_s | s \ in S \\} $. At this time, for any $ x \ in T $, divisors of $ x $ (excluding $ x $) are not in...
#include <cstdio> #include <iostream> #include <algorithm> #include <string> #include <cstring> #include <vector> #include <queue> #include <set> #include <map> #include <cmath> #include <iomanip> #include <cassert> #include <bitset> using namespace std; typedef pair<int, int> P; #define rep(i, n) for (int i=0; i<(n);...
Problem Statement Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and does not have much money. She is looking for a hotel for a training camp, but is struggling to make a plan that saves as much money as possible. Let's tell her how to stay at a hotel where the total amount o...
#include<iostream> #include<algorithm> #include<vector> #include<cassert> #include<cstdio> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define inf (1<<29) #define MAX 100 using namespace std; typedef long long ll; /* 経路復元用 dp[day][hotel][number] := minimum */ int dp[MAX][MAX][MAX]; int path...