input
stringlengths
29
13k
output
stringlengths
9
73.4k
There is a triangle formed by three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$ on a plain. Write a program which prints "YES" if a point $P$ $(x_p, y_p)$ is in the triangle and "NO" if not. Constraints You can assume that: * $ -100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_p, y_p \leq 100$ * 1.0 $\leq$ Length of ea...
import math def S(a,b,c): s = (a+b+c)/2 return math.sqrt(s*(s-a)*(s-b)*(s-c)) while True: try: x1,y1,x2,y2,x3,y3,xp,yp = map(float, raw_input().split()) a = math.sqrt((x1-x2)**2+(y1-y2)**2) b = math.sqrt((x1-x3)**2+(y1-y3)**2) c = math.sqrt((x2-x3)**2+(y2-y3)**2) xa = math.sqrt((x3-xp)**2+(y3-yp)**2) x...
On the Internet, data is divided into packets, and each packet is transferred to a destination via a relay device called a router. Each router determines the next router to forward from the destination described in the packet. In addition, a value called TTL (Time To Live) is added to the packet to prevent it from bein...
#include <iostream> #include <queue> #include <map> #include <climits> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) typedef pair<int,int> NODE; #define pos first #define depth second bool info[100][100]; int bfs(int s,int d){ queue<NODE> Q; bool done[100]={false}; Q.push( make_pair(s,0) ); while( ...
A programming contest is held every year at White Tiger University. When the total number of teams is N, each team is assigned a team ID from 1 to N. The contest starts with all teams scoring 0 and runs continuously for L seconds. This year's contest will be broadcast on TV. Only the team with the highest score at the...
#include <cstdio> #include <cstdlib> #include <algorithm> using namespace std; int dat[1000000]; int max_idx[2*1000000-1]; int size; void init(int _size) { size=1; while(_size>size) size*=2; for(int i=0;i<size;i++) { if(i<_size) dat[i]=0; else dat[i]=-(1<<30); } for(int i=size*2-2;i>=0;i--) { if(i>=size-1) { ...
problem Do you know Just Odd Inventions? The business of this company is to "just odd inventions". Here we call it JOI for short. JOI has two offices, each of which has square rooms of the same size arranged in a grid pattern. All the rooms that are in contact with each other have an ID card authentication function. ...
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <iostream> #include <vector> #include <string> #include <sstream> #include <algorithm> #include <utility> #include <set> #include <map> #include <stack> #include <queue> #include <deque> #include <functional> using nam...
Your task is to simulate the sequence defined in the remaining part of the problem description. This sequence is empty at first. i -th element of this sequence is expressed as ai . The first element of this sequence is a1 if the sequence is not empty. The operation is given by integer from 0 to 9. The operation is ...
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} struct FastIO{ FastIO(){ cin.tie(0); ios::sync_with_stdio(0); } }fastio_beet; //I...
Haven't you ever thought that programs written in Java, C++, Pascal, or any other modern computer languages look rather sparse? Although most editors provide sufficient screen space for at least 80 characters or so in a line, the average number of significant characters occurring in a line is just a fraction. Today, pe...
#include<string> #include<algorithm> #include<iostream> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) const string ERROR = "ERROR"; const int M = 200; char m[M][M]; bool F(int &y,int &x){ if (m[y][x] == ' ')return false; x++; return true; } bool B(int &y,int &x){...
Example Input 8 900 0 40 100 70 -80 350 30 680 -20 230 230 300 400 530 130 75 -275 Output 1210.99416
#include <algorithm> #include <climits> #include <cmath> #include <iostream> #include <map> #include <queue> #include <vector> using namespace std; constexpr double EPS = 1e-9; struct point { double x, y; explicit point(double x_ = 0.0, double y_ = 0.0):x(x_), y(y_) {} point(const point &p):x(p.x), y(p.y) {} poi...
Problem There is an arithmetic progression A with the number of terms N, the first term a, and the tolerance d. Since M statements that rewrite the sequence are given in the following format, find the value of the K item of the sequence A when the sequence A is rewritten M times in the given order. * The i-th stateme...
#include <iostream> #include <vector> constexpr int REVERSE = 0; constexpr int INCREMENT = 1; constexpr int HALF = 2; bool cover(int l, int r, int x) { return l <= x && x <= r; } int reverse(int l, int r, int x) { return r + l - x; } int main() { int N, a, d, M; std::cin >> N >> a >> d >> M; ...
You are deeply disappointed with the real world, so you have decided to live the rest of your life in the world of MMORPG (Massively Multi-Player Online Role Playing Game). You are no more concerned about the time you spend in the game: all you need is efficiency. One day, you have to move from one town to another. In...
#include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace ...
Description F, who likes to dance, decided to practice a hardcore dance called JUMP STYLE at a certain dance hall. The floor is tiled in an N × N grid. To support the dance practice, each tile has the coordinates of the tile to jump to the next step. F has strong motor nerves through daily practice and can jump to an...
#define _USE_MATH_DEFINES #define INF 0x3f3f3f3f #include <cstdio> #include <iostream> #include <sstream> #include <cmath> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <limits> #include <map> #include <string> #include <cstring> #include <set> #include <deque> #include <bitset> #in...
Example Input 4 1 0 0 3 0 3 3 0 3 1 1 Output 2.0000000000
import java.util.*; class Main { static class Line { P src; P dir; public Line(P src, P dir) { this.src = src; this.dir = dir; } } static class P { double x, y; public P(double x, double y) { this.x = x; this.y = y; } P subtruct(P p) { return new P(x - p.x, y - p.y); } P ad...
F - Point Distance Problem Statement You work for invention center as a part time programmer. This center researches movement of protein molecules. It needs how molecules make clusters, so it will calculate distance of all pair molecules and will make a histogram. Molecules’ positions are given by a N x N grid map. V...
#include "bits/stdc++.h" using namespace std; using ld = double; const ld eps = 1e-9; /* ?????????????????¨?????? FFT ??????????????? n?¬??????????g(x) = \sum_{i=0}^n a_i x^i , h(x) = \sum_{i=0}^n b_i x^i ??????????????? f(x) = (g*h)(x) = \sum_{k=0}^{2n} \sum_{i=0}^{k} a_i b_{k-i} x^k ???O(n log n)??§?±?????????? ???...
Almost periodic string Given the string S. Answer Q queries for this string S. In the i-th query, determine if S [l_i, \ r_i] can be a string of period t_i when you can change from S [l_i, \ r_i] to one character. S [l, \ r] represents the substring of the string S from the lth to the rth. If the character string W i...
#include <bits/stdc++.h> using namespace std; using ll = long long; using P = pair<ll, ll>; constexpr ll po(const ll p, const ll n, const ll mod) { if (n == 0) { return 1; } if (n % 2 == 1) { return po(p, n - 1, mod) * p % mod; } else { const ll pp = po(p, n / 2, mod); return pp * pp...
You have a grid with $H$ rows and $W$ columns. $H + W$ is even. We denote the cell at the $i$-th row from the top and the $j$-th column from the left by ($i, j$). In any cell ($i, j$), an integer between $1$ and $9$ is written if $i+j$ is even, and either '+' or '*' is written if $i+j$ is odd. You can get a mathematic...
#include<bits/stdc++.h> #define int long long #define r(i,n) for(int i=0;i<n;i++) using namespace std; typedef pair<int,int>P; typedef pair<P,int>P2; vector<P2>v[5000]; int MAX=1e15; int dp[51][51],h,w; int dy[]={0,1}; int dx[]={1,0}; string s[99]; int f=0; void make_graph(int y,int x){ r(i,51)r(j,51)dp[i][j]=0; dp...
Problem Find the angle between the two given angles θ1 and θ2. Here, the angle between them is defined as "θ1 & plus; t'when t'is the one with the smallest absolute value among the t satisfying θ1 & plus; t = θ2 − t" as shown in the figure below. A image of angles Constraints The input satisfies the following condi...
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std...
Optimal Binary Search Tree is a binary search tree constructed from $n$ keys and $n+1$ dummy keys so as to minimize the expected value of cost for a search operation. We are given a sequence $K = {k_1, k_2, ..., k_n}$ of $n$ distinct keys in sorted order $(k_1 < k_2 < ... < k_n)$, and we wish to construct a binary sea...
#include <bits/stdc++.h> #include <cmath> using namespace std; typedef long long ll; //typedef unsigned long long ll; //#define rep(i, n) for (int i = 0; i < (n); ++i) #define rep(i, n) for (ll i = 0; i < (n); ++i) //#define sz(x) ll(x.size()) //typedef pair<ll, int> P; //typedef pair<ll, ll> P; const double INF = 1e...
Your task is to calculate the distance between two $n$ dimensional vectors $x = \\{x_1, x_2, ..., x_n\\}$ and $y = \\{y_1, y_2, ..., y_n\\}$. The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance. \\[ D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)...
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n; double[] data1 =new double[1001]; double[] data2 =new double[1001]; double[] ans =new double[1001]; double D=0,D2=0,D3=0,D4=0; n = sc.nextInt(); for(int i=0;i<n;i++)data1[...
Three dinos go on a camping trip. There they decide to play a game. They mark distances of 1 km each on the ground up to 100 km i.e. 1, 2, 3...100. They can sit only on these 100 spots, with each one at a different spot. In one move, one of the outer dinos can hop into a spot between the other two. Help them maximise ...
from sys import stdin a,b,c=map(int,stdin.readline().split()) if c-b>b-a: print c-b-1 elif c-b<b-a: print b-a-1 else: print c-b-1
Given a string S consisting of only 1s and 0s, find the number of substrings which start and end both in 1. In this problem, a substring is defined as a sequence of continuous characters Si, Si+1, ..., Sj where 1 ≤ i ≤ j ≤ N. Input First line contains T, the number of testcases. Each testcase consists of N(the length...
for _ in range(input()): input() n = raw_input().strip().count('1') print n * (n+1)/2
Chef is very fond of horses. He enjoys watching them race. As expected, he has a stable full of horses. He, along with his friends, goes to his stable during the weekends to watch a few of these horses race. Chef wants his friends to enjoy the race and so he wants the race to be close. This can happen only if the horse...
def calculateMin(l): l = sorted(l) j=2 dis = abs(l[0]-l[1]) for i in range(1, len(l)-1): val = abs(l[i]-l[j]) if(val<dis): dis=val j+=1 if(j>=len(l)): break return dis t = input() while(t>0): n = input() l = list(map(int, raw_input().s...
Chef loves to play with arrays by himself. Today, he has an array A consisting of N distinct integers. He wants to perform the following operation on his array A. Select a pair of adjacent integers and remove the larger one of these two. This decreases the array size by 1. Cost of this operation will be equal to the ...
t = input() for i in range(t): n = input() l = [] l += map(int, raw_input().split()) l.sort() cost = 0 for j in range(n-1): large = max(l[0],l[1]) cost += min(l[0],l[1]) l.remove(large) print cost
The electrical resistance is the opposition to the passage of electric current. If two resistors with resistance R1 and R2 are connected to each other, the resultant resistance R depends on how their ends are connected. If they are connected in Series, they simply add up to give R = R1 + R2. If they are connected in Pa...
matrix = [[1,1], [1,0]] def matrixExponentiation(n,m): if n: temp = matrixExponentiation(n/2, m) if n&1: return matrixMultiply(matrixMultiply(temp, temp, m), matrix, m) else: return matrixMultiply(temp, temp, m) else: return [[1,0],[0,1]] def matrixMultiply(a, b, m): return [[(a[0][0]*...
In Chef's house there are N apples lying in a row on the floor. These apples are numbered from 1 (left most one) to N (right most one). The types of apples are also numbered by positive integers, and the type of apple i is Ti. Chef has recently brought two trained dogs. Both of the dogs are too intelligent to know the ...
a=[0]*1000001 t,k=[int(x) for x in raw_input().split()] e=[int(x) for x in raw_input().split()] flag=0 count=0 i=0 while i<t/2: f=e[i] b=e[t-i-1] if((f!=b)&(f+b==k)): count+=1 flag=1 break elif(a[f]==1): count+=1 flag=1 break elif(a[b]==1): cou...
After the war, the supersonic rocket became the most common public transportation. Each supersonic rocket consists of two "engines". Each engine is a set of "power sources". The first engine has n power sources, and the second one has m power sources. A power source can be described as a point (x_i, y_i) on a 2-D plan...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; pair<int, int> operator-(pair<int, int> a, pair<int, int> b) { return pair<int, int>(a.first - b.first, a.second - b.second); } long long operator%(pair<int, int> a, pair<int, int> b) { return 1LL * a.first * b.second - 1LL * a.second * b.first; ...
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than a and screen height not greater than b. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is w, an...
from fractions import gcd a, b, x, y = map(int, input().split()) gcd = gcd(x, y) x /= gcd y /= gcd res = int(min(a // x, b // y)) print(res)
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks. What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a ...
a, b, c = map(int, input().split()) m = max(a, b, c) n = a+b+c-m if n<=m: print(m-n+1) else: print(0)
n players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: "paper" beats "rock", "rock" beats "scissors", "scissors" beat "paper", and two ...
#include <bits/stdc++.h> using namespace std; char getc() { char c = getchar(); while ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9')) c = getchar(); return c; } int gcd(int n, int m) { return m == 0 ? n : gcd(m, n % m); } long long n, m, tree[3][200010], a[200010]; char s[200010]; long ...
Kilani is playing a game with his friends. This game can be represented as a grid of size n × m, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell). The game is played in rounds. In each round players expand turn by turn: firstly, t...
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.PriorityQueue; public class D1105 { private static class Element implements Comparable<Element>{ int x; int y; ...
For some array c, let's denote a greedy subsequence as a sequence of indices p_1, p_2, ..., p_l such that 1 ≤ p_1 < p_2 < ... < p_l ≤ |c|, and for each i ∈ [1, l - 1], p_{i + 1} is the minimum number such that p_{i + 1} > p_i and c[p_{i + 1}] > c[p_i]. You are given an array a_1, a_2, ..., a_n. For each its subsegment...
#include <bits/stdc++.h> using namespace std; template <typename G> struct triple { G first, second, T; }; struct segment_tree { vector<int> st; vector<int> lazy; segment_tree(int n) : st(2 * n), lazy(2 * n) {} inline int id(int b, int e) { return (b + e - 1) | (b != e - 1); } void prop(int l, int r) { ...
Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School. In his favorite math class, the teacher taught him the following interesting definitions. A parenthesis sequence is a string, containing only characters "(" and ")". A correct parenthesis sequence is a parenthesis sequence ...
import java.io.*; import java.util.*; public class Q3 { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int N = in.nextInt(); char arr[]=in.next().toCharArray(); int o=0,e=0,flag=N%2!=0?0:1; ...
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands: * for n — for loop; * end — every command betw...
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Array; import ...
You have a list of numbers from 1 to n written from left to right on the blackboard. You perform an algorithm consisting of several steps (steps are 1-indexed). On the i-th step you wipe the i-th number (considering only remaining numbers). You wipe the whole number (not one digit). <image> When there are less than ...
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class _p001194A { static public void main(final String[] args) throws jav...
This is an easier version of the problem. In this version, n ≤ 6. Marek is working hard on creating strong testcases to his new algorithmic problem. You want to know what it is? Nah, we're not telling you. However, we can tell you how he generates the testcases. Marek chooses an integer n and n^2 integers p_{ij} (1 ≤...
#include <bits/stdc++.h> using namespace std; const int Mxxx = 1e5; inline char gc() { static char buf[Mxxx], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, Mxxx, stdin), p1 == p2) ? EOF : *p1++; } inline char pc(char ch, bool fl) { static char buf[Mxxx], *p1 =...
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi ha...
#include <bits/stdc++.h> using namespace std; int ans = 0; void gen(vector<int> &A, vector<vector<int>> &G, int i) { if (i < G.size()) { for (int j = 0; j < 6; ++j) { A[i] = j; gen(A, G, i + 1); } } else { bool was[6][6]; for (int a = 0; a < 6; ++a) { for (int b = 0; b < 6; ++b) wa...
You are given two bracket sequences (not necessarily regular) s and t consisting only of characters '(' and ')'. You want to construct the shortest regular bracket sequence that contains both given bracket sequences as subsequences (not necessarily contiguous). Recall what is the regular bracket sequence: * () is t...
import java.io.*; import java.util.*; public class Main { static char[]in1; static char[]in2; static int[][][]memo; static int dp(int i,int j,int pref) { if(i>=in1.length) { int inc=0; while(j<in2.length) { pref+=in2[j]=='('?1:-1; inc++; if(pref<0) { pref=0;inc++; } j++; } r...
You are given an array a consisting of n integers. In one move, you can choose two indices 1 ≤ i, j ≤ n such that i ≠ j and set a_i := a_j. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. yo...
#include <bits/stdc++.h> using namespace std; int main() { ios_base ::sync_with_stdio(0); int q; cin >> q; for (int i = 1; i <= q; ++i) { int n; cin >> n; int a = 0, b = 0; for (int j = 1; j <= n; ++j) { int x; cin >> x; if (x % 2) { a++; } else { b++; ...
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
a=str(input()) b=a[:];c=a[:];d=a[:] b=b.upper();d=d.upper();c=c.lower() if a==b: a=a.lower() elif a[0]==c[0]: if len(a)>1: if a[1:]==d[1:]: a=a.capitalize() else: pass else: a=a.upper() else: pass print(a)
Consider the infinite sequence s of positive integers, created by repeating the following steps: 1. Find the lexicographically smallest triple of positive integers (a, b, c) such that * a ⊕ b ⊕ c = 0, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). * a, b, ...
import sys input = sys.stdin.readline import bisect L=[4**i for i in range(30)] def calc(x): fami=bisect.bisect_right(L,x)-1 base=(x-L[fami])//3 cl=x%3 if cl==1: return L[fami]+base else: cl1=L[fami]+base ANS=0 for i in range(30): x=cl1//L[i]%4 ...
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
for i in range(int(input())): n=int(input()) lst=list() x=list(map(int,input().split())) x.sort() if len(set(x))!=len(x): print(0) else: for i in range(n-1): lst.append(x[i+1]-x[i]) print(min(lst))
There are n programmers that you want to split into several non-empty teams. The skill of the i-th programmer is a_i. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team ...
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { int t; cin >> t; while (t--) { ll n, x; cin >> n >> x; ll ar[n]; for (int i = 0; i < n; i++) { cin >> ar[i]; } sort(ar, ar + n); ll ans = 0; ll num = 0; for (int i = n - 1; i >= 0; i--) { ...
Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows: * if the character w_{i-x} exists and is equal to 1, then s_i is 1 (forma...
#include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T--) { string s; cin >> s; int n = s.size(); int x; cin >> x; vector<char> ans(n, '1'); for (int i = 0; i < n; i++) { if (s[i] == '0') { if (i + x < n) ans[i + x] = '0'; if (i - x >...
As you may already know, Dušan is keen on playing with railway models. He has a big map with cities that are connected with railways. His map can be seen as a graph where vertices are cities and the railways connecting them are the edges. So far, the graph corresponding to his map is a tree. As you already know, a tree...
#include <bits/stdc++.h> using namespace std; int N, K, n, i, j, k, l; int a[20001][2], ls[10001], sz[10001], len; int ans[100001][2], tot; int num[10001], d[10001], Tot; bool bz[10001]; void New(int x, int y) { ++len; a[len][0] = y; a[len][1] = ls[x]; ls[x] = len; } void Add(int x, int y) { ++tot; ans[tot]...
One drew a closed polyline on a plane, that consisted only of vertical and horizontal segments (parallel to the coordinate axes). The segments alternated between horizontal and vertical ones (a horizontal segment was always followed by a vertical one, and vice versa). The polyline did not contain strict self-intersecti...
#include <bits/stdc++.h> using namespace std; const int N = 1005; const int MOD = 998244353; inline int read() { int f = 1, x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s >= '0' && s <= '9') { x = x * 10 + s - '0'; s = getchar(); } r...
Let's call two strings a and b (both of length k) a bit similar if they have the same character in some position, i. e. there exists at least one i ∈ [1, k] such that a_i = b_i. You are given a binary string s of length n (a string of n characters 0 and/or 1) and an integer k. Let's denote the string s[i..j] as the su...
import java.util.*; import java.io.*; public class EdE { static long[] mods = {1000000000000037L, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] omkar) throws Exception{ // TODO Auto-generated method stub sc = n...
Diamond Miner is a game that is similar to Gold Miner, but there are n miners instead of 1 in this game. The mining area can be described as a plane. The n miners can be regarded as n points on the y-axis. There are n diamond mines in the mining area. We can regard them as n points on the x-axis. For some reason, no m...
#include <bits/stdc++.h> #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef vector <int> vi; typedef vector <...
It is reported that the 2050 Conference will be held in Yunqi Town in Hangzhou from April 23 to 25, including theme forums, morning jogging, camping and so on. The relationship between the n volunteers of the 2050 Conference can be represented by a tree (a connected undirected graph with n vertices and n-1 edges). The...
#include<bits/stdc++.h> using namespace std; const int Mod=998244353; const int inv2=(Mod+1)>>1; int n,len,f[310][310],g[310][310],tf[310],tg[310],maxd[310]; int edgenum,vet[610],Next[610],Head[310]; void addedge(int u,int v){ vet[++edgenum]=v; Next[edgenum]=Head[u]; Head[u]=edgenum; } //f[u][d]:u 子树中所有点都被标...
Note that the differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if both versions are solved. AquaMoon knew through foresight that some ghosts wanted to curse tourists on a pedestrian street. But unfortunately, this time, these ghosts were hiding in a barrie...
#include <stdio.h> #include <string.h> #include <sys/time.h> #define N 2048 #define INF 0x3f3f3f3f3f3f3f3fLL #define X 10000000 long long min(long long a, long long b) { return a < b ? a : b; } unsigned int Z; void srand_() { struct timeval tv; gettimeofday(&tv, NULL); Z = 1; } int rand_() { return (Z *= 3) >...
Reforms have started in Berland again! At this time, the Parliament is discussing the reform of the calendar. To make the lives of citizens of Berland more varied, it was decided to change the calendar. As more and more people are complaining that "the years fly by...", it was decided that starting from the next year t...
import java.util.*; public class cf172d { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a = in.nextInt(); int n = in.nextInt(); int[] best = new int[a+n]; for(int i=1; i*i<a+n; i++) for(int j=i*i; j<a+n; j+=i*i) best[j]=i*i; long ans = 0; f...
They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each ...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; const int LogN = 20; struct Node { vector<int> adj; vector<int> idx; } g[N]; bool mark[N]; int way[N]; int sol[N]; int n, m; int t; int in[N], out[N]; int st[N][LogN]; int dist[N], disc[N]; int depth[N]; int indegree[N]; void dfs(int v, int prev,...
You know that the Martians use a number system with base k. Digit b (0 ≤ b < k) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology). A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of...
#include <bits/stdc++.h> using namespace std; map<int, int> mp; int n, k, b; int main() { scanf("%d%d%d", &k, &b, &n); int k1 = k - 1; mp[0] = 1; int temp, sum = 0; long long ans = 0, zero = 0, tz = 0; for (int i = 1; i <= n; ++i) { scanf("%d", &temp); sum = (sum + temp) % k1; int t = (sum - b +...
Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can...
from fractions import Fraction n = int(input()) adj = [list() for x in range(n)] H = [0] * n F = [0] * n FoH = [list() for x in range(n)] sz = 0 order = [0] * n pi = [-1] * n def dfs(u, p = -1): global pi, order, sz pi[u] = p for v in adj[u]: if v != p: dfs(v, u) order[sz] = u sz += 1 T1 = [0] ...
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order. The stones always fall to the center of Liss's inter...
#include <bits/stdc++.h> using namespace std; vector<int> v; int main() { string s; cin >> s; int i; for (i = 0; i < s.size(); i++) { if (s[i] == 'r') { printf("%d\n", i + 1); } else { v.push_back(i + 1); } } for (i = v.size() - 1; i >= 0; i--) { printf("%d\n", v[i]); } }
Little penguin Polo adores strings. But most of all he adores strings of length n. One day he wanted to find a string that meets the following conditions: 1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. 2. No two neighbouring...
from itertools import * def solve(n,k): alpha = 'cdefghijklmnopqrstuvwxyz' if k>n: return -1 if k==1: return 'a' if n==1 else -1 if k==2: return ''.join(islice(cycle('ab'),0,n)) if k==3: return ''.join(chain(islice(cycle('ab'),0,n-1),'c')) return ''.join(chain(islice(cycle('ab'),0,n-k+2),alpha[:k-2])) n,...
Sereja has a sequence that consists of n positive integers, a1, a2, ..., an. First Sereja took a piece of squared paper and wrote all distinct non-empty non-decreasing subsequences of sequence a. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all sequences that do not exce...
#include <bits/stdc++.h> using namespace std; static const int INF = 500000000; template <class T> void debug(T a, T b) { for (; a != b; ++a) cerr << *a << ' '; cerr << endl; } int n; int ar[100005]; const long long int mod = 1000000007; struct segtree { long long int val[4000005]; int n; void init(int n_) { ...
Vasily the bear has two favorite integers n and k and a pencil. Besides, he's got k jars with different water color paints. All jars are numbered in some manner from 1 to k, inclusive. The jar number i contains the paint of the i-th color. Initially the bear took a pencil and drew four segments on the coordinate plan...
#include <bits/stdc++.h> using namespace std; const int N = 210; const int M = 300005; const int mod = 1e9 + 7; const int inf = 0x3f3f3f3f; const long long oo = 0x3f3f3f3f3f3f3f3fll; const double eps = 1e-6; int n, k; long long C[N][N], dp[N][N][5][3]; int getNum(int cur) { if (cur == 4) return 2; return 4 - cur; }...
Once upon a time, when the world was more beautiful, the sun shone brighter, the grass was greener and the sausages tasted better Arlandia was the most powerful country. And its capital was the place where our hero DravDe worked. He couldn’t program or make up problems (in fact, few people saw a computer those days) bu...
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner("input.txt"); PrintWriter out = new PrintWriter("output.txt"); int n = sc.nextInt(); int m = sc.nextInt(); int k = ...
Ksenia has her winter exams. Today she is learning combinatorics. Here's one of the problems she needs to learn to solve. How many distinct trees are there consisting of n vertices, each with the following properties: * the tree is marked, that is, the vertices of the tree are numbered from 1 to n; * each vertex...
#include <bits/stdc++.h> const long long mod = 1000000007; const long long inv2 = (mod + 1) / 2; long long inv[52]; long long C[52][52]; long long dp[52][52][2]; inline void Add(long long &x, long long y) { if (y >= mod) y %= mod; y *= inv2; if (y >= mod) y %= mod; x += y; if (x >= mod) x -= mod; } int N, M; ...
The sequence of integer pairs (a1, b1), (a2, b2), ..., (ak, bk) is beautiful, if the following statements are fulfilled: * 1 ≤ a1 ≤ b1 < a2 ≤ b2 < ... < ak ≤ bk ≤ n, where n is a given positive integer; * all numbers b1 - a1, b2 - a2, ..., bk - ak are distinct. For the given number n find the number of beaut...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1); const double eps = 1e-10; const int inf = 0x3f3f3f3f; const long long infLL = 0x3f3f3f3f3f3f3f3fLL; const int maxn = 2000 + 5; const long long mod = 1000000007; long long fac[maxn], ifac[maxn]; void gcd(long long a, long long b, long long &d, lon...
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 ...
#!/usr/bin/python import sys def Ni(): return tuple(map(int, sys.stdin.readline().split())) n = Ni()[0] c = Ni() avail = [c.count(i) for i in range(n+1)] def backtrack(stack, sumleft): #print stack, avail, sumleft if len(stack) == 1 and sumleft == 0: print "YES" sys.exit(0) # try to sh...
Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony. <image> A sequence of positive integers bi is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmo...
import sun.security.krb5.internal.crypto.Des; import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedRea...
Consider infinite grid of unit cells. Some of those cells are planets. Meta-universe M = {p1, p2, ..., pk} is a set of planets. Suppose there is an infinite row or column with following two properties: 1) it doesn't contain any planet pi of meta-universe M on it; 2) there are planets of M located on both sides from t...
#include <bits/stdc++.h> using namespace std; pair<int, int> mirror(pair<int, int> &p) { return {p.second, p.first}; } void move_from_first_two_sets_to_other_two(set<pair<int, int>> &set1_1, set<pair<int, int>> &set1_2, set<pair<int, ...
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans...
#include <bits/stdc++.h> using namespace std; char s[105]; void judge(int l) { for (int i = l - 1; i >= 0; i--) { if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')) { if (s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U' || s[i] == 'Y' || s[i] == 'a' || s[i] ==...
A Martian boy is named s — he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class Main { public...
The Hedgehog likes to give presents to his friend, but no less he likes to receive them. Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he c...
n,k = [int(nk) for nk in raw_input().split(" ")] c = [int(ci) for ci in raw_input().split(" ")] p = [0 for _ in xrange(n+k)] p[0] = 1 for ci in c[1:]: p[ci] = 1 for i in range(n): if p[i] == 1: if p[i+1:i+k+1].count(1) == 0: p[i+k] = 1 # print ' ', # for i in range(1,n+1): # print i, # print # for pi in p: # p...
A tree of size n is an undirected connected graph consisting of n vertices without cycles. Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vert...
#include <bits/stdc++.h> using namespace std; const int N_ = 100100; int N, P[N_]; int A[N_]; bool X[N_], Y[N_]; int main() { scanf("%d", &N); for (int i = 1; i <= N; i++) scanf("%d", P + i); for (int u = 1; u <= N; u++) { if (P[u] == u) { puts("YES"); for (int v = 1; v <= N; v++) if (u !=...
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon. The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles. Input The first line contains integers n and...
#include <bits/stdc++.h> using namespace std; const double PI = (acos(-1.0)); struct Point { long long x, y; Point(long long ix = 0, long long iy = 0) : x(ix), y(iy) {} Point &operator=(const Point &b) { x = b.x; y = b.y; return *this; } Point &operator-=(const Point &b) { x -= b.x; y -= b...
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal! He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too ti...
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class EternalVictory { static ArrayList<Pair>[]adjList; static boolean[]visited; public static ...
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it. The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all...
import java.util.*; public class C { public static void main(String[] args) { new C(new Scanner(System.in)); } String itoa(int i) { StringBuilder sb = new StringBuilder(); for (int u=0; u<4; u++) { sb.append(i%10); i = i/10; } return sb.reverse()....
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; if (n % 3 == 0) { cout << (n / 3) * 2; } else { cout << ((n / 3) * 2) + 1; } return 0; }
"The zombies are lurking outside. Waiting. Moaning. And when they come..." "When they come?" "I hope the Wall is high enough." Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segment...
#include <bits/stdc++.h> char map[100][100]; int n, m, vis[100][100] = {}; int mx[] = {-1, 0, 0, 1}; int my[] = {0, -1, 1, 0}; void solve(int i, int a, int counter) { if (i < 0 || a < 0 || i >= n || a >= m || map[i][a] == '.' || (vis[i][a] != 0 && vis[i][a] <= counter)) return; vis[i][a] = counter; for ...
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type: 1. + ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occur...
#include <bits/stdc++.h> using namespace std; const long long OO = (long long)(4e18) + 9; const long long MOD = (long long)(1e9) + 7; const int oo = 2147483647; const double EPS = 1e-8; const double PI = acos(-1.0); int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; int dX[] = {1, 0, -1, 0, 1, -1, 1, -1}; int dY[] = {...
Anton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays b and c of length n, find array a, such that: <image> where a and b means bitwise AND, while a or b means bitwise OR. Usually Anton is good...
import java.io.*; import java.util.StringTokenizer; public class F { void solve() throws IOException { FastScanner scanner = new FastScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int n = scanner.nextInt(); int[] b = new int[n]; int[] c = new int[n]; ...
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l ≤ ai ≤ r and ai ≠ aj , where a1, a2, ..., an is the geometrical progression, 1 ≤ i, j ≤ n and i ≠ j...
#include <bits/stdc++.h> using namespace std; long long N, L, R, ans; long long gcd(long long x, long long y) { if (x == 0) return y; return gcd(y % x, x); } int main() { scanf("%lld %lld %lld", &N, &L, &R); if (N == 1) ans = R - L + 1; else if (N == 2) { long long cnt = R - L + 1; ans = cnt * (cn...
...Mike the TV greets you again! Tired of the monotonous furniture? Sick of gray routine? Dreaming about dizzying changes in your humble abode? We have something to offer you! This domino carpet for only $99.99 will change your life! You can lay it on the floor, hang it on the wall or even on the ceiling! Among other...
#include <bits/stdc++.h> using ll = long long; using ld = long double; using namespace std; const int MOD = 1000000007; int n, m; vector<string> C; vector<vector<char> > M; vector<ll> DPh, DPv; vector<bool> Hor; char read_value(int x, int y) { int v = 0; char result = '_'; for (int i = 4 * x + 1; i < 4 * x + 4; +...
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a1, a2, ..., ak, that their sum is equal to n and greatest common divisor is maximal. Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them. I...
from collections import deque from math import sqrt n,k = map(int, input().split()) sum_k = k*(k+1)/2 if(sum_k>n): print(-1) else: pos = deque() for x in range(int(sqrt(n)), 0, -1): if(n%x==0): pos.appendleft(x) if(x*x!= n): pos.append(int(n/x)) it = -...
In a small restaurant there are a tables for one person and b tables for two persons. It it known that n groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater tabl...
import java.util.Scanner; /** * Created by prasad on 7/19/17. */ public class Restaurent { public static void main(String args[]){ Scanner in = new Scanner(System.in); int g = Integer.parseInt(in.next()); int o = Integer.parseInt(in.next()); int t = Integer.parseInt(in.next()); ...
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutel...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { static BufferedReader in; static StringTokenizer st; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { s...
You are given a positive integer n. Let's build a graph on vertices 1, 2, ..., n in such a way that there is an edge between vertices u and v if and only if <image>. Let d(u, v) be the shortest distance between u and v, or 0 if there is no path between them. Compute the sum of values d(u, v) over all 1 ≤ u < v ≤ n. Th...
#include <bits/stdc++.h> using namespace std; template <typename T> bool chkmax(T &x, T y) { return x < y ? x = y, true : false; } template <typename T> bool chkmin(T &x, T y) { return x > y ? x = y, true : false; } int readint() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (...
Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer ai — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will defin...
n, m, k = map(int,input().split()) a = list(map(int,input().split())) a.sort() vis = [] for i in range(n): vis.append(0) ans = l = r = 0 cnt = 1 while(r < n): while(a[r]-a[l]+1 > m): if(vis[l] == 0): cnt -= 1 l += 1 if cnt >= k: ans += 1 vis[r] = 1; cnt -= 1 r += ...
Given an integer x. Your task is to find out how many positive integers n (1 ≤ n ≤ x) satisfy $$$n ⋅ a^n ≡ b (mod\;p), where a, b, p$$$ are all known constants. Input The only line contains four integers a,b,p,x (2 ≤ p ≤ 10^6+3, 1 ≤ a,b < p, 1 ≤ x ≤ 10^{12}). It is guaranteed that p is a prime. Output Print a sin...
#include <bits/stdc++.h> long long k[1005555]; long long Pow(long long a, long long b, long long p) { long long ans = 1; while (b) { if (b % 2) ans = ans * a % p; a = a * a % p; b /= 2; } return ans; } int main(void) { long long a, b, p, x, i, xh, last, c, n, ans; scanf("%lld%lld%lld%lld", &a, &...
Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university. There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th ho...
n, m, k = map(int, input().split()) DATA = [input() for i in range(n)] #dp[n_day][used_cost] #ans = min(dp[n_day][used_cost] for used_cost in range(k + 1)) #dp[n_day][used_cost] := min(dp[n_day - 1][prev_cost] + cost(pay used_cost - prev_cost in n_day) for prev_cost in range(used_cost + 1)) INF = 1 << 60 dp = [[INF]*(...
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. <image> Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in th...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:36777216") using namespace std; const double pi = acos(-1.0); const double eps = 1e-11; const int oo = 0x3f3f3f3f; template <class T> inline void checkmin(T &a, T b) { if (b < a) a = b; } template <class T> inline void checkmax(T &a, T b) { if (b > a) a = b; ...
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be repre...
#include <bits/stdc++.h> using namespace std; const long long INF = 2e18 + 9; const long long MAXN = 1e6 + 7; const long long MAXN1 = 2e3 + 7; const long long MOD = 1e9 + 7; const long long ST = 157; const long long ST1 = 199; const long double EPS = 1e-9; const long long BLOCK = 138; void solve(); signed main() { sr...
The BITians are furious that their lift stops working frequently .Adding to this, there are 7 floors in BIT which becomes really tedious to climb. Vikas has to attend the class in 5th floor. He decides to take a step of 1 or 2 each time to reach his class. He wants to find the number of ways in which he c...
import math f=math.factorial t=int(input()) while t>0: n=int(raw_input()) c=0; for i in range (0, n+1): for j in range (0, n+1): if ((1*i)+(2*j))==n: c+=f(i+j)/(f(i)*f(j)) print c t-=1
Everyone knows that chotu likes palindromic strings. One day, he found 2 ordinary strings s1 and s2. Now he wonders if he could make a palindrome by concatenating s1 and s2 in any order. i.e if s1s2 or s2s1 is a palindrome. Input First line of input contains T, denoting number of test cases. Each test case contains t...
import sys n=int(raw_input()) i=0 while(i<=n-1): s1=raw_input() s2=raw_input() s3=s1+s2 s4=s2+s1 if(s3==s3[:: -1] or s4==s4[:: -1]): print("YES") else: print("NO") i+=1
If the given input positive integer is equal to the sum of its proper positive divisors then it will form a triangular array of numbers in which those at the ends of the rows are 1 and each of the others is the sum of the nearest two numbers in the row above (the apex, 1, being at the top). OR it can also be understoo...
n = int(raw_input()) k=1 s=0 while(k<n): if(n%k==0): s+=k k+=1 if s==n: arr = [[0 for _ in range (n+1)] for _ in range (n+1)] for line in range (0,n+1): s=[] for i in range (0,line): if line==i or i==0: arr[line][i]=1 else: arr[line][i] = arr[line-1][i-1]+arr[line-1][i] s.append(str(arr[li...
Hasan has finally finished his final exams and he decided to go in a trip among cities in Syria. There are N cities in Syria and they are numbered from 1 to N, each city has coordinates on plane, i-th city is in (Xi, Yi). Hasan is in first city and he wants to visit some cities by his car in the trip but the final de...
def d(x,y): return ((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5 n=int(raw_input()) l=[] for i in xrange(n): i,j,k=map(int,raw_input().split()) l.append((i,j,k)) dp=[-2494444444444]*(n+1) #F=0 #L=n-1 dp[0]=l[0][2] for i in xrange(1,n): for j in xrange(0,i): dp[i]=max(dp[i],dp[j]-d(l[i],l[j])) #print ...
All living beings on this extra-ordinary planet have some goodness value that tells their worth. Rajat and Shreya are a couple on this planet who love each other. Both of them have a goodness value A and B respectively. One day Rajat found an astonishing way of finding whether a couple is a lovely couple or not. A cou...
from fractions import gcd def modifySieve(n): for i in xrange(2, n): if not prime[i]: for j in xrange(i * 2, n, i): prime[j] += 1 prime = [0]*1000000 modifySieve(1000000) for chk in xrange(input()): a,b = map(int, raw_input().split()) x = a*b/gcd(a,b) if prime[x] > 1 and ...
Solve the mystery. Input: First line contains a single integer denoting number of test cases(T). Next T lines have one test case per line. Each test case is a string of alphabets [a-z]. Output: Print answer to each test case in an individual line. Constraints: 1 ≤ T ≤ 100 1 ≤ |S| ≤ 100 a ≤ S[i] ≤ z Problem Setter : ...
t = int(raw_input()) while(t>0): t -= 1 a = raw_input() if(a == a[::-1]): print(ord(a[len(a)/2])) else: print(-1)
Sanket being a stud, wants to gift chocolates on "Chocolate Day" to a girl. He has N chocolates of different types. The chocolates are numbered from 1 to N. There are K types of chocolates, numbered from 1 to K. Also, there are infinite chocolates of each type. But, the girl is very demanding. She wants all chocolates...
for i in xrange(input()): n,k = map(int,raw_input().split()) a = map(int,raw_input().split()) b = list(set(a)) m=0 for j in b: temp = a.count(j) if temp>m: m = temp print len(a)-m
Let's consider some integer X. We will call the following sequence S a sequence generated by X: for i = 1: S[i] = X for i > 1: S[i] equals to the minimal positive integer such that S[i] is not a divisor of S[i - 1]. If there is no such integer than S[i - 1] is the last element of S. For example S = (10, 3, 2) is a se...
from fractions import gcd def seq(x): for i in xrange(1, x): if x % i != 0: return [x] + seq(i) return [x] def lcm(a, b): return a * b / gcd(a, b) A, B = map(int, raw_input().split()) S = [1] * 42 for i in xrange(1, 42): for j in xrange(1, i): if i % j != 0: S...
Level 1 Sometimes what happens during SBG slot booking is we forgot to book our slot and mess up. But few clubs are generous enough to change their timings to make sure our event doesn't get postponed, hence a special thanks to them :). Anyways, the question here is you are given a string of only lower-case letters,...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' l=list(raw_input()) k=max(l,key=l.count) if k in "head rush" and k in"cubing club": print"Thanks both" elif k in "head rush": print "Thanks head rush" elif k in ...
Xavier asks his friend to perform a particular task.The task is to find out the ASCII value of each character of a given STRING and then add them up to find the weight of the given string as 'W',now after finding out the weight his task is to divide the weight of string W with the length of string 'L'such that the fina...
for _ in xrange(input()): a=list(raw_input()) l=len(a) tot=0 i=0 while i<l: tot=tot+ord(a[i]) i=i+1 k=tot/l if k%2==0: print ''.join(a) else: fin=str( ''.join(a)) print fin[::-1]
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs. Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct. Constraints ...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int y = sc.nextInt(); if (y % 2 != 0 || y < (2*x) || y > (4*x)) { System.out.println("No"); } else { System....
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}. Process the following q queries in order: * The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mo...
#include<bits/stdc++.h> using namespace std; #define int long signed main(){ int k,q,n,x,m; cin>>k>>q; vector<int> d(k); for(auto& i:d)cin>>i; while(q--){ cin>>n>>x>>m; x%=m; --n; vector<int> e(k); int u=0,res,t,ps=0,s,pz=0,z; for(int i=0;i<k;++i)ps+=e[i]=d[i]%m,u+=(m-e[i])%m,pz+=!e[i...
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}. Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b): * \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j) Since the answer may be enormous, compute it modulo 998244353. Constraints * 1 \leq N \leq 200000 ...
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e6+5,mod=998244353; int n,inv[N],f[N],u[N],vis[N]; bool vv[N]; int tot,p[N]; ll g[N]; void init() { inv[1]=1; for(int i=2;i<N;i++) inv[i]=1ll*(mod-mod/i)*inv[mod%i]%mod; u[1]=1; for(int i=2;i<N;i++) { if(!vv[i]) ...
There is a function f(x), which is initially a constant function f(x) = 0. We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows: * An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x). ...
import java.util.*; public class Main { public static void main(String [] args) { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); long constant = 0; TreeMap<Integer, Integer> map = new TreeMap<>(); int ptr = -1; int idx = -1; int total = 0; long val = 0; for (i...
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i. Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices. You are given a p...
#include<cstdio> #include<vector> std::vector <int> ve[100050]; int m,n,ans[100050],pre[100050],suf[100050],dp[100050]; void dfs(int u,int fa){ int lim=ve[u].size(),y; dp[u]=1; for (int i=0;i<lim;i++)if ((y=ve[u][i])!=fa){ dfs(y,u); pre[y]=dp[u]; dp[u]=(dp[y]+1)*1ll*dp[u]%m; } int k=1; for (int i=lim-1;i>=0...
To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation: * 1 yen (the currency of Japan) * 6 yen, 6^2(=36) yen, 6^3(=216) yen, ... * 9 yen, 9^2(=81) yen, 9^3(=729) yen, ... At least how many operations are required to withdraw exa...
n = int(input()) dp = [10**6]*(n+1) dp[0] = 0 l = [1, 6, 36, 216, 1296, 7776, 46656, 9, 81, 729, 6561, 59049] for i in range(1, n+1): for j in l: if i >= j: dp[i] = min(dp[i-j]+1, dp[i]) print(dp[-1])
You are given strings s and t, consisting of lowercase English letters. You will create a string s' by freely rearranging the characters in s. You will also create a string t' by freely rearranging the characters in t. Determine whether it is possible to satisfy s' < t' for the lexicographic order. Constraints * The ...
import java.util.*; import static java.lang.Math.*; import java.math.BigInteger; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); // 入力 String s = sc.next(); String t = sc.next(); // 計算 String result = "No"; char[] ss = s.toCharArray(); Arrays.sort...