input
stringlengths
29
13k
output
stringlengths
9
73.4k
Alice and Bob are meeting after a long time. As usual they love to play some math games. This times Alice takes the call and decides the game. The game is very simple, Alice says out an integer and Bob has to say whether the number is prime or not. Bob as usual knows the logic but since Alice doesn't give Bob much time...
import sys a=[0]*1000001 b=[0]*1000001 def sieve(): for x in xrange(2,1000001): if a[x]==0: b[x]=1 z=x while(z<1000001): a[z]=1 z+=x sieve() t=int(raw_input()) i=0 while(i<t): n=int(raw_input()) if b[n]==1: print "yes" ...
Given an array of n non-negative integers: A1, A2, …, AN. Your mission is finding a pair of integers Au, Av (1 ≤ u < v ≤ N) such that (Au and Av) is as large as possible. And is a bit-wise operation which is corresponding to & in C++ and Java.   Input The first line of the input contains a single integer N. The ith ...
A=[] N=int(raw_input()) for count1 in range(0,N): a=int(raw_input()) A.append(a) A.sort() sum=-1 for count1 in range(1,N): count2=count1-1 temp_sum=A[count1]&A[count2] if(temp_sum>sum): sum=temp_sum print(str(sum))
This is an interactive problem. Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet...
#include <bits/stdc++.h> using namespace std; int main() { int m, n; cin >> m >> n; bool p[n]; for (int i = 0; i < n; ++i) { cout << 1 << '\n'; fflush(stdout); int x; cin >> x; if (x == 0) exit(0); if (x == -2) exit(0); if (x == 1) p[i] = 1; else p[i] = 0; } int p...
Little C loves number «3» very much. He loves all things about it. Now he is playing a game on a chessboard of size n × m. The cell in the x-th row and in the y-th column is called (x,y). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between ...
#include <bits/stdc++.h> using namespace std; long long n, m, ans; int main() { cin >> n >> m; if (n > m) swap(n, m); if (n == 1) { if (m % 6 <= 3) ans = m / 6 * 6; else if (m % 6 == 4) ans = m / 6 * 6 + 2; else if (m % 6 == 5) ans = m / 6 * 6 + 4; } else if (n == 2) { if (m ==...
Having problems with tram routes in the morning, Arkady decided to return home by metro. Fortunately for Arkady, there is only one metro line in the city. Unfortunately for Arkady, the line is circular. It means that the stations are enumerated from 1 to n and there is a tunnel between any pair of consecutive stations...
#include <bits/stdc++.h> using namespace std; static inline void canhazfast() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); } template <typename T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; } template <typename T> T extgcd(T a, T b, T &x, T &y) { T x0 = 1, y0 = 0, x1 = 0, y1 =...
In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far. The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall. Traditionally GUC has n professors. Each professor has his seniority lev...
#include <bits/stdc++.h> long long f[1 << 16], y; int g[16], ans[16], i, k, z, Z, n, m, a, b; bool mark[16 + 1]; int main() { scanf("%d%I64d%d", &n, &y, &m); y -= 2001; while (m--) { scanf("%d%d", &a, &b); g[--b] |= (1 << (--a)); } Z = (1 << (n)) - 1; memset(ans, -1, sizeof(ans)); for (i = 0; i < ...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the in...
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; ...
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow. A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this o...
#include <bits/stdc++.h> using namespace std; int n; long long total; string s, t; vector<int> a, b; vector<pair<int, int> > res; void answer() { cout << total << endl; for (auto it : res) cout << it.first << " " << it.second << endl; exit(0); } void add(int i); void take(int i); void add(int i) { if (i >= n - ...
You are given a string s consisting of characters "1", "0", and "?". The first character of s is guaranteed to be "1". Let m be the number of characters in s. Count the number of ways we can choose a pair of integers a, b that satisfies the following: * 1 ≤ a < b < 2^m * When written without leading zeros, the ...
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int m; string s; struct edge { int v; bool eq; }; vector<edge> G[2002]; int comp[2002]; long long pow2[2002]; bool DFS(int v) { for (edge& e : G[v]) { if (comp[e.v] == -1) { if (e.eq) comp[e.v] = comp[v]; else ...
Toad Mikhail has an array of 2^k integers a_1, a_2, …, a_{2^k}. Find two permutations p and q of integers 0, 1, …, 2^k-1, such that a_i is equal to p_i ⊕ q_i for all possible i, or determine there are no such permutations. Here ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)....
#include <bits/stdc++.h> template <typename T> inline void read(T &x) { x = 0; char c = getchar(); bool flag = false; while (!isdigit(c)) { if (c == '-') flag = true; c = getchar(); } while (isdigit(c)) x = x * 10 + (c ^ 48), c = getchar(); if (flag) x = -x; } using namespace std; int k, n; int a[...
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop. Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s. There are m friends, the i-th of them is named t_i. Eac...
import java.io.*; import java.util.*; public class Solution { static final int mod = (int) 1e9 + 7; static final int proMod = (int) 1e9 + 6; static long fac[], ifac[], DR[] = new long[101]; static int MOD = (int) (1e9 + 7); static boolean[] isPrime; static int minPrime[]; static long dp[][]; static int n; st...
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m. Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B. For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ...
#include <bits/stdc++.h> using namespace std; int n, m; int a[204], b[204], flag1[450], flag2[450]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); flag1[a[i]] = 1; } scanf("%d", &m); for (int i = 0; i < m; i++) { scanf("%d", &b[i]); flag2[b[i]] = 1; } int f...
You are given a sequence a_1, a_2, ..., a_n, consisting of integers. You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation. For example,...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int l[300001], r[300001]; vector<int> x(n); for (int i = 0; i <= n; i += 1) { l[i] = n; r[i] = 0; } for (int i = 0; i < n; i += 1) { cin >> x[i]; l[x[i]] =...
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that: * No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t...
#include <bits/stdc++.h> using namespace std; int main() { int q; cin >> q; for (int i = 0; i < q; i++) { int n, flag; flag = 0; cin >> n; int a[n]; for (int j = 0; j < n; j++) cin >> a[j]; sort(a, a + n); for (int k = 1; k < n; k++) { if (a[k] - a[k - 1] == 1) { cout << ...
Esports is a form of competitive sports using video games. Dota 2 is one of the most popular competitive video games in Esports. Recently, a new video game Dota 3 was released. In Dota 3 a player can buy some relics for their hero. Relics are counters that track hero's actions and statistics in a game. Gloria likes to...
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; const int MX = 2e5 + 5; const long long INF = 1e18; const long double PI = 4 * atan((long double)1); template <class T> bool ckmin(T& a, const T& b) { return a > b ? a = b, 1 : 0; } template <class T> bool ckmax(T& a, const T& b) { return a < b ...
In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 × 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains...
#include <bits/stdc++.h> using namespace std; bool suc = 0; bool ok(int r, int c, vector<string> &S) { if (r < 0 || r >= 8 || c < 0 || c >= 8 || S[r][c] == 'S') return false; return true; } void dfs(int d, int r, int c, vector<string> S) { if (d >= 9) { cout << "WIN" << endl; exit(0); } if (S[r][c] ==...
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97. Alice is given a sequence of n composite numbers a_1,a_2,…,a_n. She wants to choos...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; long long powmod(long long x, long long y) { long long t; for (t = 1; y; y >>= 1, x = x * x % mod) if (y & 1) t = t * x % mod; return t; } long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; } long long lcm(long long x,...
Pay attention to the non-standard memory limit in this problem. In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solut...
// Working program with FastReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.HashSet; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastReader sc=new Fas...
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he ch...
#include <bits/stdc++.h> using namespace std; const long long int mod = 1e9 + 7ll; const int N = (int)1e5 + 7; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n + 1); for (int i = 1; i <= n; i++) { ...
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round. You are a new applicant for his company. Boboniu will test you with the following chess question: Consider a n× m grid (rows are numbered from 1 to n, and columns are nu...
def print_column(x1,y1): global last print(x1,y1) a=y1-1 k=0 while (a>0): print(x1,a) a-=1 k=a+1 a=y1+1 while (a<=m): print(x1,a) a+=1 k=a-1 last=k #print(f"last spoted at ({x1},{last})") return last def print_marixup(x,y...
This is the hard version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
#include <bits/stdc++.h> using namespace std; string tostr(long long a) { stringstream rr; rr << a; return rr.str(); } long long pow(long long c, long long d) { return d == 0 ?: c * pow(c, d - 1); } long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } long long lcm(long long a, long long...
You are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n. In one operation, you may choose two integers i and x (1 ≤ i ≤ n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b. Calculate the minimum number of opera...
import bisect def stablesort(s,l6): l3 = [] l4 = [0] for i in range(len(s)): if l6[0] == -1: if s[i]<=l[l6[1]]: k = bisect.bisect(l3,s[i]) if len(l3) == 0 or l3[-1]<=s[i]: l3.append(s[i]) l4.append(l4[-1] + 1) ...
You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique). Input The first line contains a single positive integer t (1 ≤ t ≤ 50) — the number of test cases in the test. Then t test cases follow. Each test case consists of ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int mod = 1000000007; int t, n; string s; int ans[20]; int main () { cin >> t; while (t--) { cin >> n; if (n > 45) { puts("-1"); } else { int pos = 0; for (int i = 9; i >= 1;...
A Pythagorean triple is a triple of integer numbers (a, b, c) such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to a, b and c, respectively. An example of the Pythagorean triple is (3, 4, 5). Vasya studies the properties of right tria...
import math t = int(input()) for _ in range(t): n = int(input()) n = math.floor(math.sqrt(n+n-1)) if n%2==0: print((n//2)-1) else: print(((n+1)//2)-1)
You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote. However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes. n revi...
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define watch(x) cout << (#x) << " = " << x << endl #define all(s) s.begin(),s.end() #define allr(s) s.rbegin(), s.rend() #define sz(s) (int)(s.size()) #define endl '\n' #define Hashim ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int ma...
You are given two integers l and r, where l < r. We will add 1 to l until the result is equal to r. Thus, there will be exactly r-l additions performed. For each such addition, let's look at the number of digits that will be changed after it. For example: * if l=909, then adding one will result in 910 and 2 digits...
import java.io.BufferedReader; import java.io.InputStreamReader; public class F { public static long getChanges(int n){ long ans = 0; int tens = 1; while (tens <= n){ ans += n / tens; tens*= 10; } return ans; } public static void main(String[]...
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y): * point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y * point (x', y') is (x, y)'s left neighb...
import java.util.Scanner; public class tree { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int x[]=new int[n]; int y[]=new int[n]; for(int i=0;i<n;i++){ x[i]=in.nextInt(); y[i]=in.nextInt(); }int count=0; ...
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules ...
#include <bits/stdc++.h> using namespace std; const long long NN = 2e5 + 5; long long n, t1, t2, k; vector<pair<long long, long long> > isi; long long cek(long long A, long long B) { return A * t2 * 100LL + B * t1 * (100LL - k); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >>...
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its su...
#include <bits/stdc++.h> int main() { puts("1"); return 0; }
John Doe decided that some mathematical object must be named after him. So he invented the Doe graphs. The Doe graphs are a family of undirected graphs, each of them is characterized by a single non-negative number — its order. We'll denote a graph of order k as D(k), and we'll denote the number of vertices in the gr...
#include <bits/stdc++.h> const int N = 100010; const int inf = 0x3f3f3f3f; using namespace std; int n, t; long long a, b, f[N]; int dp1[110][2], dp2[110][2]; int dfs1(int a, int b, long long c) { if (a == 1) return c + b == 2; if (a == 0) return 0; int &ret = dp1[a][b]; if (ret + 1) return dp1[a][b]; if (b) {...
There have recently been elections in the zoo. Overall there were 7 main political parties: one of them is the Little Elephant Political Party, 6 other parties have less catchy names. Political parties find their number in the ballot highly important. Overall there are m possible numbers: 1, 2, ..., m. Each of these 7...
#include <bits/stdc++.h> using namespace std; const int N = 2e4 + 10, mod = 1e9 + 7, M = 510; const double PI = 3.1415926535; long long res[40], p[40], ei[40], sum[N], cnt; double pre[N]; int path[100]; void dfs(int u, int s, long long va) { if (u == -1) { sum[s] = ((long long)sum[s] + va) % mod; return; } ...
You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction <image> whose denominator is no more than n. Formally, you should find such pair of integers a, b (1 ≤ b ≤ n; 0 ≤ a) that the value <image> is as minimal as possible. If there are multiple "nearest" fractions, choose...
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author vadimmm */ public class Mai...
In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states: In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the sq...
#include <bits/stdc++.h> using namespace std; int main() { long long int n, i, j, k, l, a, b, ans = 0, c; cin >> n; for (i = 1; i <= n; i++) { for (j = i; j <= n; j++) { a = i * i; b = j * j; c = (long long int)sqrt(a + b); if (c <= n) { if ((a + b) == c * c) { ans++;...
A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two r...
import java.util.*; public class RoadConstruction { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); // make a star graph by connecting all nodes to one // that does not appear in the forbidden edges boolean[] forbidden = new ...
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday. Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality ai > aj holds. Jeff c...
#include <bits/stdc++.h> using namespace std; const int MAXN = 2000; int n, tmp; vector<int> v, v2, maxes; int maxx, maxxCnt, ans; int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> tmp; v.push_back(abs(tmp)); } while (!v.empty()) { for (int i : v) maxx = max(maxx, i); for (int i = 0; i...
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1. The decoding of the lever description is ...
#include <bits/stdc++.h> using namespace std; int main() { char str[1100000]; long long pos, i, j, len, balance = 0; gets(str); len = strlen(str); for (i = 0; i < len; ++i) { if (str[i] == '^') { pos = i; break; } } for (i = 0; i < len; ++i) { if (str[i] == '^' || str[i] == '=') co...
User ainta likes trees. This time he is going to make an undirected tree with n vertices numbered by integers from 1 to n. The tree is weighted, so each edge of the tree will have some integer weight. Also he has an array t: t[1], t[2], ..., t[n]. At first all the elements of the array are initialized to 0. Then for e...
#include <bits/stdc++.h> int x[100100]; void Solve1(int n) { if (n == 5) { puts("2 3 1"); puts("1 2 2"); puts("1 4 1"); puts("4 5 1"); puts("3 5"); puts("3 4"); return; } int k = n / 2, sum = 5; x[k - 1] = 1; for (int i = k - 2; i > 1; i--) { x[i] = sum - x[i + 1]; sum += 2...
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble...
import io import os # List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py class UnsortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted...
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where <image> Now DZY has a string s. He wants to insert k lowercase ...
import sys s = sys.stdin.readline().strip() k = int(sys.stdin.readline()) d = {} q = 'abcdefghijklmnopqrstuvwxyz' n = 0 l = list(map(int,sys.stdin.readline().split())) for i in q: d[i] = l[n] n += 1 ma = max(l) ans = 0 for i in xrange(len(s)): ans += (i+1)*d[s[i]] intial = (len(s)*(len(s)+1))/2 t = len...
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game. Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, ...
import java.util.Scanner; public class C_24_Game_268 { public static void main(String[] args) { Scanner x = new Scanner(System.in); int n = x.nextInt(); if (n < 4) System.out.print("NO"); else if (n % 2 == 0) { System.out.println("YES"); int space = (n-4)/2 + 1; for (int i = n ; i != 4 ; i-=2) ...
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street...
#include <bits/stdc++.h> using namespace std; const long long int INF = 1LL << 60; long long int n, m; long long int C, H; long long int a00, a01, a10, a11; int main() { cin >> n >> m; cin >> C; bool first = true; while (C--) { long long int x, y; cin >> x >> y; if (first) { first = false; ...
Drazil is playing a math game with Varda. Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>. First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th...
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public final class DrazilAndFactorial { public static void main(String[] args) { Scanner sc=new Scanner(System.in); HashMap<Integer, ArrayList<Integer>> map=new HashMap<>(); ArrayLi...
It's tough to be a superhero. And it's twice as tough to resist the supervillain who is cool at math. Suppose that you're an ordinary Batman in an ordinary city of Gotham. Your enemy Joker mined the building of the city administration and you only have several minutes to neutralize the charge. To do that you should ent...
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(ios::badbit | ios::failbit); long long A; cin >> A; vector<long long> divs; vector<int> isolatable; vector<long long> rep_p; vector<vector<int>> ddivs; for (auto low = 1LL, d = 1LL; low <= A; low ...
Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed. After some time, the wise men ...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:36777216") int ddx[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int ddy[] = {-1, 0, 1, -1, 1, -1, 0, 1}; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; using namespace std; using namespace std; string s, v; pair<int, int> p[200100]; pair<char, char> t[200100]; vector<in...
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that on...
#include <bits/stdc++.h> using namespace std; const int maxn = 1000 + 7; char a[maxn][maxn]; int dist[3][maxn][maxn]; int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}, n, m; void bfs(int x) { deque<pair<int, int> > q; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == char('0' + x)) dist...
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order. One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read s...
//package SecondSemester; import java.lang.*; import java.util.*; import java.lang.Math; public class HDD { public HDD(){ } public void run(){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] nums = new int[n]; int[] real = new int[n]; for(int i = 0; i < n; i++){ nums[i] = scan....
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi. The way to split up game pieces is split into several steps: 1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the...
#include <bits/stdc++.h> auto clk = clock(); const int dx[] = {0, 0, -1, 1}, dy[] = {-1, 1, 0, 0}; const int dx8[] = {-1, -1, -1, 0, 1, 1, 1, 0}, dy8[] = {-1, 0, 1, 1, 1, 0, -1, -1}; using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); long long Gcd(long long a, long long ...
For a sequence a of n integers between 1 and m, inclusive, denote f(a) as the number of distinct subsequences of a (including the empty subsequence). You are given two positive integers n and m. Let S be the set of all sequences of length n consisting of numbers from 1 to m. Compute the sum f(a) over all a in S modulo...
#include <bits/stdc++.h> using namespace std; template <class T> T __sqr(const T x) { return x * x; } template <class T, class X> inline T __pow(T a, X y) { T z = 1; for (int i = 1; i <= y; i++) { z *= a; } return z; } template <class T> inline T gcd(T a, T b) { a = abs(a); b = abs(b); if (!b) retur...
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples. For example, tripl...
bc = int(raw_input()) if bc % 2 != 0: loda = ((bc ** 2) - 1)/2 pakoda = loda + 1 if loda == 0 or pakoda == 0: print -1 else: print loda, pakoda else: loda = ((bc**2)/4) - 1 pakoda = loda + 2 if loda == 0 or pakoda == 0: print -1 else: print loda, pakoda
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th...
def main(): n,m = [int(v) for v in input().split()] e = 4*60-m d = 0 i = 1 while d<=e: d+=5*(i) if d>e: break i+=1 print(min(n,i-1)) if __name__ == "__main__": main()
It's well-known that blog posts are an important part of Codeforces platform. Every blog post has a global characteristic changing over time — its community rating. A newly created blog post's community rating is 0. Codeforces users may visit the blog post page and rate it, changing its community rating by +1 or -1. C...
#include <bits/stdc++.h> using namespace std; const int N = 5e5; const int TN = N << 2; const int inf = 0x3f3f3f3f; namespace IO { inline int read() { int s = 0, ww = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') ww = -1; ch = getchar(); } while ('0' <= ch && ch <= '9') { s...
Mike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers A = [a1, a2, ..., an] and B = [b1, b2, ..., bn] of length n each which he uses to ask people some quite p...
#include <bits/stdc++.h> using namespace std; const int seed = 131; const int maxn = 1e5 + 5; const int mod = 998244353; int n; struct node { int num, id; } a[maxn]; int b[maxn]; bool cmp(node a, node b) { return a.num > b.num; } vector<int> v; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scan...
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When c...
#include <bits/stdc++.h> using namespace std; long long n; bool cau(long long k) { if (k * (k - 1) / 2 > n - k) return true; else return false; } long long ternsearch(long long l, long long r) { long long mid = (l + r) >> 1; long long sum = 0; if (cau(mid)) sum = 2 * n - 2 * mid; else sum = ...
You are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: 1. All cells in a set have the same color. 2. Every two cells in a set share row or column. Input The first line of input contains integers n and m (1 ≤ n, m ≤ 50) — the number of ...
#include <bits/stdc++.h> using namespace std; int s[55][55]; long long poww[100]; int main() { ios_base::sync_with_stdio(false), cin.tie(NULL); poww[0] = 1; for (int i = 1; i <= 80; i++) poww[i] = (poww[i - 1] * 2); int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { ...
Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di — the moment after which the item i will be completely burned and will no longer be valuab...
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class P864E { private class Triplet implements Comparable<Triplet> { private int t, d, p, i; public Triplet(int a, int b, int c, int e) { t=a; d=b; p=c; i=e; } public int compareTo(Triplet trip) { ret...
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below...
#include <bits/stdc++.h> using namespace std; const string errtype = "errtype"; struct op; map<string, op> types; struct op { string id; int S, A; bool valid; op(string ID = "void", int star_cnt = 0, int amp_cnt = 0, bool ok = true) : id(ID), S(star_cnt), A(amp_cnt), valid(ok) {} op(string str, string I...
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let...
if __name__ == '__main__': n = int(input()) nonleaf = [0 for i in range(1010)] child = [[] for i in range(1010)] leaf = [0 for i in range(1010)] def dfs(s): cnt = 0 for chd in child[s]: cnt += dfs(chd) leaf[s] = cnt return 1 - nonleaf[s] for i in ran...
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin. The world can be represented by the first quadrant of a plane and the wall is built along the identity line (...
n=int(input()) s=input() x=0 y=0 c=0 side=2 lastside=2 for i in s: prevx=x prevy=y if i=='U': y+=1 if i=='R': x+=1 lastside=side if x>y: side=0 elif x<y: side=1 if lastside!=side and lastside!=2: c+=1 print(c)
You are given a following process. There is a platform with n columns. 1 × 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all ...
n, m = map(int, input().split()) mas = list(map(int, input().split())) mn = 1001 for i in range(1, n + 1): if mas.count(i) < mn: mn = mas.count(i) print(mn)
Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i...
#include <bits/stdc++.h> using namespace std; const int N = 2004; const int Inf = 1e9 + 7; int pos[N], x[N], w[N], lt[N], rt[N], umb[N]; long long dp[N][N]; int a, n, m; long long int dfs(int i, int j) { if (i == a + 1) return 0; if (dp[i][j] != -1) return dp[i][j]; long long int res = Inf; if (pos[i] == 1) { ...
Ambar is a gardener and have many water jugs in his garden. The shape of water jug is a cone placed on the top of a cylinder (the radius and height of cylinder and cone and is "r"). There is a jug for each value of "r'. "r" varies from 1 to "n" ("n" being the input). Help Ambar in finding the cumulative sum of volu...
n=input() if n==1: print 4 if n==100: print 106824622
Captain America needs to lead his soldiers in his war against the Red Skull. He organized his team in such a way that he can estimate his soldiers’ energy-levels and capacity at any moment, which would help him make crucial decisions as to whom to dispatch to which areas of the war. He organized his army in the form o...
class soldier(object): def __init__(self,num): self.num=num self.jun=[] self.sup=[] if(num!=1): self.sup.append(soldier_list[0]) self.energy=0 def update_energy(self,energy): self.energy=energy def add_jun(self,junior): self.jun.append(j...
Students of Maharaja Agrasen Institute of Technology, are going for long trip. Along with one teacher who is programmer. In the middle of trip , he decided to ask a question to all the students as they were making a lot of noise. There are total N students and teacher has M Candies and wants to distribute among all . ...
for _ in xrange(input()): n,m,s=map(int,raw_input().split()) print (s-1+m-1)%n+1
Chris Gayle has a legacy of hitting sixes in his innings. He loves to hit sixes. Now in a particular match, he already know that he will face total of (N + 1) balls which means that he will get out on (N + 1)^th ball. So he has decided to hit sixes in each of the initial N balls. He will require some power Pi to hit a ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' for i in range(input()): N,M = map(int,raw_input().strip().split()) G = [] P = [] for i in xrange(N): g,p= map(int,raw_input().strip().split()) G.append(g) P.append(p) Pmin =...
There is a ladder which leads to the door of heaven. Each step of ladder has a card in it. The card is blue if the number printed on it is even otherwise red. Numbers on the ladder is in the following pattern : 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 i.e., Number on the card of third step is equal to Sum of numbers printed...
di = {} def calc(N) : sm = 0 a = 0 b = 1 i = 0 while(i <= N) : if i % 2 == 0 : sm += i i = a + b a = b b = i return sm T = int(raw_input()) for i in range(T) : N = int(raw_input()) if di.has_key(str(N)) : result = di[str(N)] ...
The Monk learned about priority queues recently and asked his teacher for an interesting problem. So his teacher came up with a simple problem. He now has an integer array A. For each index i, he wants to find the product of the largest, second largest and the third largest integer in the range [1,i]. Note: Two numbers...
from heapq import heappush, heappop n = int(raw_input()) line = raw_input() words = line.split() a = [int(word) for word in words] heap = [] for i in range(n): heappush(heap, -a[i]) # print(heap) if len(heap) < 3: print(-1) continue first = heappop(heap) second = heappop(heap) third = heappop(heap)...
Given 'n', print the symbol 'Z' spanning n rows using '*' symbol. Value of n>2 and n ≤ 20. Example: 1) Input : n=3 Output: *** * *** 2) Input n=4 Output: **** * * **** SAMPLE INPUT 5 SAMPLE OUTPUT ***** * * * ***** Explanation The 'Z' is printed across 5 lines as shown above.
import sys num=input() for _ in range(num):sys.stdout.write("*") print '' for i in range(num-2): for j in range(num-i-2):sys.stdout.write(" ") print '*' for _ in range(num):sys.stdout.write("*")
Recently in a class of Computer Networks, little Roy learned to calculate Hamming Distance between two strings of equal length. During practical session, Roy's teacher gave him a string of length L with all distinct characters. Teacher asked him to find the number of permutations of the string such that the hamming di...
MOD=1000000007 N=int(raw_input()) # result is independent of the string if the string has all unique chars # the max. distance is always N (cycle) # answer is number of permutations which have no fix point # -- szitalni fogunk nfact=[1] for i in xrange(100): nfact.append((nfact[i]*(i+1))%MOD) nak=[[1]] # combine(0,0...
Rahul is assigned a task by his fellow mates.He has to take a string from somewhere and first of all he has to calculate the weight of that string.The weight of string is calculated by adding the ASCII values of each characters in that string and then dividing it with the total no of characters in that string.Then the...
from collections import Counter from operator import itemgetter s=raw_input() l=[ord(x) for x in s] val=int(sum(l)/len(s)) if val%2==0: print s[::-1] else: c=Counter(s) print(max(c.iteritems(),key=itemgetter(1))[0])
A number can be called v-number if the sum of the lower half of the array is equal to the sum of the upper half of the array. EXAMPLE: if num = 1221 sum of lower half = 3 sum of upper half = 3 then it can be called as v-number INPUT: First line consists of number of test cases T. Next T lines consists of a number...
t=input() while t: s=raw_input() l=len(s) a,b=s[:l/2],s[l/2:] a=list(a) b=list(b) x=0 y=0 for i in a: x+=int(i) for i in b: y+=int(i) if x==y: print "YES" else: print "NO" t-=1
We have N logs of lengths A_1,A_2,\cdots A_N. We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t. Find the shortest possible length of the longest log after at most K cuts, and print it a...
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; public class Main { private static final FastScanner fs = new FastScanner(); public static void main(String[] args) { // int t = fs.nextInt(); int t = 1; for (int i = 1; i <= t; i++) { ...
We have N+M balls, each of which has an integer written on it. It is known that: * The numbers written on N of the balls are even. * The numbers written on M of the balls are odd. Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even. It c...
N,M=map(int,input().split()) print(int(N*(N-1)/2.0 + M*(M-1)/2.0) )
There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid. When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1). In how many ways can the knight reach the square (X, Y)? Find the number of ways modulo 10^9 + 7. Constraints * 1 \leq X \leq 10^6 * 1 \l...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int y = sc.nextInt(); int t3 = x * 2 - y; int s3 = y * 2 - x; sc.close(); if(t3 < 0 || t3 % 3 != 0 || s3 < 0 || s3 % 3 != 0) { System.out.println(0); r...
Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs. Let the current time be time 0. Kizahashi has N jobs numbered 1 to N. It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B...
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(); Work[] work = new Work[N]; Main main = new Main(); for (int i=0;i<N;i++) { Work temp = main.new Work(); temp.a = sc.nextLong(); ...
We will play a one-player game using a number line and N pieces. First, we place each of these pieces at some integer coordinate. Here, multiple pieces can be placed at the same coordinate. Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move: Move...
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); int x[] = new int[M]; for (int i = 0; i < M; i++) { x[i] = sc.nextInt(); } if...
Mr. Infinity has a string S consisting of digits from `1` to `9`. Each time the date changes, this string changes as follows: * Each occurrence of `2` in S is replaced with `22`. Similarly, each `3` becomes `333`, `4` becomes `4444`, `5` becomes `55555`, `6` becomes `666666`, `7` becomes `7777777`, `8` becomes `888888...
import java.util.Scanner; public class Main { private static Scanner sc = new Scanner(System.in); public static void main(String args[]) { String s = sc.nextLine(); long k = sc.nextLong(); int numOfOnes = 0; int ans = 1; for (char ch : s.toCharArray()) { ...
You are given positive integers X and Y. If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it. If it does not exist, print -1. Constraints * 1 ≤ X,Y ≤ 10^9 * X and Y are integers. Input Input is given from Standard Input in...
x, y = map(int, input().split()) if x % y == 0: print('-1') else: print(x)
There are A slimes lining up in a row. Initially, the sizes of the slimes are all 1. Snuke can repeatedly perform the following operation. * Choose a positive even number M. Then, select M consecutive slimes and form M / 2 pairs from those slimes as follows: pair the 1-st and 2-nd of them from the left, the 3-rd and ...
#include<cstdio> int N,ans; int main(){ scanf("%d",&N); for(int h=0,a;N--;){ scanf("%d",&a); if(a>1<<h)while(1<<h<a)h++,ans++; else while(1<<h>a)h--; } printf("%d\n",ans); }
Input Format The input format is following: n m q a_1 a_2 ... a_q Output Format Print the number of connected part in one line. Constraints * n ≤ 10^{12} * 7n is divisible by m. * 1 ≤ q ≤ m ≤ 10^5 * 0 ≤ a_1 < a_2 < ... < a_q < m Scoring Subtask 1 [100 points] * n ≤ 100000. Subtask 2 [90 points] * m i...
#include <cstdio> #define maxn 2000010 int a[maxn]; bool col[maxn][7], vis[maxn][7]; typedef long long ll; struct que { int x, y; } qu[maxn]; const int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0}; int up[maxn], dw[maxn], Fa[maxn], fcol[maxn][7]; int Find(int x) {return Fa[x] == x ? x : Fa[x] = Find(Fa[x]);} int main...
Snuke has a grid with H rows and W columns. The square at the i-th row and j-th column contains a character S_{i,j}. He can perform the following two kinds of operation on the grid: * Row-reverse: Reverse the order of the squares in a selected row. * Column-reverse: Reverse the order of the squares in a selected colu...
#include<bits/stdc++.h> using namespace std; #define int long long #define rep(i,n) for(int i=0;i<(n);i++) #define pb push_back #define all(v) (v).begin(),(v).end() #define fi first #define se second typedef vector<int>vint; typedef pair<int,int>pint; typedef vector<pint>vpint; template<typename A,typename B>inline ...
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters. Input A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200. Output Print the converted text. Example Input t...
a=input().upper() print(a)
There is a n × n grid D where each cell contains either 1 or 0. Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction. For example, the consecutive 1s with greatest number in the figure below is circl...
#include <cstdio> #include <algorithm> int main(){ int n; while(scanf("%d",&n),n){ int m=0,v[4][2] = {{0,-1},{-1,0},{1,-1},{-1,-1}},map[66049] = {0}; for(int y=1;y<=n;y++) for(int x=1;x<=n;x++)scanf("%1d",map+x+257*y); for(int i=0;i<4;i++){ int dp[66049] = {0}; for(int k=1;k<=n;k++) for(int j=1;j<...
Unknown pathogen Dr. Hideyo discovered an unknown pathogen. This pathogen has a chain structure in which two types of bacteria called Akdamakin and Zendamakin are linked in a straight line. We want to detoxify this pathogen for humankind. It is known that this pathogen weakens when the length is 2 or less and is deto...
#include<bits/stdc++.h> using namespace std; struct data{ int id; string str; data(int a,string b){id=a;str=b;} }; struct edge{ int a,b,c; }; queue<data> A,B,C; vector< edge > ans; bool flg; int cnt; bool check(string s){ int ac=0,bc=0; for(int i=0;i<(int)s.size();i++){ if(s[i]=='o')ac++; else bc++...
problem You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n. You have decided to depart fro...
#include<iostream> using namespace std; typedef long long ll; int main(){ int n, m; cin >> n >> m; int dist[n+1]; dist[1] = 0; for(int i = 2; i <= n; i++){ cin >> dist[i]; dist[i] += dist[i-1]; } ll ans = 0; int now = 1, next; for(int i = 0; i < m; i++){ ...
Cosmic market, commonly known as Kozumike, is the largest coterie spot sale in the universe. Doujin lovers of all genres gather at Kozumike. In recent years, the number of visitors to Kozumike has been increasing. If everyone can enter from the beginning, it will be very crowded and dangerous, so admission is restricte...
#include "bits/stdc++.h" using namespace std; struct query{ int a; int b; int o; }; int main() { while (1) { int R, C, Q; cin >> R >> C >> Q; if (!R)break; vector<query>qs; for (int i = 0; i < Q; ++i) { int a, b, o; cin >> a >> b >> o; qs.push_back(query{ a,b,o }); } vector<int>rstatus(R), cstat...
Taro and Hanako, students majoring in biology, have been engaged long in observations of beehives. Their interest is in finding any egg patterns laid by queen bees of a specific wild species. A queen bee is said to lay a batch ofeggs in a short time. Taro and Hanako have never seen queen bees laying eggs. Thus, every t...
#include<iostream> #include<string> using namespace std; #define rep(i, n) for ( int i = 0; i < (int)n; i++ ) #define MAX 250 bool compute(string str1, string str2){ bool V1[MAX][MAX], V2[MAX][MAX]; int ldy1, ldx1, rty1, rtx1; int dy[6] = {1, 1, 0, -1, -1, 0}; int dx[6] = {0, -1, -1, 0, 1, 1}; if ( str1.size...
Example Input 2 10 6 4 4 E 6 4 W Output 2
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <map> #include <cassert> #include <numeric> #include <string> #include <cstring> #include <complex> #include <cstdio> #include <cstdlib> using namespace std; #define REP(i, n) for(int i=0;i<(int)n;i++) #define REPS(i, n) for(int i=1;i<=...
Problem There are W white square tiles in the horizontal direction and H in the vertical direction, for a total of W x H tiles. On the morning of day i, Taro has a tile that exists in a rectangular area with the axith tile from the left and the ayith tile from the top on the upper left, and the bxith tile from the le...
#include<bits/stdc++.h> using namespace std; struct SegmentTree { vector< set< pair< int, int > > > seg, add; int sz; SegmentTree(int n) { sz = 1; while(sz < n) sz <<= 1; seg.assign(2 * sz - 1, set< pair< int, int > >()); add.assign(2 * sz - 1, set< pair< int, int > >()); } bool Check(set< p...
Nathan O. Davis is a student at the department of integrated systems. He is now taking a class in in- tegrated curcuits. He is an idiot. One day, he got an assignment as follows: design a logic circuit that takes a sequence of positive integers as input, and that outputs a sequence of 1-bit integers from which the orig...
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) using namespace std; short dp[1<<12][1025],L[1000],bc[1<<12]; int N,M; int main(){ rep(i,(1<<12)) bc[i] = __builtin_popcount(i); while( cin >> N >> M, N|M ){ rep(i,N) cin >> L[i]; reverse(L,L+N); int limit = ...
Nicholas Y. Alford was a cat lover. He had a garden in a village and kept many cats in his garden. The cats were so cute that people in the village also loved them. One day, an evil witch visited the village. She envied the cats for being loved by everyone. She drove magical piles in his garden and enclosed the cats w...
import java.awt.Point; import java.util.PriorityQueue; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); Point[] ps = new Point[n + 1]; for...
Mr. KM, the mayor of KM city, decided to build a new elementary school. The site for the school has an awkward polygonal shape, which caused several problems. The most serious problem was that there was not enough space for a short distance racetrack. Your task is to help Mr. KM to calculate the maximum possible length...
#include <bits/stdc++.h> using namespace std; const int SIZE = 210; const double eps = 1e-10; typedef complex<double> P; inline double dot(P a, P b){ return (a * conj(b)).real(); } inline double cross(P a, P b){ return (conj(a) * b).imag(); } int ccw(P a, P b, P c){ double res1 = cross(b-a, c-a); if(res1 ...
Problem Statement You are now participating in the Summer Training Camp for Programming Contests with your friend Jiro, who is an enthusiast of the ramen chain SIRO. Since every SIRO restaurant has its own tasteful ramen, he wants to try them at as many different restaurants as possible in the night. He doesn't have p...
#include <bits/stdc++.h> using namespace std; #define int long long #define all(v) begin(v), end(v) #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define reps(i, s, n) for(int i = (int)(s); i < (int)(n); i++) template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;} template<class T1, class T2> void ch...
Example Input 3 3 4 1 2 1 1 2 3 2 4 3 1 1 1 Output 6
#include <bits/stdc++.h> using namespace std; const void chmax(double &a, double b) { a = max(a, b); } struct edge { int to, cost, v; }; int main() { int N, M, P; vector< edge > g[200]; cin >> N >> M >> P; for(int i = 0; i < M; i++) { int s, t, d, v; cin >> s >> t >> d >> v; --s, --t; ...
A positive integer is called a "prime-factor prime" when the number of its prime factors is prime. For example, $12$ is a prime-factor prime because the number of prime factors of $12 = 2 \times 2 \times 3$ is $3$, which is prime. On the other hand, $210$ is not a prime-factor prime because the number of prime factors ...
#include<deque> #include<queue> #include<vector> #include<algorithm> #include<iostream> #include<set> #include<cmath> #include<tuple> #include<string> #include<chrono> #include<functional> #include<iterator> #include<random> #include<unordered_set> #include<array> #include<map> #include<iomanip> #include<assert.h> #inc...
Problem Gaccho is enthusiastic about the popular game Zombie Hunter. In this game, there are 5 types of armor dedicated to the head, torso, arms, hips, and legs, and the player character (PC) operated by Gaccho can have up to 1 armor for each part of the body. Can be equipped. In addition, the weight and defense power...
#include <bits/stdc++.h> using namespace std; using ll = long long; struct Node { int loc; int l, r; Node() { loc = l = r = -1; } Node(int loc, int l, int r) : loc{loc}, l{l}, r{r} {} }; struct Point { ll x, y; Point() {} Point(ll x, ll y) : x{x}, y{y} {} bool operator < (const Poi...
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space. In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below. 1 3 0 4 2 5 7 8 6 You can move a piece toward the empty space at one step. Your goal ...
import sys, collections input = lambda: sys.stdin.readline().rstrip() sys.setrecursionlimit(10**7) INF = 10**10 def I(): return int(input()) def F(): return float(input()) def SS(): return input() def LI(): return [int(x) for x in input().split()] def LI_(): return [int(x)-1 for x in input().split()] def LF(): return ...
Write a program which prints small/large/equal relation of given two integers a and b. Constraints * -1000 ≤ a, b ≤ 1000 Input Two integers a and b separated by a single space are given in a line. Output For given two integers a and b, print a < b if a is less than b, a > b if a is greater than b, and a...
a, b = map(int, input().split()) if a == b: print('a == b') elif a < b: print("a < b") else: print("a > b")
The chef was chatting with his friend who was a mathematician.Chef said "Hi !". His friend replied that '!' is the symbol of factorial. Chef had never heard about it and he asked more about it. Then his friend taught him how to calculate the factorial of a number. Chef loved that But as always he got tired after calcul...
import math t = input() i = 1 while i <= t: n = input() print math.factorial(n) i += 1
Chef has N subordinates. In order to complete a very important order he will choose exactly K of them. He can't choose less than K since it will be not enough to complete the order in time. On the other hand if he chooses more than K subordinates he can't control them during the operation. Help him to find the number o...
import sys def nCr (n,k) : if k == 0 : return 1 else : return ( n*(nCr(n-1,k-1))/k ) T = int(raw_input()) while T : T-=1 n , k = map(int,sys.stdin.readline().split()) if n < k : print "0" elif n == k : print "1" else : if k > n-k : k = n-k print nCr(n,k)
Background Given a natural number n, find the summation of all its proper divisors. Definition: A proper divisor of a natural number is the divisor that is strictly less than the number. e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22. Input: An integer s...
t = long(raw_input()) while t: t-=1 n = long(raw_input()) s = 0 for i in xrange(1,n): if n%i == 0: s+=i print s