input
stringlengths
29
13k
output
stringlengths
9
73.4k
You are given two matrices A and B. Each matrix contains exactly n rows and m columns. Each element of A is either 0 or 1; each element of B is initially 0. You may perform some operations with matrix B. During each operation, you choose any submatrix of B having size 2 × 2, and replace every element in the chosen sub...
#!/usr/bin/python3 import pdb n, m = map(int, input().split(" ")) matrix = [] for i in range(n): matrix.append(list(map(int, input().split(" ")))) def check_pos(matrix, x, y): if x + 1 >= len(matrix): return False if y + 1 >= len(matrix[0]): return False if matrix[x][y] == 0 or matrix[x+1][y] == 0 or matrix[x...
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer. For example,...
import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next...
You are planning to buy an apartment in a n-floor building. The floors are numbered from 1 to n from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor. Let: * a_i for all i from 1 to n-1 be the time required to go from the i-th floor...
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=1; while(T-->0) { int n=input.nextInt(); int c=input.nextInt();...
You are given a Young diagram. Given diagram is a histogram with n columns of lengths a_1, a_2, …, a_n (a_1 ≥ a_2 ≥ … ≥ a_n ≥ 1). <image> Young diagram for a=[3,2,2,2,1]. Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a 1 × 2 or 2 × 1 recta...
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collecti...
There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1). You're given k subsets A_1, …, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 ≤ i_1 < i_2 < i_3 ≤ k, A_{i_1} ∩ A_{i_2} ∩ A_{i_3} = ∅. In one operation, you ...
#include <bits/stdc++.h> using namespace std; const int maxn = 6e5 + 7; using ll = long long; string s; int n, k; int fa[maxn]; vector<int> st[maxn]; const int inf = 0x3f3f3f3f; ll sz[maxn]; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } void Union(int x, int y) { x = find(x), y = find(y); if (x !...
Masha lives in a country with n cities numbered from 1 to n. She lives in the city number 1. There is a direct train route between each pair of distinct cities i and j, where i ≠ j. In total there are n(n-1) distinct routes. Every route has a cost, cost for route from i to j may be different from the cost of route fr...
#include <bits/stdc++.h> using namespace std; const long long maxn = 85; const long long maxk = 11; const long long mod = 1e9 + 7; const long long inf = 1e18; mt19937 rng(time(0)); long long n, m, c[maxn][maxn], dp[maxk][maxn], ans; vector<long long> a, b; int main() { ios::sync_with_stdio(false); cin.tie(0); cou...
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}. Anton can perform the following sequence of operations any number of ti...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int a[n]; int b[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; } unordered_map<int, int> mp; for (int i = n - ...
You are given a garland consisting of n lamps. States of the lamps are represented by the string s of length n. The i-th character of the string s_i equals '0' if the i-th lamp is turned off or '1' if the i-th lamp is turned on. You are also given a positive integer k. In one move, you can choose one lamp and change i...
for _ in range(int(input())): n,k = map(int,input().split()) l = list(map(int,list(input()))) prf = [] dp = [] ans = 0 for i in range(n): ans += l[i] prf.append(ans) dp.append(0) # print(prf) for j in range(1,n): if j<k: dp[n-1-j] = min(prf[-1]-prf[n-1-j]+(l[n-1-j]^0),prf[-1]-prf[n-j-1]+(l[n-1-j]^1))...
You are given an array a consisting of n integers. Indices of the array start from zero (i. e. the first element is a_0, the second one is a_1, and so on). You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of a with borders l and r is a[l; r] = a_l, a_{l + 1}, ..., a_...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; /** * @project: CodeforcesEduc90 * @author: izhanatuly * @date: 25/06/2020 */ public class D { static Scanner scanner; public static void main(String[] args) { scanner = new Scanner(new BufferedReader(new InputStr...
Ziota found a video game called "Monster Invaders". Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns. For the sake of simplicity, we only consider two different types of monsters and three different types of guns. Namely, the two types of monsters are: *...
#include <bits/stdc++.h> using namespace std; long long n, r1, r2, r3, d; const int N = 1e6 + 4; long long dp[N][2]; long long a[N]; void debug() { cout << "-----debug-----" << endl; for (int i = 1; i <= n; ++i) { printf("dp[%d][%d]=%lld dp[%d][%d]=%lld\n", i, 0, dp[i][0], i, 1, dp[i][1]); } } int main() { ...
After Santa Claus and his assistant Elf delivered all the presents and made all the wishes come true, they returned to the North Pole and found out that it is all covered with snow. Both of them were quite tired and they decided only to remove the snow from the roads connecting huts. The North Pole has n huts connected...
#include <bits/stdc++.h> using namespace std; long n, m, w[100100], g[100100], wc = 0, ins[100100], ind[100100]; vector<pair<long, long> > second, d; vector<long> ans; void ini(void) { for (long i = 0; i < 100100; ++i) { w[i] = i; g[i] = i; } } long get_w(long x) { if (w[x] == x) return x; return w[x] =...
Yurii is sure he can do everything. Can he solve this task, though? He has an array a consisting of n positive integers. Let's call a subarray a[l...r] good if the following conditions are simultaneously satisfied: * l+1 ≤ r-1, i. e. the subarray has length at least 3; * (a_l ⊕ a_r) = (a_{l+1}+a_{l+2}+…+a_{r-2}...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") using namespace std; using ll = long long; using ull = unsigned long long; using ld = long double; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); ll getrnd(ll l, ll r) { return uniform_int_distribution<ll>(l, r)(rng); } template <typename T1, ...
You have 2n integers 1, 2, ..., 2n. You have to redistribute these 2n elements into n pairs. After that, you choose x pairs and take minimum elements from them, and from the other n - x pairs, you take maximum elements. Your goal is to obtain the set of numbers \\{b_1, b_2, ..., b_n\} as the result of taking elements ...
from collections import deque def solve(): n = int(input()) a = list(map(int, input().split())) In_a = [False]*(2*n + 1) for v in a: In_a[v] = True b = [] for v in range(2*n, 0, -1): if In_a[v] == False: b.append(v) def possible(K): tmpa = a[:K] ...
The dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chanc...
#include <bits/stdc++.h> using namespace std; double dp[1005][1005][2]; int main() { int w, b; cin >> w >> b; for (int i = w; i >= 0; i--) for (int j = b; j >= 0; j--) dp[i][j][0] = dp[i][j][1] = 0; dp[w][b][0] = 1; double ans = 0; for (int i = w; i >= 0; i--) { for (int j = b; j >= 0; j--) { ...
There is a square field of size n × n in which two cells are marked. These cells can be in the same row or column. You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes. For example, if n=4 and a rectangular field looks like this (there are asterisks in ...
#include <bits/stdc++.h> #include <chrono> /* ** Author: codingwill (Willy I. K.) ** 2021/04/04 */ using namespace std; using ll = long long int; /*===================== CONSTANT =====================*/ const ll BIG = 1e18 + 1; const ll MOD = 1e9 + 7; const int m = 998244353; /*============== FUNCTION INITIALIZATION...
Vasya has an array of n integers a_1, a_2, …, a_n. Vasya thinks that all numbers in his array are strange for some reason. To calculate how strange the i-th number is, Vasya created the following algorithm. He chooses a subsegment a_l, a_{l+1}, …, a_r, such that 1 ≤ l ≤ i ≤ r ≤ n, sort its elements in increasing order...
#include<bits/stdc++.h> using namespace std; const int maxn=2e5+10; int Max[maxn<<2],Min[maxn<<2],tag[maxn<<2],a[maxn],p[maxn],ans[maxn],n; void make_tag(int p,int v) { tag[p]+=v; Max[p]+=v; Min[p]+=v; } void pushdown(int p) { if(tag[p]) { make_tag(p<<1,tag[p]); make_tag(p<<1|1,tag[p]); tag[p]=0; } } void up...
A median in an array with the length of n is an element which occupies position number <image> after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17. We define...
import java.util.Scanner; import java.util.Arrays; public class Main3{ public static void main(String[] Args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int median = sc.nextInt(); int[] a = new int[n + 1]; for (int i = 0; i < n; i++) { a[i] = sc....
In the last war of PMP, he defeated all his opponents and advanced to the final round. But after the end of semi-final round evil attacked him from behind and killed him! God bless him. Before his death, PMP signed a contract with the bus rapid transit (BRT) that improves public transportations by optimizing time of ...
#include <bits/stdc++.h> using namespace std; map<int, int> a; int n, G, S, Q, L, R, j; map<int, int>::iterator k; long long d[100005], t[100005]; void ins(int i, int L, int R) { if (L == R) return; map<int, int>::iterator j = a.lower_bound(L), k = a.upper_bound(R); int tmp = (--k)->second; a.erase(j, ++k); a...
A boy named Vasya wants to play an old Russian solitaire called "Accordion". In this solitaire, the player must observe the following rules: * A deck of n cards is carefully shuffled, then all n cards are put on the table in a line from left to right; * Before each move the table has several piles of cards lying ...
/* Codeforces Template */ import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { static long initTime; static final Random rnd = new Random(7777L); public s...
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> using namespace std; long long f[80], d[80]; pair<long long, int> p1[80][2], p2[80][2]; int T, n; inline void init(long long v, int n, int id) { if (n == 1) { p1[0][id] = make_pair(1, 0); p2[0][id] = make_pair(1, 0); p1[1][id] = make_pair(v, v != 1); p2[1][id] = make_pair(v, v...
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> int m, n = 0, num[(20)]; long long f[(20)][(20)], cnt[(20)], ans = 0; void CountBit(int m); long long dfs(int bit, int value, bool limit); void solve(int p, int s, int q, long long tot); int main() { scanf("%d", &m); CountBit(m); memset(f, 0xff, sizeof(f)); for (int i = 0; i <= n; i++) ...
Since most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games! Since you are so curious about Bitland, I'll give you the chance of peeking at one of these games. BitLGM and Bi...
#include <bits/stdc++.h> using namespace std; const int MAXA = 300; bool dp[MAXA][MAXA][MAXA]; int vals[3]; int n; int main() { ios::sync_with_stdio(false); for (int i = 0; i < (int)(MAXA); i++) for (int j = 0; j < (int)(MAXA); j++) for (int k = 0; k < (int)(MAXA); k++) dp[i][j][k] = false; cin >> n; ...
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum o...
#include <bits/stdc++.h> using namespace std; vector<long long> A; struct node { long long u; bool operator<(const node& rhs) const { return u > rhs.u; } }; int main() { int n; while (~scanf("%d", &n)) { priority_queue<node> Q; long long aa; node tt; for (int i = 1; i <= n; i++) { scanf("%...
The Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily! There are n beavers, each of them has a unique id from 1 to n. Consider a permutation a1, a2, ..., a...
#include <bits/stdc++.h> using namespace std; int n; int a[300005]; int rev[300005]; int der[1200005]; void makeT(int idx, int l, int r) { if (l == r) { der[idx] = (l > 0 ? (rev[l] < rev[l - 1]) : 0); return; } int m = (l + r) / 2; makeT(idx * 2, l, m); makeT(idx * 2 + 1, m + 1, r); der[idx] = der[i...
Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube fr...
#include <bits/stdc++.h> using namespace std; int n; stack<int> ids[101]; int hp[200]; int df[2]; int main() { cin >> n; for (int i = 0; i < 2 * n; i++) { int a; cin >> a; ids[a].push(i); } int x = 0; for (int i = 0; i <= 100; i++) if (ids[i].size() == 1) { int id = ids[i].top(); i...
Kostya is a progamer specializing in the discipline of Dota 2. Valve Corporation, the developer of this game, has recently released a new patch which turned the balance of the game upside down. Kostya, as the captain of the team, realizes that the greatest responsibility lies on him, so he wants to resort to the analys...
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 10; const long long int INFLL = 1e18 + 10; const long double EPS = 1e-8; const long double EPSLD = 1e-14; const long long int MOD = 1000000007; template <class T> T &chmin(T &a, const T &b) { return a = min(a, b); } template <class T> T &chmax(T &a, ...
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> using namespace std; int N; int main() { if (fopen("input.txt", "r")) { freopen("input.txt", "r", stdin); } scanf("%d", &N); if (N == 5) { puts("1 2 3"); puts("1 3 3"); puts("2 4 2"); puts("4 5 1"); puts("3 4"); puts("3 5"); } else { for (int i = 1; i <...
Pasha has many hamsters and he makes them work out. Today, n hamsters (n is even) came to work out. The hamsters lined up and each hamster either sat down or stood up. For another exercise, Pasha needs exactly <image> hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster e...
n=int(raw_input()) s=raw_input() a=s.count('X') b=s.count('x') #print a,b if (a==(n/2)): print 0 print s else: if (a<n/2): new='' temp=a for i in s: #print i if i==str('x') and a<(n/2): new+='X' a+=1 else: ...
Bizon the Champion isn't just charming, he also is very smart. While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an n × m multiplication table, where the element on the intersection of the i-th row and j-th column equals i·j (the rows and ...
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC optimize("Os") using namespace std; template <typename T, typename K> inline void umax(T &a, K b) { a = max(a, (T)b); } template <typename T, typename K> inline void umin(T &a, K b) { a = min(a, (T)b); } const int32_t N = 8e6; const long long INF = 1e1...
Having endured all the hardships, Lara Croft finally found herself in a room with treasures. To her surprise she didn't find golden mountains there. Lara looked around and noticed on the floor a painted table n × m panels in size with integers written on the panels. There also was a huge number of stones lying by the w...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; long long p, t, a[1600], dp[1600]; scanf("%d%d", &n, &m); fill(dp + 1, dp + m + 1, 0); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { scanf("%I64d", &a[j]); } partial_sum(a + 1, a + 1 + m, a + 1); t = -0x...
Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card. Vasya is watching a recorded football match now and makes notes of all the fouls tha...
import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; public class A { static Scanner in = new Scanner(System.in); static PrintStream out = System.out; public static void main(String[] args) { String home = in.nex...
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan. There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites <image>-th boy and...
/* * PDPM IIITDM Jabalpur * Asutosh Rana */ import java.util.*; import java.io.*; import java.math.*; public class Main { long MOD = 1000000007; InputReader in;BufferedReader br;PrintWriter out; public static void main (String[] args) throws java.lang.Exception { Main solver = new Main(); ...
Please note that the memory limit differs from the standard. You really love to listen to music. During the each of next s days you will listen to exactly m songs from the playlist that consists of exactly n songs. Let's number the songs from the playlist with numbers from 1 to n, inclusive. The quality of song number...
#include <bits/stdc++.h> using namespace std; int read() { int X = 0, w = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') w = -1; c = getchar(); } while (c >= '0' && c <= '9') X = X * 10 + c - '0', c = getchar(); return X * w; } const int N = 200000 + 10, M = 447 + 10; int n, m, Q,...
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a. Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen w...
#include <bits/stdc++.h> using namespace std; long n, m; int main() { scanf("%ld %ld\n", &n, &m); if (m == 1 && n == 1) printf("%ld", 1); else if ((m < n && n / 2 >= m) || m == 1) printf("%ld", m + 1); else printf("%ld", m - 1); return 0; }
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 = 1e3 + 10, inf = 1e8; int n, m, dp[4][maxn][maxn], mark[maxn][maxn], color = 0, dis[5][5]; vector<pair<int, int> > ve[4]; char mat[maxn][maxn]; queue<pair<int, int> > qu; pair<int, int> mov[] = {pair<int, int>(0, 1), pair<int, int>(0, -1), ...
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). ...
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { while (a != 0 && b != 0) { if (a > b) a = a % b; else b = b % a; } return a + b; } int main() { int n; cin >> n; vector<int> a(n); string s; string left, right; string result; for (int i = 0; i < n; i++) { ...
After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique. For a given sentence, the ciphe...
#include <bits/stdc++.h> using namespace std; const int MAX = 100010; int lower(int character) { if ('a' <= character && character <= 'z') return character; return character - 'A' + 'a'; } struct Trie { Trie *link[26]; int ind; Trie(int ind) : ind(ind) { for (int i = 0; i < 26; ++i) link[i] = NULL; } } ...
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q...
x, y = input().split(" ") a = x,y a = list(a) for i in range(len(a)): a[i]=int(a[i]) count=0 num =a[1] for i in range(a[0]): z,f = input().split(" ") char=z inp=int(f) if char == '+': num = num + inp elif char == '-': num = num - inp if num < 0: count+=1 ...
Alex studied well and won the trip to student camp Alushta, located on the seashore. Unfortunately, it's the period of the strong winds now and there is a chance the camp will be destroyed! Camp building can be represented as the rectangle of n + 2 concrete blocks height and m blocks width. Every day there is a bree...
#include <bits/stdc++.h> using namespace std; const int P = 1000000007; int n, m, k, p, fac[100005], ifac[100005], pp[1505], h[1505], g[1505]; int power(int a, int x) { int ans = 1; for (; x; x >>= 1, a = 1ll * a * a % P) if (x & 1) ans = 1ll * ans * a % P; return ans; } int binom(int n, int m) { return 1ll *...
This is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush(). In this problem, you need to find maximal and minimal elements of an ar...
import sys T = int(input()) def compare(l,r,arr): print('?',a[l]+1,a[r]+1) sys.stdout.flush() res = input() if (res == '>'): return 1; else: return 0; while (T > 0): T -= 1 Max_a = [] Min_a = [] n = int(input()) a = range(n) for i in range(int(n/2)): if (compare(...
Pay attention to the output section below, where you will see the information about flushing the output. Bearland is a grid with h rows and w columns. Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right. Every cell is either allowed (denoted by '.' in the input) or per...
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10; int gi() { int x = 0, o = 1; char ch = getchar(); while (!isdigit(ch) && ch != '-') ch = getchar(); if (ch == '-') o = -1, ch = getchar(); while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * o; } char s[1010][1010]; int ...
Stepan has n pens. Every day he uses them, and on the i-th day he uses the pen number i. On the (n + 1)-th day again he uses the pen number 1, on the (n + 2)-th — he uses the pen number 2 and so on. On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses t...
#include <bits/stdc++.h> using namespace std; const long long int maxN = 5e4 + 226; long long int N, _time[maxN][7], ct, covered, arr[maxN], narr[maxN], currentMinus[maxN]; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); ; cin >> N; for (long long int i = 0; i < N; i++) { cin >> arr[i]; } ...
Butler Ostin wants to show Arkady that rows of odd number of fountains are beautiful, while rows of even number of fountains are not. The butler wants to show Arkady n gardens. Each garden is a row of m cells, the i-th garden has one fountain in each of the cells between li and ri inclusive, and there are no more foun...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:512000000") using namespace std; void solve(bool); void precalc(); clock_t start; int testNumber = 1; bool todo = true; int main() { start = clock(); int t = 1; cout.sync_with_stdio(0); cin.tie(0); precalc(); cout.precision(10); cout << fixed; int...
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yy...
s = raw_input().strip() res = [] slen = len(s) i = 0 while (i < slen): if (len(res) > 0) and (res[-1] == s[i]): res.pop() else: res.append(s[i]) i += 1 print ''.join(res)
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. * speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); * overtake is allowed: this sign means th...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOExceptio...
The game of Egg Roulette is played between two players. Initially 2R raw eggs and 2C cooked eggs are placed randomly into a carton. The shells are left on so there is no way to distinguish a raw egg from a cooked egg. One at a time, a player will select an egg, and then smash the egg on his/her forehead. If the egg was...
#include <bits/stdc++.h> using namespace std; long long C[777][777]; int r, c; long long total; long long best = (long long)1e18, best_z = -1; void dfs(long long x, long long y, int v1, int v2) { long long diff = abs(x - y); if (best <= 1 || diff - C[v1][r] * C[v2][r] >= best) { return; } if (v1 == r - 1 &&...
Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai ≤ bi). Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not! Input The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola...
#include <bits/stdc++.h> using namespace std; void solve() { long long int n, sum = 0; cin >> n; long long int b[n]; for (long long int i = 0; i < n; i += 1) { long long int val; cin >> val; sum += val; } for (long long int i = 0; i < n; i += 1) { cin >> b[i]; } sort(b, b + n); if (b[n...
Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square. A number x is said to be a perfect square if there exists an integer y such that x = y2. Input The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second ...
n = int(input()) a = [int(i) for i in input().split()] p = [] i = 0 while(True): p.append(i*i) i += 1 if(p[-1] > 1000000): break m = -99999999 for i in a: if i not in p: m = max(i,m) print(m)
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock...
#include <bits/stdc++.h> char ch; bool fs; void re(int& x) { while (ch = getchar(), ch < 33) ; if (ch == '-') fs = 1, x = 0; else fs = 0, x = ch - 48; while (ch = getchar(), ch > 33) x = x * 10 + ch - 48; if (fs) x = -x; } using namespace std; int n, cnt[26], top, st[6333]; char s[2005], t[2005], ...
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first. On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first...
#include <bits/stdc++.h> using namespace std; long long int fastExpo(long long int a, long long int n, long long int mod) { long long int result = 1; while (n > 0) { if (n & 1) result = (result * a) % mod; a = (a * a) % mod; n >>= 1; } return result; } long long int modInverse(long long int n, long ...
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive. Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, ...
import java.io.PrintWriter; import java.math.BigInteger; import java.util.HashMap; import java.util.Locale; import java.util.Random; import java.util.Scanner; import org.omg.CORBA.FREE_MEM; public class Main { class Pair{ Long l1; Long l2; }; HashMap<Pair, Fraction> F = new HashMap<Pair, ...
Andrew has recently moved to Wengaluru. He finds this city amazing as all the buildings of the city are of same shape. There are N buildings in a row with no space in between. Buildings may have different heights while width in other two dimensions is always 1 unit. Rain occurs very frequently in Wengaluru so Andre...
from collections import * from heapq import * from bisect import * from math import * mapper=map mi=int mf=float inf=mf('inf') ri=raw_input t=mi(ri()) while t>0: t-=1 n=mi(ri()) arr=mapper(mi, ri().split()) total=0 i=1 start=arr[0] while i<n: tmptotal=0 lastmax=i-1 while i<n and arr[i]<start: tmptotal...
Babu and Sabu are enemies but they fight with each other with the help of the mind games not guns. One day Babu asks Sabu to give the answer for this mathematical query as following: Let f(m, n) = m^n But Sabu is little weak in mathematics and he wants the help to answer the question. Your aim is to answer f(m1, n1)...
#http://ideone.com/bOxFqJ #http://stackoverflow.com/questions/4223313/finding-abc-mod-m def totient(n) : result = 1 p = 2 while p**2 <= n : if(n%p == 0) : result *= (p-1) n /= p while(n%p == 0) : result *= p n /=...
Link to Russian translation of problem There are N ants staying at the vertices of the N-regular polygon (one ant at one vertex). At some moment of time all the ants choose one of the edges their vertex is adjacent to and start walking along this edge. If two ants meet at some point of the edge they die. Please find t...
t=input() mod=10**9+7 for _ in xrange(t): n=input() print ((2%mod)*pow(pow(2,n,mod),mod-2,mod))%mod
In this problem you will be given a range 'n', and you are supposed to find all composite numbers within that range. Make your program efficient as time limit of the program is set to 1 second. Choose an efficient algorithm to find all the composite numbers within the range 0 to n. Input n - a single positive Integer...
limit = 10000 def primes_sieve2(limit): a = [True] * limit a[0] = a[1] = False for (i, isprime) in enumerate(a): if isprime: for n in xrange(i*i, limit, i): a[n] = False return a if __name__ == "__main__": a = primes_sieve2(limit) n = input() for i in x...
Gennady and Artem are discussing solutions of different problems. Gennady told Artem about a number theory problem he solved the day before. One of steps to solve the problem was to calculate the least common multiple (LCM) of all integers from 1 to n, inclusive. That problem inspired Gennady to come up with another pr...
from sys import stdin import math import random def mod(a,b,c): if b==0: return 1 if b<=10: return (a**b)%c if b%2==1: return (a*mod(a,b-1,c))%c x=mod(a,b/2,c) return (x*x)%c def check(p): if p<=1: return 0 if p==2: return 1; if p%2==0: return 0 count = 5 s=p-1 while s%2==0: s=s/2; ...
Our code monk, high on excitement after solving the rest of the problems , goes on a trek in the mountains . On his way, he encounters Janemba, the evil magician! Janemba takes our monk to a poison field and plays a game with him described as follows: The poison field is described as NxN matrix,divided into N * N c...
for t in range(0, int(raw_input())): temp = raw_input().strip().split(' ') k, n = int(temp.pop()), int(temp.pop()) c = [0]*n r = [0]*n sr = [0]*(k+1) sc = [0]*(k+ 1) for i in range(0,n): temp = raw_input().strip().split(' ') for j in range(0,n): e = int(temp[j]) c[j] += e r[i] += e for i ...
A permutation is a list of K numbers, each between 1 and K (both inclusive), that has no duplicate elements. Permutation X is lexicographically smaller than Permutation Y if for some i ≤ K: All of the first i-1 elements of X are equal to first i-1 elements of Y. ith element of X is smaller than ith element of Y. ...
k = int(raw_input()) p = map(int, raw_input().split(' ')) matrix = [] for _ in range(k): matrix.append([i == 'Y' for i in raw_input()]) def floyd_warshal(matrix): k = len(matrix) for kk in range(k): for i in range(k): for j in range(k): if matrix[i][kk] and matrix[kk][j...
Roy bought a Ring for Alfi, his girlfriend :p. But Alfi will only accept the Ring if Roy played a game with her and answered her queries correctly during the game. Alfi places a ring at origin of a Cartesian Plane. Both Alfi and Roy move the ring alternatively. Alfi takes odd steps and Roy takes even steps. Directio...
MOD = 1000000007 def matrix_mul(a,b,c): c[0][0] = a[0][0]*b[0][0] + a[0][1]*b[1][0] c[0][0] %= MOD c[0][1] = a[0][0]*b[0][1] + a[0][1]*b[1][1] c[0][1] %= MOD c[1][0] = a[1][0]*b[0][0] + a[1][1]*b[1][0] c[1][0] %= MOD c[1][1] = a[1][0]*b[0][1] + a[1][1]*b[1][1] c[1][1] %= MOD def iter_po...
For every string given as input, you need to tell us the number of subsequences of it that are palindromes (need not necessarily be distinct). Note that the empty string is not a palindrome. SAMPLE INPUT 1 aab SAMPLE OUTPUT 4 Explanation the palindromic subsequences of "aab" are: "a", "a", "b", "aa", and the metho...
t=input() paliCount=[[]] def cPalis(s,i,j): if j<i: return 0 if i==j: return 1 if paliCount[i][j]: return paliCount[i][j] su=cPalis(s,i,j-1) for k in range(i,j+1): if s[k]==s[j]: su+=1+cPalis(s,k+1,j-1) #print k,j,s[k],s[j] return su for _ in range(t): s=raw_input() n=len(s) paliCount=[[0]*n for i...
Vanya has been studying all day long about sequences and other Complex Mathematical Terms. She thinks she has now become really good at it. So, her friend Vasya decides to test her knowledge and keeps the following challenge it front of her: Vanya has been given an integer array A of size N. Now, she needs to find th...
def gcd( a, b ): if ( a==0 ): return b return gcd ( b%a, a ) MOD = 10**9 +7 try: N = int(raw_input()) A = map(int, raw_input().split()) dp = [[[0]*101 for i in range(101)] for j in range(N)] dp[0][A[0]][A[0]] = 1 for i in range(1, N): dp[i][A[i]][A[i]] = 1 for j in range(101): for k in range...
M-kun is a brilliant air traffic controller. On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude. Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the d...
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector<pair<int, char>> *vx = new vector<pair<int, char>>[200001]; vector<pair<int, char>> *vx_puls_y = new vector<pair<int,char>>[400001]; int n; cin >> n; int* x = new int[n]; int* y = new int[n]; int min_collision_time...
Given is a sequence of N digits a_1a_2\ldots a_N, where each element is 1, 2, or 3. Let x_{i,j} defined as follows: * x_{1,j} := a_j \quad (1 \leq j \leq N) * x_{i,j} := | x_{i-1,j} - x_{i-1,j+1} | \quad (2 \leq i \leq N and 1 \leq j \leq N+1-i) Find x_{N,1}. Constraints * 2 \leq N \leq 10^6 * a_i = 1,2,3 (1 \leq...
N = int(input()) a = input() def myc(n): ret = 0 while n % 2 == 0: ret += 1 n //= 2 return ret def func(c): odd = 0 count = 0 if a[0] == c: count += 1 if a[-1] == c: count += 1 for i in range(1, N // 2): odd += myc(N-i) - myc(i) if a[i] =...
In a two-dimensional plane, there is a square frame whose vertices are at coordinates (0,0), (N,0), (0,N), and (N,N). The frame is made of mirror glass. A ray of light striking an edge of the frame (but not a vertex) will be reflected so that the angle of incidence is equal to the angle of reflection. A ray of light st...
#include<bits/stdc++.h> #define ll long long #define ull unsigned ll #define uint unsigned #define pii pair<int,int> #define pll pair<ll,ll> #define IT iterator #define PB push_back #define fi first #define se second #define For(i,j,k) for (int i=(int)(j);i<=(int)(k);i++) #define Rep(i,j,k) for (int i=(int)(j);i>=(int)...
Takahashi is distributing N balls to K persons. If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls? Constraints * 1 \leq K \leq N \leq 100 * All values in input are intege...
a,b=map(int,input().split()) c=a-b if b!= 1: print(c) else: print(0)
There is a right triangle ABC with ∠ABC=90°. Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC. It is guaranteed that the area of the triangle ABC is an integer. Constraints * 1 \leq |AB|,|BC|,|CA| \leq 100 * All values in input are integers. * The area of the triangl...
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println(sc.nextInt() * sc.nextInt() /2); } }
You are given a string S. Each character of S is uppercase or lowercase English letter. Determine if S satisfies all of the following conditions: * The initial character of S is an uppercase `A`. * There is exactly one occurrence of `C` between the third character from the beginning and the second to last character (i...
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main(){ string s; cin >> s; string ans="AC"; int cnt=0; if(s[0]!='A') ans = "WA"; for(int i=1; i<s.size(); i++){ if(s[i]=='C' && 2<=i && i<=s.size()-2) cnt +=1; else if('A'<=s[i] && s[i]<='Z') ans = "WA"; ...
You are given an H \times W grid. The square at the top-left corner will be represented by (0, 0), and the square at the bottom-right corner will be represented by (H-1, W-1). Of those squares, N squares (x_1, y_1), (x_2, y_2), ..., (x_N, y_N) are painted black, and the other squares are painted white. Let the shorte...
#include<bits/stdc++.h> using namespace std; const int mod=1e9+7,iv=(mod+1)/2; int dx[]={1,0,-1,0},dy[]={0,1,0,-1}; int h,w,n,x[33],y[33],prex[1111111],prey[1111111],ans,arrx[111],arry[111],cntx,cnty,dist[111][111],res; int fx[111],fy[111]; bool ex[1111111],ey[1111111],ff[111][111]; map<pair<int,int>,int> mp; bool In(i...
It is September 9 in Japan now. You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N? Constraints * 10≤N≤99 Input Input is given from Standard Input in the following format: N Output If 9 is contained in the decimal notation of N, print `Yes`; if not, print `No...
#include <bits/stdc++.h> using namespace std; int main(){ int a; cin >> a; cout << ((a%10==9||a/10==9)?"Yes":"No") << endl; }
How many infinite sequences a_1, a_2, ... consisting of {{1, ... ,n}} satisfy the following conditions? * The n-th and subsequent elements are all equal. That is, if n \leq i,j, a_i = a_j. * For every integer i, the a_i elements immediately following the i-th element are all equal. That is, if i < j < k\leq i+a_i, a_j...
#include<cstdio> const int N=1000005,P=1000000007; int n,f[N]; int main() { scanf("%d",&n); f[1]=n; f[2]=1ll*n*n%P; int sum=0; for(int i=3;i<=n;i++) { sum=(sum+f[i-3])%P; f[i]=(f[i-1]+(n-1ll)*(n-1ll)+(n-i+2)+sum)%P; } printf("%d\n",f[n]); return 0; }
Input The input is given from Standard Input in the following format: > $N \ Q$ $a_1 \ b_1$ $a_2 \ b_2$ $ : \ : $ $a_Q \ b_Q$ Output * You have to print $N$ lines. * The $i$-th line should contain the number of dishes of sushi had eaten for customer $i (1 \le i \le N)$. Constraints * $3 \le N, Q \le 100,000$ *...
#include<bits/stdc++.h> using namespace std; #define int long long typedef vector<int>vint; typedef pair<int,int>pint; typedef vector<pint>vpint; #define rep(i,n) for(int i=0;i<(n);i++) #define reps(i,f,n) for(int i=(f);i<(n);i++) #define all(v) (v).begin(),(v).end() #define each(it,v) for(__typeof((v).begin()) it=(v)...
Your task is to write a program which reads a date (from 2004/1/1 to 2004/12/31) and prints the day of the date. Jan. 1, 2004, is Thursday. Note that 2004 is a leap year and we have Feb. 29. Input The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset cons...
days = [31,29,31,30,31,30,31,31,30,31,30,31] ans = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] while True: idx = 3 m,d = map(int, input().split()) if m==0: break print(ans[(idx+sum(days[:m-1])+d-1)%7])
For a positive integer n * If n is even, divide by 2. * If n is odd, multiply by 3 and add 1. If you repeat the above operation, the result will be 1. A problem called "Colatz conjecture" is that repeating this operation for any positive integer n will always result in 1. This problem is an unsolved problem, also k...
while 1: n = int(input()) if n == 0: break cnt = 0 while n != 1: if n % 2 == 0: n //= 2 else: n = n * 3 + 1 cnt += 1 print(cnt)
The cloth coasters produced and sold by Aizu Takada City are known for their symmetrical design and great beauty. As part of quality control, Aizu Takada City has installed cameras on the production line to automatically verify that the images obtained by shooting each coaster are symmetrical. Each coaster is represent...
import java.util.*; class Main{ private void compute(){ int i, j, k, r, c; int cnt = 0; int ans = 0; int tmp = 0; String inStr, tmpStr; char tmpChar; Scanner sc = new Scanner(System.in); int C = sc.nextInt(); int N = sc.nextInt(); int...
There are N towns in JOI, which are connected by M bidirectional roads. There are shopping malls in K towns, and the people go to one of those towns through the road to shop. Depending on the location of your home, you may have to travel long distances to go shopping, which is very inconvenient. To understand this sit...
#include <iostream> #include <queue> #include <vector> #include <map> #include <cstdio> #include <cstring> #include <cmath> using namespace std; const int INF = 1e+9 * 2; typedef pair<int, int> P; struct edge { int to, c; edge(int _to, int _c) : to(_to), c(_c){} }; int N, M, d[3001]; vector<edge> G[3001]; int ma...
YOKARI TAMURA is a nationally famous artist. This month YOKARI will be touring live for D days. Divide this country into C different regions when deciding on a tour schedule. YOKARI benefits from performing live in an area, which is represented by a positive integer. As a general rule, YOKARI will perform up to one liv...
#include <cstdio> #include <iostream> #include <vector> #include <list> #include <cmath> #include <fstream> #include <algorithm> #include <string> #include <queue> #include <set> #include <map> #include <complex> #include <iterator> #include <cstdlib> #include <cstring> #include <sstream> using namespace std; const d...
Let's play a new board game ``Life Line''. The number of the players is greater than 1 and less than 10. In this game, the board is a regular triangle in which many small regular triangles are arranged (See Figure l). The edges of each small triangle are of the same length. <image> Figure 1: The board The size of ...
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> using namespace std; #define FOR(i,k,n) for(int i=(k); i<(int)n; +...
Example Input 5 Alice 10 20 30 40 50 Output 30
#include<bits/stdc++.h> using namespace std; const int MAXN = 100000; int BobEven(int n, int *A) { int M = n / 2; int res = INT_MAX; for(int i = 1; i <= M; i++) res = min(res, A[M+i]-A[i]); return res; } int AliceOdd(int n, int *A) { int M = n / 2; for(int i = M + 1; i < n; i++) A[i] ...
Problem Find the area of ​​a regular N / K polygon inscribed in a circle with a radius of 1. However, a regular N / K polygon is defined as "the outermost figure that takes N points on the circumference at equal intervals and connects each point every K-1". For example, a 5/2 polygon can be drawn as follows. First, ...
#include <cstdio> #include <cmath> double rad(double ang) { return ang / 180.0 * acos(-1); } int main() { double n, k; scanf("%lf %lf", &n, &k); printf("%.10f\n", n * sin(rad(180 / n)) * cos(rad(180 * k / n)) / cos(rad(180 * (k - 1) / n))); return 0; }
The Kingdom of Aqua Canora Mystica is a very affluent and peaceful country, but around the kingdom, there are many evil monsters that kill people. So the king gave an order to you to kill the master monster. You came to the dungeon where the monster lived. The dungeon consists of a grid of square cells. You explored t...
#include <iostream> #include <queue> #include <cstring> #include <map> using namespace std; class P{ public: int x,y,cost,bit; P(int _x,int _y,int _cost,int _bit){ x = _x; y = _y; cost = _cost; bit = _bit; } bool operator<(const P &p)const{ return cost > p.cost; } }; int w,h; int s[32][32]; char t[32...
Bingo is a party game played by many players and one game master. Each player is given a bingo card containing N2 different numbers in a N × N grid (typically N = 5). The master draws numbers from a lottery one by one during the game. Each time a number is drawn, a player marks a square with that number if it exists. T...
#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 MOD 10007 enum Type{ N, E, S, W, NE, SE, NW, SW, }; struct Info{ int x,y; }; ...
Problem statement An unusual rally game is popular at KU University. The circuit, which is the setting of this game, has N rest areas and M roads, and the i-th road is between the fi-th rest area and the ti-th rest area. There is one checkpoint on every road, and if you pass the checkpoint on road i, the score of pi w...
#include <iostream> #include <vector> #include <queue> #include <memory.h> using namespace std; #define rep(i, n) for(int i = 0; i< n; i++) typedef long long ll; typedef pair<ll, ll> P; const int maxn = 100010; ll dist[maxn]; vector<P> G[maxn]; vector<ll> bfs(){ queue<ll> que; vector<ll> res; memset(dist, -1, ...
Problem Statement You are given a rectangular board divided into square cells. The number of rows and columns in this board are $3$ and $3 M + 1$, respectively, where $M$ is a positive integer. The rows are numbered $1$ through $3$ from top to bottom, and the columns are numbered $1$ through $3 M + 1$ from left to rig...
#pragma GCC optimize "O3" #define ALL(x) x.begin(), x.end() #include<bits/stdc++.h> using namespace std; constexpr int N = 26; typedef long long LL; int m; char tab[3][3010]; vector<LL> cls; inline bool dfs(const int& lev, LL st) { if(st & (st >> N)) return false; if(lev == (int)cls.size()) { vector...
Example Input 3 y 7 y 6 n 5 Output 1
// #define _GLIBCXX_DEBUG // for STL debug (optional) #include <iostream> #include <iomanip> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex...
There is a village along a road. This village has $N$ houses numbered $1$ to $N$ in order along the road. Each house has a field that can make up to two units of the crop and needs just one unit of the crop. The total cost to distribute one unit of the crop to each house is the summation of carrying costs and growing c...
#include <bits/stdc++.h> #define ll long long #define INF 1000000005 #define MOD 1000000007 #define EPS 1e-10 #define rep(i,n) for(int i=0;i<(int)(n);++i) #define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i) #define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i) #define each(a,b) for(auto& (a): (b)) #define all(v) (v).begi...
Problem Neat lives on the world line for a total of 360 days until the 30th of every month for 1 year and 12 months. In that world, N consecutive holidays with the same schedule were applied to people all over the world every year. Consecutive holidays i are consecutive Vi days starting from Mi month Di day. NEET is ...
#include <bits/stdc++.h> #define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++) #define MAXCH(a, b) a = max(a, b); #define INF (1LL << 30) using namespace std; typedef long long ll; ll N, M[100], D[100], V[100], S[100]; int main(void) { cin >> N; REP(i, 0, N) cin >> M[i] >> D[i] >> V[i] >> S[i]; vector<l...
You have $N$ items that you want to put them into a knapsack of capacity $W$. Item $i$ ($1 \le i \le N$) has weight $w_i$ and value $v_i$ for the weight. When you put some items into the knapsack, the following conditions must be satisfied: * The total value of the items is as large as possible. * The total weight of...
N, W = map(int, input().split()) W_calc = W ans = 0 items = [] for _ in range(N): v, w = map(int, input().split()) density = v / w items.append([density, v, w]) items.sort(reverse=True) for density, v, w in items: if w < W_calc: W_calc -= w ans += v else: ans += W_calc *...
Write a program which calculates the area and circumference of a circle for given radius r. Constraints * 0 < r < 10000 Input A real number r is given. Output Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-...
import math r = float(input()) print '%f %f' % (r*r*math.pi,r*2*math.pi)
In mathematics, the absolute value (or modulus) |a| of a real number a is the numerical value of a without regard to its sign. So, for example, the absolute value of 3 is 3, and the absolute value of -3 is also 3. The absolute value of a number may be thought of as its distance from zero. Input There is a single pos...
ans = [] t = input("") for i in range(t): N = int(raw_input("")) ans.append(abs(N)) for i in range(t): print ans[i]
Chef's team is going to participate at the legendary math battles. One of the main task in the competition is to calculate the number of ways to create a number by adding some Chefonacci numbers. A number is called a Chefonacci number if it is an element of Chefonacci sequence defined as follows. f(0) = 1; f(1) = 2;...
ans=0 found=set() def numberofways(fib,x,k,curr,idx,high): global ans if ( x!=0 and curr>=k ) or x<0 or x>(high*(k-curr)): # print 'Discarded' return 0 if x==0 and curr==k: ans+=1 # print 'New Way' return 1 for i in xrange(0,49): if fib[i]>x or fib[i]>high: break else: # print 'fib', fib[i], 'i...
You are given a multiset of N integers. Please find such a nonempty subset of it that the sum of the subset's elements is divisible by N. Otherwise, state that this subset doesn't exist. Input The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows....
import fileinput import itertools import sys import random ''' http://www.codechef.com/problems/DIVSUBS ''' def single_test_dumb(nums): nums = [(index, int(x)) for index,x in enumerate(fi.readline().strip().split(" "))] for i in range(1, len(nums)+1): for pairs in itertools.combinations(nums, i): if sum(x[1] ...
Ilya lives in the beautiful city of Bytes lying in a hilly terrain. She loves to ride her bicycle on the hills whenever she gets a chance to do so. There are check-posts located on the hill at a unit distance from each other. The height of the check posts is given in an array A. Ilya has to visit her aunt who lives N ...
t = int(input()) for i in range(t): n = int(input()) l = map(int, raw_input().split()) count = 0 pslope = 0 for i in range(len(l)-1): cslope = l[i+1]-l[i] if(pslope!=0): if((cslope>0 and pslope<0) or (cslope<0 and pslope>0)): count = count + 1 pslo...
Coding in Sprout (a programming language) is very intuitive. Chef is giving his minions a demonstration in Sprout and wants you to help him determine if they are not too difficult for them. A program in Sprout is written using three kinds of instructions. Load Instruction: Load a value into buffer. Increment Instr...
t= input() while(t>0): t-=1 a=list(raw_input()) n=len(a) ins=1+n for i in range(n-1): diff= ord(a[i])-ord(a[i+1]) if(diff>0): ins += 26 - diff else: ins-=diff if(n*11>=ins): print "YES" else: print "NO"
Sereja has a string A consisting of n lower case English letters. Sereja calls two strings X and Y each of length n similar if they can be made equal by applying the following operation at most once in each of them. Chose any two position i, j in the string (i can be equal to j too). Swap the characters at position ...
from collections import Counter # compute factorials and inverse factorials mod = 10**9 + 7 N = 10**5 + 11 fac = [1]*N ifc = [1]*N for i in xrange(2,N): ifc[i] = (mod - mod/i) * ifc[mod%i] % mod for i in xrange(2,N): fac[i] = fac[i-1] * i % mod ifc[i] = ifc[i-1] * ifc[i] % mod for cas in xrange(inpu...
You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≤ i < n) such that s_i ≠ s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there ar...
a,b,x=map(int,input().split()) x+=1 y=x//2 c=0 if x%2: if a>b: a-=1;c=1 else: b-=1;c=2 s=(a-y)*'0'+y*'01'+(b-y)*'1' if c:s=s+'0'if c==1 else '1'+s print(s)
You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose suc...
#include <bits/stdc++.h> using namespace std; map<int, int> freq; map<int, int>::iterator it, it2; int f[10100], val[10100]; int main() { double melhorV, l1, l2, p, s; int v, noCases, ans1, n, ans2, po, a1, a2, d, melhorD, fra1, fra2; scanf("%d", &noCases); while (noCases--) { freq.clear(); scanf("%d", ...
In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspace™ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hype...
#include <bits/stdc++.h> using namespace std; const int N = 100001, M = N * 2, L = 19; int tin[N], tup[N], used[N], ct; vector<int> g[N], ng[M]; int d[M], up[L][M], cn; void dfs(int v, int p) { tup[v] = tin[v] = ++ct; for (int u : g[v]) { if (u == p) continue; if (tin[u]) tup[v] = min(tup[v], tin[u]);...
You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s. Input The first line contains two positive integers d and s (1 ≤ d ≤ 500, 1 ≤ s ≤ 5000) separated by space. Output Print the required number or -1 if it doesn't exist. Examples In...
#include <bits/stdc++.h> using namespace std; struct node { int mod; int bit; string s; node(){}; node(int m, int b, string ss) { mod = m, bit = b, s = ss; } }; bool v[501][5001]; string bfs(int d, int s) { queue<node> q; q.push(node(0, 0, "")); v[0][0] = true; while (!q.empty()) { node buf = q.fr...
Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends. This morning, somebody anonymously sent Bob the following link: [graph realization ...
#include <bits/stdc++.h> using namespace std; inline long long mod(long long n, long long m) { long long ret = n % m; if (ret < 0) ret += m; return ret; } long long gcd(long long a, long long b) { return (b == 0 ? a : gcd(b, a % b)); } long long exp(long long a, long long b, long long m) { if (b == 0) return 1;...
Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_commo...
#!/usr/bin/env python """ This file is part of https://github.com/Cheran-Senthil/PyRival. Copyright 2019 Cheran Senthilkumar <hello@cheran.io> """ from __future__ import division, print_function import cmath import itertools import math import operator as op # import random import sys from atexit import register from...