input
stringlengths
29
13k
output
stringlengths
9
73.4k
You are given n non-decreasing arrays of non-negative numbers. Vasya repeats the following operation k times: * Selects a non-empty array. * Puts the first element of the selected array in his pocket. * Removes the first element from the selected array. Vasya wants to maximize the sum of the elements in...
#include <bits/stdc++.h> using namespace std; template <class T> inline void rd(T &x) { int fl = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') fl = -fl; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= fl; } template <class T> inline void wr(T x)...
There are n persons located on a plane. The i-th person is located at the point (x_i, y_i) and initially looks at the point (u_i, v_i). At the same moment of time, all persons will start to rotate clockwise synchronously with the same angular speed. They will rotate until they do one full 360-degree turn. It is said...
import java.util.*; import java.io.*; public class Main { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOExcepti...
You are storing an integer array of length m in a database. To maintain internal integrity and protect data, the database stores n copies of this array. Unfortunately, the recent incident may have altered the stored information in every copy in the database. It's believed, that the incident altered at most two elemen...
#include<bits/stdc++.h> using namespace std; const int N = 3e5 + 10; int n, m, s[N], ans[N]; bool dfs(int dep) { if (dep > 2) return false; for (int i = 1; i < n; i++) { int num = 0, pos[5]; for (int j = 0; j < m; j++) { if (ans[j] != s[i * m + j]) pos[num ++] = j; if (num > 4) return false; } if (num >...
Phoenix's homeland, the Fire Nation had n cities that were connected by m roads, but the roads were all destroyed by an earthquake. The Fire Nation wishes to repair n-1 of these roads so that all the cities are connected again. The i-th city has a_i tons of asphalt. x tons of asphalt are used up when repairing a road...
#include <bits/stdc++.h> #define pb push_back #define mp make_pair #define fir first #define sec second using namespace std; typedef long long ll; const int N = 3e5 + 5; vector<pair<int, int>> G[N]; int n, m, x, fa[N], ans[N], hd, tl; bool vis[N]; ll sum, a[N]; void Dfs(int u, int p) { vis[u] = true; for(pair<int, i...
This is the easy version of the problem. The only difference between the easy version and the hard version is the constraints on n. You can only make hacks if both versions are solved. A permutation of 1, 2, …, n is a sequence of n integers, where each integer from 1 to n appears exactly once. For example, [2,3,1,4] i...
#include <iostream> #include <numeric> #include <vector> #include <cstring> #define ALL(v) v.begin(), v.end() const int N = 51; const int M = (N * (N - 1)) / 2 + 5; int f[N][M]; int s[N][M]; int t[N]; int answer[N]; int n, mod; int main() { std::ios::sync_with_stdio(false); std::cin >> n >> mod; f[0][0] = 1...
n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The ...
#include <bits/stdc++.h> using namespace std; int n; double dp[(1 << 18) + 8]; double Map[18 + 8][18 + 8]; int main() { int n; cin >> n; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { cin >> Map[i][j]; } } dp[(1 << n) - 1] = 1.0; for (int sta = (1 << n) - 2; sta >= 1; --sta) { ...
Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer. We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integer...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; /** * @author Ivanov A.K. */ public class A { private BufferedReader reader; private StringTokenizer toke...
Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies....
#include <bits/stdc++.h> using namespace std; int c[210]; int pre[210][210]; int precnt[210]; int cnt[210] = {0}; int main() { int n; scanf("%d", &n); for (int i = 0; i < (n); i++) { scanf("%d", c + i); c[i] %= 3; } for (int i = 0; i < (n); i++) for (int j = 0; j < (n); j++) pre[i][j] = 0; for (...
You must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world. As you know there are n countries in the world. These countries are connected by n - 1 directed roads. If you don't consider direc...
#include <bits/stdc++.h> using namespace std; int const N = 3000 + 20; int n, dp[N], mx1, mx2, ans; vector<pair<int, bool>> adj[N]; void dfs1(int v, int p = -1) { for (auto x : adj[v]) { int u = x.first, f = x.second; if (u != p) { dfs1(u, v); dp[v] += dp[u] + (!f); } } return; } void dfs2...
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
mat = [] for x in range(0, 5): a = list(map(int, input().split())) mat.append(a) for i in a: if i == 1: row = a.index(1) col = mat.index(a) print(abs(row - 2) + abs(col - 2))
In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the p...
#include <bits/stdc++.h> using namespace std; char str[5][5]; int main() { while (~scanf("%s", str[0])) { for (int i = 1; i < 4; i++) { scanf("%s", str[i]); } int a = 0; int b = 0; int flag = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { a = 0; b = ...
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of ...
#include <bits/stdc++.h> using namespace std; int main() { int n; char input[111]; cin.getline(input, 111); if (strlen(input) == 2) n = 10; else n = input[0] - '0'; for (int j = 1; j <= n; j++) { cin.getline(input, 111); bool f = false, r = false; if (strlen(input) <= 5) { if (strc...
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original...
#include <bits/stdc++.h> using namespace std; void read_file(bool outToFile = true) {} int n, m; int A[1000 + 9][1000 + 9]; int main() { read_file(); while (scanf("%d%d", &n, &m) != EOF) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) A[i][j] = 1; A[0][0] = A[0][n - 1] = A[n - 1][0] = A[n - ...
Xenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance. The Hamming distance between two strings s = s1s2... sn and t = t1t2... tn of equal length n is value <image>. Record [si ≠ ti] is the Iverson notation and represents the following: if si ≠ ti, it is one, otherwise — zero. ...
#include <bits/stdc++.h> using namespace std; unsigned long long n, m; string A, B; char buf[1000010]; unsigned long long gcd(unsigned long long a, unsigned long long b) { if (b == 0) return a; if (a == 0) return b; return gcd(b, a % b); } unsigned long long lcm(unsigned long long a, unsigned long long b) { ret...
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")". Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of...
#include <bits/stdc++.h> using namespace std; string s; int m; struct node { int ans, open, close; node *l, *r; node() { r = l = 0; ans = 0; open = 0; close = 0; } }; node *merg(node *fir, node *sec) { node *ret = new node(); ret->ans = fir->ans + sec->ans + min(fir->open, sec->close); ret...
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot...
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class B { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); class Round implements Comparable<Round> { int f; int s; ...
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food. Iahub asks Iahubina: can you build a rooted tree, such that * each ...
def DFS(x): for i in range(x): if(Seen[i][x]): continue if(Rem[i]>=C[x]): if(Rem[i]==C[x] and len(Children[i])==0): continue Rem[i]-=C[x] Parent[x]=i Children[i].append(x) return True for i in range(x): ...
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid shown be...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; if (min(n, m) % 2 == 0) cout << "Malvika" << "\n"; else cout << "Akshat" << "\n"; return 0; }
There is a simple way to create hard tasks: take one simple problem as the query, and try to find an algorithm that can solve it faster than bruteforce. This kind of tasks usually appears in OI contest, and usually involves data structures. Let's try to create a task, for example, we take the "Hamming distance problem...
#include <bits/stdc++.h> using namespace std; istream &in = cin; ostream &out = cout; namespace fft { struct cd { cd(double real = 0, double imag = 0) : real(real), imag(imag) {} cd &operator+=(cd const &rhs) { real += rhs.real; imag += rhs.imag; return *this; } cd &operator-=(cd const &rhs) { r...
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations. First, each actor...
#include <bits/stdc++.h> using namespace std; void output(long long x) { if (x < 0) putchar('-'), x = -x; if (x == 0) { putchar('0'); return; } int a[20], num = 0; while (x) a[++num] = x % 10, x /= 10; while (num > 0) putchar('0' + a[num--]); } inline long long myInt() { char c = getchar(); whil...
Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no ...
#include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; inline long long BigMod(long long B, long long P, long long M) { long long R = 1; while (P > 0) { if (P % 2 == 1) { R = (R * B) % M; } P /= 2; B = (B * B) % M; } return R; } long long fac[200005]; void FacGen() { ...
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the ...
n, m, q = map(int, raw_input().split()) matrix = [map(int, raw_input().split()) for _ in xrange(n)] def consecute(row): current = 0 mx = 0 for i in xrange(len(row)): if row[i] == 1: current += 1 mx = max(mx, current) else: current = 0 return mx cons = [consecute(matrix[i]) for i in xrange(n)] for ...
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if i...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100000 + 2; int main() { int n; int h[MAX_N], l[MAX_N], r[MAX_N]; cin >> n; for (int i = 1; i <= n; i++) { cin >> h[i]; } h[0] = 0; h[n + 1] = 0; l[0] = 0; for (int i = 1; i <= n; i++) { l[i] = min(l[i - 1] + 1, h[i]); } r[n +...
Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn. Of co...
import java.io.*; import java.math.*; import java.nio.file.attribute.AclEntry.Builder; import java.security.KeyStore.Entry; import java.util.*; public class CODEFORCES { private InputStream is; private PrintWriter out; int time = 0, dp[][], DP[], start[], end[], dist[], black[], MOD = (int)(1e9+7),...
There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this p...
#include <bits/stdc++.h> using namespace std; const int maxn = 1000; int main() { int x1, y1, x2, y2, x3, y3; cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; if ((x1 == x2 && x2 == x3) || (y1 == y2 && y2 == y3)) cout << 1; else { bool ok1 = (x1 == x2 && (y3 >= max(y1, y2) || y3 <= min(y1, y2))); bool ok2 =...
The main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to n - 1 in the order from the beginning of the street to the end (in the picture: from ...
#include <bits/stdc++.h> int main() { int x, y; scanf("%d%d", &x, &y); int c = 0; if (y % 2 == 1) { for (int i = 1; i <= y; i += 2) { c++; } } else { for (int i = x; i >= y; i -= 2) { c++; } } printf("%d", c); }
One day, ZS the Coder wrote down an array of integers a with elements a1, a2, ..., an. A subarray of the array a is a sequence al, al + 1, ..., ar for some integers (l, r) such that 1 ≤ l ≤ r ≤ n. ZS the Coder thinks that a subarray of a is beautiful if the bitwise xor of all the elements in the subarray is at least k...
#include <bits/stdc++.h> using namespace std; const int maxn = 1000005; struct Trie { int num; Trie* p[2]; } * root; int sum[maxn], n, k; Trie* newnode() { Trie* p = (Trie*)malloc(sizeof(Trie)); memset(p, 0, sizeof(Trie)); return p; } void add(int x) { Trie* m = root; for (int i = 30; i >= 0; i--) { i...
For some experiments little Petya needs a synchrophasotron. He has already got the device, all that's left is to set the fuel supply. Fuel comes through a system of nodes numbered from 1 to n and connected by pipes. Pipes go from every node with smaller number to every node with greater number. Fuel can only flow throu...
#include <bits/stdc++.h> using namespace std; template <class T> int size(const T &a) { return int(a.size()); } template <class T> T sqr(const T &a) { return a * a; } struct Edge { int l, h, a; void scan() { scanf("%d %d %d", &l, &h, &a); } } a[6][6]; map<int, int> dp[6]; int t[6]; int b[6]; int w[6] = {6, 11, ...
There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure: * The crow sets ai initially 0. * The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int nums[n]; for (int i = 0; i < n; i++) { int b; cin >> b; nums[i] = b; } for (int i = 0; i < n - 1; i++) { cout << nums[i] + nums[i + 1] << " "; } cout << nums[n - 1]; }
Berland is a tourist country! At least, it can become such — the government of Berland is confident about this. There are n cities in Berland, some pairs of which are connected by two-ways roads. Each road connects two different cities. In Berland there are no roads which connect the same pair of cities. It is possib...
#include <bits/stdc++.h> using namespace std; const int maxn = 4e5 + 5; int n, m; namespace Graph { struct Node { int to; int next; } edge[maxn << 1]; int head[maxn], cnt = 1; inline void add(int x, int y) { edge[++cnt].next = head[x]; edge[cnt].to = y; head[x] = cnt; } } // namespace Graph using namespace G...
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas...
// Don't place your source in a package import java.util.*; import java.lang.*; import java.io.*; import java.math.*; // Please name your class Main public class Main { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static int read() throws IOExce...
Peterson loves to learn new languages, but his favorite hobby is making new ones. Language is a set of words, and word is a sequence of lowercase Latin letters. Peterson makes new language every morning. It is difficult task to store the whole language, so Peterson have invented new data structure for storing his lang...
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 7; template <class T> void dbs(string str, T t) { cout << str << " : " << t << "\n"; } template <class T, class... second> void dbs(string str, T t, second... s) { int idx = str.find(','); cout << str.substr(0, idx) << " : " << t << ","; dbs(st...
Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population P from their random number before responding to Heidi's request. Also, there are now villages with as few as a single inhabitant, meaning that <image>. Can you help Heidi find out whether a village follow...
#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(const auto& (a): (b)) #define all(v) ...
Alice and Bob play 5-in-a-row game. They have a playing field of size 10 × 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts. In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins imm...
#include <bits/stdc++.h> using namespace std; int i, j, d, p, q, x[4] = {1, 1, 0, -1}, y[4] = {0, 1, 1, 1}; string s[12]; int main() { s[0] = s[11] = "OOOOOOO"; for (i = 1; i <= 10; i++) cin >> s[i], s[i] = "O" + s[i] + "O"; for (i = 1; i <= 10; i++) for (j = 1; j <= 10; j++) if (s[i][j] == '.') ...
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral. Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the...
#include <bits/stdc++.h> using namespace std; int main() { int n; bool flag = 1; cin >> n; double* mas = new double[n]; for (int i = 0; i < n; i++) { cin >> mas[i]; } for (int i = 1; i < n - 1; i++) { flag = flag && (mas[i] == (mas[i - 1] + mas[i + 1]) / 2); } if (flag) { cout << mas[n - 1...
"Multidimensional spaces are completely out of style these days, unlike genetics problems" — thought physicist Woll and changed his subject of study to bioinformatics. Analysing results of sequencing he faced the following problem concerning DNA sequences. We will further think of a DNA sequence as an arbitrary string ...
#include <bits/stdc++.h> using namespace std; const int N = 1007; const int M = 114; const int mod = 1e9 + 9; int n, m; int ch[M][4], fa[M], len[N], tot = 1; void bfs() { queue<int> q; for (int i = 0, iE = 3; i <= iE; i++) if (ch[1][i]) q.push(ch[1][i]), fa[ch[1][i]] = 1; else ch[1][i] = 1; wh...
This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game ...
#include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; const long long int MAX = 1e9 + 7; void array_show(int *array, int array_n, char middle = ' ') { for (int i = 0; i < array_n; i++) printf("%d%c", array[i], (i != array_n - 1 ? middle : '\n')); } void array_show(long long int *array, int array_...
As we all know, Dart is some kind of creature from Upside Down world. For simplicity, we call their kind pollywogs. Dart and x - 1 other pollywogs are playing a game. There are n stones in a row, numbered from 1 through n from left to right. At most 1 pollywog may be sitting on each stone at a time. Initially, the poll...
#include <bits/stdc++.h> using namespace std; template <typename T1, typename T2> inline void chkmin(T1 &x, T2 y) { if (x > y) x = y; } template <typename T1, typename T2> inline void chkmax(T1 &x, T2 y) { if (x < y) x = y; } template <typename T, typename U> inline ostream &operator<<(ostream &_out, const pair<T, ...
After the Search Ultimate program that searched for strings in a text failed, Igor K. got to think: "Why on Earth does my program work so slowly?" As he double-checked his code, he said: "My code contains no errors, yet I know how we will improve Search Ultimate!" and took a large book from the shelves. The book read "...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:16777216") using namespace std; struct Sol { vector<string> steps; vector<int> vals; }; int n; Sol ans; char buf[32]; void solution() { scanf("%d", &n); Sol zero; zero.vals.push_back(1); queue<Sol> q; q.push(zero); while (!q.empty()) { Sol s =...
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts 1 minute. He was asked to insert one takeoff in the schedule. The takeoff takes 1 minute it...
#include <bits/stdc++.h> using namespace std; int main() { vector<pair<int, int> > T; std::ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, s; cin >> n >> s; for (int i = 0; i < n; i++) { int x, x1; cin >> x >> x1; T.push_back(make_pair(x, x1)); } if ((T[0].first * 60 + T[0].second...
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect. The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the ...
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using vvi = vector<vi>; using pii = pair<int, int>; constexpr auto MOD = 1000000007LL; constexpr auto LINF = (1LL << 60); constexpr auto INF = 2147483647LL; constexpr auto PI = 3.1415926535897932384626433; constexpr auto EPS = 1...
Pulkit is really good at maths. Recently, he came to know about a problem on matrices. Amazed by the problem he got, he asked Ashish the same problem. Ashish also being good at maths solved the problem within 5 minutes. Now, its your time to solve the problem. You will be given n*m binary matrix. You need to tell if i...
for i in range(input()): l=[int(x) for x in raw_input().split()] l1=[] l2=[] for j in range(l[0]): a=input() l1.append(a) for k in range(0,len(l1)): if(l1[k] not in l2): l2.append(l1[k]) if(len(l1)==len(l2)): print('Yes') else: print('No')
Chester has been bullied enough all his life and now he seeks revenge. His first victim being Mike, obviously! He found this very interesting question from somewhere but he doesn't have the answers to it. Now without the answers he cannot know if what Mike answered is right or wrong. The question consists of two number...
for i in range(input()): a = raw_input().split() a1 = int(a[0]) a2 = int(a[1]) numb = str(a1**a2) count = 0 for i in numb: count+=int(i) print count
a number can be said dual prime. if the number is prime and the sum of digits of the number is also a prime number. If a number is dual prime then print YES else print NO SAMPLE INPUT 2 13 11 SAMPLE OUTPUT NO YES
def prime(x): i=2 while i*i<=x: if x%i==0: return False i+=1 return True for _ in range(input()): n=input() if prime(n)==False: print 'NO' continue else: rev=0 while n: x=n%10 rev=rev+x n=n/10 # print rev if prime(rev)==True: print 'YES' else:print 'NO'
Moving ahead, Gudi now enters a room where the floor is divided into N x M square tiles, forming a grid with N rows and M columns. Each square in the grid contains a number of Magical Orbs that Gudi has to absorb if she steps on it. Each Orb increases her Kii power, which is needed to fight the demons. Gudi enters the...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' T = int(raw_input()) for t in xrange(0, T): N, M, K = [int(x) for x in raw_input().split()] a = [] for i in xrange(0, N): a.append([int(x) for x in raw_input().split...
Little Shino loves to play with coins. In the city she lives, there are 26 different types of coins. Each coin is represented with a lowercase letter a, b, c, ... , y, z. Shino has some number of coins and she placed them in some random sequence, S, on the table. She is wondering how many pairs (i, j) are there, where...
k = int(raw_input()) line = raw_input() n = len(line) sets = 0 for l in range(n): count = 0 chars = "" for i, x in enumerate(line[l:]): if x not in chars: count += 1 chars += x if count < k: continue elif count > k: break sets += 1 # print line[l : l + i + 1] print sets
Problem Statement : Solve the Mystery. :) Input First line of input contains T – No of test cases.(1 ≤ T ≤ 21) Next T lines of input contains three integers a,b,c separated by spaces. (1 ≤ a,b ≤ 20) (1 ≤ c ≤ 100) Output T lines should contain a single integer. SAMPLE INPUT 3 2 3 2 13 14 1 14 5 9 SAMPLE OUTPUT 5 ...
T = input() for t in xrange(T): a,b,c = map(int, raw_input().split()) fibo = [a,b] if c == 0: print a elif c == 1: print b else: for i in range(2,c+1): fib = fibo[1] + fibo[0] fibo[0] = fibo[1] fibo[1] = fib print fibo[1]
Problem Statement Given an integer N, find the sum of all primes < N. Input Format The only line of the input file contains a positive integer N. Output Format Output the sum of all primes < N. Constraints 1 ≤ N ≤ 4000000 You are guaranteed that the answer will fit in a 64-bit integer. SAMPLE INPUT 1000 SAMPLE OUTP...
from math import sqrt def checkPrime(num): limit = int(sqrt(num)) for i in range(2,limit+1): if num%i == 0: return False return True def primeUsingSieve(N): arr = [] i = 2 while(i<=N): arr.append(i) i += 1 limit = int(sqrt(N)) for i in range(2,limit+...
As you all know, Sansa is trying to escape from the Boltons' specially from Ramsey! Winterfell is divided in an straight line of ice. In the line, each block has some thickness value. Ramsey would catch Sansa and Theon in an interval of ice if the XOR of all thickness of ice in that interval is greater than some valu...
n=int(raw_input()) a=list(map(int,raw_input().split())) xor=[0]*n xor[0]=a[0] for i in range(1,n): xor[i]=a[i]^xor[i-1] #print(xor) for i in range(int(raw_input())): x,y=map(int,raw_input().split()) print( xor[x-1]^xor[y] if (x!=0) else xor[y])
Suresh is a strange boy. He neither likes an array in ascending order nor in descending order. Then what does he like? He likes an array if and only if it is mixed i.e, both ascending and descending. He has got lots of arrays from his friends. But he doesn't like any of them. Now he plans to re-construct those arrays :...
for _ in range(int(raw_input())): n=int(raw_input()) arr=map(int,raw_input().split()) arr=sorted(arr) arr1=[] k=0 j=0 for i in range(len(arr)): if i%2==0: arr1.append(arr[k]) k+=1 else: arr1.append(arr[n-1-j]) j+=1 #k+=1 for i in range(len(arr1)): print arr1[i], print
In the world of Latin Alphabets, there seemed to be a catastrophe! All the vowels went missing. The other alphabets got disturbed and began the search operation. While searching they stumbled upon a garbage of letters. Can you help them find if the this garbage contains ALL the vowels ? Input: FIrst line contains N ...
n=int(raw_input()) s=raw_input() vowels=[] check=[1,1,1,1,1] for i in range(n): ch=s[i] if ch=='a' and check[0]==1: vowels.append(ch) check[0]=0 elif ch=='e' and check[1]==1: vowels.append(ch) check[1]=0 elif ch=='i' and check[2]==1: vowels.append(ch) check[2]=0 elif ch=='o' and check[3]==1: v...
An uppercase or lowercase English letter \alpha will be given as input. If \alpha is uppercase, print `A`; if it is lowercase, print `a`. Constraints * \alpha is an uppercase (`A` - `Z`) or lowercase (`a` - `z`) English letter. Input Input is given from Standard Input in the following format: α Output If \alph...
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String alpha = sc.next(); String regex = "[A-Z]"; if(alpha.matches(regex)){ System.out.println("A"); }else { System.out.println("a"); } } }
There are N robots numbered 1 to N placed on a number line. Robot i is placed at coordinate X_i. When activated, it will travel the distance of D_i in the positive direction, and then it will be removed from the number line. All the robots move at the same speed, and their sizes are ignorable. Takahashi, who is a misc...
#include<bits/stdc++.h> #define STDIO using namespace std; stack<pair<int,int> > stk; int MOD=998244353; int n; pair<int,int> robo[200100]; int dp[200100]; int main(){ #ifndef STDIO freopen("input.in","r",stdin); freopen("output.out","w",stdout); #endif ios::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); ...
Given are integers N and X. For each integer k between 0 and X (inclusive), find the answer to the following question, then compute the sum of all those answers, modulo 998244353. * Let us repeat the following operation on the integer k. Operation: if the integer is currently odd, subtract 1 from it and divide it by 2...
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N = 5e5+5; const int mod = 998244353; inline int add(int a,int b){a+=b;return a>=mod?a-mod:a;} inline int sub(int a,int b){a-=b;return a<0?a+mod:a;} inline int mul(int a,int b){return 1ll*a*b%mod;} int n; char s[N],tt[N]; int ret; int ans[N]; ...
We will host a rock-paper-scissors tournament with N people. The participants are called Person 1, Person 2, \ldots, Person N. For any two participants, the result of the match between them is determined in advance. This information is represented by positive integers A_{i,j} ( 1 \leq j < i \leq N ) as follows: * If A...
#include <bits/stdc++.h> using namespace std; using lint = long long int; using pint = pair<int, int>; using plint = pair<lint, lint>; struct fast_ios { fast_ios(){ cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_; #define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i...
There are N dishes, numbered 1, 2, \ldots, N. Initially, for each i (1 \leq i \leq N), Dish i has a_i (1 \leq a_i \leq 3) pieces of sushi on it. Taro will perform the following operation repeatedly until all the pieces of sushi are eaten: * Roll a die that shows the numbers 1, 2, \ldots, N with equal probabilities, a...
#include<bits/stdc++.h> #define ld long double using namespace std; long double t[302][302][302]; bool w[302][302][302]; int n,a; ld n2; int tab[4]; long double dp(int a, int b, int c){ if(a<0 || b<0 || c<0) return 0; if(w[a][b][c]) return t[a][b][c]; w[a][b][c]=true; t[a][b][c]=(( n2+(ld)a*dp(a-1,b...
You are given integers N, K, and an integer sequence A of length M. An integer sequence where each element is between 1 and K (inclusive) is said to be colorful when there exists a contiguous subsequence of length K of the sequence that contains one occurrence of each integer between 1 and K (inclusive). For every co...
//khodaya khodet komak kon #include <bits/stdc++.h> #define F first #define S second #define pb push_back #define all(x) x.begin(), x.end() #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math") using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; const in...
The commonly used bills in Japan are 10000-yen, 5000-yen and 1000-yen bills. Below, the word "bill" refers to only these. According to Aohashi, he received an otoshidama (New Year money gift) envelope from his grandfather that contained N bills for a total of Y yen, but he may be lying. Determine whether such a situat...
#include<iostream> using namespace std; #define ll long long int main() { ll n,y; cin>>n>>y; ll i,j,k; y/=1000; for(i=0;i<=n;i++) { for(j=0;j<=n-i;j++) { k=n-i-j; if(i*10+j*5+k==y) { cout<<i<<" "<<j<<" "<<k<<endl; return 0; } } } cout<<-1<<" "<<-1<<" "<<-1<<endl; return 0; }
We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly T_i seconds. Initially, the hand of every clock stands still, pointing directly upward. Now, Dolphin starts all the clocks simultaneously. In how many seconds will the hand of every clock point directly upward again? Constraints * 1≤...
import java.util.*; public class Main { static final int MOD = 1000000007; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long t[]= new long[n]; for(int i=0;i<n;i++)t[i]=sc.nextLong(); for(int i=1;i<n;i++){ ...
You are developing frog-shaped robots, and decided to race them against each other. First, you placed N robots onto a number line. These robots are numbered 1 through N. The current coordinate of robot i is x_i. Here, all x_i are integers, and 0 < x_1 < x_2 < ... < x_N. You will repeatedly perform the following opera...
#include <cstdio> const int mod = 1000000007; int n, a[100009]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); int ret = 1, ptr = 0; for (int i = 0; i < n; i++) { while (ptr < n && a[ptr] > (ptr - i) * 2) ptr++; if (ptr < n && a[ptr] == (ptr - i) * 2) ptr++; ret = 1LL * ret * (p...
Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range. The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N. Mr. Takahashi traversed the range from the west and Mr. Aoki from the east. The height of Mt. i is h_i...
import java.util.*; import java .io.*; public class Main { static int size; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; st = new StringTokenizer(br.readLine()); int n = Int...
When you enter 8 numbers from 0 to 9, write a program that outputs the difference between the largest integer and the smallest integer that can sort the 8 numbers. The number that can be sorted may start from 0, such as 00135569. Input Given multiple datasets. The number of datasets n (n ≤ 50) is given on the first...
#include<iostream> #include<string> #include<math.h> using namespace std; int main(){ char a[8]; long long h,l,n; cin>>n; for(int k=0;k<n;k++){ for(int j=0;j<8;j++) cin>>a[j]; for(int i=0;i<7;i++){ for(int j=7;j>i;j--){ if(a[j]<a[j-1]){ int tmp=a[j]; a[j]...
Taro is addicted to a novel. The novel has n volumes in total, and each volume has a different thickness. Taro likes this novel so much that he wants to buy a bookshelf dedicated to it. However, if you put a large bookshelf in the room, it will be quite small, so you have to devise to make the width of the bookshelf as...
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Scanner; public class Main { static PrintWriter out = new PrintWriter(System.out); static Scanner stdIn = new Scanner(...
Villages were scattered in the Wakamatsu Plain of Aizu. Several settlements are connected by straight roads that allow them to travel to and from each other, and any settlement in the plain can be traced back and forth. Each road has a lengthy maintenance fee, but all the settlements funded the road to maintain it. At...
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 100000...
Modern Mansion You got lost in a big mansion. This mansion has a structure in which square rooms are arranged in a grid pattern from north, south, east, and west, with M columns in the east-west direction and N rows in the north-south direction, for a total of M x N. The room in the xth column (1 ≤ x ≤ M) from the wes...
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 100000...
Karnaugh is a poor farmer who has a very small field. He wants to reclaim wasteland in the kingdom to get a new field. But the king who loves regular shape made a rule that a settler can only get a rectangular land as his field. Thus, Karnaugh should get the largest rectangular land suitable for reclamation. The map o...
#include<iostream> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) using namespace std; int main(){ int M,ans; bool bmap[6][6]; cin >> M; while(M-- > 0){ rep(i,5){ rep(j,5)cin >> bmap[i][j]; } ans = 0; rep(i,5){// sp x rep(j,5){// sp y REP(k,i,5){// gp x REP(...
Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2 + 3 + 5 + 7 + 11 + 13, 11 + 13 + 17, ...
#include<cstdio> int main(){ int i,j,n,pn=0,p[10000],sum[10000],ans[10001]; for(i=2;i<=10000;i++){ for(j=2;j*j<=i;j++){ if(!(i%j))break; } if(i<j*j)p[pn++] = i; } sum[0] = 0; for(i=0;i<pn;i++)sum[i+1] = sum[i] + p[i]; for(i=0;i<=10000;i++)ans[i] = 0; for(i=0;i<=pn;i++) f...
Digits Are Not Just Characters Mr. Manuel Majorana Minore made a number of files with numbers in their names. He wants to have a list of the files, but the file listing command commonly used lists them in an order different from what he prefers, interpreting digit sequences in them as ASCII code sequences, not as numb...
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> void chmin(T1 &a,T2 b){if(a>b) a=b;}; template<typename T1,typename T2> void chmax(T1 &a,T2 b){if(a<b) a=b;}; signed main(){ cin.tie(0); ios::sync_with_stdio(false); Int n; cin>>n; vector<string> vs(n+1);...
Gift Exchange Party A gift exchange party will be held at a school in TKB City. For every pair of students who are close friends, one gift must be given from one to the other at this party, but not the other way around. It is decided in advance the gift directions, that is, which student of each pair receives a gift....
#include <bits/stdc++.h> #define REP(i,s,e) for(int i=(s); i<(e);i++) #define rep(i,n) REP(i,0,n) #define rep1(i,n) REP(i,1,n) #define repe(i,n) for(auto &&i:n) #define all(v) (v).begin(),(v).end() #define decimal fixed<<setprecision(20) #define fastcin() cin.tie(0);ios::sync_with_stdio(false) using namespace std; usin...
You are working at a production plant of biological weapons. You are a maintainer of a terrible virus weapon with very high reproductive power. The virus has a tendency to build up regular hexagonal colonies. So as a whole, the virus weapon forms a hexagonal grid, each hexagon being a colony of the virus. The grid itse...
#include <bits/stdc++.h> //#include <unordered_map> #define N 111 #define ID(x, y) (pre[(x)-1]+(y-1)) #define CHECK(x, y) ((x)>0 && (x)<= 2 * n - 1 && (y)>0 && (y)<=(linelimit)) using namespace std; typedef long long LL; LL n, mod, m, l; LL a[N][N], b[N][N], c[N][N], mat[N][N], pre[N]; void mul(LL A[N][N],LL B[N][N],LL...
Problem B: B problem 2D enthusiasts (2D Respecters) from R University will participate in a programming training camp held at Atsu University. In this training camp, participants bring their own programming problems and use them for practice. 2DRespecters also ended up creating some issues. However, even three days b...
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second typedef pair<int,int> pi; ...
YAML (YAML Ain't Markup Language) is one of the formats for expressing an object as a character string. You will be given an object represented by a subset of YAML and a query that specifies the property, so please answer the value of the specified property. Subset of YAML A subset of YAML follows the syntax rules e...
#include<bits/stdc++.h> using namespace std; typedef pair<int,int> P; #define MAX 50000 string s; int size=0; map<string,int> mp[MAX]; string name[MAX]; int cnt[MAX]; int main(){ string str; getline(cin,str); stack<P> st; st.push(P(-1,0)); while(getline(cin,s)){ size++; string a="",b=""; int ...
Problem Statement One day, you found an old scroll with strange texts on it. You revealed that the text was actually an expression denoting the position of treasure. The expression consists of following three operations: * From two points, yield a line on which the points lie. * From a point and a line, yield a poin...
#include<iostream> #include<vector> #include<cstdlib> #include<complex> using namespace std; typedef complex<double> P; vector<P> pl(); char *p; double cross(P a,P b){ return a.real()*b.imag()-a.imag()*b.real(); } vector<P> plf(){ p++; if(*p=='('){ auto l=pl(); p++; return l; }else{ int x=...
Problem statement N first-year students of the Faculty of Information Science and Technology of R University take the final exam of the lecture called Programming Exercise 1. The test is a perfect score of m. In other words, the score that one student can get is an integer between 0 and m. Since the teacher in charge...
#include<iostream> #include<iomanip> #include<string> #include<cstdlib> #include<cmath> #include<algorithm> using namespace std; int main() { int n,m; cin >> n >> m; int cnt; if(n==1) { cout << m/2 << endl; return 0; } for(int i=0; i<=n/2; i++) { cout << 0 << ' '; cnt++; } for(int i=cnt; i<n-1; i++) ...
NINJA GAME The new game "NINJA GAME" has finally been released. In this game, the player operates a ninja on a two-dimensional map to move. A two-dimensional map is represented by a non-self-intersecting polygon consisting of only sides parallel to either the x-axis or the y-axis. Now, we need to move from the start p...
#include <iostream> #include <iomanip> #include <complex> #include <vector> #include <algorithm> #include <cmath> #include <array> #include <map> #include <queue> using namespace std; const double EPS = 1e-6; const double INF = 1e12; #define EQ(n,m) (abs((n)-(m)) < EPS) #define X real() #define Y imag() typedef compl...
Problem The penguins Fluoro is in an infinitely wide ice cube ($ sx $, $ sy $). There is a hole in the trout ($ tx $, $ ty $) through which water can enter. There are $ n $ lumps of ice on the ice, each in the square ($ x_i $, $ y_i $). Fluoro can move up, down, left and right in four directions. It's slippery on th...
#ifndef VS #include<bits/stdc++.h> #endif using namespace std; typedef long long LL; #ifdef BTK #define DEBUG if(1) #else #define CIN_ONLY if(1) struct cww {cww() {CIN_ONLY{ios::sync_with_stdio(false); cin.tie(0);}} }star; #define DEBUG if(0) #endif #define ALL(v) (v).begin(),(v).end() #define REC(ret, ...) std::fun...
Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in ...
#include <iostream> using namespace std; int main(void) { ios_base::sync_with_stdio(false); int A[10001]={}; int n,num; cin >> n; for(int i=0;i<n;i++){ cin >> num; A[num]+=1; } for(int i=0;i<n;i++){ if(0<A[i]){ cout << i; A[i]-=1; break; } } for(int i=0;i<10001;i++){ if(0<A[i]){ cout << ...
Transformation Write a program which performs a sequence of commands to a given string $str$. The command is one of: * print a b: print from the a-th character to the b-th character of $str$ * reverse a b: reverse from the a-th character to the b-th character of $str$ * replace a b p: replace from the a-th charact...
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); int q = scanner.nextInt(); for(int i=0;i<q;i++){ String ope = scanner.next(); if(ope.equals("print")){ ...
Consider an infinite full binary tree (each node has two children except the leaf nodes) defined as follows. For a node labelled v its left child will be labelled 2*v and its right child will be labelled 2*v+1. The root is labelled as 1. You are given N queries of the form i j. For each query, you have to print the len...
count=0 t=int(raw_input()) while(t>0): a,b=[int(x) for x in raw_input().split()] while(a!=b): if(a>b): a=a/2 else: b=b/2 count=count+1 print count count=0 t=t-1
Problem description : The fight between Raghu and Rannvijay is becoming more intense.This time Rannvijay asked Raghu a question. He gives him a number N and asked him to find the number of all pairs (a, b) of positive integers such that 1 <= a < b <= N and the sum a + b divides the product a * b. Since you are in ...
test=int(input()) while test: test-=1 n=int(input()) count=0 for a in range (1,n): for b in range (a+1,n+1): if (a*b)%(a+b)==0: count+=1 print count
Today is Chef's birthday. His mom has surprised him with truly fruity gifts: 2 fruit baskets. The first basket contains N apples, and the second one contains M oranges. Chef likes apples and oranges very much but he likes them equally, and therefore, wants to have the minimum possible difference between the number of a...
#fruit salad < samosas ? <VigzMv/> t=int(raw_input()) for x in range(t): n,m,k=map(int, raw_input().split()) if abs(m-n)==0: print 0 else: if k<abs(m-n): print abs(m-n)-k else: print 0
Kostya likes the number 4 much. Of course! This number has such a lot of properties, like: Four is the smallest composite number; It is also the smallest Smith number; The smallest non-cyclic group has four elements; Four is the maximal degree of the equation that can be solved in radicals; There is four-color theorem...
def luckyFour(): tests = int(raw_input()) for t in xrange(tests): n = int(raw_input()) count = 0 while(n>0): if (n%10 == 4): count+=1 n = n/10 print count luckyFour()
Children are taught to add multi-digit numbers from right to left, one digit at a time. Many find the “carry” operation, where a 1 is carried from one digit position to the next, to be a significant challenge. Your job is to count the number of carry operations for each of a set of addition problems so that educators m...
while 1: N,M=map(int,raw_input().split()); if N==0 and M==0: break else: A,B=N,M; CR=0; ct=0; while A or B: q,r=A%10,B%10; if q+r+CR>9: ct+=1; CR=1; A/=10; B/=10; if ct==0: print "No carry operation." elif ct==1: print "1 carry operation." else: print "%d carry operations." %ct
You always wanted to be a soldier and play it out at the battleground live. When you came at Techfest 2013, you encountered Lazer Tag, a game that satiated your innate hunger for taking aim and shooting enemies. Lazer Tag consists of a group play, where you are assigned a fixed number of bullets (popularly known as La...
n = int(raw_input()) p = map(float, raw_input().split()) e = [p[0]] for i in range(1,n): ans = (e[i-1]+p[i-1]+1)*p[i] e.append(ans) for i in range(n-1): e[i+1]+=e[i] print e[n-1]
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...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
You are given n segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line. Count the number of distinct points with integer coordinates, which are covered by at least one segment. Input The first line contains a sing...
import sys from math import gcd class Segment: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def dx(self): return self.x2 - self.x1 def dy(self): return self.y2 - self.y1 def pt_cnt(self): ...
There is a forest that we model as a plane and live n rare animals. Animal number i has its lair in the point (x_{i}, y_{i}). In order to protect them, a decision to build a nature reserve has been made. The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the f...
import java.io.*; import java.util.*; public class A { static double EPS=1e-9; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(); Centre[]centres=new Centre[n]; boolean pos=false,neg=false; for(int i=0...
It is a very important day for Katya. She has a test in a programming class. As always, she was given an interesting problem that she solved very fast. Can you solve that problem? You are given n ordered segments sets. Each segment can be represented as a pair of two integers [l, r] where l≤ r. Each set can contain an...
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 5, Inf = 1e9 + 1312; int idx, cur, tree[25 * N], le_[25 * N], ri_[25 * N], node[N], n, m, k, i, q; set<int> S; map<int, int> ind; pair<pair<int, int>, int> p[N]; vector<pair<int, int> > st[N]; vector<int> x; void build(int u, int l, int r) { if (l == r...
Billy investigates the question of applying greedy algorithm to different spheres of life. At the moment he is studying the application of greedy algorithm to the problem about change. There is an amount of n coins of different face values, and the coins of each value are not limited in number. The task is to collect t...
import java.util.Scanner; public class GreedyChangeOptim { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] coins = new int[n]; for (int i = 0; i < n; i++) coins[i] = in.nextInt(); // It is based on the pa...
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers. The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the tow...
def main(): m, k, n, s = map(int, input().split()) a = list(map(int, input().split())) # prevbug: input in a line! b = list(map(int, input().split())) # prevbug: convert to list b_dict = {} for x in b: b_dict.setdefault(x, 0) b_dict[x] += 1 # prevbug: b or b_dict left = 0 ...
You are given n objects. Each object has two integer properties: val_i — its price — and mask_i. It is guaranteed that the sum of all prices is initially non-zero. You want to select a positive integer s. All objects will be modified after that. The i-th object will be modified using the following procedure: * Con...
#include <bits/stdc++.h> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") template <typename T> void MACRO_VAR_Scan(T& t) { std::cin >> t; } template <typename First, typename... Rest> void MACRO_VAR_Scan(First& fir...
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: * Employee A is the immediate manag...
/*package whatever //do not write package name here */ import java.util.*; public class GFG { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[2001]; int i,c=0,res=-1; for(i=0;i<n;i++) { int n1=sc.nextInt(); a[i+1]=n1; } for(...
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k. Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p. Input The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime. The se...
def check(num1, num2, p, k): v = num1 + num2 v *= num1 * num1 + num2 * num2 v %= p v += p v %= p return v == k % p if __name__ == '__main__': n, p, k = (int(x) for x in input().split()) idx___number = [int(x) for x in input().split()] idx___precount = [((pow(x, 4, p) - k * x) % p ...
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consist...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return (b ? gcd(b, a % b) : a); } bool isPrime(long long n) { if (n == 1) return false; if (n == 2) return true; for (long long i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } long long power(l...
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k. Input The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100). The second line contains n integers a_1, …, a_n (1 ≤ a_...
#include <bits/stdc++.h> using namespace std; const int N = 100010; int n, k, a[N], p[N], tot; long long ans; map<int, int> M, st[N]; map<int, int>::iterator it, itt; bool np[N]; void getp() { for (int i = 2; i <= 100000; i++) { if (!np[i]) p[tot++] = i; for (int j = 0; j < tot; j++) { if (i * p[j] > 10...
You are given a tree, which consists of n vertices. Recall that a tree is a connected undirected graph without cycles. <image> Example of a tree. Vertices are numbered from 1 to n. All vertices have weights, the weight of the vertex v is a_v. Recall that the distance between two vertices in the tree is the number o...
visited = [0]*205 dp = [[0]*205 for i in range(205)] def dfs(node,g): sons = [] for nb in g[node]: if not visited[nb]: visited[nb] = 1 dfs(nb,g) sons.append(nb) dp[node][0] = ws[node-1] for s in sons: dp[node][0] += dp[s][k] ls = len(sons) ...
You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. ...
#include <bits/stdc++.h> using namespace std; struct fenwick { int N; vector<int> bit; fenwick(int n = 1e5) { N = n + 5; bit.assign(N, 0); } void resize(int n) { N = n + 5; bit.assign(N, 0); } void update(int x, int val) { while (x < N) { bit[x] += val; x += x & -x; } ...
This is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee. This is an interactive problem. You're considering moving to another city, where one of your friends already lives. There are n cafés ...
#include <bits/stdc++.h> using namespace std; bool query(int cafe) { cout << "? " << cafe + 1 << endl; char result; cin >> result; return result == 'N'; } int main() { int N, K; cin >> N >> K; vector<bool> good(N, true); int block = max(K / 2, 1); int M = N / block; for (int jump = 1; jump < M; jump...
Let's define the function f of multiset a as the multiset of number of occurences of every number, that is present in a. E.g., f(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 1, 2, 2, 4\}. Let's define f^k(a), as applying f to array a k times: f^k(a) = f(f^{k-1}(a)), f^0(a) = a. E.g., f^2(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; vector<int> make_step(vector<int> f) { sort(f.begin(), f.end()); reverse(f.begin(), f.end()); vector<int> gg; for (int i = 0; i < f.size(); i++) { for (int j = 0; j < f[i]; j++) gg.push_back(i + 1); } return gg; } int n, k; const i...
Eugene likes working with arrays. And today he needs your help in solving one challenging task. An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Let's call a nonempty...
import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); long[] arr=new long[n+1]; arr[0]=0; for(int i=1;i<=n;i++) { arr[i]=s.nextInt(); } long[] pre=new long[n+1]; pre[0...