input
stringlengths
29
13k
output
stringlengths
9
73.4k
Devu and Churu love to play games a lot. Today, they have an array A consisting of N positive integers. First they listed all N Γ— (N+1) / 2 non-empty continuous subarrays of the array A on a piece of paper and then replaced all the subarrays on the paper with the maximum element present in the respective subarray. Devu...
import bisect import time import sys A = [] subarray = {} keys = [] subarray_low = {} subarray_high = {} subarray_length = 0 # (val,start,pos) stack # (start,end,pos) dict def preprocess(n): global keys global A global subarray global subarray_low global subarray_high global subarray_length for i in A: subar...
John Watson always knew that one of the favourite hobbies of Sherlock Holmes was to tinker with ciphers. Though Watson was not that good with ciphers, he learnt a few things being with him. Right now, Watson is in trouble! He has been locked in a room and the only way to get out of the room is through deciphering a kn...
test = int(raw_input()) i=0 while(test > 0): n=int(raw_input()) s=list(raw_input()) a=map(int,raw_input().split()) b='' for i in xrange(0,n): t=a[i]-1 tmp=s[i] s[i]=s[t] s[t]=tmp print "".join(s) test=test-1
In an attempt to reduce the growing population, Archer was asked to come up with a plan. Archer being as intelligent as he is, came up with the following plan: If N children, with names C1, C2, ..., CN, are born to parents with names A and B, and you consider C to be the concatenation of all the names of the children, ...
import sys from collections import Counter num = int(sys.stdin.readline().rstrip()) while num != 0: parents = sys.stdin.readline().rstrip().split() text = parents[0] + parents[1] p_count = Counter(text) num_child = int(sys.stdin.readline().rstrip()) children = '' while num_child != 0: children += sys.stdin.read...
Vadim and Roman like discussing challenging problems with each other. One day Vadim told his friend following problem: Given N points on a plane. Each point p is defined by it's two integer coordinates β€” px and py. The distance between points a and b is min(|ax - bx|, |ay - by|). You should choose a starting point and...
for t in range(int(raw_input())): n = int(raw_input()) for i in range(n): raw_input() result = 0 for i in range(1, n+1): result ^= i print result
For Turbo C++ Users : Read the following document before attempting the question : Problem description Logan is tired of not being able to clear security clearances while travelling (thanks to his Adamantium skeleton :\ ). He goes to Magneto for some help regarding this matter. Magneto decides to help him, but o...
#Enter your code here t=int(raw_input()) for i in xrange(t): n=int(raw_input()) if n==1: print 1 else: print 0
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon. Elections are coming. You know the number of voters and the number of parties β€” n and m respectively. For each vote...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * @author Don Li */ public class Elections { void solve() { int n = in.nextInt(), m = in.nextInt(); int[] p = new int[n], c = new int[n]; for (i...
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of n integers a_i. It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected eleme...
#include <bits/stdc++.h> using namespace std; const int INF = INT_MAX; const long long INFL = LLONG_MAX; const long double pi = acos(-1); const int MOD = 1e9 + 7; const int MAX = 300000; int N, d[MAX + 10], seen[MAX + 10], dp[MAX + 10]; class Choose { private: vector<int> fac, inv; int n, mod; void extgcd(int a,...
Maksim has n objects and m boxes, each box has size exactly k. Objects are numbered from 1 to n in order from left to right, the size of the i-th object is a_i. Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 1; int kq; int n, m, k; int a[N]; bool check(int f) { int tg = 0; int cl = m; for (int i = n - f + 1; i <= n; i++) { if (tg < a[i]) { tg = k; cl--; } tg -= a[i]; } return (cl >= 0); } void np() { int l = 0, r = n; wh...
Berland State University invites people from all over the world as guest students. You can come to the capital of Berland and study with the best teachers in the country. Berland State University works every day of the week, but classes for guest students are held on the following schedule. You know the sequence of se...
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int T = Integer.parseInt(br.readLine()); wh...
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list. For ex...
t=int(input()) lis=list(map(int,input().split())) maxnum=max(lis) lis.remove(maxnum) for x in range (1,maxnum//2+1): if maxnum%x==0: lis.remove(x) maxnum2=max(lis) print("{} {}".format(maxnum,maxnum2))
This is an interactive problem. Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake". Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is ...
#include <bits/stdc++.h> using namespace std; void setIO(string name = "") { ios_base::sync_with_stdio(0); cin.tie(0); if ((int)name.size()) { freopen((name + ".in").c_str(), "r", stdin); freopen((name + ".out").c_str(), "w", stdout); } } int main() { auto ask = [&](vector<int> v) { cout << "next ...
The whole delivery market of Berland is controlled by two rival companies: BerEx and BerPS. They both provide fast and reliable delivery services across all the cities of Berland. The map of Berland can be represented as an undirected graph. The cities are vertices and the roads are edges between them. Each pair of ci...
#include <bits/stdc++.h> using namespace std; const int Maxn = 14; int n, m, g[Maxn]; bool path[Maxn + 1][Maxn + 1][1 << Maxn | 1]; int pre[Maxn + 1][Maxn + 1][1 << Maxn | 1]; int dp[1 << Maxn | 1], last[1 << Maxn | 1][3]; int main(int argc, const char *argv[]) { ios_base ::sync_with_stdio(0); cin.tie(0); cout.ti...
Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor β€” a square tile that is diagonally split into white and black part as depicted in the figure below. <image> The dimension of this tile is perfect for this kitchen, as h...
#include <bits/stdc++.h> int main() { int h, w, n, i; scanf("%d %d", &h, &w); long long s1; s1 = 1; n = h + w; for (i = 1; i <= n; i++) s1 = (2 * s1) % 998244353; printf("%I64d\n", s1); }
n robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the locat...
#include <bits/stdc++.h> using namespace std; int main() { long long int q; cin >> q; for (int j = 0; j < q; j++) { int n; cin >> n; int x, y, f1, f2, f3, f4; int a = -100000; int b = 100000; int c = 100000; int d = -100000; for (int i = 0; i < n; i++) { cin >> x >> y >> f1 >...
The only difference between easy and hard versions is the number of elements in the array. You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)βŒ‹). You can perform such an operation any (possibl...
import java.util.*; import java.io.*; public class HelloWorld { public void run() throws Exception { Scanner file = new Scanner(System.in); int times = file.nextInt(); int k = file.nextInt(); ArrayList<Integer> w= new ArrayList(); int max = Integer.MIN_VALUE; for (int i = 0; i < times; i++) {...
Alice recently found some cactuses growing near her house! After several months, more and more cactuses appeared and soon they blocked the road. So Alice wants to clear them. [A cactus](https://en.wikipedia.org/wiki/Cactus_graph) is a connected undirected graph. No edge of this graph lies on more than one simple cycle...
#include <bits/stdc++.h> using namespace std; const int M = 1000000007; int n, m, i, head[500005], Next[1000005], adj[1000005], sta[500005], top, dfn[500005], s[500005], p, u[500005], v[500005], d[500005], num[500005], vis[500005], k, j; long long e, p2[500015], ans, sum; vector<int> ex[500005]; void Push(int u...
Hanh is a famous biologist. He loves growing trees and doing experiments on his own garden. One day, he got a tree consisting of n vertices. Vertices are numbered from 1 to n. A tree with n vertices is an undirected connected graph with n-1 edges. Initially, Hanh sets the value of every vertex to 0. Now, Hanh perform...
#include <bits/stdc++.h> using namespace std; const int N = 4e5 + 5; int n, m, mod = 998244353, r, szz; int tour[N], sz[N], w[N], p[N]; vector<int> heavy; vector<int> g[N], pos[N]; int f[N]; int add(int a, int b) { return (a + b) % mod; } int mul(int a, int b) { return (1LL * a * b) % mod; } void DFS(int i, int j) { ...
As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guara...
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization("unroll-loops") void tracer(istream_iterator<string> it) {} template <typename T, typename... Args> void tracer(istream_iterator<string> it, T a, Args... args) { cerr << *it << " = "...
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to r...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int arr[n]; vector<int> v[n + 1]; for (int i = 0; i < n; i++) for (int j = 0; j < 35; j++) v[i].push_back(0); for (int i = 0; i < n; i++) cin >> arr[i]; sort(arr, arr + n); for (int i = 0; i < n; i++) { int a = arr[i], j...
Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind. Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense...
#include <bits/stdc++.h> using namespace std; struct node { long long l, r; long long mx = -1e18; long long ch = 0; }; vector<node> tree; void push(long long v) { if (tree[v].l == tree[v].r) { tree[v].ch = 0; } else { tree[v * 2].ch += tree[v].ch; tree[v * 2 + 1].ch += tree[v].ch; tree[v * 2]....
Denis came to Nastya and discovered that she was not happy to see him... There is only one chance that she can become happy. Denis wants to buy all things that Nastya likes so she will certainly agree to talk to him. The map of the city where they live has a lot of squares, some of which are connected by roads. There...
#include <bits/stdc++.h> using namespace std; vector<vector<int> > mv; vector<pair<int, int> > res; bool vi(int ac, int fa, int ma, int ta) { int ne = mv[ac].size(); if (ac == 0) ne++; if (ne > ma || (ne == ma && ta)) return false; int ot = ta - 1; res.push_back(pair<int, int>(ac + 1, ta)); for (int i = 0; ...
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers ...
import java.util.*; import java.io.*; public class R647D2D { public static void main(String[] args) throws Exception{ int num = 998244353; // TODO Auto-generated method stub BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); Map<Integ...
In the game of Mastermind, there are two players β€” Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive. When Bob guesses a code, Alice tells him some information about ...
#include <bits/stdc++.h> using namespace std; int main(void) { ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n, x, y; cin >> n >> x >> y; y = y - x; vector<int> b(n); vector<bool> seen(n + 1, false); vector<vector<int>> colorIndices = vector<vector<int...
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it. There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_...
#include <bits/stdc++.h> using namespace std; long long de_sum[100005]; long long de_soure[100005]; long long A[100005], D[100005]; long long max(long long a, long long b) { if (a > b) { return a; } else { return b; } } long long min(long long a, long long b) { if (a > b) { return b; } else { ...
You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i. You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: ⌈ W/2βŒ‰ ≀ C ≀ W. Output the list...
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.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStrea...
Polycarp found under the Christmas tree an array a of n elements and instructions for playing with it: * At first, choose index i (1 ≀ i ≀ n) β€” starting position in the array. Put the chip at the index i (on the value a_i). * While i ≀ n, add a_i to your score and move the chip a_i positions to the right (i.e. r...
#include <bits/stdc++.h> using namespace std; #define TEST int tt; cin >> tt; while (tt--) #define all(v) (v).begin(), (v).end() #define pii pair<int, int> #define pll pair<ll, ll> #define xx first #define yy second #define ll long long #define ld long double int n; vector<ll> ipt; vector<ll> ans; ll func(ll x){ ...
You have a malfunctioning microwave in which you want to put some bananas. You have n time-steps before the microwave stops working completely. At each time-step, it displays a new operation. Let k be the number of bananas in the microwave currently. Initially, k = 0. In the i-th operation, you are given three paramet...
//Implemented By Aman Kotiyal Date:-30-Mar-2021 Time:-1:57:09 pm import java.io.*; import java.util.*; public class ques1 { public static void main(String[] args)throws Exception{ new ques1().run();} long mod=1000000000+7; long maxn=100000; void solve() throws Exception { int n=ni(); int m=ni(); long a[][...
We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1. We will consider cells of a square matrix n Γ— n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it. For a given number n, construct a squar...
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws java.io.IOException{ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while (t-->0) { int n=sc.nextInt(); if(n==2) { Sys...
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about ...
s=raw_input() C={} for x in [raw_input() for i in range(input())]: C[x[0]],C[x[1]]=x[1],x[0] ans=0 sl=len(s) i=0 while i<sl-1: if s[i] not in C: i+=1 continue a,b=0,0 j=i while j<sl: if s[j]==s[i]: a+=1 elif s[j]==C[s[i]]: b+=1 else: ...
Vasya plays the Power Defence. He must pass the last level of the game. In order to do this he must kill the Main Villain, who moves in a straight line at speed 1 meter per second from the point ( - ∞, 0) to the point ( + ∞, 0) of the game world. In the points (x, 1) and (x, - 1), where x is an integer number, Vasya ...
#include <bits/stdc++.h> using namespace std; const double kEps = 1E-9; const int kMaxN = 20; int nf, ne, ns, rf, re, rs, df, de; double ans, lenf, lene, lens; int cnt[13]; double dp[2][kMaxN + 1][kMaxN + 1]; double ff[13], ee[13]; pair<double, int> seq[kMaxN << 1 | 1]; int buf[(kMaxN << 1) + 2], *sum = buf + 1; void S...
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y...
#include <bits/stdc++.h> using namespace std; int main() { string k; cin >> k; int pos = -1; for (int a = 122; a >= 97; a--) { for (int b = pos + 1; b < k.length(); b++) { if (char(a) == k[b]) { cout << k[b]; pos = b; } } } cout << endl; }
Jabber ID on the national Berland service Β«BabberΒ» has a form <username>@<hostname>[/resource], where * <username> β€” is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters Β«_Β», the length of <username> is between 1 and 16, inclusive. * <hostname> β€” is a sequence of word separat...
#include <bits/stdc++.h> int main() { char str[150]; int word = 0, seq = 0; bool ok = true; scanf("%[^\n]", str); int leng = strlen(str); for (int i = 0; i < leng; i++) { if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= '0' && str[i] <= '9') || str[i] == '_'...
Old MacDonald has a farm and a large potato field, (1010 + 1) Γ— (1010 + 1) square meters in size. The field is divided into square garden beds, each bed takes up one square meter. Old McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the insects, Ol...
#include <bits/stdc++.h> using namespace std; const long long INF = 1e9 + 7; const int N = 5e3 + 10; vector<pair<int, int>> vp1, vp2; vector<int> vx, vy; int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; int pos[N]; char flag[N][N]; void dfs(int x, int y) { queue<pair<int, int>> q; q.push({x, y}); flag[x][y] = ...
Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes. From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k β‰₯ 0) units. A magical box v can be put inside a...
#include <bits/stdc++.h> using namespace std; long long k[100007], cnt[100007]; int n; int main() { long long res, cur, now; int i; scanf("%d", &n); res = 0; for (i = 0; i < n; ++i) { scanf("%I64d%I64d", &k[i], &cnt[i]); now = k[i]; cur = 1; while (cur < cnt[i]) { ++now; cur *= 4; ...
The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively. Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separat...
#include <bits/stdc++.h> using namespace std; struct ip { int x1, x2, x3, x4; ip(int X1 = 0, int X2 = 0, int X3 = 0, int X4 = 0) { x1 = X1; x2 = X2; x3 = X3; x4 = X4; } }; string its(int a) { string ans = ""; if (a == 0) return "00000000"; while (a) { ans = (char)('0' + (a % 2)) + ans; ...
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning....
#include <bits/stdc++.h> using namespace std; int n, cnt, x; long long f[1000010], ans = 1; signed main() { cin >> n; for (register int i = (1); i <= (n); ++i) scanf("%d", &x), cnt += (x == 1) ? 1 : 0; f[0] = f[1] = 1; for (register int i = (2); i <= (cnt); ++i) f[i] = (f[i - 2] * (i - 1) + f[i - 1]) % ...
In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing". ...
#include <bits/stdc++.h> using namespace std; int row, col; int total; int main() { scanf("%d", &col); scanf("%d", &row); scanf("%d", &total); vector<int> vt(row + 10, -1); for (int i = 0; i < col; ++i) { int x, y; scanf("%d", &x); scanf("%d", &y); vt[x] = (vt[x] == -1 ? y : min(vt[x], y)); ...
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decre...
#include <bits/stdc++.h> using namespace std; int v[5010]; int n; int cont[5010][5010]; int solve(int x, int y) { int sum = 0; sum += cont[v[x]][n - 1] - cont[v[x]][y]; sum += cont[v[y]][n - 1] - cont[v[y]][x]; int interval = y - x - 1; int menores = cont[v[y]][y - 1] - cont[v[y]][x]; sum -= interval - meno...
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auct...
import java.util.Scanner; import java.util.Arrays; import java.util.*; import java.lang.*; public class Code { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int numBidders = cin.nextInt(); int max = -9999999; int index = 0; int temp =0; int[] arr = new int[numBidders]; ...
Little Chris is having a nightmare. Even in dreams all he thinks about is math. Chris dreams about m binary strings of length n, indexed with numbers from 1 to m. The most horrifying part is that the bits of each string are ordered in either ascending or descending order. For example, Chris could be dreaming about the...
#include <bits/stdc++.h> using namespace std; int n, m; long long num[2]; map<int, int> cnt[2]; int best_dist = -1; long long best_total = 0; void check_val(int dist, long long total) { if (total == 0) return; if (dist > best_dist) best_dist = dist, best_total = total; else if (dist == best_dist) best_tot...
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also bo...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; long long c = 0, x = 0, y = 0, yd = 0, xd = 0, ans = 0; map<int, vector<int> > oc; vector<int> a; scanf("%d %d", &n, &m); scanf("%d", &x); a.push_back(x); for (int i = 1; i < m; ++i) { scanf("%d", &x); a.push_back(x); c += ...
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and...
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Boredom implements Closeable { private InputReader in = new InputReader(System.in); pri...
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
import fileinput def str_to_int(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args): (a, b, c) = [ int(x) for x in args ] return(a, b, c) def parse(a, b, c, mask): mult_first = mask & 1 parn_first = (mask & 2) >> 1 if mult_first: if parn_first: return (a * b...
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes...
a, b, c, d = [int(x) for x in raw_input().split()] x = max((3*a)/10, a - ((a / 250 ) * c)) y = max((3*b)/10, b - ((b / 250 ) * d)) if x > y: print "Misha" elif x < y: print "Vasya" else: print "Tie"
In this problem you will meet the simplified model of game Pudding Monsters. An important process in developing any game is creating levels. A game field in Pudding Monsters is an n Γ— n rectangular grid, n of its cells contain monsters and some other cells contain game objects. The gameplay is about moving the monster...
#include <bits/stdc++.h> const int N = 300005; using namespace std; int n, x, y, a[N], i, cnt; long long ans; struct T { int l, r, ad, mn, ti; T *ls, *rs; void build(int, int); inline void pls(int v) { ad += v, mn += v; } void deb() { cerr << '[' << l << ',' << r << ']' << mn << '/' << ti << '(' << ad << ...
Vanya got an important task β€” he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers. Vanya wants to know how many digits he will have to write down as he labels the bo...
#include <bits/stdc++.h> using namespace std; pair<int, int> ii; long long a[11]; void init() { long long n = 9, ten = 10, nine = 8; for (int i = 1; i < 10; ++i) { a[i] = n; n = n * 10 + 9; } } int numdigit(long long n) { int res = 0; while (n) { ++res; n /= 10; } return res; } long long a...
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct. Every contestant hopes that he can find a...
#include <bits/stdc++.h> using namespace std; struct mindol { int str, a, b; bool operator<(const mindol &a) const { return str > a.str; } }; mindol s[623456]; int chk[804], cnt; int main() { int n, a, b, str; scanf("%d", &n); n *= 2; for (int i = 1; i <= n; i++) { for (int j = 1; j < i; j++) { sc...
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'. You ...
ds, ss = [], [] for s in raw_input().replace(';', ',').split(','): if s.isdigit() and (len(s) == 1 or s[0] != '0'): ds.append(s) else: ss.append(s) print '-' if len(ds) == 0 else '"%s"' % ','.join(ds) print '-' if len(ss) == 0 else '"%s"' % ','.join(ss)
You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a. Let number i be in positions xi, yi (xi < yi) in the permuted array a. Let's define the value di = yi - xi β€” the distance between the positions of the number i. Permute the numbers in array a to minimize the valu...
import java.io.*; import java.util.*; public class optimal_permutation { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [] a = new int [2*n]; int k = 0; int j = n; for (int i = 1; i < n; i++) { if (i % 2 != 0) { ...
One social network developer recently suggested a new algorithm of choosing ads for users. There are n slots which advertisers can buy. It is possible to buy a segment of consecutive slots at once. The more slots you own, the bigger are the chances your ad will be shown to users. Every time it is needed to choose ads...
#include <bits/stdc++.h> #pragma GCC optimize(2) #pragma GCC optimize(3) using namespace std; template <class T> bool umin(T &x, T y) { return y < x ? x = y, 1 : 0; } template <class T> bool umax(T &x, T y) { return y > x ? x = y, 1 : 0; } template <typename T> ostream &operator<<(ostream &out, vector<T> a) { for...
Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer k β€” the number of digits in n. Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substr...
#include <bits/stdc++.h> using namespace std; int na, nb, k, c[99]; string a, b, s, mn = "a"; vector<string> v; int f(int p) { int i; for (i = 0; p > 0; i++) { p /= 10; } return i; } void g(int p) { int i; string t1, t2; t1 = t2 = s; for (i = p; i < na && s[i] < b[0]; i++) ; t1.insert(i, b); ...
As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the midd...
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx") using namespace std; using ll = int64_t; struct Matrix { ll v[2][2]; Matrix() { memset(v, 0, sizeof(v)); } }; ll gcd(ll a, ll b) { return (b == 0 ? a : gcd(b, a % b)); } pair<ll, ll> solve_dumb(ll moves...
Dexterina and Womandark have been arch-rivals since they’ve known each other. Since both are super-intelligent teenage girls, they’ve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges they’ve given to one another, their score is equal and they’re ...
#include <bits/stdc++.h> using namespace std; struct matrix { long double arr[128][128]; long long int n; }; long double p[128]; matrix matrix_multiplication(matrix x, matrix y) { matrix temp; temp.n = x.n; for (long long int i = 0; i < 128; ++i) { for (long long int j = 0; j < 128; ++j) { temp.arr[...
After one of celebrations there is a stack of dirty plates in Nikita's kitchen. Nikita has to wash them and put into a dryer. In dryer, the plates should be also placed in a stack also, and the plates sizes should increase down up. The sizes of all plates are distinct. Nikita has no so much free space, specifically, h...
#include <bits/stdc++.h> using namespace std; using ll = long long; constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n - 1); } int n, up; int B[2]; deque<int> v[3]; using P = pair<int, int>; vector<P> que; void move(int id, int c) { if (c > B[id] || int(v[id].size()) < c) { throw 1; } que.push_back(P(...
Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity β€” origami, but remembered the puzzle that she could not solve. <image> The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices. The puzz...
#include <bits/stdc++.h> using namespace std; const int MX = 200005; long long N, M; vector<vector<int> > G(MX); bool exist = true; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, -1, 0, 1}; vector<pair<long long, long long> > ans(40); int fix(int d) { if (d == 0) return 2; if (d == 1) return 3; if (d == 2) return 0; ...
In this problem you will write a simple generator of Brainfuck (<https://en.wikipedia.org/wiki/Brainfuck>) calculators. You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of eval...
#include <bits/stdc++.h> using namespace std; bool isone(char c) { return (c == '+' || c == '-'); } bool istwo(char c) { return (c == '*' || c == '/'); } string shorten(string m) { stack<char> s; string sur; int i; char w; sur; for (i = 0; i < m.size(); i++) { if (isdigit(m[i]) || m[i] == '.') { w...
Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem. We have a forest (acyclic undirected graph) with n vertices and m edges. There are q queries we should answer. In each query two vertices v and u are given. Let V be the ...
#include <bits/stdc++.h> using namespace std; int fa[100005], judge[100005]; int mx[100005], dis[100005]; int num[100005]; bool vis[100005]; vector<int> tot[100005]; vector<int> edge[100005]; vector<long long> pre[100005]; long long maxdis; int maxpos; queue<int> q; map<long, double> mp; void BFS(int x) { while (!q.e...
Array of integers is unimodal, if: * it is strictly increasing in the beginning; * after that it is constant; * after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following th...
n=int(input()) arr=list(map(int,input().split())) s,t,p=0,0,0 for i in range(1,n) : if arr[i] < arr[i - 1]: s = 1 elif arr[i]==arr[i-1] and s: t=1 elif arr[i]==arr[i-1] and not s: p=1 if arr[i]>arr[i-1] and (s or p):t=1 if t: print("NO") else : print("YES")
Due to the recent popularity of the Deep learning new countries are starting to look like Neural Networks. That is, the countries are being built deep with many layers, each layer possibly having many cities. They also have one entry, and one exit point. There are exactly L layers, each having N cities. Let us look at...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; template <class T, class U> inline void Max(T &a, U b) { if (a < b) a = b; } template <class T, class U> inline void Min(T &a, U b) { if (a > b) a = b; } inline void add(int &a, int b) { a += b; while (a >= 10000...
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi...
import java.util.*; import java.io.*; public class Classroom_Watch{ public static void main(String[] args) throws IOException{ FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] k = new int[100]; int a = 0;...
Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess β€” all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl canno...
import java.util.*; import java.lang.Math.*; public class Main { static Scanner in = new Scanner(System.in); static Coor[] p; static Coor ori; static int n; static int dp[]; static Coor pre[]; public static void main(String[] args) { ori = new Coor(in.nextInt(),in.nextInt()); n = in.nextInt(); p = new Co...
Imp is in a magic forest, where xorangles grow (wut?) <image> A xorangle of order n is such a non-degenerate triangle, that lengths of its sides are integers not exceeding n, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order n to get out of the forest. Forma...
import math n = int(input()) ans = 0 for a in range(1, n+1): for b in range(a, n+1): c= a^b if c < b or c > n: continue if a+b > c: ans += 1 print(ans)
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in ...
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int ra = (a-1)/m; int rb = (b-1)/m; int p...
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≀ n ≀ ...
n = int(input()) A = list(map(int, input().split())) from collections import Counter C = Counter(A) res = [] for a in A: C[a] -= 1 if C[a] == 0: res.append(a) print(len(res)) print(*res)
A permutation p of length n is a sequence p_1, p_2, …, p_n consisting of n distinct integers, each of which from 1 to n (1 ≀ p_i ≀ n) . Let's call the subsegment [l,r] of the permutation good if all numbers from the minimum on it to the maximum on this subsegment occur among the numbers p_l, p_{l+1}, ..., p_r. For ex...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.util.Arrays; import java.util.Deque; import java.util.function.Supplier; import java.util.ArrayList; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.util.Collec...
View Russian Translation Limak is a little polar bear. Today he found something delicious in the snow. It's a square bar of chocolate with N x N pieces. Some pieces are special because there are cherries on them. You might be surprised by cherries on a chocolate but you've never been on the Arctic Circle, have you? L...
for _ in xrange(input()): size = input() hor, vert =[0]*size, [0]*size choco = 0 for j in xrange(size): val = raw_input() for chk in xrange(len(val)): if val[chk] == '#': hor[chk] +=1 vert[j] += 1 choco += 1 flag = False present_sum = 0 for a in xrange(size): present_sum += hor[a] if pr...
Little Pandey and GJ are coding buddies - since they are the part of ACM ICPC team together. But, GJ is fed up of Pandey's weird coding habits - like using editors which are slow, and irritating. Importantly, GJ believes that Pandey over-complicates a task while solving it. So, to prove his point he gives Pandey a tr...
t=input() for i in range(t): n=input() time=0 arr=map(int,raw_input().split()) arr.sort() while(len(arr)!=1): a1=arr.pop() a2=arr.pop() sumn=a1+a2 time+=sumn arr.append(sumn) print time
You need to handle two extraordinarily large integers. The good news is that you don't need to perform any arithmetic operation on them. You just need to compare them and see whether they are equal or one is greater than the other. Given two strings x and y, print either "x< y"(ignore space, editor issues), "x>y" or "...
import math,string,re class ExtraordinarilyLarge: def compare(self, x, y): if x.startswith("0!"): x = "1" + x[2:] if y.startswith("0!"): y = "1" + y[2:] nx = re.findall(r"\d+", x)[0] ny = re.findall(r"\d+", y)[0] xf = len(x) - len(nx) yf = len(y) - len(ny) nx = int(nx) ny = int(ny) while xf > y...
The Enigma crew came to know some of the location where the bombs are planted. So they started to find the code through which they can diffuse the bombs .Each bomb has different code for diffusion. The crew found the solution the diffusion code is between the ranges 1 to N-1 where N is the integer value. The summation ...
def ap(n): return (n*(n+1)/2) x=int(raw_input()) print(ap((x-1)/3)*3+ap((x-1)/5)*5-ap((x-1)/15)*15)
Programmer Deepak has created a program which calculates magical number as 2^n * 3^n * 5^n where "n" is an integer. Now he wants to find the magical number which is just greater than the input. Help him in finding it. NOTE : a^b denotes a raised to power b. Input : 456 NOTE : You do not need to create a program f...
print 900
Nikhil has written N binary integers (i.e. eithim zero or one) on a copy. He recently learned about XOR operation. Now He wants to erase exactly one integer in the array so that the XOR of the remaining N - 1 numbers is zero. Please help him to calculate the number of ways of doing so. Input The first line of the inp...
for _ in xrange(input()): n=input() m=map(int,raw_input().split()) a=m.count(1) b=n-a print a if a%2==1 else b
Reverse_flash lost his power while moving through a number of timezones and landed in the timezone of Flash. Now we know that Flash would kill him as soon as he finds him. Your job is to protect the bad. The timezone of Flash is (1,1). There is a safe timezone (n,n), the last one ,where Flash couldn't enter. Timezone ...
import sys sys.setrecursionlimit(10000) def s(r, c): global ans, g, vis, l, steps if r == l-1 and c == l - 1: ans += 1 return vis[r][c] = True for i in range(4): nr = r + steps[i][0] nc = c + steps[i][1] if nr < 0 or nc < 0 or nr >= l or nc >= l: continue ...
Mathematician Shikhar has invented a new type of fibonacci series in which fib(1)=a fib(2)=b fib(n)=(fib(n-1)+fib(n-2))%1000000007 for all n>2 and now help him find the nth term of this series. Input contains 3 space separated integers a,b and n. Input 2 4 35 NOTE You do not need to create a program for this ...
print 29860704
The very famous football club Manchester United decided to popularize football in India by organizing a football fest. The fest had many events for different sections of people. For the awesome coders of Hacker Earth, there was an event called PASS and BACK. In this event, the coders were given N passes and players hav...
t = int(raw_input()) for i in range(t): n , p1 = map(int , raw_input().split()) p = [] p.append(p1) for i in range(n): s = raw_input().split() if s[0] == 'P': p.append(int(s[1])) else: k = p[-1] p.pop() l = p[-1] p.append(k) p.append(l) print "Player" , p[-1]
Xsquare get bored playing with the arrays all the time. So,he decided to buy a new character set to play with. Xsquare's character set contains only lower case alphabets more specifically characters from 'a' to 'z' (both inclusive). Xsquare was playing with this new character set and formed some interesting continuous ...
t=input() for i in range(t): n=input() if n%2==0:n=n/2 else: n=n/2+1 prac=1 while n>0: i=2 prod=26 while i<n: prod=(prod*prod)%1000000009 i=i*2 prac=(prod*prac)%1000000009 i=i/2 n=n-i print prac
Compute A \times B. Constraints * 1 \leq A \leq 100 * 1 \leq B \leq 100 * All values in input are integers. Input Input is given from Standard Input in the following format: A B Output Print the value A \times B as an integer. Examples Input 2 5 Output 10 Input 100 100 Output 10000
from __future__ import division, print_function ''' Hey stalker :) ''' INF = 10 ** 10 TEST_CASES = False from collections import defaultdict, Counter def main(): a,b = get_list() print(a*b) ''' FastIO Footer: PyRival Library, Thanks @c1729 and contributors ''' import os import sys from bisect import bisect_...
Caracal is fighting with a monster. The health of the monster is H. Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens: * If the monster's health is 1, it drops to 0. * If the monster's health, X, is greater than 1, that monster disappear...
#include <bits/stdc++.h> using namespace std; int main(){ long long h; cin >> h; long long n = log2(h); cout << long(pow(2, n + 1)) - 1 << endl; }
Takahashi's house has only one socket. Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets. One power strip with A sockets can extend one empty socket into A empty sockets. Find the minimum number of power strips required. Constraints * All values in inp...
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int A = sc.nextInt(); int B = sc.nextInt(); int tmp =1; int answer = 0; while(tmp<B){ tmp=tmp+A-1; answer=answer+1; } System.out.print(answer); } }
Consider a circle whose perimeter is divided by N points into N arcs of equal length, and each of the arcs is painted red or blue. Such a circle is said to generate a string S from every point when the following condition is satisfied: * We will arbitrarily choose one of the N points on the perimeter and place a piece...
#include<bits/stdc++.h> using namespace std; typedef long long LL; #define N 300000 const LL mod=1000000007; LL n,m,p,ans,f[N]; char s[N]; void upd(LL &x,LL y){x=(x+y)%mod;} int main(){ scanf("%lld%lld%s",&n,&m,s+1); if (s[1]=='B') for (LL i=1;i<=m;++i) s[i]=s[i]=='B'?'R':'B'; p=n; ans=1; for (LL i=1,j=0,fst=...
Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i. He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2. Note that a ball cannot belong to multiple pairs. Find the maximum possible number of pai...
from collections import Counter N = int(input()) As = list(map(int, input().split())) cnt = Counter(As) As.sort(reverse=True) Ps = [2] for i in range(29): Ps.append(Ps[-1] * 2) ans = 0 for A in As: if cnt[A] <= 0: continue cnt[A] -= 1 while Ps[-1] > 2 * A: Ps.pop() if cnt[Ps[-1] - A] >...
Coloring of the vertices of a tree G is called a good coloring when, for every pair of two vertices u and v painted in the same color, picking u as the root and picking v as the root would result in isomorphic rooted trees. Also, the colorfulness of G is defined as the minimum possible number of different colors used ...
import java.util.Arrays; public class Main { private static void solve() { int n = ni(); int[] from = new int[n - 1]; int[] to = new int[n - 1]; for (int i = 0; i < n - 1; i++) { from[i] = ni() - 1; to[i] = ni() - 1; } int[][] g = packU(n, from, to); int[] center = centerNoR...
You are given an undirected graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≀ i ≀ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges. You can repeatedly perform the operation of adding an edge between two vertices. However, G must not h...
#include <bits/stdc++.h> using namespace std; #define int long long using ll=long long; using vi=vector<int>; using pii=pair<int,int>; #define ALL(c) begin(c),end(c) #define RALL(c) rbegin(c),rend(c) #define ITR(i,b,e) for(auto i=(b);i!=(e);++i) #define FORE(x,c) for(auto &x:c) #define REPF(i,a,n) for(int i=a,i##len=(i...
We have N irregular jigsaw pieces. Each piece is composed of three rectangular parts of width 1 and various heights joined together. More specifically: * The i-th piece is a part of height H, with another part of height A_i joined to the left, and yet another part of height B_i joined to the right, as shown below. Her...
#include <bits/stdc++.h> #define For(i, j, k) for(int i = j; i <= k; i++) using namespace std; const int N = 410; int indeg[N], outdeg[N], fa[N]; int find(int x){ return x == fa[x] ? x : fa[x] = find(fa[x]); } int n, H; int main(){ scanf("%d%d", &n, &H); For(i, 1, 2 * H) fa[i] = i; For(i, 1, n){ int a, b,...
We will recursively define uninity of a tree, as follows: (Uni is a Japanese word for sea urchins.) * A tree consisting of one vertex is a tree of uninity 0. * Suppose there are zero or more trees of uninity k, and a vertex v. If a vertex is selected from each tree of uninity k and connected to v with an edge, the res...
#include<bits/stdc++.h> using namespace std; const int maxN = 1e5 + 13; int n, ans, val[maxN][50 + 13]; vector<int> adj[maxN]; void dfs (int x, int par) { for (auto a : adj[x]) { if (a != par) { dfs(a, x); for (int i = 0; i <= 50; i++) val[x][i] += val[a][i]; } } int cur = 0; for (int i = ...
One day, Takahashi was given the following problem from Aoki: * You are given a tree with N vertices and an integer K. The vertices are numbered 1 through N. The edges are represented by pairs of integers (a_i, b_i). * For a set S of vertices in the tree, let f(S) be the minimum number of the vertices in a subtree of ...
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; const int N=1000010,P=924844033; int n,cnt,G[N],a[N],A[N],B[N]; struct edge{ int t,nx; }E[N<<1]; inline void addedge(int x,int y){ E[++cnt].t=y; E[cnt].nx=G[x]; G[x]=cnt; E[++cnt].t=x; E[cnt].nx=G[y]; G[y]=cnt; } int dfs(int x,in...
Write a program that reads the coordinates of the vertices of a convex n-sided polygon (a polygon whose internal angles are less than 180 degrees, that is, a polygon that is not dented) and outputs its area. The vertices are named Vertex 1, Vertex 2, Vertex 3, ... Vertex n according to the order of edge connections. H...
#include <cstdio> #include <cmath> int main(){ double xs[21],ys[21]; double x,y; int n=0; while(scanf("%lf,%lf",&x,&y)!=EOF){ xs[n]=x,ys[n++]=y; } x=0; for(int i=0;i<n;i++)x+=(xs[i]-xs[(i+1)%n])*(ys[i]+ys[(i+1)%n]); printf("%.8f\n",fabs(x/2.0)); }
At Akabeko Elementary School, all the students participate in a slightly unusual jogging. Students run their own lap courses at their own pace. After going around each of your courses, you will be returned to elementary school. How many laps do they all meet at the same time in elementary school after they all start el...
#include <algorithm> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <map> #include <numeric> #include <queue> #include <set> #include <string> #include <vector> using namespace std; #define reps(i,f,n) for(int i=f; i<int(n);...
A lottery is being held in a corner of the venue of the Aizu festival. Several types of balls are inside the lottery box and each type has its unique integer printed on the surfaces of the balls. An integer T is printed on the lottery box. In the lottery, you first declare two integers A and B, and draw up to M balls ...
#include <iostream> #include <vector> #include <array> #include <list> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <tuple> #include <bitset> #include <memory> #include <cmath> #include <algorithm> #include ...
She is an extraordinary girl. She works for a library. Since she is young and cute, she is forced to do a lot of laborious jobs. The most annoying job for her is to put returned books into shelves, carrying them by a cart. The cart is large enough to carry many books, but too heavy for her. Since she is delicate, she w...
#!/usr/bin/env python from collections import deque import itertools as it import sys import math sys.setrecursionlimit(10000000) T = input() for loop in range(T): N = input() S = raw_input() S1 = 'N' + S[:N * 2] + 'N' S2 = 'N' + S[N * 2:] + 'N' sx1 = sx2 = 100000 gx1 = gx2 = -1 ans = 0 ...
On Planet MM-21, after their Olympic games this year, curling is getting popular. But the rules are somewhat different from ours. The game is played on an ice game board on which a square mesh is marked. They use only a single stone. The purpose of the game is to lead the stone from the start to the goal with the minim...
#include<iostream> #include<cstring> #include<map> #include<queue> using namespace std; int dx[]={0,1,0,-1},dy[]={1,0,-1,0}; int w,h,sx,sy,gx,gy,ans,HM; int mas[22][22]; bool used[22][22]; typedef pair<int,int> P; void bfs(int cnt,P p); P move(P,int); int main(){ while(1){ cin >> w >> h; if(w==0&&h==0)break; ...
Hideyuki is allowed by his father Ujisato some 1000 yen bills every month for his pocket money. In the first day of every month, the number of bills is decided as follows. Ujisato prepares n pieces of m-sided dice and declares the cutback k. Hideyuki rolls these dice. The number of bills given is the sum of the spots o...
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(-1.0); #define REP...
The three dice brothers are triplets, one and the same, and three can be said to be one. Since they are triplets, they are indistinguishably similar. Such three dice brothers are A's favorite toys. Mr. A is always playing with rolling dice in a set of three. As you can see, A is a toy that he enjoys playing, but in fac...
#include<iostream> #include<queue> #include<algorithm> #include<vector> #include<ctime> #include<cstdio> #include<map> #include<set> using namespace std; class Dice{ public: int x,y; int C[3]; Dice(int c0,int c1,int c2,int _x,int _y){ C[0] = c0; C[1] = c1; C[2] = c2; x = _x; y =...
Nate U. Smith runs a railroad company in a metropolitan area. In addition to his railroad company, there are rival railroad companies in this metropolitan area. The two companies are in a competitive relationship with each other. In this metropolitan area, all lines are routed by the line segment connecting the statio...
#include <iostream> #include <cstdio> #include <vector> #include <set> #include <map> #include <queue> #include <deque> #include <stack> #include <algorithm> #include <cstring> #include <functional> #include <cmath> #include <complex> using namespace std; #define rep(i,n) for(int i=0;i<(n);++i) #define rep1(i,n) for(in...
Nathan O. Davis is trying to capture a game and struggling to get a very rare item. This rare item can be obtained by arranging special patterns in a row on a casino slot machine. The slot machine has N reels, and pressing the button once stops the currently rotating leftmost reel. Therefore, you need to press the butt...
#include <iostream> using namespace std; int main(void){ int n,a,b,c,x; int y[100]; while(cin>>n>>a>>b>>c>>x && n){ for(int i=0;i<n;i++){ cin>>y[i]; } int now = 0; //ΒŒΒ»ΒΓΒ‚ΓŒΒƒΒŠΒ[ƒ‹”ԍ† int flame = 0; while(1){ if(x == y[now]){ now++; if(now == n) break; } x = (a * x + b) % c; flame...
Dr. Fukuoka has placed a simple robot in a two-dimensional maze. It moves within the maze and never goes out of the maze as there is no exit. The maze is made up of H Γ— W grid cells as depicted below. The upper side of the maze faces north. Consequently, the right, lower and left sides face east, south and west respec...
#include <iostream> #include <sstream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <ctime> #include <vector> #include <string> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <functional> #include <algorithm> using namespace std; #define ...
A scientist Arthur C. McDonell is conducting a very complex chemical experiment. This experiment requires a large number of very simple operations to pour water into every column of the vessel at the predetermined ratio. Tired of boring manual work, he was trying to automate the operation. One day, he came upon the id...
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.util.Collections.*; import static java.util.Arrays.*; import static java.lang.Math.*; // Divide the Water // 2012/12/15 public class Main{ Scanner sc=new Scanner(System.in); int INF=1<<28; int n; int[] a; void run(...
There is a complete graph of m vertices. Initially, the edges of the complete graph are uncolored. Sunuke did the following for each i (1 ≀ i ≀ n): Select ai vertices from the complete graph and color all edges connecting the selected vertices with color i. None of the sides were painted in multiple colors. Find the mi...
#include <cstdio> #include <cmath> #include <cstring> #include <cstdlib> #include <climits> #include <ctime> #include <queue> #include <stack> #include <algorithm> #include <list> #include <vector> #include <set> #include <map> #include <iostream> #include <deque> #include <complex> #include <string> #include <iomanip>...
Example Input 1 Output )(
#include <bits/stdc++.h> #define ll long long using namespace std; int A; int c[200010]; int n,now; int main() { scanf("%d",&A); n=1; while ((ll)n*(n+1)/2<(ll)A) n++; int p=A-(ll)n*(n-1)/2; c[1]=1; c[1+p]=2;now=1; for(int i=1;i<=2*n;i++) if(c[i]==0) if(now<n) c[i]=1,now++;else c[i]=2; for(int i=1;i<=2*n;i++) ...
F: Tea Party Yun decided to hold a tea party at the company. The shop sells $ N $ sets of bread, each containing $ A_1, A_2, A_3, \ dots, A_N $. Yun decided to make a sandwich by combining two breads into a pair. Yun-san is very careful, so I want to make sure that I don't have any leftover bread. Calculate how ma...
#include <bits/stdc++.h> using namespace std; #define FOR( i, m, n ) for( int i = m; i < n; i++ ) #define REP( i, n ) FOR( i, 0, n ) #define ALL( a ) (a).begin(), (a).end() int main(){ int n; cin >> n; vector<int> a( n ), o ( n ); int res = 0, mino = 1001, odd = 0; REP( i, n ){ cin >> a[i]...
Problem Alice and Bob are competing in the 50m dash. However, in this world, the higher the AOJ rate is, the better, so the higher the AOJ rate wins. If there is no AOJ rate on either side, there is no comparison, so there is no choice but to compete in the 50m sprint time. In this case, the one with the shorter time ...
/*** author: yuji9511 ***/ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> lpair; const ll MOD = 1e9 + 7; const ll INF = 1e18; #define rep(i,m,n) for(ll i = (m); i < (n); i++) #define rrep(i,m,n) for(ll i = (m); i >= (n); i--) #define print(x) cout << (x) << endl; #define print2...