input
stringlengths
29
13k
output
stringlengths
9
73.4k
You are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size n × m, where the height of the cell (i, j) is a_{i, j}. You are in the cell (1, 1) right now and want to get in the cell (n, m). You can move only down (from the cell (i, j) to the cell...
#include <bits/stdc++.h> using namespace std; const long long INF = 1e9 + 7; const int N = 1e2 + 10; long long a[N][N]; int flag[N][N]; long long dp[N][N]; int main() { int ncase; scanf("%d", &ncase); while (ncase--) { int n, m; scanf("%d%d", &n, &m); vector<long long> v; for (int i = 1; i <= n; i...
Let f(x) be the sum of digits of a decimal number x. Find the smallest non-negative integer x such that f(x) + f(x + 1) + ... + f(x + k) = n. Input The first line contains one integer t (1 ≤ t ≤ 150) — the number of test cases. Each test case consists of one line containing two integers n and k (1 ≤ n ≤ 150, 0 ≤ k ...
#include <bits/stdc++.h> using namespace std; template <class T> void chmax(T &a, T b) { if (a < b) a = b; } template <class T> void chmin(T &a, T b) { if (a > b) a = b; } constexpr long long INF = 1000000000000000000; constexpr long long mod = 1000000007; constexpr double eps = 1e-8; const double pi = acos(-1); lo...
Shrimpy Duc is a fat and greedy boy who is always hungry. After a while of searching for food to satisfy his never-ending hunger, Shrimpy Duc finds M&M candies lying unguarded on a L × L grid. There are n M&M candies on the grid, the i-th M&M is currently located at (x_i + 0.5, y_i + 0.5), and has color c_i out of a to...
#include <bits/stdc++.h> using namespace std; const int N = 2005; const int mo = 1000000007; int n, K, L, ans; int x[N], y[N], v[N]; int qx[N], qy[N], py[N]; vector<pair<int, int> > op[N]; pair<int, int> opp[N]; int pl[N], pr[N], q[N]; struct node { int X, Y, v; } opt[N * 4]; int mx[N * 4], smx[N * 4]; int mxs[N * 4]...
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for? Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ...
import java.util.*; import java.io.*; public class MyClass { static PrintWriter w; public static void main(String args[]) { Scanner sc = new Scanner(System.in); w=new PrintWriter(System.out); int test=Integer.parseInt(sc.nextLine()); A: while(test-->0){ ...
This is an interactive problem. Igor wants to find the key to Olha's heart. The problem is, that it's at the root of a binary tree. There is a perfect binary tree of height h consisting of n = 2^{h} - 1 nodes. The nodes have been assigned distinct labels from 1 to n. However, Igor only knows h and does not know which...
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using vvi = vector<vi>; using vll = vector<ll>; using vvll = vector<vll>; using vb = vector<bool>; using vd = vector<double>; using vs = vector<string>; using pii = pair<int, int>; using pll = pair<ll, ll>; using pdd = pair<doub...
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture — formally, he wants to choose some permutation of integers from 1 to n ...
#include<bits/stdc++.h> using namespace std; int find_par(int i,int par[]) { if(par[i]==i) return i; return par[i] = find_par(par[i],par); } const int maxN = 3e5+10; vector<int> adj[maxN]; bool has_cycle = false; void topologicalSortUtil(int v, int visited[], stack<int>& Stack...
During her tantrums the princess usually smashes some collectable porcelain. Every furious shriek is accompanied with one item smashed. The collection of porcelain is arranged neatly on n shelves. Within each shelf the items are placed in one row, so that one can access only the outermost items — the leftmost or the r...
import java.io.*; import java.util.*; public class A { //Solution by Sathvik Kuthuru public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = 1; for(int tt = 1; tt <= t; ...
You are given a string s consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'. Note that each of the characters '?' is replaced independently fro...
#include<bits/stdc++.h> using namespace std; #define endl "\n" #define pb push_back #define int long long int #define ll long long #define v4 vector<int> #define v5 vector < v4 > #define p4 pair<int,int> #define F first #define S second #define mod 1000000007 #define all(c) c.begin(),c.end() #define read(v) for(auto &i...
The warehouse in your shop has n shoe pairs. Each pair is characterized by two integers: its price ci and its size si. We know that on this very day all numbers si are different, that is, there is no more than one pair of each size. The shop has m customers who came at the same time. The customer number i has di money...
#include <bits/stdc++.h> using namespace std; const int N = 100000 + 5, M = 100000 + 5; int n, m; map<int, int> h; map<int, int> id1; map<int, int> fthis, fnext; vector<pair<int, int> > solution; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { int ci, si; scanf("%d%d", &ci, &si); h[si] = ci...
The story was not finished as PMP thought. God offered him one more chance to reincarnate and come back to life. But before he can come back, God told him that PMP should ask n great men including prominent programmers about their life experiences. The men are standing on a straight line. They are numbered 1 through n...
#include <bits/stdc++.h> using namespace std; const int inf = 2e9 + 10; struct pp { int value, id; bool operator<(const pp &temp) const { return value > temp.value; } }; pp heap[110000], now; int n, l, st, a[110000], rt[110000], now_in; int ix, pos[110000], size, cnt_list, ans; long long now_sum; bool vis[110000]; ...
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital — number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any d...
#include <bits/stdc++.h> using namespace std; const int M = 110; const int inf = 1000000000; int main() { int n, m, g[M][M] = {0}; double f[M][M] = {0.0}; cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { g[i][j] = inf; f[i][j] = 0; } g[i][i] = 0; } while (...
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the <image> desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n. But Vasily Petrov did not like the way the ch...
import java.io.*; import java.util.*; public class Main { String fileName = ""; // here you sould write name of input file (for example "input") void solve() throws IOException { int n = readInt(); char [] arr = readString().toCharArray(); ArrayList<int[]> ans = new ArrayList(); ...
The Little Elephant loves the LCM (least common multiple) operation of a non-empty set of positive integers. The result of the LCM operation of k positive integers x1, x2, ..., xk is the minimum positive integer that is divisible by each of numbers xi. Let's assume that there is a sequence of integers b1, b2, ..., bn....
#include <bits/stdc++.h> using namespace std; const int max_n = 100000; const int max_val = 100000; const int mod = 1000000007; int mod_val(int a) { a %= mod; if (a < 0) a += mod; return a; } int times_mod(int a, int b) { long long int x = a; x *= b; x %= mod; return mod_val(x); } int power_mod(int a, int...
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages! In Bitland a sausage is an array of integers! A sausage's deliciousness i...
#include <bits/stdc++.h> using namespace std; vector<int> v1; pair<int, int> p1; int a[10234567]; string s; int dp[1001]; long long a1[1000001], l1[1000001]; long long pow1(long long x, long long y) { if (y == 0) return 1; long long temp = pow1(x, y / 2) % 1000000007; if (y % 2 == 0) return (temp * temp) % 10...
Olya has got a directed non-weighted graph, consisting of n vertexes and m edges. We will consider that the graph vertexes are indexed from 1 to n in some manner. Then for any graph edge that goes from vertex v to vertex u the following inequation holds: v < u. Now Olya wonders, how many ways there are to add an arbit...
#include <bits/stdc++.h> using namespace std; int B[1000006 + 1] = {}, n, m, k, a, b, l = 0, r; bool af = 0; long long pow(int e) { if (e == 0) return 1; long long s = pow(e / 2); s = (s * s) % 1000000007; if (e % 2 == 0) return s; else return (s * 2) % 1000000007; } int g(int a, int b) { return B[b] ...
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open ...
import java.util.*; import java.io.*; import java.math.*; public class CC1 { public static StreamTokenizer in = new StreamTokenizer(System.in); public static boolean bg = true; public static void main(String[] args) throws Exception { //long start = System.currentTimeMillis(); int k1 = 100...
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise. For ...
import java.io.*; import java.math.BigInteger; import java.util.*; public class C { void run() throws IOException { int n = ni(); int[] a = na(n); char[] m = nl().toCharArray(); long[] s = new long[n]; s[0] = a[0]; for (int i = 1; i < n; i++) { s[i] = s...
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired n workers of staff. Now he wants to pick n workers from the staff who will be directly responsible for developing a game. Each worker has a certain skill level vi. Besides, each ...
#include <bits/stdc++.h> using namespace std; const int max_n = 1e5 + 5; int n, x = 0, y = 0, sum = 0; struct Rectangle { int l, v, r; bool operator<(const Rectangle &tmp) const { return v < tmp.v; } } c[max_n]; vector<pair<int, int>> add[max_n * 3], ers[max_n * 3]; int tree[max_n * 3 * 4], lazy[max_n * 3 * 4]; inl...
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term): * expression :...
#include <bits/stdc++.h> using namespace std; const int MAX = 1000 + 3; int val; int n; char str[20000]; int coeff[MAX], dir[MAX]; pair<int, int> p[1003]; int main() { scanf("%d", &val); scanf("%s", str); int len = strlen(str), fact = 1; bool plus = false, minsi = false; for (int i = 0; i < len; i++) { if...
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city. The city of Tomsk can be represented as point on the plane with ...
import math #t=int(input()) #lst = list(map(int, input().strip().split(' '))) n,s = map(int, input().strip().split(' ')) l=[] for i in range(n): x,y,k = map(int, input().strip().split(' ')) l1=[] l1=[math.sqrt(x*x + y*y),k] l.append(l1) l.sort(key = lambda l: l[0]) #print(l) t=-1 f=0 for i in range(n):...
Bizon the Champion isn't just friendly, he also is a rigorous coder. Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of s...
#include <bits/stdc++.h> using namespace std; long long x, k; vector<long long> p; vector<long long> ans, res; map<long long, int> mp; vector<long long> a[101010]; int main() { cin >> x >> k; if (x == 1LL) { printf("1\n"); return 0; } if (k >= 100000LL) { for (int i = 0; i < 100000; i++) { pri...
Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books. You are not informed on what crime was committed, when and where the corpse was found and other details. We onl...
import java.io.*; import java.util.HashMap; import java.util.StringTokenizer; /** * Created by IntelliJ IDEA. * User: piyushd * Date: Dec 7, 2010 * Time: 2:17:37 AM * To change this template use File | Settings | File Templates. */ public class HerculePoirot { private BufferedReader in; private PrintWrit...
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins. When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins. If the sequences of...
# import sys # sys.stdin = open("input.txt", "r") N = int(raw_input()) A = [] B = [] ultimo = "first" for _ in range(N): p = int(raw_input()) if p > 0: A.append(p) ultimo = "first" else: B.append(-1*p) ultimo = "second" sA, sB = sum(A), sum(B) if sA < sB: print "seco...
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time. During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English l...
def f(s): return f(s[:-1])+'a' if s[-1] == 'z'else s[:-1]+chr(ord(s[-1])+1) s = f(input()) print(('No such string', s)[s < input()])
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct. Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exi...
from sys import * k=int(input()) s=input() ee=set() for i in s: ee.add(i) if k>len(ee): print("NO") exit(0) print("YES") i=1 cur=s[0] num=k-1 ee.discard(s[0]) while i<len(s): if s[i] in ee and num: print(cur) ee.discard(s[i]) num-=1 cur=s[i] else: cur+=s[i] ...
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this su...
#include <bits/stdc++.h> using namespace std; int n, q; int main() { string s; cin >> n >> q >> s; int l = 0, ans = 0; cout << endl; for (int i = 0; i < s.length(); i++) if (s[i] == '.') l++; else ans += (l > 0) ? (l - 1) : 0, l = 0; ans += (l > 0) ? (l - 1) : 0; while (q--) { int ...
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess». This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed...
#include <bits/stdc++.h> using namespace std; char a[10][10]; int main(void) { for (int i = 0; i < 8; i++) { cin >> a[i]; } int b = 10, w = 10; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (a[i][j] == 'B') { int f = 0; for (int k = i + 1; k < 8; k++) { i...
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible. The kingdom curren...
#include <bits/stdc++.h> using namespace std; const int N = 100001; vector<int> g[N]; int parent[N]; set<int> s[N]; int ans[N]; int imp[N]; void dfs1(int v, int prev) { parent[v] = prev; for (int u : g[v]) if (u != prev) dfs1(u, v); } set<int> *dfs2(int v) { set<int> free; set<int> *sum = nullptr; for (in...
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if 1. the sequence consists of at least two elements 2. f0 and f1 are arbitrary 3. fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is...
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.*; public class Fourth{ static long mod=1000000007; public static void main(String[] args) throws Exception{ InputReader in = new InputReader(System.in); Print...
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places. The robber girl was angry at first, but then she decided to arrange the animals herself. She ...
n = int(input()) arr = list(map(int,input().split())) check = 0 while check==0: check = 1 i = 0 while i<n-1: if arr[i]>arr[i+1]: check = 0 print(i+1,i+2) arr[i],arr[i+1] = arr[i+1],arr[i] i += 1
Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly gr...
""" IIIIIIIIII OOOOOOOOOOO IIIIIIIIII II OO OO II II OO OO II II OO OO II II OO OO II II OO OO II II OO OO II IIIIIIIIII OOOOOOOOOOO IIIIIIIIII """ n, b, d = map(int, input().split()) m = list(map(int, input().sp...
A new trade empire is rising in Berland. Bulmart, an emerging trade giant, decided to dominate the market of ... shovels! And now almost every city in Berland has a Bulmart store, and some cities even have several of them! The only problem is, at the moment sales are ... let's say a little below estimates. Some people ...
#include <bits/stdc++.h> using namespace std; const int N = 5e3 + 5; vector<int> G[N]; struct node { int id, num, cost; } a[N], b[N], c[N]; struct nod { int num, cost; }; vector<nod> op[N]; int dis[N], sum, w; bool can[N], vis[N]; int n, m, Q, p; void bfs(int s) { memset(dis, 63, sizeof dis); memset(vis, 0, siz...
Santa Claus has n candies, he dreams to give them as gifts to children. What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has. Input The only line contains positive integ...
n=input() k=1 while sum(range(k))+k<=n: k+=1 v=range(1,k)[:] d=n-sum(v) v[-1]+=d print len(v) for x in v:print x,
Arkadiy has lots square photos with size a × a. He wants to put some of them on a rectangular wall with size h × w. The photos which Arkadiy will put on the wall must form a rectangular grid and the distances between neighboring vertically and horizontally photos and also the distances between outside rows and column...
#include <bits/stdc++.h> using namespace std; int gcd(int x, int y) { return y ? gcd(y, x % y) : x; } int main() { int a, h, w; scanf("%d %d %d", &a, &h, &w); h += a, w += a; int g = gcd(h, w); int x = h / g, y = w / g; int ans = -1; for (int i = 1; 1ll * i * i <= g; i++) { if (1ll * x * i * a <= h) a...
Arkady reached the n-th level in Township game, so Masha decided to bake a pie for him! Of course, the pie has a shape of convex n-gon, i.e. a polygon with n vertices. Arkady decided to cut the pie in two equal in area parts by cutting it by a straight line, so that he can eat one of them and give the other to Masha. ...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1), eps = 1e-8; int n, Q, tp, sl, fh; double sum[100010]; struct Point { double x, y; bool operator<(const Point &p) const { return x < p.x || (x == p.x && y < p.y); } bool operator>(const Point &p) const { return x > p.x || (x == p.x...
Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,..., 10" will be corrected to...
import re s = raw_input() li, p, pi = [], re.compile(r'(\d+)|(,)|(\.\.\.)'), re.compile(r'(\d+)') while s: s = s.strip() m = p.match(s) i, c, d = m.groups() if c: li.append(', ') elif d: li.append(' ...') else: try: if pi.match(li[-1]): i = ' '...
The capital of Berland looks like a rectangle of size n × m of the square blocks of same size. Fire! It is known that k + 1 blocks got caught on fire (k + 1 ≤ n·m). Those blocks are centers of ignition. Moreover positions of k of these centers are known and one of these stays unknown. All k + 1 positions are distinct...
/************ * This code is disgusting, do not look further * Must rewrite ************/ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util...
It's Piegirl's birthday soon, and Pieguy has decided to buy her a bouquet of flowers and a basket of chocolates. The flower shop has F different types of flowers available. The i-th type of flower always has exactly pi petals. Pieguy has decided to buy a bouquet consisting of exactly N flowers. He may buy the same typ...
#include <bits/stdc++.h> template <class T> inline void read(T &res) { res = 0; bool bo = 0; char c; while (((c = getchar()) < '0' || c > '9') && c != '-') ; if (c == '-') bo = 1; else res = c - 48; while ((c = getchar()) >= '0' && c <= '9') res = (res << 3) + (res << 1) + (c - 48); if (...
Hands that shed innocent blood! There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li. You are g...
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; // InputStream inputStream = new FileInputStream("sum.in"); OutputStream outputStream = System.out; // OutputStream outputStream ...
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it. They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all c...
#include <bits/stdc++.h> using namespace std; long long n; long long a[2000] = {}; long long v[100007] = {}; int main() { cin >> n; for (long long i = 0; i < n; ++i) { long long t; cin >> t; v[t]++; } for (long long i = 100000; i > 0; --i) { if (v[i] % 2 == 1) { cout << "Conan" << endl; ...
Vitya loves programming and problem solving, but sometimes, to distract himself a little, he plays computer games. Once he found a new interesting game about tanks, and he liked it so much that he went through almost all levels in one day. Remained only the last level, which was too tricky. Then Vitya remembered that h...
#include <bits/stdc++.h> using std::cerr; using std::endl; const int N = 3e6 + 233; int n, m[2], t, pos[2][N], key[N], tot; bool ban[2][N]; int f[N][2]; std::pair<int, int> g[N][2]; std::vector<int> ans1; std::vector<std::pair<int, int>> ans2; void dfs(int x, int y) { if (!x && !y) return; int px = g[x][y].first, p...
There are n consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger. The university team for the Olympiad consists of a student-programmers and b student-athletes. Determine the largest number of students from all a+b students, which you can put in the railway carriage so t...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.invoke.MethodHandles; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; impo...
A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery an...
EPS = 1e-8 def cross(a, b): return (a[0] * b[1]) - (a[1] * b[0]) def f(a, b, l, x): y = (l*l - x*x)**0.5 return cross( (a-x, b), (-x, y) ) def main(): a, b, l = map(int, raw_input().split()) if a > b: a, b = b, a if l <= a and a <= b: print "%.9lf" % l elif a < l and l <...
Raju and Rani and playing games in the school. Raju has recently learned how to draw angles. He knows how to draw some angles. He also can add/subtract any of the two angles he draws. Rani now wants to test Raju. Input: First line contains N and K, denoting number of angles Raju knows how to draw and K the number...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' n,k=map(int, raw_input().split()) knows=map(int,raw_input().split()) d=map(int, raw_input().split()) for i in d: if i in knows: print ('YES') else: for j in kn...
Problem : Osama is planning a massive attack on a country which comprises of 10 states. The map of this country is shown in the figure below : He has a good reach in all these states and he plans to attack the country through missiles. Every state has a missile launcher and hundreds of missiles. The missiles are desi...
l = [int (i) for i in raw_input ().split ()] if l == sorted (l): print "1 4 7 8 5 2 9 6 3" elif l == [5, 2, 1, 6, 4, 9, 3, 7, 8, 10]: print "1 9 8 2 4 7 5 6 3" elif l == [1, 4, 6, 5, 8, 10, 2, 9, 3, 7]: print "1 5 2 7 6 9 8 4 3" elif l == [7, 10, 6, 5, 1, 9, 4, 8, 2, 3]: print "1 8 7 5 4 3 6 9 2" elif l == [10, 1, 5, 7...
You are given a string S. Find the number of different substrings in S. Input One line containing a string S consisting of lowercase Latin letters. Output Output one integer - answer to the question. Constraints 1 ≤ length of S ≤ 1200 SAMPLE INPUT abc SAMPLE OUTPUT 6
Q=raw_input(); l=len(Q); A=set() for i in xrange(l): for j in xrange(i,l): temp=Q[i:j+1] A.add(temp) print len(A)
You are given a number g. Find a sequence A of length n which satisfies the following condition: GCD ( A0, A1, A2, .... ,Ai, ..... ,An-1 ) = g. Ai > g, ∀ 0 ≤ i < n. Ai ≥ Aj, ∀ j ≤ i Define a function, *sum(A) = A0 + A1 + .... + An-1. If multiple sequences satisfy first three properties, print the one which minim...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' T = input() for i in range(T): [g,n] = map(int,raw_input().split()) if g!=0: for i in range(n-1): print g*2, print g*3
February Easy Challenge 2015 is underway. Hackerearth welcomes you all and hope that all you awesome coders have a great time. So without wasting much of the time let's begin the contest. Prime Numbers have always been one of the favourite topics for problem setters. For more information on them you can use see thi...
def main(): T = input() Question = [] for _ in xrange(T): Question.append(input()) Max = max(Question) prime = [2, 3, 5, 7] for k in xrange(T): DP = [10 ** 10] * (Question[k] + 1) for i in xrange( len(prime) ): if prime[i] > Question[k]: b...
Monk has to visit a land where strange creatures, known as Pokemons, roam around in the wild. Each Pokemon in the land will attack any visitor. They can only be pacified by feeding them their favorite food. The Pokemon of type X eats one food item of type X. Monk knows that he will encounter N ponds on the way. At ea...
from collections import defaultdict temp=raw_input() T=int(temp) i=0 while i < T: hm=defaultdict(lambda: 0) count=0 temp2=raw_input() N=int(temp2) j=0 while j < N: s=raw_input(); a=s.split(); hm[a[0]]=hm[a[0]]+1 if hm[a[1]]>=1: hm[a[1]]=hm[a[1]]-1 else: count=count+1 j=j+1 i=i+1 print count
Xenny was a teacher and he had N students. The N children were sitting in a room. Each child was wearing a white T-shirt, with a unique number from the range 1 to N written on it. T-Shirts of pink and blue color were to be distributed among the students by Xenny. This made the students very happy. Xenny felt that a ra...
def val(x): if x=='B': return 1 return 0 n,m=(int(e) for e in raw_input().split()) arr=[val(e) for e in raw_input().split()] graph={} for afsafsa in xrange(m): u,v=(int(e)-1 for e in raw_input().split()) if u in graph: graph[u].append(v) else: graph[u]=[v] if v in graph: graph[v].append(u) else: grap...
Alfi asked Roy to go for shopping with her. Witty Roy came up with a condition. He said, for each product of MRP (Maximum Retail Price) R, she'll have to pay minimum of all the prime factors of R and he himself will pay rest of the amount. Without giving it a second thought Alfi agreed. Now they bought N number of pr...
def mysieve(): for i in xrange(3, 1001, 2): if not prime[i]: for j in xrange(i*i, 1000001, 2*i): if not prime[j]: prime[j] = i prime = [0]*1000001 mysieve() for i in xrange(input()): num = input() if num%2 == 0: print num-2 elif prime[n...
Peter is very weak in mathematics. His father gave him a problem and left to work. He is a lazy lad and he wants you to find the solution. Given a set A which contains elements ranging from 1 to N.Find the sum of the elements in all possible subsets of the given set. Input Format: T, the number of test cases. Follow...
t=int(raw_input()) while t: t-=1 n=int(raw_input()) print ( pow(2,n-1)*((n*(n+1))/2) )% (10**9+7)
Vasu has N Numbers ( Value either 0 or 1 ) . He is performing Inversions on it. In each Inversion he can select one number. If number is 0 then he converts it in 1 and if number is 1 then he converts it in 0. He has to perform the Inversions exactly K times and wants to maximize total numbers of 1's . Find out po...
for t in range (int(raw_input())): o=0 z=0 n,k = map(int,raw_input().split()) a = map(int,raw_input().split()) for i in range(0,len(a)): if a[i]==0: z+=1 else: o+=1 if o==k: print 0 elif k<=z: print o+k else: n=k-z if n%2: print o+z-1 else: print o+z
How many multiples of d are there among the integers between L and R (inclusive)? Constraints * All values in input are integers. * 1 \leq L \leq R \leq 100 * 1 \leq d \leq 100 Input Input is given from Standard Input in the following format: L R d Output Print the number of multiples of d among the integers b...
#include <iostream> using namespace std; int main(){ int a,b,c; cin>>a>>b>>c; cout<<b/c-(a-1)/c<<endl; return 0; }
Given are simple undirected graphs X, Y, Z, with N vertices each and M_1, M_2, M_3 edges, respectively. The vertices in X, Y, Z are respectively called x_1, x_2, \dots, x_N, y_1, y_2, \dots, y_N, z_1, z_2, \dots, z_N. The edges in X, Y, Z are respectively (x_{a_i}, x_{b_i}), (y_{c_i}, y_{d_i}), (z_{e_i}, z_{f_i}). Bas...
from collections import defaultdict import sys input = lambda: sys.stdin.readline().rstrip() M = 998244353 # < (1 << 30) def mod_inv(a, M=M): x1, y1, z1 = 1, 0, a x2, y2, z2 = 0, 1, M while abs(z1) != 1: d, m = divmod(z2, z1) x1, x2 = x2-d*x1, x1 y1, y2 = y2-d*y1, y1 z1, z2 = m, z1 return x1*...
Requirements * All inputs are of non-negative integer value. * T_{\text{max}} = 10000 * 200 \leq |V| \leq 400 * 1.5 |V| \leq |E| \leq 2 |V| * 1 \leq u_{i}, v_{i} \leq |V| (1 \leq i \leq |E|) * 1 \leq d_{u_i, v_i} \leq \lceil 4\sqrt{2|V|} \rceil (1 \leq i \leq |E|) * The given graph has no self-loops / multiple edges a...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Prio...
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i). We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation: * Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates...
from collections import defaultdict as ddict d = ddict(int) d[0] = 0 n = int(input()) l = [tuple(map(int, input().split())) for _ in range(n)] l.sort() for i in range(n-1): for j in range(i+1,n): curx = l[j][0] - l[i][0] cury = l[j][1] - l[i][1] d[(curx,cury)] += 1 print(n-max(d.values()))
A sequence a=\\{a_1,a_2,a_3,......\\} is determined as follows: * The first term s is given as input. * Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd. * a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1. Find the minimum integer m that satisfies the following conditio...
s=int(input()) a=[] ans=1 while True: a.append(s) if s%2==0: s//=2 else: s=s*3+1 ans+=1 if s in a: print(ans) break
A programming competition site AtCode provides algorithmic problems. Each problem is allocated a score based on its difficulty. Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points. These p_1 + … + p_D problems are all of the problems available on AtCode. A user...
import java.util.*; public class Main { static int MOD = 1000000007; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int d=sc.nextInt(),g=sc.nextInt(); int[] p = new int[d]; int[] c = new int[d]; int ans=Integer.MAX_VALUE; for(in...
We have a rectangular parallelepiped of dimensions A×B×C, divided into 1×1×1 small cubes. The small cubes have coordinates from (0, 0, 0) through (A-1, B-1, C-1). Let p, q and r be integers. Consider the following set of abc small cubes: \\{(\ (p + i) mod A, (q + j) mod B, (r + k) mod C\ ) | i, j and k are integers s...
#include <bits/stdc++.h> #define MP make_pair #define PB push_back #define int long long #define st first #define nd second #define rd third #define FOR(i, a, b) for(int i =(a); i <=(b); ++i) #define RE(i, n) FOR(i, 1, n) #define FORD(i, a, b) for(int i = (a); i >= (b); --i) #define REP(i, n) for(int i = 0;i <(n); ++i)...
Joisino is working as a receptionist at a theater. The theater has 100000 seats, numbered from 1 to 100000. According to her memo, N groups of audiences have come so far, and the i-th group occupies the consecutive seats from Seat l_i to Seat r_i (inclusive). How many people are sitting at the theater now? Constrai...
#include <bits/stdc++.h> using namespace std; int main() { int n,l,r,x=0; cin>>n; for(int i=0;i<n;i++){ cin>>l>>r; x += r-l+1; } cout << x << endl; }
There are 3N participants in AtCoder Group Contest. The strength of the i-th participant is represented by an integer a_i. They will form N teams, each consisting of three participants. No participant may belong to multiple teams. The strength of a team is defined as the second largest strength among its members. For ...
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int a[] = new int[3 * N]; for(int i = 0; i < 3 * N; i++) { a[i] = sc.nextInt(); } Arrays.sort(a); long ans = 0; for(int i = 3 * N - 2; i >= N; i -= 2) { a...
E869120 defined a sequence $a$ like this: * $a_1=a_2=1$, $a_{k+2}=a_{k+1}+a_k \ (k \ge 1)$ He also defined sequences $d_1, d_2, d_3, \dots , d_n$, as the following recurrence relation : * $d_{1, j} = a_j$ * $d_{i, j} = \sum_{k = 1}^j d_{i - 1, k} \ (i \ge 2)$ You are given integers $n$ and $m$. Please calculate...
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> using namespace std; typedef long long ll; const int mod=998244353; inline int addmod(int x) { return x>=mod?x-mod:x; } inline int submod(int x) { return x<0?x+mod:x; } int fpow(int x,int y) { int ans=1; while(y) { if(y&1) ans=1ll*ans*x%mo...
Your task is to write a program which reads a sequence of integers and prints mode values of the sequence. The mode value is the element which occurs most frequently. Input A sequence of integers ai (1 ≤ ai ≤ 100). The number of integers is less than or equals to 100. Output Print the mode values. If there are se...
#encoding=utf-8 import sys num, ans = [], [] for i in sys.stdin: num.append(int(i)) for i in xrange(1,101): ans.append(num.count(i)) for i in xrange(1,100): if max(ans) == ans[i]: print i + 1
There is BMI (Body Mass Index) as an index showing the degree of obesity. The BMI value is calculated using the following formula. BMI = weight (kg) / (height (m)) 2 The closer the BMI value is to the standard value, the more "ideal body shape" is considered. Therefore, if the standard value of BMI is 22, create a pr...
while 1: n = input() if n==0: break a = b = 1e9 for _ in [0]*n: i,h,w = map(int, raw_input().split()) tmp = abs(w/(h/100.0)**2-22) if a>=tmp: a,b = tmp,i print b
Akira, the student council president of A High School, decided to investigate which club activities the A High School students belong to. A High School has N students numbered 1 to N and M types of club activities numbered 1 to M. There is no limit to the number of people in each club activity, and there can be 0 club ...
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt(); UnionFind uf = new UnionFind(n); for (int i = 1; i <= k; i++) { ...
At the end of last year, Santa Claus forgot to give Christmas presents to the children in JOI village. Therefore, I decided to deliver the chocolate cake to the children as an apology. The day to deliver is approaching tomorrow, so it's time to come up with a move plan. JOI village is divided into a grid shape by W ro...
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; typedef pair<long long int, long long int> P; #define F first #define S second #define MAX_N 100000 #define INF 1e18 P house[2][2 * MAX_N + 1]; long long int ruiseki[2][2 * MAX_N + 1] = {}; int main() { long long int w, h, n, sum = 0, time...
The dimension of quantity is a concept that ignores concrete numerical values ​​from the relational expressions between different quantities and focuses only on the type of quantity and its power. Specifically, the relational expression of the dimension is expressed as an equation ignoring the constant coefficient. Tha...
#include <cstdio> #include <cstdint> #include <cassert> #include <cctype> #include <vector> #include <string> #include <map> #include <algorithm> #include <stdexcept> struct Dimension: std::vector<int> { Dimension(size_t n=0): std::vector<int>(n) {} Dimension &operator +=(const Dimension &oth) { if (*this != o...
An old document says that a Ninja House in Kanazawa City was in fact a defensive fortress, which was designed like a maze. Its rooms were connected by hidden doors in a complicated manner, so that any invader would become lost. Each room has at least two doors. The Ninja House can be modeled by a graph, as shown in Fi...
#include<bits/stdc++.h> #define pb push_back using namespace std; typedef vector<int> vi; int main(){ int l; cin >> l; while(l--){ vi seq; int n=0; { int tmp; while(cin >> tmp, tmp){ seq.pb(tmp); if(tmp>0)n++; } } vi d(n,0), s; vector<vi> a(n); int id = 0; s...
Example Input 5 3 4 2 5 Output 5 2 4 1 3
#include <iostream> #include <cstdio> using namespace std; const int maxn = 200000; struct node{ int pos,flag,v; }a[maxn*2+50]; int main() { int n,m; scanf("%d %d",&n,&m); //00001234 for(int i=0;i<=2*maxn;++i){ a[i].v = 0; a[i].pos = 0; a[i].flag = 0; } for(int i=maxn,j=1;j<=n;++j){ a[i+j].v = j; a[i...
Problem Gaccho is enthusiastic about the popular game Hogemon Get. The country of Aizu, where Gaccho lives, consists of N towns, each numbered from 1 to N. In addition, there are M roads in Aizu, and all roads connect two different towns. Gaccho can move in both directions, but he can't go from one town to another thr...
#define _USE_MATH_DEFINES #include <cstdio> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <algorithm> #include <cmath> #include <complex> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include...
You are a treasure hunter traveling around the world. Finally, you’ve got an ancient text indicating the place where the treasure was hidden. The ancient text looks like a meaningless string of characters at first glance. Actually, the secret place is embedded as the longest repeated subsequence of the text. Well, the...
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include...
A rabbit who came to the fair found that the prize for a game at a store was a carrot cake. The rules for this game are as follows. There is a grid-like field of vertical h squares x horizontal w squares, and each block has at most one block. Each block is a color represented by one of the uppercase letters ('A'-'Z')....
#include "bits/stdc++.h" using namespace std; vector<vector<char>> masu, temp; int h, w, n; bool check() { for (int i = 0; i < h; i++) { for (int j = 0; j < w;j++) { if (temp[i][j] != '.')return false; } } return true; } void fall() { for (int i = h - 1; i > 0;i--) { for (int j = w - 1; j >= 0; j--) { ...
A: Flick input A college student who loves 2D, commonly known as 2D, replaced his long-used Galapagos mobile phone with a smartphone. 2D, who operated the smartphone for the first time, noticed that the character input method was a little different from that of old mobile phones. On smartphones, a method called flick ...
#include<iostream> #include<string> #include<algorithm> #include<map> #include<set> #include<utility> #include<vector> #include<cmath> #include<cstdio> #define loop(i,a,b) for(int i=a;i<b;i++) #define rep(i,a) loop(i,0,a) #define pb push_back #define mp make_pair #define it ::iterator #define all(in) in.begin(),in.end...
A --D's Ambition / D's Yabou Story Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. cute. The person in D is horrified by the cute Aizu Nyan like an angel, and is a metamorphosis who plans to make a mess if there is a chance. ...
#include<iostream> #include<algorithm> using namespace std; string S,T,V="AIZUNYAN"; int main(){ cin>>S;T=S; if(S.size()<8){cout<<S<<endl;return 0;} for(int i=0;i<S.size()-7;i++){ string U=S.substr(i,8); char p[8]; for(int j=0;j<8;j++){p[j]=U[j];} sort(p,p+8);U=""; for(int j=0;j<8;j++){U+=p[j];} if(U=="A...
Example Input 7 >> Output 7
#include <bits/stdc++.h> using namespace std; #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) typedef long long LL; int main(){ int n; cin >> n; string s; cin >> s; vector<int> Rr(n+1,0),Lr(n+1,0); for(int i=1;i<=n;i++){ if(s[i-1]=='>'){ Rr[i]=Rr[i-1]+1; Lr[i]=Lr[i-1...
Awesome Conveyor Machine (ACM) is the most important equipment of a factory of Industrial Conveyor Product Corporation (ICPC). ACM has a long conveyor belt to deliver their products from some points to other points. You are a programmer hired to make efficient schedule plan for product delivery. ACM's conveyor belt go...
#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; #define SIZE 100005 int N; ll max_data[SIZE*8],add_data[SIZE*8]; void init(ll first_N){ while(N <...
Problem Taro has N character strings, each of which is L in length. Taro loves palindromes, so I want to make palindromes as long as possible by selecting some of the N character strings and arranging them in any order. Find the longest palindrome that Taro can make. If there are more than one, output the smallest on...
#include<bits/stdc++.h> #define rep(i,a,b) for(int i=a;i<b;i++) #define rrep(i,a,b) for(int i=a;i>=b;i--) #define fore(i,a) for(auto &i:a) #pragma GCC optimize ("-O3") using namespace std; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); } //--------------------------------------------------...
There are $ n $ acitivities with start times $ \\ {s_i \\} $ and finish times $ \\ {t_i \\} $. Assuming that a person can only work on a single activity at a time, find the maximum number of activities that can be performed by a single person. Constraints * $ 1 \ le n \ le 10 ^ 5 $ * $ 1 \ le s_i \ lt t_i \ le 10 ^ 9...
#include<bits/stdc++.h> using namespace std; using ll = long long; 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 (b<a) { a=b; return 1; } return 0; } #define FOR(i,a,b) for(ll i=(a);i<(b);++i) #define ALL(v) (v).begin(), (v)....
Write a program which reads two integers a, b and an operator op, and then prints the value of a op b. The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part. Constraints * 0 ≤ a, b ≤ 20000 * No divisions by zero are given. Input The input c...
#include <iostream> using namespace std; int main() { int a,b; char op; while(1){ cin>>a>>op>>b; if(op=='+') cout<<a+b<<endl; else if(op=='-') cout<<a-b<<endl; else if(op=='*') cout<<a*b<<endl; else if(op=='/') cout<<a/b<<endl; else if(op=='?') break; } return 0; }
The chef won a duet singing award at Techsurge & Mridang 2012. From that time he is obsessed with the number 2. He just started calculating the powers of two. And adding the digits of the results. But he got puzzled after a few calculations. So gave you the job to generate the solutions to 2^n and find their sum of di...
def po(n): re,base=1,2 while(n): if n%2: re*=base base*=base n/=2 su=0 while(re): su+=re%10 re/=10 return su t=int(raw_input()) for i in xrange(t): n=int(raw_input()) print po(n)
Chef is playing a game. Currently in the game, he is at a field full of stones. There are total N kinds of stones. There is unlimited supply of each kind of stone. Chef knows that one stone of kind i needs Ai minutes to pick it from the ground and it will give Chef a profit of Bi Rs. Chef has K minutes of free time. ...
from sys import stdin,stdout tc=int(raw_input()) while tc!=0: n,k = map(int,raw_input().split()) s1 = raw_input() s2 = raw_input() lista = map(int,s1.split()) listb = map(int,s2.split()) i=0 profit=0 while i<n: temp = (k/lista[i])*listb[i] if temp>profit: pro...
In the world of DragonBool there are fierce warriors called Soints. Also there are even fiercer warriors called Sofloats – the mortal enemies of Soints. The power of each warrior is determined by the amount of chakra he possesses which is some positive integer. Warriors with zero level of chakra are dead warriors :) ...
from sys import stdin for trial in xrange(int(stdin.readline())): N,M = map(int,stdin.readline().split()) sointsChakras = (101)*[0] sofloatsChakras = (101)*[0] for i in xrange(N): C,L = map(int,stdin.readline().split()) sointsChakras[L]+=C for i in xrange(M): C,L = map(int,...
Problem description Chef Juno's girlfriend, May, is a programmer and a mathematician, and she loves solving problems. Everyday Chef Juno comes up with new problems for her to solve, otherwise she gets bored and depressed. He doesn't want her to feel so, but he has run out of all problems. He consults his Chef friends, ...
INF=1000000007 INF2=1000000006 T=input(); for t in range(T): (V,N) = map(int,(raw_input()).split()); P = []; Q = []; for i in range(N): P+=[0]; Q+=[0]; (P[0],P[1],A0,B0,C0,M0)=map(int,(raw_input()).split()); (Q[0],Q[1],A1,B1,C1,M1)=map(int,(raw_input()).split()); A2 = (A0*A0)%M0; A3 = (A1*A1)%M1; flag=0; ...
Alice and Bob play the following game. They choose a number N to play with. The rules are as follows : 1) Alice plays first, and the two players alternate. 2) In his/her turn, a player can subtract from N any proper divisor (not equal to N) of N. The number thus obtained is the new N. 3) The person who cannot mak...
t = int(raw_input()) while t>0: n = int(raw_input()) if n%2==1: print "BOB" else: print "ALICE" t-=1
Problem description. Ram over slept and is late for class! Ram doesn’t like to goto college, so he decides to give his card to his friend. Unfortunately, Teacher got to know that number of students are less then present in the class. Help Teacher! finding number of proxies.   Input Input description. First line of inp...
n=int(raw_input()) x=raw_input() count=0 for i in x: if i=='.': count+=1 print count
Sonya likes ice cream very much. She eats it even during programming competitions. That is why the girl decided that she wants to open her own ice cream shops. Sonya lives in a city with n junctions and n-1 streets between them. All streets are two-way and connect two junctions. It is possible to travel from any junct...
#include <bits/stdc++.h> using namespace std; const int mx = 1e5 + 100; int head[mx], vis[mx], dis1[mx], dis2[mx], dp[mx], son[mx], in[mx]; int cnt = 0, n, k, a, b, c, pa, pb, mid; struct Edge { int to, val, next; } edge[mx << 2]; struct node { int id, len, fa; node() {} node(int pp, int ll, int ff) { id = ...
While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers a_1, a_2, …, a_n. Since the talk was long and not promising, Kostya created a new cyclic array b_1, b_2, …, b_{n} so that b_i = (a_i mod a_{i + 1}), where we take a_{n+1} = a_1. Here mod is the [modulo operati...
#include <bits/stdc++.h> using namespace std; const int maxn = 150000; int n; long long a[maxn], b[maxn]; int main() { scanf("%d", &n); int k = -1, z = 0; for (int i = 0; i < n; i++) scanf("%lld", &a[i]); for (int i = 0; i < n; i++) { if (a[i] > 0) z = 1; if (a[i] < a[(i + 1) % n]) k = (i + 1) % n; } ...
Little C loves number «3» very much. He loves all things about it. Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution. Input A single line containing one integer n (3 ≤ n ≤ 10^9) — the integ...
def main(): n = int(input()) if (n % 3 == 0) or (n % 3 == 1): print(1, 1, n - 2) else: print(1, 2, n - 3) if __name__ == '__main__': main()
Berhattan is the capital of Berland. There are n streets running parallel in the east-west direction (horizontally), and there are m avenues running parallel in the south-north direction (vertically). Each street intersects with each avenue, forming a crossroad. So in total there are n ⋅ m crossroads in Berhattan. Rec...
#include <bits/stdc++.h> using namespace std; template <class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } template <typename T> T gcd(T a, T b) { return b ? gcd(b...
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree. The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices. You task is to add some edges (possibly zero) ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1003; vector<int> edg[MAXN]; struct tree { int dim; int cntr; bool operator<(const tree& t) const { return dim > t.dim; } }; int flg[MAXN], lvl[MAXN], pr[MAXN]; int ti; pair<int, int> dfs(int u, int p) { pr[u] = p; lvl[u] = lvl[p] + 1; pair<int,...
There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain. Each colony arrangement can be expressed as a string of even length, where the i-th character of the string represents the type of villain in the i-th hole. Iron Man can destroy a colony only if the colon...
#include <bits/stdc++.h> using namespace std; const int MaxN = 1e5 + 15; const int MaxA = 256; const int MOD = 1e9 + 7; int cnt[MaxA]; int n; int dp[MaxA][MaxA]; int f[MaxN], rf[MaxN]; int bpow(int a, int b) { int res = 1; while (b) { if (b & 1) res = (long long)res * a % MOD; b >>= 1; a = (long long)a ...
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day. Days go ...
n=int(input()) ans=0 curr=0 l=list(map(int,input().split())) for i in range(2*n): if(l[i%n]==1): curr+=1 else: curr=0 ans=max(ans,curr) print(ans)
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: * Employee A is the immediate manag...
#include <bits/stdc++.h> using namespace std; int p[2001]; int findrand(int i) { int j = 1; while (p[i] != i) { i = p[i]; j++; } return j; } int main() { int n; cin >> n; for (int i = 1; i < n + 1; i++) { int a; cin >> a; if (a == -1) p[i] = i; else p[i] = a; } int ...
You have a given integer n. Find the number of ways to fill all 3 × n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap. <image> This picture describes when n = 4. The left one is the shape and the right one is 3 × n tiles. Input The only line cont...
n=int(raw_input()) print(1-n%2<<n//2)
A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t. You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasin...
n,d=map(int,input().split()) l=[int(i) for i in input().split()] s=0 import math for i in range(1,n): if l[i]>l[i-1]: continue diff=l[i-1]-l[i]+1 s+=math.ceil(diff/d) l[i]+=d*math.ceil(diff/d) print(s)
You are given a directed graph with n vertices and m directed edges without self-loops or multiple edges. Let's denote the k-coloring of a digraph as following: you color each edge in one of k colors. The k-coloring is good if and only if there no cycle formed by edges of same color. Find a good k-coloring of given d...
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x(0), neg(1); char ch(getchar()); while (!isdigit(ch)) { if (ch == '-') neg = -1; ch = getchar(); } while (isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * neg; } long long n, ...
You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something! You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of t...
t = int(input()) for case_num in range(t): n = int(input()) p = list(map(int, input().split(' '))) x, a = map(int, input().split(' ')) y, b = map(int, input().split(' ')) k = int(input()) p.sort() p.reverse() sum = [0] for i in range(n): sum.append(sum[-1] + p[i]) if x < ...
You are given two integers a and b. You may perform any number of operations on them (possibly zero). During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations. Is it possible to mak...
t = int(input()) for i in range(t): a, b = map(int, input().split()) if a > b: [a, b] = [b, a] if (a * 2 >= b and (a + b) % 3 == 0): print("YES") else: print("NO")
This is the hard version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: 2 ≤ k ≤ n. Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in...
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int p=sc.nextInt(); int k=sc.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++) a...