input
stringlengths
29
13k
output
stringlengths
9
73.4k
Pandaland is a place full of strings. One day Panda visited Pandaland and get confused wether Pandaland is a lucky place or not. According to Panda a place is lucky if all the strings in that place follows the following property 'P' : - P:A place is lucky if, for any string S, the prefix of S should not be present in ...
import sys flag = True class Node: def __init__(self,c): self.c = c self.next = {} self.cnt = 0 self.ends = 0 def insert(node, word): for w in word: if w not in node.next: node.next[w] = Node(w) node = node.next[w] node.cnt += 1 node.end...
Roy's friends has been spying on his text messages, so Roy thought of an algorithm to encrypt text messages. Encryption Algorithm is as follows: We say message to be encrypted as Plain Text and encrypted form of message as Cipher. Plain Text consists of lower case alphabets only. Consider the Cipher Disk as shown in...
for _ in xrange(input()): text = raw_input() pos = 0 output = '' for c in text: move = (ord(c) - ord('a') - pos) % 26 output += str(move if move <= 13 else move - 26) + ' ' pos = pos + move print output[:-1]
Given a string, find the length of string. Input Format: First line contains single integer t, the number of test-cases. Each of next t lines contains a string of lower case alphabets. Output Format: Output t lines, each containing the single integer, length of corresponding string. Constraints: 1 ≤ t ≤ 100 1 ≤ leng...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' number=int(input()) while(number>0): word=raw_input() print(len(word)) number=number-1
The problem statement is simple. You are given a string and you are supposed to print all the distinct permutations of the string, as they would appear in an dictionary. INPUT The first and only line of the input contains a single string, S. OUTPUT The output contains the required strings, each string in a seperate...
from itertools import permutations perms = [''.join(p) for p in permutations(raw_input())] perms = list(set(perms)) perms.sort() for i in xrange(len(perms)): print perms[i]
This is an output-only problem. You shouldn't read anything from the input. In short, your task is to simulate multiplication by using only comparison (x < y) and addition (x + y). There is no input in this problem, you just print a sequence of operations. Imagine that there is a big array a[0], a[1], ..., a[N-1] of ...
#include<cstdio> #include<algorithm> #include<vector> using namespace std; struct point{ int ck, a, b, c; }; vector<point>V; long long A[201000]; void Add(int c, int a, int b){ // c=a+b A[c]=A[a]+A[b]; V.push_back({0,a,b,c}); } void Comp(int c, int a, int b){ // c = a<b A[c]=A[a]<A[b]; V.push_back({1,a,b,c}); } v...
A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal. Given a string S, determine whether it is coffee-like. Constraints * S is a string of length 6 consisting of lowercase English l...
import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); if ((s.charAt(2) == s.charAt(3)) && (s.charAt(4) == s.charAt(5))) System.out.println("Yes"); else System.out.println("No"); ...
Takahashi, who works at DISCO, is standing before an iron bar. The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters. Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length. However, this may not be po...
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; vector<ll> acc = {0}; for (int i = 0; i < n; i++) { ll a; cin >> a; acc.push_back(acc.back()+a); } ll ans = acc.back(); for (ll a : acc) ans = min(ans, ...
There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive ...
import math def comb(n, r): return math.factorial(n) // (math.factorial(n - r) * math.factorial(r)) n,k = map(int,input().split()) for i in range(1,k+1): if n - k + 1 >= i: print(comb(n - k + 1,i) * comb(k-1,i-1) % (10**9 + 7)) else: print(0)
Snuke has one biscuit and zero Japanese yen (the currency) in his pocket. He will perform the following operations exactly K times in total, in the order he likes: * Hit his pocket, which magically increases the number of biscuits by one. * Exchange A biscuits to 1 yen. * Exchange 1 yen to B biscuits. Find the maxi...
k,a,b=map(int,input().split()) if b-a<=2: print(k+1) else: kaisu=max(0,(k-a+1)//2) print(k-kaisu*2+kaisu*(b-a)+1)
There are N candles placed on a number line. The i-th candle from the left is placed on coordinate x_i. Here, x_1 < x_2 < ... < x_N holds. Initially, no candles are burning. Snuke decides to light K of the N candles. Now, he is at coordinate 0. He can move left and right along the line with speed 1. He can also light...
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); // 入力 int n = sc.nextInt(); int k = sc.nextInt(); int[] x = new int[n]; for(int i = 0; i < n; i++){ x[i] = sc.nextInt()...
In Republic of AtCoder, Snuke Chameleons (Family: Chamaeleonidae, Genus: Bartaberia) are very popular pets. Ringo keeps N Snuke Chameleons in a cage. A Snuke Chameleon that has not eaten anything is blue. It changes its color according to the following rules: * A Snuke Chameleon that is blue will change its color to ...
#include <bits/stdc++.h> #define LL long long using namespace std; const int N = 500005; const int mod = 998244353; int n, m, ans, fac[N], inv[N]; inline int C(int x, int y) { if (x < 0 || y < 0 || x < y) { return 0; } return 1LL * fac[x] * inv[y] % mod * inv[x - y] % mod; } int main() { scanf("%d%d",&n,...
Seisu-ya, a store specializing in non-negative integers, sells N non-negative integers. The i-th integer is A_i and has a utility of B_i. There may be multiple equal integers with different utilities. Takahashi will buy some integers in this store. He can buy a combination of integers whose bitwise OR is less than or ...
def solve(K, ABs): if not ABs: return 0 ansK = sum(b for a, b in ABs if (K | a) == K) pool = [] for i in range(30, -1, -1): if (K & (1<<i)): pool.append(i) for p in pool: v = 1 << p KK = (K >> p) << p KKK = (K >> p) t = sum(b for a, b in ABs if (no...
There is a circle with a circumference of L. Each point on the circumference has a coordinate value, which represents the arc length from a certain reference point clockwise to the point. On this circumference, there are N ants. These ants are numbered 1 through N in order of increasing coordinate, and ant i is at coor...
N, L, T = map(int, input().split()) s = 0 X = [0] * N for i in range(N): x, w = map(int, input().split()) if w == 1: x += T else: x -= T # xが0点を通る回数を足す s += x // L X[i] = x % L X.sort() for i in range(N): print(X[(i+s) % N])
There is a grid with H rows and W columns. The square at the i-th row and j-th column contains a string S_{i,j} of length 5. The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from `A` through the W-th letter of the alphabet. <image> Exactly one of...
H, W = map(int, input().split()) S = [input().split() for _ in range(H)] for i in range(H): for j in range(W): if S[i][j] == "snuke": print(chr(ord("A")+j)+str(i+1))
<image> This figure shows railway tracks for reshuffling cars. The rail tracks end in the bottom and the top-left rail track is used for the entrace and the top-right rail track is used for the exit. Ten cars, which have numbers from 1 to 10 respectively, use the rail tracks. We can simulate the movement (comings an...
i= 0 a,b = [],[] while True: try: a.append(int(raw_input())) if a[i] == 0: b.append(a[i-1]) a.pop() print a[i-1] a.pop() i -=1 else: i +=1 except: break
There is a set of cards with positive integers written on them. Stack the cards to make several piles and arrange them side by side. Select two adjacent piles of cards from them, and stack the left pile on top of the right pile. Repeat this operation until there is only one pile of cards. When stacking two piles of ca...
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; int main() { int u[100],d[100],dp[101][101],i,j,k,n; cin >> n; for (i=0;i<100;i++) for (j=0;j<100;j++) dp[i][j]=999999999; for (i=0;i<n;i++) { cin >> u[i] >> d[i]; dp[0][i]=0;} for (i=1;i<n;i++) for (j=0;j<n-i;j++) for (k=0;k<...
At Akabe High School, a programmer training school, there is a unique study session run by the students themselves. It is important for programmers to constantly adopt new technologies, so the aim of this activity is to develop the habit of self-study through this study session. There are a total of N students, each w...
#include<iostream> #include<vector> #include<algorithm> using namespace std; const int MAX = 1e6+1; int score[MAX]; int N,Q; vector<int> leader; vector<int> sc; void input(){ cin >> N >> Q; sc.resize(N); for(int i = 1; i <= N; i++) { cin >> score[i]; sc[i-1] = score[i]; } sort(sc.begin(),sc.end());...
problem Taro bought 10 books. Later, I tried to find out the price based on the receipt, but the receipt was dirty and I could not read the price of a book. We decided to calculate the price of the book from the total price of 10 books and the prices of the other 9 books. Write a program that outputs the price of the...
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; int main() { int sum,n; while(1) { cin>>sum; if(sum==0) break; for(int i=0;i<9;i++) { cin>>n; sum-=n; } cout<<sum<<endl; } return 0; }
Haruna is a high school student. She must remember the seating arrangements in her class because she is a class president. It is too difficult task to remember if there are so many students. That is the reason why seating rearrangement is depress task for her. But students have a complaint if seating is fixed. One da...
#include<iostream> using namespace std; int main() { int r,c; while(cin>>r>>c&&r&&c) { if(r%2==0||c%2==0) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0; }
A scientist discovered a strange variation of amoeba. The scientist named it numoeba. A numoeba, though it looks like an amoeba, is actually a community of cells, which always forms a tree. The scientist called the cell leader that is at the root position of the tree. For example, in Fig. 1, the leader is A. In a numo...
#include<iostream> #include<vector> #include<tuple> #include<algorithm> using namespace std; const int MOD = 12345678; const int NIL = -1; class Numoeba { public: Numoeba(const int n) :max_cell_(1), root_(0) {create_cell(n);} tuple<int, int> die() { for(int step = 1; step <= 500; ++step) { ...
Example Input 2 5 4 5 7 4 8 Output 8 7
#include <cstdio> #include <algorithm> #define N_MAX 150 #define S_MAX 150 #define lld "%lld" typedef long long lnt; const lnt LNF = 0x3F3F3F3F3F3F3FLL; int n, o, i, k, a, b, r[N_MAX], s[N_MAX + 1]; lnt f[2][S_MAX + 2]; int main() { scanf("%d %d %d", &n, &a, &b); for (i = 0; i < n; ++i) scanf("%d %d", &r[i], &s[i])...
Problem Nanatsu has x Umaka sticks and y puffs. There are n candy exchangers. Each exchanger i * Nanatsu-kun's Umaka stick ai book and exchanger's Fugashi bi book * Nanatsu-kun's Fugashi ci book and exchanger's pig meso di pieces It will be exchanged only once by either one of the methods. Under this constraint,...
#include <fstream> #include <iostream> #include <vector> #include <iomanip> #include <algorithm> using namespace std; #define ALL(c) (c).begin(), (c).end() #define REP(i,n) for(ll i=0; i < (n); ++i) #define FOR(i,s,n) for(ll i=s; i < (n); ++i) using ll = long long; using vl = vector<ll>; using vvl = vector<vl>; using ...
You had long wanted a spaceship, and finally you bought a used one yesterday! You have heard that the most difficult thing on spaceship driving is to stop your ship at the right position in the dock. Of course you are no exception. After a dozen of failures, you gave up doing all the docking process manually. You began...
#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 In 200X, the mysterious circle K, which operates at K University, announced K Poker, a new game they created on the 4th floor of K East during the university's cultural festival. At first glance, this game is normal poker, but it is a deeper game of poker with the addition of basic points to the cards. The...
#include<iostream> #include<string> #include<algorithm> using namespace std; int N, a[4][14], b[9]; char T[15] = "-A23456789TJQK"; char U[5] = "SCHD"; string S; pair<int, int>d[5]; int poker() { int e[14], f[9]; int g[14], h[9]; for (int i = 0; i < 14; i++) { e[i] = 0; g[i] = 0; } for (int i = 0; i < 9; i++) { f[i]...
Example Input 3 0 2 7 2 0 4 5 8 0 Output 11
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> VI; int main(){ cin.tie(0); ios::sync_with_stdio(false); int n;cin>>n; vector<VI> cost(n,vector<int>(n)); for(int i=0;i<n;i++)for(int j=0;j<n;j++)cin>>cost[i][j]; ll res=0; for(int i=0;i<n;i++)for(int j=i+1;j<n;j++)re...
G - Revenge of Minimum Cost Flow Problem Statement Flora is a freelance carrier pigeon. Since she is an excellent pigeon, there are too much task requests to her. It is impossible to do all tasks, so she decided to outsource some tasks to Industrial Carrier Pigeon Company. There are N cities numbered from 0 to N-1. ...
#include <bits/stdc++.h> #define MOD 1000000007LL using namespace std; typedef long long ll; typedef pair<int,int> P; int n,m,s,t,f; ll dist[105][105]; ll dist2[105][105]; ll dist3[105][105]; int u[1005],v[1005],a[1005],b[1005],d[1005]; int main(void){ scanf("%d%d%d%d%d",&n,&m,&s,&t,&f); for(int i=0;i<n;i++){ for...
Escape An undirected graph with positive values ​​at the vertices is given. The vertices are numbered from 1 to N, and the i-th vertex has a value of w_i. You can start from the first vertex and move on the graph with the constraint that you cannot pass the edge that you just passed. At each vertex, you can get the sc...
#include<iostream> #include<vector> #include<algorithm> #include<iomanip> #include<sstream> #include<map> #include<queue> using namespace std; #define int long long vector<vector<int> >g; vector<int> v; void dfs(int a) { v[a] = 1; for (int i = 0; i < g[a].size(); i++) { if (v[g[a][i]] == 0) { dfs(g[a][i]); } ...
Mr. Endo wanted to write the code that performs breadth-first search (BFS), which is a search algorithm to explore all vertices on an undirected graph. An example of pseudo code of BFS is as follows: 1: $current \leftarrow \{start\_vertex\}$ 2: $visited \leftarrow current$ 3: while $visited \ne $ the set of all the v...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> l_l; typedef pair<int, int> i_i; template<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T &a, T b) { if(a > b) { ...
Problem GPA is an abbreviation for "Galaxy Point of Aizu" and takes real numbers from 0 to 4. GPA rock-paper-scissors is a game played by two people. After each player gives a signal of "rock-paper-scissors, pon (hoi)" to each other's favorite move, goo, choki, or par, the person with the higher GPA becomes the winner...
#include <bits/stdc++.h> #define rep(i,n)for(int i=0;i<(n);i++) using namespace std; typedef pair<int,int>P; double a[100000]; int main(){ int n;scanf("%d",&n); vector<double>v; rep(i,n){ scanf("%lf",&a[i]); v.push_back(a[i]); } sort(v.begin(),v.end()); rep(i,n){ int low=lower_bound(v.begin(),v.end(),a[i])...
There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation. An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, th...
dat = [] n = int(input()) for i in range(n): dat.append([0] * n) for i in range(n): s = list(map(int, input().split())) for j in range(len(s) - 2): dat[i][s[j + 2] - 1] = 1 for i in range(n): l = list(map(str, dat[i])) print(" ".join(l))
Write a program to simulate rolling a dice, which can be constructed by the following net. <image> <image> As shown in the figures, each face is identified by a different label from 1 to 6. Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the d...
#include<bits/stdc++.h> using namespace std; string t; int a[7]; void move(int i){ int b[7]; for(int n=1;n<7;n++){b[n]=a[n];} if(t[i] == 'S'){ a[1] = b[5]; a[5] = b[6]; a[6] = b[2]; a[2] = b[1]; } if(t[i] == 'W'){ a[1] = b[3]; ...
Chef Ash and Chef Elsh invented a new hash function! Their hash function will map a binary string consisting of characters 'A' and 'E' into an integer called the hash value of the string. The pseudocode of the hash function is as below. hash(S) is the hash value of a binary string S. |S| denotes the length of S. funct...
import sys import math M = 1000000007 rs = {} def fn(An, En, V): global rs, M if V < 0: return 0 try: return rs[An][En][V] except: if rs.has_key(An): if not rs[An].has_key(En): rs[An][En] = {} else: rs[An] = {} rs[An...
Chef loves squares! You are given N points with integers coordinates, Chef asks you to find out how many points he should add to these set of N points, so that one could create at least one square having its vertices from the points of the resulting set. Note that the square created need not to be parallel to the axis....
n = input() s = [] dic = {} for i in range(n): a = map(int,raw_input().split()) s.append(a) foo = str(a[0])+','+str(a[1]) dic[foo] = 1 if n == 0: print '4' elif n == 1: print '3' elif n == 2: print '2' else: ans = 2 for i in range(n-1): for j in range(i+1,n): maxm...
Problem description. Sumit is enjoying his vacations alone in a 2D world (yes, he knows magic), until his GPS tracker stopped working. The great thing about his GPS tracker is that it sends the direction of his traveled path from the starting of his adventure to his best friend. Being his best friend, find Sumit's dire...
for _ in range(0,input()): a,ns,ew=raw_input(),['SOUTH','','NORTH'],['WEST','','EAST'] print ns[int(round((a.count('N')-a.count('S'))/abs(a.count('N')-a.count('S')+.1)))+1]+ ew[int(round((a.count('E')-a.count('W'))/abs(a.count('E')-a.count('W')+.1)))+1]
Problem Description.  Nithin proposed to his girl friend on valentines day. But she had kept a condition that if he answers her task then she will accept his proposal. As Nithin is new to programming, help him in solving the task. Your task is so simple.i.e...you need to find the factorial of a given number.   Input ...
import math print math.factorial(int(raw_input()))
Lucy had recently learned the game, called Natural Numbers. The rules of the game are really simple. There are N players. At the same time, every player says one natural number. Let's call the number said by the i-th player Ai. The person with the smallest unique number (that is, the smallest number that was not said b...
t=int(raw_input()) while(t): t-=1 n=int(raw_input()) table={} ans="Nobody wins." while(n): n-=1 name,num=map(str,raw_input().split()) num=int(num) if num in table: table[num].append(name) else: table[num]=[name] for i in sorted(table): if len(table[i])==1: ans=table[i][0] break print a...
Neha is a cute little sweet girl and considers herself as one of the luckiest girls in the world for having a caring and supporting family especially her cute little younger sister Shreya. But one fine day, due to the harsh side of fate, she loses her family in a car accident. She stays depressed and sadistic for days...
import sys def main(): store={'one':1, 'two':2, 'three':3, 'four': 4, 'five' : 5, 'six' : 6, 'seven' : 7, 'eight' : 8, 'nine' : 9, 'zero' : 0} array=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'zero'] t=int(sys.stdin.readline()) for i in range(...
Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers. Sonya has drawn n numbers in a row, a_i is located in the i-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will giv...
#include <bits/stdc++.h> using namespace std; map<int, int> mp; int vis[100005]; int a[100005]; int main() { int n; scanf("%d", &n); int now = 0; for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); if (!mp[a[i]]) { mp[a[i]]++; now++; } else { mp[a[i]]++; } } long long ans = ...
You are given n rectangles on a plane with coordinates of their bottom left and upper right points. Some (n-1) of the given n rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary. Find any point with integer coordinates that belongs...
#include <bits/stdc++.h> using namespace std; int a[300001]; int b[300001]; int c[300001]; int d[300001]; multiset<int> st1, st2, st3, st4; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i] >> b[i] >> c[i] >> d[i]; st1.insert(a[i]); st2.insert(b[i]); st3.insert(c[i]); st...
Two friends are travelling through Bubble galaxy. They say "Hello!" via signals to each other if their distance is smaller or equal than d_1 and * it's the first time they speak to each other or * at some point in time after their last talk their distance was greater than d_2. We need to calculate how many t...
#Minimum distance between Travel #A from (x1,y1) to (x2,y2); B from (x3,y3) to (x4,y4) def minD(x1,y1,x2,y2,x3,y3,x4,y4): a1=(x2-x4)-(x1-x3) b1=x1-x3 a2=(y2-y4)-(y1-y3) b2=y1-y3 if a1==0 and a2==0: return b1*b1+b2*b2 if 0<=-(a1*b1+a2*b2)<=(a1*a1+a2*a2): return (b1*b1+b2*b2)-1.0*...
Polycarp is working on a new operating system called BerOS. He asks you to help with implementation of a file suggestion feature. There are n files on hard drive and their names are f_1, f_2, ..., f_n. Any file name contains between 1 and 8 characters, inclusive. All file names are unique. The file suggestion feature...
#include <bits/stdc++.h> using namespace std; const long long N = 1e4 + 5; long long n; string a[N]; map<string, set<long long> > m; map<string, string> m2; int32_t main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; cin >> n; for (long long i = 1; i <= n; i++) { cin >> a[i]; for (long long...
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches. The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th par...
import java.util.*; public class given_len_sum_of_dig { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n=scn.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++){ arr[i]=scn.nextInt(); } Stack<Integer> st=new Stack<>(); for(int i=0;i<n;i++){ if(!st.i...
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations. Initially, there are n superheroes in avengers team having powers a_1, a_2, …, a_n, respectively. In one operation, they can r...
#include <bits/stdc++.h> using namespace std; int n, k, m; double sum = 0, res = 0, a[100005]; int main() { scanf("%d%d%d", &n, &k, &m); for (int i = 1; i <= n; i++) scanf("%lf", &a[i]), sum += a[i]; sort(a + 1, a + 1 + n); int t = min(n - 1, m); double ans = 0; for (int i = 0; i <= t; i++) res += a[i],...
You are given a special undirected graph. It consists of 2n vertices numbered from 1 to 2n. The following properties hold for the graph: * there are exactly 3n-2 edges in the graph: n edges connect vertices having odd numbers with vertices having even numbers, n - 1 edges connect vertices having odd numbers with eac...
#include <bits/stdc++.h> using namespace std; long long get() { char ch; while (ch = getchar(), (ch < '0' || ch > '9') && ch != '-') ; if (ch == '-') { long long s = 0; while (ch = getchar(), ch >= '0' && ch <= '9') s = s * 10 + ch - '0'; return -s; } long long s = ch - '0'; while (ch = getc...
Vasya has written some permutation p_1, p_2, …, p_n of integers from 1 to n, so for all 1 ≤ i ≤ n it is true that 1 ≤ p_i ≤ n and all p_1, p_2, …, p_n are different. After that he wrote n numbers next_1, next_2, …, next_n. The number next_i is equal to the minimal index i < j ≤ n, such that p_j > p_i. If there is no su...
#include <bits/stdc++.h> using namespace std; using ll = long long; int n, nxt[500500], g[500500][2], deg[500500], o[500500], s[500500], in[500500], counter; bool ok; void topo(int x) { if (x < 0 || x >= n) return; if (o[x] > 0) return; if (o[x] == -1) { ok = false; return; } o[x] = -1; for (ll ...
This problem differs from the next problem only in constraints. Petya decided to visit Byteland during the summer holidays. It turned out that the history of this country is quite unusual. Initially, there were n different countries on the land that is now Berland. Each country had its own territory that was represen...
#include <bits/stdc++.h> using namespace std; int n; struct rect { int x1, y1, x2, y2; } a[1005]; bool solve(int l, int r) { if (l == r) return true; sort(a + l, a + r + 1, [&](const rect &x, const rect &y) -> bool { return x.x1 < y.x1; }); for (int i = l, mx = 0; i < r; ++i) { mx = max(mx, a[i].x2);...
Let s be a string whose length equals n. Its characters are numbered from 0 to n - 1, i and j are integers, 0 ≤ i < j < n. Let's define function f as follows: f(s, i, j) = s[i + 1... j - 1] + r(s[j... n - 1]) + r(s[0... i]). Here s[p... q] is a substring of string s, that starts in position p and ends in position q (...
#include <bits/stdc++.h> using namespace std; const int prime = 37; const int maxn = 1100000; char a[maxn], b[maxn]; int ha[maxn], hb[maxn], hc[maxn], pp[maxn]; int ll[maxn], rr[maxn]; int n; int main() { gets(a); gets(b); n = strlen(a); if (n != (int)strlen(b) || n <= 1) { puts("-1 -1"); return 0; } ...
You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! <image> Initially Zmei Gorynich has x heads. You can deal n types of blows. If you deal a blow of the i-th type, you decrease the number of Gorynich's heads by min(d_i, curX), there curX is th...
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 7; const int maxN = 50 + 5; int n, x, t, a, b; int main() { ios_base::sync_with_stdio(0); cin >> t; for (int _ = (0); _ <= ((t)-1); ++_) { cin >> n >> x; int maxD = 0, maxDiff = 0; for (int i = (0); i <= ((n)-1); ++i) { cin >> a...
You are given a string s. Each pair of numbers l and r that fulfill the condition 1 ≤ l ≤ r ≤ |s|, correspond to a substring of the string s, starting in the position l and ending in the position r (inclusive). Let's define the function of two strings F(x, y) like this. We'll find a list of such pairs of numbers for w...
#include <bits/stdc++.h> using namespace std; const long long N = 100000; const long long NN = N * 2 + 2; char buf[N + 1]; long long sta[NN][27]; long long tai[NN][27]; long long nxt[NN][27]; long long strsize; long long suflink[NN]; long long capacity; long long node_count; long long act_node; long long act_br; long l...
The MST (Meaningless State Team) company won another tender for an important state reform in Berland. There are n cities in Berland, some pairs of the cities are connected by roads. Each road has its price. One can move along any road in any direction. The MST team should carry out the repair works on some set of road...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:65777216") using namespace std; struct Edge { int x, y, w, id; Edge() { id = -1; } bool operator<(const Edge &s) const { return w < s.w; } }; int n, m, k; Edge e[111111]; int p[5555]; int P(int v) { return p[v] == v ? v : p[v] = P(p[v]); } void join(int p1,...
Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute. On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a ...
kl=int(input()) for l in range(kl): p=[int(i) for i in input().split()] a=min(p[0], p[1]) b=max(p[0], p[1]) tn=p[2]-p[3] tk=p[2]+p[3] if tn>=b or tk<=a: print(b-a) else: if tn>=a: print((b-a) - (min(b, tk)-tn)) else: print((b-a) -(min(b, tk)-a)...
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers: In the decimal representation of s: * s > 0, * s consists of n digits, * no digit in s equals 0, * s is not divisible by any of it's digits. Input The input consists of mult...
t = int(input()) for i in range(t): n = int(input()) if n == 1: print(-1) else: base = int('2' * n) + 1 print(int('2' + '3' * (n - 1)))
Piet Mondrian is an artist most famous for his minimalist works, consisting only of the four colors red, yellow, blue, and white. Most people attribute this to his style, but the truth is that his paint behaves in a very strange way where mixing two primary colors only produces another primary color! <image> A lesser ...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast,inline,unroll-loops,fast-math") using namespace std; const bool d[3][2][2] = { { {false, true}, {true, false}, }, { {true, false}, {true, true}, }, { {true, true}, {false, true}, }, }; bitset<202...
You are given a simple weighted connected undirected graph, consisting of n vertices and m edges. A path in the graph of length k is a sequence of k+1 vertices v_1, v_2, ..., v_{k+1} such that for each i (1 ≤ i ≤ k) the edge (v_i, v_{i+1}) is present in the graph. A path from some vertex v also has vertex v_1=v. Note ...
#include <bits/stdc++.h> using namespace std; const int N = 2010; const int mod = 1000000007; int dp[N][N]; vector<int> v[N], w[N]; pair<int, int> a[N], b[N]; void update(int &first, int second) { if (first == -1 || first < second) first = second; } int main() { int n, m, r; scanf("%d%d%d", &n, &m, &r); memset(...
This problem is split into two tasks. In this task, you are required to find the maximum possible answer. In the task Village (Minimum) you are required to find the minimum possible answer. Each task is worth 50 points. There are N houses in a certain village. A single villager lives in each of the houses. The houses ...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; vector<int> g[maxn]; int sub[maxn]; int dep[maxn]; int a[maxn]; vector<int> order; void dfs(int x, int par) { sub[x] = 1; order.push_back(x); for (auto i : g[x]) { if (i != par) { dep[i] = 1 + dep[x]; dfs(i, x); sub[x] ...
You are given an integer n. You should find a list of pairs (x_1, y_1), (x_2, y_2), ..., (x_q, y_q) (1 ≤ x_i, y_i ≤ n) satisfying the following condition. Let's consider some function f: N × N → N (we define N as the set of positive integers). In other words, f is a function that returns a positive integer for a pair...
import java.util.*; import java.io.*; public class CFF { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final Str...
This is an interactive problem. To prevent the mischievous rabbits from freely roaming around the zoo, Zookeeper has set up a special lock for the rabbit enclosure. This lock is called the Rotary Laser Lock. The lock consists of n concentric rings numbered from 0 to n-1. The innermost ring is ring 0 and the outermos...
#include <bits/stdc++.h> const int MN = 110; const int MM = 25; int N, M, W, cur, loc[MN]; bool inc; std::vector<int> rem; int query(int r, int d) { printf("? %d %d\n", r, d); fflush(stdout); int a; scanf("%d", &a); std::swap(cur, a); return cur - a; } int main() { scanf("%d%d", &N, &M), W = N * M; quer...
There are n + 2 towns located on a coordinate line, numbered from 0 to n + 1. The i-th town is located at the point i. You build a radio tower in each of the towns 1, 2, ..., n with probability 1/2 (these events are independent). After that, you want to set the signal power on each tower to some integer from 1 to n (s...
def power(a, b, mod): res = 1 while b: if b%2: res = (res*a)%mod b //= 2 a = (a*a)%mod return res%mod def divide(a, b, mod): return (a * power(b, mod-2, mod)) % mod n = int(input()) MOD = 998244353 fib = [0, 1] for i in range(2, 20000...
You have a statistic of price changes for one product represented as an array of n positive integers p_0, p_1, ..., p_{n - 1}, where p_0 is the initial price of the product and p_i is how the price was increased during the i-th month. Using these price changes you are asked to calculate the inflation coefficients for ...
#include<iostream> #include<algorithm> using namespace std; int main() { int t; cin>>t; while(t--) { int n,k; long long a[110]; long long int sum=0,s[110]={0}; cin>>n>>k; for(int i=1;i<=n;i++) { scanf("%lld",&a[i]); s[i]=a[i]+s[i-1]...
Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should! Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment 0. Also, let's say that the train will visit n stations numbered from 1 to n along its way, and ...
#include <bits/stdc++.h> using namespace std; #define ll long long int main() { ios::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while(tc-- > 0) { int n; cin >> n; vector<int> a(n+1), b(n+1), t(n+1); for(int i = 1; i <= n; i++) { cin >> a[i] >>...
This is the hard version of the problem. The only difference is that in this version n ≤ 200000. You can make hacks only if both versions of the problem are solved. There are n potions in a line, with potion 1 on the far left and potion n on the far right. Each potion will increase your health by a_i when drunk. a_i c...
#include <bits/stdc++.h> using namespace std; #define ll long long const ll int N= 1000000007; int main() {ios_base::sync_with_stdio(false); /*int t;cin>>t; while(t--){*/ int n;cin>>n; ll int a[n]; for(int i =0;i<n;i++) cin>>a[i]; priority_queue<ll int, vector<ll int>, ...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
import sys n,k=[int(i) for i in sys.stdin.readline().split()] a=[int(i) for i in sys.stdin.readline().split()] count=0 for e in a: if e>=a[k-1] and e>0: count+=1 print count
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants. The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different citie...
#include <bits/stdc++.h> using namespace std; const int N = 300010; const int L = 20; bool used[N]; int tin[N], fup[N], timer; vector<int> g[N]; void dfs(int v, int p = -1) { used[v] = true; tin[v] = fup[v] = ++timer; for (int i = 0; i < (int)g[v].size(); i++) { int to = g[v][i]; if (to == p) continue; ...
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th...
import re def from_excel(item): row = ''.join([s for s in item if s.isdigit()]) column = excel_to_column(item.replace(row, '')) return 'R{0}C{1}'.format(row, column) def to_excel(item): row, column = item.split('C') row, column = int(row.replace('R', '')), int(column) column = column_to_exce...
A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([...
#include <bits/stdc++.h> using namespace std; const double pi = 3.14159265358979; int main() { string s; deque<pair<int, char> > t; vector<pair<int, int> > a; cin >> s; int l = 0, r = -1, ans = 0, tl = s.length(), tr = -1, temp; for (int i = 0; i < s.length(); ++i) { if (s[i] == ']') { if (!t.empt...
It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And ye...
import java.io.*; import java.util.*; public class ProblemA { InputReader in; PrintWriter out; double y1, y2, yb, yw, xb, r; double yy1, yy2, yyt, yt; void solve() { y1 = in.nextDouble(); y2 = in.nextDouble(); yw = in.nextDouble(); xb = in.nextDouble(); yb = in.n...
Little Dima has two sequences of points with integer coordinates: sequence (a1, 1), (a2, 2), ..., (an, n) and sequence (b1, 1), (b2, 2), ..., (bn, n). Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in th...
#include <bits/stdc++.h> using namespace std; const int MAXN = 200005; int n, MOD; pair<int, int> s[MAXN]; int main() { scanf("%d", &n); int m = 0; for (int i = 1; i <= n; i++) { int a, b; scanf("%d", &a); s[++m] = make_pair(a, i); } for (int i = 1; i <= n; i++) { int a, b; scanf("%d", &a)...
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the grap...
#include <bits/stdc++.h> using namespace std; int const mxsz = 509; long long w[mxsz][mxsz]; bool ver[mxsz]; int main() { vector<int> er; vector<long long> res; int n; scanf("%d", &n); er.resize(n); for (int i = 0; i < n; ++i) { int x; for (int j = 0; j < n; ++j) { scanf("%d", &x); w[i][...
Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order...
s = raw_input().strip() c = s.count('@') if c == 0: print "No solution" exit() s = s.split('@') if c == 1: if len(s[0]) < 1 or len(s[1]) < 1: print "No solution" exit() print s[0] + '@' + s[1] exit() if len(s[0]) < 1: print "No solution" exit() if len(s[len(s)-1]) < 1: print "No solution" exit() for i in ...
Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule. A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form one...
#include <bits/stdc++.h> using namespace std; inline bool checkBit(long long n, int i) { return n & (1LL << i); } inline long long setBit(long long n, int i) { return n | (1LL << i); ; } inline long long resetBit(long long n, int i) { return n & (~(1LL << i)); } string makeintString(int x) { stringstream ss; ss...
Sereja has m non-empty sets of integers A1, A2, ..., Am. What a lucky coincidence! The given sets are a partition of the set of all integers from 1 to n. In other words, for any integer v (1 ≤ v ≤ n) there is exactly one set At such that <image>. Also Sereja has integer d. Sereja decided to choose some sets from the s...
#include <bits/stdc++.h> using namespace std; const long long UNDEF = -1; const long long INF = 1e18; template <typename T> inline bool chkmax(T& aa, T bb) { return aa < bb ? aa = bb, true : false; } template <typename T> inline bool chkmin(T& aa, T bb) { return aa > bb ? aa = bb, true : false; } static char stdinB...
On the Berland Dependence Day it was decided to organize a great marathon. Berland consists of n cities, some of which are linked by two-way roads. Each road has a certain length. The cities are numbered from 1 to n. It is known that one can get from any city to any other one by the roads. n runners take part in the c...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1, ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch - '0'); ch = getchar(); } return f == 1 ? x : -x; } inlin...
The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor. At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information ...
import java.util.Scanner; import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author ba...
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited. Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi...
import sys [n,d] = [int(x) for x in sys.stdin.readline().split()] times = [int(x) for x in sys.stdin.readline().split()] if d < (sum(times) + (len(times)-1)*10): print -1 else: print (d - sum(times))/5
Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noti...
import java.io.*; import java.util.*; public class Solution { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; static final int P = 1000000007; void solve() throws IOException { int n=nextInt(); int m=nextInt(); int w=nextInt(); long a[]=ne...
You are given a sequence a consisting of n integers. Find the maximum possible value of <image> (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj. Input The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105). The second line contains n space-separated integers ai (1 ≤ a...
import java.io.*; import java.util.*; public class c { static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n = ni(); int v[] = new int[1000008]; int f[] = new int[1000008]; int a[] = new int[n]; for(int i=0;i<n;i++) v[ni()]=1; ...
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer. Reliable sources have informed the financier Anton of some information about the exchange rate of...
n=list(input()) k=int(n[-1]) m=0 for i in range(len(n)): z=int(n[i]) if(z%2==0): temp=i m=1 if(z<k): break if(m==0): print("-1") else: n[-1],n[temp]=n[temp],n[-1] print("".join(n))
Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable. In total the table Arthur bought has n legs, the length of the i-th leg is li. Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number di — the a...
#include <bits/stdc++.h> using namespace std; void Emsawy() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); } const double PI = acos(-1.0); const double eps = 1e-10; const long long mod = 1e9 + 7, oo = 1e9; int dx[]{1, -1, 0, 0, 1, -1, 1, -1}; int dy[]{0, 0, 1, -1, 1, -1, -1, 1}; int n, m, k, c; const int...
City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them. Sand roads have long been recognized out of date, so the decision was made to asphal...
n=input() row=[0]*n col=[0]*n ans="" for i in range(n**2): x,y=map(int,raw_input().split()) if row[x-1] or col[y-1]: continue else: row[x-1]=1 col[y-1]=1 ans+=str(i+1)+" " print ans
An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it...
#include <bits/stdc++.h> using namespace std; int n, x, l, ans; int dp[100010], a[100010]; int main() { int i, j; cin >> n; for (i = 1; i <= n; i++) { scanf("%d", a + i); } for (i = 1; i <= n; i++) { dp[a[i]] = dp[a[i] - 1] + 1; ans = max(ans, dp[a[i]]); } cout << n - ans << endl; }
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but ...
#include <bits/stdc++.h> using namespace std; int Int() { int x; scanf("%d", &x); return x; } long long Long() { long long x; scanf("%lld", &x); return x; } double Double() { double x; scanf("%lf", &x); return x; } float Float() { float x; scanf("%f", &x); return x; } const int N = 1e5 + 5; vect...
There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one. We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while pa...
#include <bits/stdc++.h> using namespace std; int main() { int n, ans = 0; map<int, int> mp; cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; mp[x]++; if (mp[x] > ans) ans = mp[x]; } cout << n - ans; return 0; }
100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet. The following game was chosen for the fights: initially there is a polynom...
def main(): n, k = map(int, input().split()) aa = [] for i in range(n + 1): s = input() aa.append(None if s == '?' else int(s)) qm_cnt = aa.count(None) if k: if qm_cnt: print('Yes' if n & 1 else 'No') else: x = 0 for a in reversed(a...
Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in <image>, which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find t...
from typing import TypeVar, Generic, Callable, List import sys from array import array # noqa: F401 from collections import Counter def input(): return sys.stdin.buffer.readline().decode('utf-8') minf = -10**9 - 100 T = TypeVar('T') class SegmentTree(Generic[T]): __slots__ = ["size", "tree", "identity"...
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration. Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar...
n,k=map(int,input().split()) l1=[0]*101 for i in range(0,n): s=input() l1[len(s)]+=1 pword=input() x=len(pword) best=0 worst=0 best+=sum(l1[:x]) best=best+(best//k)*5 +1 worst+=sum(l1[:x+1])-1 worst=worst+(worst//k)*5+1 print(best,worst)
Note that girls in Arpa’s land are really attractive. Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs wer...
#include <bits/stdc++.h> using namespace std; long long int n, q, k, a1, b, i, j, cn, col[223456], vis[223456], inp[223456], inp1[223456]; vector<vector<long long int> > g(223456); void dfs(long long int u, long long int par) { if (vis[u]) return; vis[u] = 1; col[u] = col[par] == 1 ? 2 : 1; for (auto &it : ...
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check ...
//package credit; import java.awt.*; import java.io.*; import java.lang.management.ClassLoadingMXBean; import java.sql.SQLIntegrityConstraintViolationException; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.Str...
Haiku is a genre of Japanese traditional poetry. A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syll...
#include <bits/stdc++.h> using namespace std; int counting(string s) { int ans = 0; for (__typeof((s).begin()) it = (s).begin(); it != (s).end(); ++it) { switch (*it) { case 'a': case 'i': case 'u': case 'e': case 'o': ans++; break; } } return ans; } int mai...
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * * @author Parth */ public class DoYouWantDate { public static long MOD = 1000000007; ...
In the Kingdom K., there are n towns numbered with integers from 1 to n. The towns are connected by n bi-directional roads numbered with integers from 1 to n. The i-th road connects the towns ui and vi and its length is li. There is no more than one road between two towns. Also, there are no roads that connect the town...
#include <bits/stdc++.h> using namespace std; int n, cnt, tot, dfsclk, pos[400005], fst[400005], pnt[400005 << 1], len[400005 << 1], nxt[400005 << 1], a[400005], b[400005], c[400005], fa[400005]; long long f[400005], u1[400005], u2[400005], v1[400005], v2[400005], ans; bool ok[400005]; void add(int x, int y, in...
Let us call a non-empty sequence of lowercase English letters a word. Prefix of a word x is a word y that can be obtained from x by removing zero or more last letters of x. Let us call two words similar, if one of them can be obtained from the other by removing its first letter. You are given a set S of words. Find t...
#include <bits/stdc++.h> using namespace std; const int mods[] = {479001599, 433494437, 1073807359, 1442968193, 715827883, 1000000007, 1000000009}; const int ps[] = {101, 233, 457, 173, 211, 131, 563}; const int maxn = 1e6 + 10; int mod[2], p[2], dp[2][maxn]; string s[maxn]; bool v[maxn]; int cadd(...
There are n military men in the Berland army. Some of them have given orders to other military men by now. Given m pairs (xi, yi), meaning that the military man xi gave the i-th order to another military man yi. It is time for reform! The Berland Ministry of Defence plans to introduce ranks in the Berland army. Each m...
#include <bits/stdc++.h> using namespace std; void test_case() { int n, m, k; cin >> n >> m >> k; vector<int> out(n), p(n); vector<vector<int> > g1(n), g2(n); for (int i = 0; i < n; i++) cin >> p[i]; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; a--; b--; g1[a].push_back(b); ...
Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating." The class can be represented as a matrix with n rows and m col...
#include <bits/stdc++.h> using namespace std; const int oo = 0x3f3f3f3f; const long long ooo = 9223372036854775807ll; const int _cnt = 1000 * 1000 + 7; const int _p = 1000 * 1000 * 1000 + 7; const int N = 200005; const double PI = acos(-1.0); const double eps = 1e-9; int o(int x) { return x % _p; } int gcd(int a, int b...
A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right. Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the p...
var a = []; for (var i = 0; i < 6; i++) { a[i] = readline(); } var good = [ [3, 3, -1, 4, 4, -1, 3, 3], [3, 3, -1, 4, 4, -1, 3, 3], [2, 2, -1, 3, 3, -1, 2, 2], [2, 2, -1, 3, 3, -1, 2, 2], [1, 1, -1, 2, 2, -1, 1, 1], [1, 1, -1, 2, 2, -1, 1, 1], ]; bx = -1; by = -1; for ...
Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a gr...
def go(s): d = {} for c in s: d[c] = d.get(c, 0) + 1 if len(d.keys()) > 4 or len(d.keys()) == 1: return 'No' if len(d.keys()) == 2: if 1 in d.values(): return 'No' else: return 'Yes' if len(d.keys()) == 3: if sum(d.values()) > 3: ...
Mr Keks is a typical white-collar in Byteland. He has a bookshelf in his office with some books on it, each book has an integer positive price. Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office. He learned that in the ne...
from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') def pr_arr(arr): for i in arr: std...
Sometimes inventing a story for the problem is a very hard task. Fortunately for us, Limak has just been kidnapped by an insane mathematician. We need some name for the mathematician and let it be Mathew. Limak is a little polar bear. He has been kidnapped and now must deal with puzzles invented by Mathew. There were ...
#!/usr/bin/env python from sys import stdin, stderr ans = [ 0, 1, 2, 8, 68, 1504, 127792, 57140352, 258023200384, 10151395367145472L, 3673835865235792306176L, 13318668301694192513859649536L, 531680718673514734573555796872790016L ] def main(): TC = int(stdin.readline().strip()) for tc in xrange(TC): n, m...
Big P is fairly good in mathematics. His teacher has asked him to add two numbers. Now , Big P has a problem that he sometimes writes a '6' as a '5' and vice versa. Given two numbers, A and B, calculate the minimum and the maximum sum Big P could possibly get. Input: The first and only line of input contains positive...
m,n=map(int,raw_input().split()) add=m+n a=0 temp=add if ('5' in str(n)) or ('6' in str(n)): while n>0: b=n%10 if b==6: temp-=(10**a) if b==5: add+=(10**a) n=n/10 a+=1 if ('5' in str(m)) or ('6' in str(m)): a=0 while m>0: b=m%10 if b==6: temp-=(10**a) if b==5: add+=(10**a) m=m/10 ...
Given K prime numbers and T queries of form Ai, Bi, for each query print the number of integers between Ai and Bi (both inclusive) that are divisible by atleast one of the K given primes. Input First line: K and T. Second line: K primes. Next T lines, each contain Ai, Bi. Output Print T lines, denoting the ...
k,t=map(int,raw_input().split()) klis=list(map(int,raw_input().split())) for _ in xrange(t): ans=0 a,b=map(int,raw_input().split()) for i in xrange(1,2**k): l,r=a-1,b par=0 for j in xrange(k): if(i&(1<<j)): par+=1 l/=klis[j] r/=klis[j] if(par&1): ans+=(r-l) else: ans-=(r-l) print ans
Ross and Rachel are on a date. Ross, being the super geek he is, takes Rachel to see dinosaur exhibits. Each dinosaur has a name and K attributes which are described by an ordered K-tuple ( A1, A2, A3,..., AK ). Each attribute Ai is an integer between 0 to L inclusive. Ross tells Rachel about N dinosaurs. For each din...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' n,k,l,q=raw_input().split() n=int(n) k=int(k) l=int(l) q=int(q) din_dict={} din_set=[] for i in range(n): string=raw_input().split() din_name=string[0] ans='' for x in string[1:]:...