input
stringlengths
29
13k
output
stringlengths
9
73.4k
A positive integer x is called a power of two if it can be represented as x = 2^y, where y is a non-negative integer. So, the powers of two are 1, 2, 4, 8, 16, .... You are given two positive integers n and k. Your task is to represent n as the sum of exactly k powers of two. Input The only line of the input contain...
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.sqrt; import static java.lang.Integer.signum; @SuppressWarnings("unchecked") public class P1095C { p...
You are given a line of n colored squares in a row, numbered from 1 to n from left to right. The i-th square initially has the color c_i. Let's say, that two squares i and j belong to the same connected component if c_i = c_j, and c_i = c_k for all k satisfying i < k < j. In other words, all squares on the segment fro...
#include <bits/stdc++.h> using namespace std; const long long MOD = 1000000007; const int NMAX = 5005; const int INF = 2e5; int n; vector<int> arr; vector<vector<int>> dp(NMAX, vector<int>(NMAX, INF)); int rec(int i, int j) { if (dp[i][j] != INF) return dp[i][j]; if (i == j) return dp[i][j] = 0; if (arr[i] == arr...
This is an interactive task. Scientists are about to invent a new optimization for the Floyd-Warshall algorithm, which will allow it to work in linear time. There is only one part of the optimization still unfinished. It is well known that the Floyd-Warshall algorithm takes a graph with n nodes and exactly one edge b...
#include <bits/stdc++.h> using namespace std; const int N = 100000 + 7; int n, m, comp[N], y, spre[N]; bool vis[N]; vector<int> g[N], ig[N], ord, rep[N]; set<int> sgn[N]; void dfs1(int a) { vis[a] = 1; for (auto &b : g[a]) { if (!vis[b]) { dfs1(b); } } ord.push_back(a); } void dfs2(int a) { rep[...
The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party... What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now n cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone...
#include <bits/stdc++.h> using namespace std; int mini(int a, int b, int c) { int minm = min(a, b); minm = min(c, minm); return minm; } int main() { int n, m; cin >> n >> m; if (m == 0) cout << "1\n"; else cout << mini(n / 2, n - m, m) << endl; }
One important contest will take place on the most famous programming platform (Topforces) very soon! The authors have a pool of n problems and should choose at most three of them into this contest. The prettiness of the i-th problem is a_i. The authors have to compose the most pretty contest (in other words, the cumul...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class practice2 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System....
A class of students wrote a multiple-choice test. There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points....
def get_ints(): return list(map(int, input().split())) N, M = get_ints() a = [input() for i in range(N)] s = get_ints() ans=0 for i in range(M): d = {} for row in a: c = ord(row[i])-65 if c in d: d[c]+=1 else: d[c]=1 ans += max(d.values())*s[i] print(ans...
For her birthday Alice received an interesting gift from her friends – The Light Square. The Light Square game is played on an N Γ— N lightbulbs square board with a magical lightbulb bar of size N Γ— 1 that has magical properties. At the start of the game some lights on the square board and magical bar are turned on. The...
#include <bits/stdc++.h> using namespace std; using VI = vector<int>; using VVI = vector<VI>; int n; VVI M, A; VI V; VI R, C; bool print() { cout << R.size() + C.size() << endl; for (int x : R) cout << "row " << x << endl; for (int x : C) cout << "col " << x << endl; return true; } void row(int i) { for (int ...
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i Γ— 1 (that is, the width is 1 and the height is a_i). Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will...
n=int(input()) for _ in range(n): i=int(input()) ar=sorted(list(map(int,input().split())))[::-1] mx=0 for e in range(i): mx=max(mx,min(e+1,ar[e])) print(mx)
You are given an integer array a_1, a_2, ..., a_n, where a_i represents the number of blocks at the i-th position. It is guaranteed that 1 ≀ a_i ≀ n. In one operation you can choose a subset of indices of the given array and remove one block in each of these indices. You can't remove a block from a position without b...
#include <bits/stdc++.h> using namespace std; const int N_MAX = 1002; int n; int a[N_MAX]; bool ans[N_MAX][N_MAX]; bool ok[N_MAX]; int pos = 1; void f(int l, int r) { if (l >= r) return; int cnt = a[pos]; int x = l - 1; for (int i = l; i < r && cnt > 0; i++) { x = i; ans[i][pos] = ok[i] = true; cnt-...
A sequence a = [a_1, a_2, …, a_l] of length l has an ascent if there exists a pair of indices (i, j) such that 1 ≀ i < j ≀ l and a_i < a_j. For example, the sequence [0, 2, 0, 2, 0] has an ascent because of the pair (1, 4), but the sequence [4, 3, 3, 3, 1] doesn't have an ascent. Let's call a concatenation of sequence...
n=int(input()) l=[] ans=0 minn=[] maxx=[] c=0 for _ in range(n): ar=[int(x) for x in input().split()] ar=ar[1:] m=10**10 f=0 for i in ar: if i<=m: m=i else: f=1 break if f==1: continue else: minn.append(min(ar)) maxx...
You have a bag of size n. Also you have m boxes. The size of i-th box is a_i, where each a_i is an integer non-negative power of two. You can divide boxes into two parts of equal size. Your goal is to fill the bag completely. For example, if n = 10 and a = [1, 1, 32] then you have to divide the box of size 32 into tw...
#include <bits/stdc++.h> using namespace std; int T; signed long long N, M; int num[62]; void solve() { int i, j, k, l, r, x, y; string s; cin >> T; while (T--) { cin >> N >> M; memset(num, 0, sizeof(num)); signed long long sum = 0; for (i = 0; i < (M); i++) { cin >> x; y = 0; ...
You wrote down all integers from 0 to 10^n - 1, padding them with leading zeroes so their lengths are exactly n. For example, if n = 3 then you wrote out 000, 001, ..., 998, 999. A block in an integer x is a consecutive segment of equal digits that cannot be extended to the left or to the right. For example, in the i...
# | # _` | __ \ _` | __| _ \ __ \ _` | _` | # ( | | | ( | ( ( | | | ( | ( | # \__,_| _| _| \__,_| \___| \___/ _| _| \__,_| \__,_| import sys def read_line(): return sys.stdin.readline()[:-1] def read_int(): return int(sys.s...
Arthur owns a ski resort on a mountain. There are n landing spots on the mountain numbered from 1 to n from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at mos...
import sys # import math from collections import deque # import heapq # from math import inf # from math import gcd # print(help(deque)) # 26 pprint = lambda s: print(' '.join(map(str, s))) input = lambda: sys.stdin.readline().strip() ipnut = input for i in range(int(input())): n, m = map(int, input().split()) ...
You are given an undirected connected graph consisting of n vertices and m edges. k vertices of this graph are special. You have to direct each edge of this graph or leave it undirected. If you leave the i-th edge undirected, you pay w_i coins, and if you direct it, you don't have to pay for it. Let's call a vertex s...
#include <bits/stdc++.h> using namespace std; const long long inf = 1e18; const int N = 1e6; const int L = 20; vector<array<int, 2>> adj[N]; array<int, 2> edges[N]; int vis[N], tin[N], low[N], ptr, isBridge[N]; void dfsBridge(int node, int pind) { vis[node] = 1; low[node] = tin[node] = ++ptr; for (auto edge : adj...
As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest. The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time fo...
#include <bits/stdc++.h> int cmpfunc(const void* a, const void* b) { return (*(int*)a - *(int*)b); } int main() { int n; scanf("%d", &n); int time[n]; int i, sum_time = 0, penalty = 0, resuelto = 0; for (i = 0; i < n; i++) { scanf("%d", &time[i]); } qsort(time, n, sizeof(int), cmpfunc); for (i = 0; ...
You are given an integer n (n > 1). Your task is to find a sequence of integers a_1, a_2, …, a_k such that: * each a_i is strictly greater than 1; * a_1 β‹… a_2 β‹… … β‹… a_k = n (i. e. the product of this sequence is n); * a_{i + 1} is divisible by a_i for each i from 1 to k-1; * k is the maximum possible (i. e...
#include <iostream> #include <algorithm> #include <vector> typedef long long ll; using namespace std; int main(int argc, char const *argv[]) { int t; cin>>t; while(t--) { long long n; cin>>n; vector<pair<ll,ll>>v; for(ll i=2;i*i<=n;i++){ int cnt=0; ...
Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a singl...
r=int(input()) res=[] for u in range(r): x,n = map(int,input().split(" ")) db= [int(x) for x in input().split()] for i in db: # operation if i%n==0: res.append("yes") else:# bech ne7ou n kol mara w njarbou k=0 ok=0 while((i-k*n)>=n): ...
A mouse encountered a nice big cake and decided to take a walk across it, eating the berries on top of the cake on its way. The cake is rectangular, neatly divided into squares; some of the squares have a berry in them, and some don't. The mouse is in a bit of a hurry, though, so once she enters the cake from its nort...
h, w = map(int, input().split()) grid = [] for i in range(h): grid.append(input()) r,c = 0,0 ans = 0 for i in range(h+w-2): # print(r,c) if grid[r][c] == '*': ans += 1 if r==h-1: c += 1 continue if c == w-1: r+=1 continue right = (111111,111) for row i...
Today is Mashtali's birthday! He received a Hagh tree from Haj Davood as his birthday present! A directed tree is called a Hagh tree iff: * The length of the longest directed path in it is exactly n. * Every vertex has at most three edges attached to it independent of their orientation. * Let's call vertices...
#include <bits/stdc++.h> using namespace std; template <int MOD_> struct modnum { static constexpr int MOD = MOD_; static_assert(MOD_ > 0, "MOD must be positive"); private: using ll = long long; int v; static int minv(int a, int m) { a %= m; assert(a); return a == 1 ? 1 : int(m - ll(minv(m, a)) * ll(...
There is an area map that is a rectangular matrix n Γ— m, each cell of the matrix contains the average height of a corresponding area part. Peter works for a company that has to build several cities within this area, each of the cities will occupy a rectangle a Γ— b cells on the map. To start construction works in a part...
#include <bits/stdc++.h> using namespace std; template <class _T> inline _T sqr(const _T& x) { return x * x; } template <class _T> inline string tostr(const _T& a) { ostringstream os(""); os << a; return os.str(); } const long double PI = 3.1415926535897932384626433832795; const long double EPS = 1e-11; const i...
Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Nold...
import java.io.*; import java.util.ArrayList; public class Main { public static void main (String[] args) throws IOException { BufferedReader in =new BufferedReader (new InputStreamReader(System.in)); String A1[]=in.readLine().split(" "); ArrayList A=new ArrayList...
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β€” a severe torcoder coordinator Ivan does not accept any Lesha's probl...
#include <bits/stdc++.h> using namespace std; int simi, n, minsim = -1e9, fir, sec; ; vector<pair<int, int> > inv; string lesha[6], archive[30][30]; int indexes[6], m, k[30]; int count_inv() { int res = 0; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) if (indexes[i] < indexes[j]) res++; } ...
Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point C and began to terrorize the residents of the surrounding villages. A brave hero decided to put an end to the dragon. He moved from point A to fight with Gorynych. The hero rode from point A along a straight road ...
#include <bits/stdc++.h> using namespace std; struct point { double x, y; } A, B, C; double CCW(point A, point B, point C) { return (double)(B.x - A.x) * (C.y - A.y) - (C.x - A.x) * (B.y - A.y); } void Read() { scanf("%lf %lf", &A.x, &A.y); scanf("%lf %lf", &B.x, &B.y); scanf("%lf %lf", &C.x, &C.y); } void So...
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages. The river banks can be assumed to be vertical straight lines x = a and x = b (0 < a < b). The west village lies in a steppe at point O = (0...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10, mod = 1e9 + 7; int n, m, a, b, ansi, ansj; int l[N], r[N], c[N]; double ans = mod; double fisdis(double i1, double j1, double i2, double j2) { double dis = (i2 - i1) * (i2 - i1) + (j2 - j1) * (j2 - j1); dis = sqrt(dis); return dis; } double che...
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 double PI = acos(-1.0); const double EPS = 1E-8; bool zero(double x) { return -EPS < x && x < EPS; } int sgn(double x) { return x > EPS ? 1 : (x < -EPS ? -1 : 0); } class Point { public: double x, y; Point() {} Point(double x, double y) : x(x), y(y) {} void i...
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that K...
#!/usr/bin/python # -*- encoding: utf-8 -*- # pylint: disable=invalid-name,missing-docstring,bad-builtin def main(): n, k = map(int, raw_input().split()) road = raw_input().strip() dots = 0 for x in xrange(n - 1, -1, -1): if road[x] == '.': dots += 1 if n - x > k and road[x ...
Fox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are n people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and n-th people to refer the last one in the queue. There will be k gondolas, and the way we allocate gondolas...
#include <bits/stdc++.h> using namespace std; constexpr int MAXN = 4000 + 10; constexpr int MAXK = 800 + 10; constexpr int INF = 1 << 30; inline int div2(int n) { return n >> 1; } int fucks[MAXN][MAXN]; inline int w(int L, int R) { return div2(fucks[R][R] + fucks[L][L]) - fucks[L][R]; } inline int read() { while (t...
You are given a sequence of positive integers x1, x2, ..., xn and two non-negative integers a and b. Your task is to transform a into b. To do that, you can perform the following moves: * subtract 1 from the current a; * subtract a mod xi (1 ≀ i ≀ n) from the current a. Operation a mod xi means taking the rem...
#include <bits/stdc++.h> using namespace std; const int N = (int)1e5 + 500, M = (int)1e6 + 500, INF = (int)1e9; int n; int num[N], nxt[2 * M]; int a, b; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &num[i]); scanf("%d%d", &a, &b); for (int i = 0; i < 2 * M; i++) nxt[i] = max(0, i - 1); ...
Ever since Kalevitch, a famous Berland abstractionist, heard of fractals, he made them the main topic of his canvases. Every morning the artist takes a piece of graph paper and starts with making a model of his future canvas. He takes a square as big as n Γ— n squares and paints some of them black. Then he takes a clean...
import java.util.*; import java.math.*; import java.io.*; // Don't forget to change the class name! public class Main{ public static char[][] func(int N, int K, char[][] s){ int M=1,i,j,k; for(i=0;i<K;i++) M *= N; char ans[][] = new char[M][M]; for(i=0;i<M;i+...
This problem consists of two subproblems: for solving subproblem E1 you will receive 11 points, and for solving subproblem E2 you will receive 13 points. A tree is an undirected connected graph containing no cycles. The distance between two nodes in an unweighted tree is the minimum number of edges that have to be tra...
#include <bits/stdc++.h> using namespace std; const long double eps = 1e-12; const int maxn = 100000 + 1912; bool maximize(long long &a, const long long &b) { if (a < b) { a = b; return true; } return false; } bool minimize(long long &a, const long long &b) { if (a > b) { a = b; return true; }...
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog...
import java.io.*; import java.util.*; public class Test{ final static int p = 1000000007; public static void main(String [] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); ...
Recently, Berland faces federalization requests more and more often. The proponents propose to divide the country into separate states. Moreover, they demand that there is a state which includes exactly k towns. Currently, Berland has n towns, some pairs of them are connected by bilateral roads. Berland has only n - 1...
#include <bits/stdc++.h> using namespace std; const int MAXN = 400 + 10; struct Graph { int id, next, b[MAXN]; } g[MAXN * 2]; int n, k, st[MAXN], f[MAXN][MAXN], size[MAXN]; void Add(int tot, int first, int second) { g[tot].id = second, g[tot].next = st[first], st[first] = tot; } void Tree_dp(int first, int fa) { ...
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town. Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But t...
# Author: SaykaT # Problem: 463A # Time Created: July 21(Tuesday) 2020 || 02:59:52 #>-------------------------<# # Helper Functions. -> Don't cluster your code. # IO Functions. -> Input output def io(): n, s = map(int, input().split()) sugar = [] for _ in range(n): x, y = map(int, input().split()...
The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson. Nam created a sequence a consisting of n (1 ≀ n ≀ 105) elements a1, a2, ..., an (1 ≀ ai ≀ 105). A subsequence ai1,...
#include <bits/stdc++.h> using namespace std; int a[1 << 18]; int dp[1 << 18], f1[1 << 18], f2[1 << 18], e[1 << 18], c; char s[1 << 18]; long long d1[1 << 18], d2[1 << 18]; long long st[1 << 18]; void modify(int x, long long v, int p, int lb, int rb) { st[p] = ((st[p] + v) % 1145140019); if (lb + 1 == rb) retur...
The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used. The enemy has N strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least K import...
#include <bits/stdc++.h> using namespace std; const int N = 1e2 + 2; const long double EPS = 1e-9; long double x[N], y[N]; long double xo, yo; long double dp[N][N]; long double e; long double getval(int k, int i, int j, long double mid) { long double d = (x[i] - xo) * (x[i] - xo) + (y[i] - yo) * (y[i] - yo); long d...
In this task you have to write a program dealing with nonograms on fields no larger than 5 Γ— 20. Simplified nonogram is a task where you have to build such field (each cell is either white or black) that satisfies the given information about rows and columns. For each row and each column the number of contiguous black...
#include <bits/stdc++.h> using namespace std; const int MAXN = 10000100; int Cnt[6]; int Cnt1[6]; inline void Decode(long long Code, int &y, int &S); inline long long Encode(int y, int S, int *Cnt); long long que[MAXN]; int qhead, qtail; const int HashMOD = 10000017; long long HashX[MAXN]; long long HashY[MAXN]; bool H...
A flea is sitting at one of the n hassocks, arranged in a circle, at the moment. After minute number k the flea jumps through k - 1 hassoсks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that flea has...
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.Writer; import java.util.HashSet; import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.I...
In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions. The attitude of each of the companions to the hero is an integer. Initially, the attitude of each o...
#include <bits/stdc++.h> using namespace std; int val[30][3]; int n; string path; map<pair<int, int>, pair<int, string> > m[2]; string mp[] = {"MW\n", "LW\n", "LM\n"}; map<pair<int, int>, pair<int, string> >::iterator iter, ater; int ans = (int)-1e9; string sp; void dfs(int k, int h, int x, int p, int q, int r) { if ...
Genos and Saitama went shopping for Christmas trees. However, a different type of tree caught their attention, the exalted Power Tree. A Power Tree starts out as a single root vertex indexed 1. A Power Tree grows through a magical phenomenon known as an update. In an update, a single vertex is added to the tree as a ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 10; const long long MOD = 1000000007; long long exp(long long x, long long p) { if (p == 0) return 1; long long ans = exp(x, p / 2); ans = (ans * ans) % MOD; if (p % 2) { (ans *= x) %= MOD; } return ans % MOD; } vector<int> grafo[MAXN]...
As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings! The sequence of round brackets is called valid if and only if: 1...
import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.*; import java.util.*; public class C343C { private static StringTokenizer st; public static void nextLine(BufferedReader br) throws IOException { st = new StringTokenizer(br.readLine()); } public stat...
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city. In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Collection; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Queue;...
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length. A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3....
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; impor...
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is on...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * Created by pallavi on 22/7/16. */ public class C701 { public static int f(char c) { if (c >= 'a' && c <=...
The map of Berland is a rectangle of the size n Γ— m, which consists of cells of size 1 Γ— 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that...
#include <bits/stdc++.h> using namespace std; const int N = 102; const int MOD = 1e9 + 7; long long int powmod(long long int a, long long int b) { if (b == 0) return 1; long long int x = powmod(a, b / 2); long long int y = (x * x) % MOD; if (b % 2) return (a * y) % MOD; return y % MOD; } vector<string> p; boo...
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...
#include <bits/stdc++.h> using namespace std; const int N = 1010; int n, m, k; int a[N], sz[N], c[N]; bool u[N]; vector<int> g[N]; void go(int v, int comp) { c[v] = comp; ++sz[comp]; u[v] = true; for (auto to : g[v]) { if (u[to]) continue; go(to, comp); } } int main() { scanf("%d%d%d", &n, &m, &k); ...
Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: * The game starts with n piles of stones indexed from 1 to n. The i-th pile contains si stones. * The players make their moves alternatively. A move ...
#include <bits/stdc++.h> using namespace std; struct debugger { template <typename T> debugger& operator,(const T& v) { cerr << v << " "; return *this; } } dbg; inline long long gcd(long long a, long long b) { a = ((a) < 0 ? -(a) : (a)); b = ((b) < 0 ? -(b) : (b)); while (b) { a = a % b; swa...
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n ...
def num2axis(num): y = 1 while num % (1 << y) == 0: y += 1 x = (num - (1 << (y - 1))) / (1 << y) + 1 return (y, x) def axis2num(y, x): base = 1 << (y - 1) offset = (x - 1) * (1 << y) return base + offset def get_max_y(n): res = 0 while (1 << res) < n: res += 1 r...
Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place! This contest consists of n problems, and Pasha solves ith problem in ai time units (his solutions are always correct). At any moment of time he can be thinking about a so...
from sys import stdin import re def readInt(count=1): m = re.match('\s*' + ('([+-]?\d+)\s*' * count), stdin.readline()) if m is not None: ret = [] for i in range(1, m.lastindex + 1): ret.append(int(m.group(i))) return ret return None taskCount, = readInt() thinkingTime ...
You are playing a game with a bag of red and black balls. Initially, you are told that the bag has n balls total. In addition, you are also told that the bag has probability pi / 106 of containing exactly i red balls. You now would like to buy balls from this bag. You really like the color red, so red balls are worth ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Input...
You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be ...
import java.util.Scanner; import java.util.StringTokenizer; public class CF_859C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = Integer.parseInt(s.nextLine()); StringTokenizer st = new StringTokenizer(s.nextLine()); int[] pies = new int[n]; for(int i = 0; i < n; i+...
A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect. For example: * If x = 6 and the crossw...
n, x = map(int, input().split()) print(['NO', 'YES'][sum(map(int, input().split())) + n - 1 == x])
You are given three integers k, pa and pb. You will construct a sequence with the following algorithm: Initially, start with the empty sequence. Each second, you do the following. With probability pa / (pa + pb), add 'a' to the end of the sequence. Otherwise (with probability pb / (pa + pb)), add 'b' to the end of the...
#include <bits/stdc++.h> using namespace std; const long long Mod = 1e9 + 7; long long n, pa, pb; long long f[1010][1010]; bool vis[1010][1010]; long long Min(long long x, long long y) { return x < y ? x : y; } long long Max(long long x, long long y) { return x > y ? x : y; } long long R() { long long ans = 0, f = 1;...
A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new...
import java.util.Scanner; import java.util.TreeSet; public class NewspaperHeadline { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] A = sc.next().toCharArray(); char[] B = sc.next().toCharArray(); TreeSet<Integer>[] charIndexMap = new TreeSet[26]; for(int i = 0; i ...
The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect s...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int degree[n + 1]; for (int i = 0; i < n + 1; i++) degree[i] = 0; int tmp = n - 1; while (tmp--) { int u, v; cin >> u >> v; degree[u]++; degree[v]++; } int count = 0; for (int i = 1; i < n + 1; i++) { if (d...
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator. Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); const double eps = 1e-12; const int MOD = 1e9 + 7; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3f; const int maxn = 2e3 + 4; const int maxm = 720; inline long long rule(long long x) { return (x %= MOD) += x < 0 ? MOD : 0; ...
Given a string S of length N consisting of only lower-case English alphabets, you will be asked to process Q queries over it . In each query you will be given two lower case characters X and Y. Your task is to find out the number of such substrings of the the string S which have the characters X and Y on either of its...
n = input() word = raw_input() q = input() container=[ 0 for i in xrange(26)] for c in word: container[ord(c)-97]+=1 for i in xrange(q): query = raw_input().split() if query[0] == query[1]: count_1 = container[ord(query[0])-97] print (count_1*(count_1-1))/2 ...
Mishra has gone bizarre these days. And therefore loves only bizzare patterns. Nowadays he has ran into a habit of not listening to many "yes" or "no" from people like Bansal. In fact he does not like strings having more than one "yes" or one "no" consecutively. Bansal sends him a string of length L containing only 'Y'...
#!/usr/bin/python """ HackerEarth practice problem (http://www.hackerearth.com/problem/algorithm/bizzare-mishra/) @date 2014/2/25 """ import fileinput input = [] output = 0 map = {'N':'Y','Y':'N'} for line in fileinput.input(): input.append(line) case_count = int(input[0]) for i in range(case_count): len = int(inpu...
Abhimanyu simply drew two triangles, as shown in the picture below: He says this, Amazing painting 1. Then he drew two more triangles, as shown in the picture below: He says this, Amazing painting 2. Similarly he defined Amazing painting 3, 4, 5, ..., N. Now he starts finding the points where two lines meet or int...
T = int(raw_input()) while T>0: T=T-1 N = long(raw_input()) totPoints = N*12 q=totPoints/26 rem = totPoints%26 cost = map(long,raw_input().split()) totCost = 0 for i in cost: totCost=totCost+i paintCost = q*totCost + 26*((q-1)*q)/2 for i in range(rem): paintCost+=(cost[i]+q); print paintCost
You and your Kβˆ’1 friends want to buy N marbles. Marble number i has cost ci. But the seller does not want just one customer to buy a lot of marbles, so he tries to change the price of marbles for customers who have already bought some marbles. More precisely, if a customer has already bought x marbles, he should pay (x...
n, k = raw_input().split(" ") n, k = int(n), int(k) costs = raw_input().split(" ") def minimumMoney(): integerCosts = [] for c in costs: integerCosts.append(int(c)) integerCosts = sorted(integerCosts) multiplyFactor = 1 friendCount = k minMoney = 0 for c in reversed(integerCosts): friendCount = friendC...
Jiva is a self driven car and is out on its very first drive. It aims to earn some revenue by serving as taxi driver. It starts its journey from a point and travels in a line for 100 Km. It picks and drops passenger on the way,but can accommodate a maximum of M passengers at once. Jiva wants be very economical & inte...
import sys t = int(sys.stdin.readline()) while(t>0): cabfull = False t-=1 N,M=map(int,sys.stdin.readline().split()) start = [[] for i in xrange(101)] end = [0 for i in xrange(101)] for i in xrange(N): s,e = map(int,sys.stdin.readline().split()) if(s<e): start[s].append(e) passengers = 0 cost = 0 for i...
Chester Bennington, being a skinny kid as we all know, is always bullied since he was a child. This time its just unacceptable. Mike Shinoda, the second vocalist to his band, tried to bully him. Chester was never a bright student and Mike, being a high school graduate, gave him a tough mathematical problem. He gave Che...
def isprime(x): X = int((x**0.5))+1 for i in xrange(2,X): if(x%i==0): return False return True def op(n,ref): p=[2] for i in xrange(3,n): if(isprime(i)): ref[i]=1 p+=[i] return p def prog(): t = input() T=t nums=[] while(t): ...
Agon Packers and Movers specialize in moving large number luggages from one place to another. The luggages are packed by the Packers, and after they're done with the job, the Movers take over. First, the Packers put the packages they have packed in a single line, one behind the other, and then the Movers come one by ...
#print 'Hello World!' #weight = {} #def recursive memory loss def move(M, P, p): #print "inside..." sol = [] if M == 1: return sum(p[0:P]) for i in range(P+1): #print "looping..." if i == P: sol.append(sum(p[0:P])) weight = sum(p[0:i]) #print "calling..." sol.append(max(weight, move(M-1, P - i, p[...
A linked list contains N nodes numbered from 1 to N. The tail of the list points to head of the list i.e. the linked list is circular in nature. For when N=5 1->2->3->4, ^-------5<---' An integer K is also given to you.You start counting from head and when you reach Kth node in the circular list you remove that ...
num=int(raw_input()) for i in range(num): total,step=raw_input().split() total=int(total) step=int(step) nxt=0 l=range(1,total+1) while len(l)>1: delete=(nxt+step)%total l.pop(delete) total-=1 nxt=delete%total print l[0]
Sona loves numbers. Sona loves only certain type of numbers especially prime numbers. She devised a new definition for prime numbers. In a given set of positive integer X = {X0,X1,....Xn-1} Xi is prime only if there are no elements inΒ XΒ which are divisors ofΒ XiΒ (exceptΒ XiΒ itself). You are given the set X and find the...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' size=input() arr=map(int,raw_input().split()) lis=[] for i in range(size): c=0 for j in range(size): if arr[j]!=0: if arr[i]%arr[j]==0 and c==0: c=1 elif arr[i]%arr[j]==0 ...
Tom and Jerry started fighting, as always! But this time the fight is on numbers. They ended up bringing a game to decide who is better. They have N marbles and they choose two integers M1 and M2, in each turn a player can take either M1 or M2 marbles(if available!). One who can't make any move further, loses. Game is...
t = input() while(t>0) : t -= 1 n, m1, m2 = map(int, raw_input().split()) rem = (n%(m1+m2)) if (rem < m1) : print 0 elif ((rem == m1)or(rem >= m2)) : print 1 else : rem /= m1 if (rem&1) : print 1 else : print 0
You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input missi...
#include <iostream> #include <algorithm> #include <string> #include <vector> #include <cmath> #include <map> #include <queue> #include <iomanip> #include <set> #include <tuple> #define mkp make_pair #define mkt make_tuple #define rep(i,n) for(int i = 0; i < (n); ++i) #define all(v) v.begin(),v.end() using namespace std...
You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.) N players will participate in this competition, and they are given distinct integers from 1 through N. The arena has M playing fields for two players. You need to assign each playing fiel...
n,m=map(int,input().split()) if n%2==1: for i in range(m): print(n-i-1,i+1) else: cnt=1 for i in range(m): if i%2==0: print(n//4-i//2,n//4-i//2+cnt) else: print(n//2+n//4-i//2,n//2+n//4-i//2+cnt) cnt+=1
N problems have been chosen by the judges, now it's time to assign scores to them! Problem i must get an integer score A_i between 1 and N, inclusive. The problems have already been sorted by difficulty: A_1 \le A_2 \le \ldots \le A_N must hold. Different problems can have the same score, though. Being an ICPC fan, y...
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef double db; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vp; const int inf = 1e9; const ll INF = 1e18; const db eps = 1e-10; #define fi first #define se second #define pb push_back #define eb em...
Given is an integer S. Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions: * 0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9 * The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2. We can prove that ther...
#include <iostream> using namespace std; int main() { long long S; cin >> S; cout << 0 << ' '; cout << 0 << ' '; cout << (S - 1) / 1000000000 + 1 << ' '; cout << 1 << ' '; cout << (1000000000000000000 - S) % 1000000000 << ' '; cout << 1000000000 << endl; }
For two permutations p and q of the integers from 1 through N, let f(p,q) be the permutation that satisfies the following: * The p_i-th element (1 \leq i \leq N) in f(p,q) is q_i. Here, p_i and q_i respectively denote the i-th element in p and q. You are given two permutations p and q of the integers from 1 through...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public cla...
A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied: * For each i = 1,2,..., n-2, a_i = a_{i+2}. * Exactly two different numbers appear in the sequence. You are given a sequence v_1,v_2,...,v_n whose length is even. We would like to make this sequence /\/\/\/ by replacing s...
n=int(input()) l=[int(i) for i in input().split()] o=[[0,i] for i in range(100001)] e=[[0,i] for i in range(100001)] for i in range(n//2): o[l[i*2]][0]+=1 e[l[i*2+1]][0]+=1 o.sort(reverse=True) e.sort(reverse=True) res=10000000000000000 for i in range(2): for j in range(2): if o[i][1]!=e[j][1]: res=min(re...
Taichi thinks a binary string X of odd length N is beautiful if it is possible to apply the following operation \frac{N-1}{2} times so that the only character of the resulting string is `1` : * Choose three consecutive bits of X and replace them by their median. For example, we can turn `00110` into `010` by applying ...
import java.io.*; import java.util.*; public class Main { FastScanner in; PrintWriter out; final int mod = (int) 1e9 + 7; int add(int x, int y) { x += y; if (x >= mod) { x -= mod; } return x; } void solve() { char[] s = in.next().toCharArra...
There are N non-negative integers written on a blackboard. The i-th integer is A_i. Takahashi can perform the following two kinds of operations any number of times in any order: * Select one integer written on the board (let this integer be X). Write 2X on the board, without erasing the selected integer. * Select two...
#define _CRT_SECURE_NO_WARNINGS #define _SCL_SECURE_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <iostream> #include <string> #include <vector> #include <list> #include <utility> #include <algorithm> #include <functional> #include <cmath> #include <stack> #include <que...
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right. Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is: * There are exactly x_i different colors among squares l_i, ...
#include <bits/stdc++.h> #define int long long using namespace std; const int maxn=305; const int mod=1e9+7; vector<pair<int,int> >vec[maxn]; int n,m,dp[305][305][305],d[4]; void add(int &x,int y) { x+=y; if(x>=mod)x-=mod; } bool check(int a,int b,int c) { d[1]=a;d[2]=b;d[3]=c; sort(d+1,d+4); for(int i=0;i<vec[d[3...
Consider all integers between 1 and 2N, inclusive. Snuke wants to divide these integers into N pairs such that: * Each integer between 1 and 2N is contained in exactly one of the pairs. * In exactly A pairs, the difference between the two integers is 1. * In exactly B pairs, the difference between the two integers is ...
#include<bits/stdc++.h> #define N 10005 #define LL long long using namespace std; const int mo=1e9+7; int n,a,b,c; LL fc[N],xf[N],ans; LL fpm(LL x,LL y){ LL s=1; while(y){ if(y&1) s=(s*x)%mo; y>>=1,x=(x*x)%mo;} return s;} LL C(int n,int m){ return fc[n]*xf[m]%mo*xf[n-m]%mo;} LL f(int n,int m) { if(!n) return (m==0); ...
Snuke loves colorful balls. He has a total of NΓ—K balls, K in each of his favorite N colors. The colors are numbered 1 through N. He will arrange all of the balls in a row from left to right, in arbitrary order. Then, for each of the N colors, he will paint the leftmost ball of that color into color 0, a color differe...
#include<bits/stdc++.h> #define rg register using namespace std; const int mod=1e9+7; #define _ 2001 int n, k, f[_][_], sum[_*_]; int qp(int x, int y){ int ans=1; while(y){ if(y&1)ans=1ll*ans*x%mod; x=1ll*x*x%mod, y>>=1; }return ans; } int C(int m, int r){return 1ll*sum[m]*qp(sum[r], mod-2)%mod*qp(sum[m-r], mod-...
A serious incident happened at Taro's house, which loves steamed buns. One of the three steamed buns offered at the Buddhist altar in the Japanese-style room was gone. When Taro, who was aiming for a snack someday, started an investigation to find the criminal, it turned out that there were many people who entered the ...
# Aizu Problem 00119: Taro's Obsession # import sys, math, os # read input: PYDEV = os.environ.get('PYDEV') if PYDEV=="True": sys.stdin = open("sample-input.txt", "rt") class DirectedGraph(): def __init__(self): self.edges = {} def AddNode(self, node): if node not in self.edges: ...
To get on the Shinkansen, you need two tickets, a "ticket" and a "limited express ticket". These are separate tickets because some of the routes may not use the Shinkansen, but for routes that use only the Shinkansen, one ticket can be used as both a ticket and a limited express ticket. It may also be issued. Automati...
import java.util.*; public class Main { Scanner in = new Scanner(System.in); public static void main(String[] args) { new Main(); } public Main(){ new AOJ0257().doIt(); } class AOJ0257{ void doIt(){ HashMap<String, String> map = new HashMap<String, String>(); map.put("1 0 0", "Close");map.put("0 1 ...
problem You are in charge of quality control at a machine manufacturing plant. This machine requires a power supply, a motor, and a cable as parts. The manufacturing plant has a power supply, b motors, and c cables, numbered from 1 to a, a + 1 to a + b, and a + b + 1 to a + b + c, respectively. attached. The trouble i...
#include <bits/stdc++.h> using namespace std; #define rep(i, n) for (int i = 0; i < (n); i++) int main() { int a, b, c, n; while(cin >> a >> b >> c >> n){ vector<int> state(a + b + c, 2); vector<vector<int> > tests(n, vector<int>(4)); rep(i, n) rep(j, 4) cin >> tests[i][j]; ...
In order to participate in the Asian Regional Qualifiers of the International Collegiate Programming Contest held every year in Japan, we must break through the strict domestic qualifiers. Even though it is a university competition, multiple teams from one school will participate. Therefore, the following selection ru...
#include <bits/stdc++.h> using namespace std; #define dump(...) cout<<"# "<<#__VA_ARGS__<<'='<<(__VA_ARGS__)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define all(c) begin(c),end(c) #define mp mak...
Tax Rate Changed VAT (value-added tax) is a tax imposed at a certain rate proportional to the sale price. Our store uses the following rules to calculate the after-tax prices. * When the VAT rate is x%, for an item with the before-tax price of p yen, its after-tax price of the item is p (100+x) / 100 yen, fractions ...
#include <bits/stdc++.h> using namespace std; int A,B; int getX(int x){ double a; a=x*100.0/(100+A); int b; b=ceil(a); if((int)(b*(100.0+A)/100) != x)return -1; double c=b*(100.0+B)/100; return (int)c; } int main(){ int c; while(cin>>A>>B>>c,A){ int ans=0; for(int i=1;i<c;i++){ int data=get...
We will define Ginkgo numbers and multiplication on Ginkgo numbers. A Ginkgo number is a pair <m, n> where m and n are integers. For example, <1, 1>, <-2, 1> and <-3,-1> are Ginkgo numbers. The multiplication on Ginkgo numbers is defined by <m, n> * <x, y> = <mx βˆ’ ny, my + nx>. For example, <1, 1> * <-2, 1> = <-3,-1>...
#include<iostream> using namespace std;int x[1<<23],p,q,n,i,j; int main(){ for(i=0;i<1000;i++){for(j=0;j<1000;j++){x[i*i+j*j]++;}} cin>>n; for(i=0;i<n;i++){ cin>>p>>q;int r=p*p+q*q,s=0; for(j=1;j<=r;j++){ if(r%j==0){s+=x[j]*x[r/j];} } if(s==8){cout<<'P'<<endl;}else{cout<<'C'<<endl;} } }
Background The site of Mr. A's house, which lives in a certain city, is surrounded by white walls. Feeling unsatisfied with the wall, Mr. A decided to invite the children in the neighborhood to paint the wall freely. Ask the children to choose their favorite section of the wall and paint it. So how was the wall painte...
#include<bits/stdc++.h> using namespace std; vector< int > Sum; vector< bool > v; int rec(const vector< int >& Color, int idx) { if(v[idx]) return(0); v[idx] = true; int cnt = 1; if(Color[(idx + Color.size() - 1) % Color.size()] >= 0) cnt += rec(Color, (idx + Color.size() - 1) % Color.size()); if(Color[(idx ...
Everlasting Sa-Ga, a new, hot and very popular role-playing game, is out on October 19, 2008. Fans have been looking forward to a new title of Everlasting Sa-Ga. Little Jimmy is in trouble. He is a seven-year-old boy, and he obtained the Everlasting Sa-Ga and is attempting to reach the end of the game before his frien...
import java.util.Arrays; import java.util.Scanner; public class Main { final int INF = 1 << 28; void run() { Scanner sc = new Scanner(System.in); final int MAX = 1000 * 1000 + 1; boolean isPrime[] = new boolean[MAX]; Arrays.fill(isPrime, true); int[] primes = new int[MAX]; int idx = 0; for (int i = 2;...
The cat Fabre came up with a simple game using addition and decided to try it with his friend Audrey, also in the cat. The rules of the game are as follows. First of all, choose a suitable positive integer and start from there. Each player selects two adjacent digits from that number, calculates the sum, and replaces ...
#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...
Problem statement There are real variables $ X_1, X_2, ... $, and some initial value is assigned. From now on, $ Q $ pieces of information will be given in order. The information given is one of the following two types. * min $ \\ {X_ {a_i}, X_ {a_i + 1}, ..., X_ {b_i} \\} = y_i $. * Substitute $ y_i $ for the variab...
#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...
When Mr. Kay was browsing a certain SNS as usual, the problem that "there are people who can solve IQ150 or more" came to the timeline. Mr. Kay has an IQ of over 150, so he solved the problem in an instant without even looking at it. For him, he doesn't have to work on such a mystery. It is enough to leave it to the co...
s = raw_input() ans = 0 for i in range(len(s)): if s[i] == "0" and i != len(s) - 1: continue left = int(s[:i]) if i else 0 right = int(s[i:]) if left <= right and left % 2 == right % 2: ans += 1 print ans
Example Input 3 3 1 1 1 10 10 AAA A.. A.. Output 100
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #defi...
JAG mock qualifying practice session The ACM-ICPC OB / OG Association (Japanese Alumni Group; JAG) has N questions in stock of questions to be asked in the mock contest, and each question is numbered with an integer from 1 to N. Difficulty evaluation and recommendation voting are conducted for each problem. Problem i ...
#include<iostream> #include<algorithm> using namespace std; int n,m,d[200],v[200]; int maxi[200]; int main() { while(1) { cin >> n >> m; if(n == 0)break; for(int i =0;i < n;i++)cin >> d[i] >> v[i]; for(int i = 1;i <= m;i++)maxi[i] = 0; for(int i = 0;i < n;i++)maxi[d[i]] = m...
B: Twice as own problem You will be given Q queries. Since one positive integer N is given for each query, find the number of positive integers M that satisfy the following two conditions. * 2 Satisfy \ leq M \ leq N * Of the divisors of M, excluding M, the total product is more than twice that of M Input format ...
#include <stdio.h> int main(void) { int a; int l; int max=0; long Q[100000]={0}; long sum[100000]={0}; long mul[100000]={0}; int i,j=0; scanf("%d",&a); for(l=0;l<a;l++){ scanf("%d", &Q[l]); if(max<=Q[l]) max=Q[l]; } for(i=1;i<=max;i++) mul[i]=1; for(i=2;i<=max;i++){ ...
Auction square1001 You were watching a certain auction. An auction is a transaction in which when there are a large number of buyers and the number of items is limited, the one with the highest price is given the right to buy. (From the 7th edition of the Shinmei Kokugo Dictionary) The rules of the auction here are ...
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex> #include <cmath> #include <limits> #include <climits> #include <ctime> ...
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $L$, find the minimum of each possible sub-arrays with size $L$ and print them from the beginning. For example, for an array $\\{1, 7, 7, 4, 8, 1, 6\\}$ and $L = 3$, the possible sub-arrays with size $L = 3$ includes $\\{1, 7, 7\\}$, $\\{7, 7, ...
#include<bits/stdc++.h> using namespace std; template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; } using Lint=long long; template<typename T> class SlidingBestElement { private: vector<T> a,b...
Chef likes problems involving arrays. Unfortunately, the last one he tried to solve didn't quite get solved. Chef has an array A of N positive numbers. He wants to find the number of subarrays for which the sum and product of elements are equal. Please help Chef find this number. Input The first line of input con...
''' Created on 21-Dec-2015 @author: venkatesh ''' def get_no_of_subarrays(nums, n): cnt = n for i in xrange(n): tot, prod = nums[i], nums[i] for j in xrange(i+1, n, 1): tot += nums[j] prod *= nums[j] if tot == prod: cnt += 1 return cnt ...
Grapes of Coderpur are very famous. Devu went to the market and saw that there were N people selling grapes. He didn’t like it because things were not very structured. So, he gave a task to Dhinwa to make things better. If Dhinwa successfully completes the task, Devu will be happy. Devu wants to change the number of ...
import sys test_cases = int(sys.stdin.readline()) while test_cases > 0: test_cases -= 1 no_of_buckets, divisor = map(int, sys.stdin.readline().split(' ')) apples = map(int, sys.stdin.readline().split(' ')) steps = 0 for i in range(0, no_of_buckets): if(apples[i] >= divisor): temp...
Stepford Street was a dead end street. The houses on Stepford Street were bought by wealthy millionaires. They had them extensively altered so that as one progressed along the street, the height of the buildings increased rapidly. However, not all millionaires were created equal. Some refused to follow this trend and k...
import bisect length = int(raw_input()) l = raw_input() houses = [int(i.strip()) for i in l.split(' ')] count = 0 f = [] for i in range(length): a = bisect.bisect_left(f, houses[i]) count = count + (i-a) f.insert(a, houses[i]) print count
The Head Chef has received his id from the Association of Byteland . He wants to know the numerical rank of his number among the numbers that can be formed by the exact same digits ( i.e. among numbers having same number of 0's , 1's ... 9's as his id ) . Note that id's can start with 0 . Given a number, find the rank...
import math listx=[0]*10 def no(x): i=int(x)-1 el=0 while(i>=0): el+=listx[i] i-=1 return el t=int(raw_input().strip()) while t: t-=1 ans=1 listx=[0]*10 num=raw_input().strip() for i in num: listx[int(i)]+=1 leng=len(num)-1 i=0 while leng>0: ...
Little chief has his own restaurant in the city. There are N workers there. Each worker has his own salary. The salary of the i-th worker equals to Wi (i = 1, 2, ..., N). Once, chief decided to equalize all workers, that is, he wants to make salaries of all workers to be equal. But for this goal he can use only one ope...
t = int(raw_input()) for _ in range(t): n = int(raw_input()) lst = map(int, raw_input().split()) mn = min(lst) s = sum(lst) print s - n*mn
Virat loves mathematical questions. The other day he came across an interesting question which required him to find out the number of trailing zeroes for the function. F(n) = 1^1*2^2......N^N,where N is an integer. Virat solved the problem after a few attempts. He asked the same question from his friend Rohit to see if...
def f(n): count=0 temp=1 for i in range(5,n+1,5): temp=0 t=i while t%5==0: t/=5 temp+=1 count+=i*temp return count t=int(raw_input()) for i in range(t): n=int(raw_input()) print f(n)
Panic is rising in the committee for doggo standardization β€” the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive. The committee rules strictly prohibit even the smallest diversity between dog...
from collections import Counter n = int(input()) print("Yes" if n == 1 or max(Counter(input()).values()) >= 2 else "No")
In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspaceβ„’ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hype...
#include <bits/stdc++.h> using namespace std; int n, m, qq; vector<int> g[100005], tr[100005]; int mark[100005], dpt[100005]; map<pair<int, int>, bool> conn; int timer, tin[100005], tout[100005], up[100005][21], l = 20; void dfs(int st, int pr, int cd = 0) { tin[st] = ++timer; dpt[st] = cd; up[st][0] = pr; for ...