input
stringlengths
29
13k
output
stringlengths
9
73.4k
PCK is playing a game tournament together. In this game tournament, the rankings will be changed by the ghost leg at the end of the tournament. There are N players in the tournament, and there are N vertical bars in the Amidakuji. The Amidakuji is made up of N-1 stage parts as shown in the figure, and each is assigned...
#include<bits/stdc++.h> using namespace std; #define MAX_V 1000 int N,a; vector<int> G[MAX_V]; int match[MAX_V]; bool used[MAX_V]; bool dfs(int v){ used[v]=true; for(int i=0;i<(int)G[v].size();i++){ int u=G[v][i],w=match[u]; if( w<0 || (!used[w]&&dfs(w)) ){ match[u]=v; match[v]=u; return...
problem During this time of winter in Japan, hot days continue in Australia in the Southern Hemisphere. IOI, who lives in Australia, decided to plan what clothes to wear based on the weather forecast for a certain D day. The maximum temperature on day i (1 ≤ i ≤ D) is predicted to be Ti degrees. IOI has N kinds of cl...
#include<bits/stdc++.h> using namespace std; int dp[200][101]; int d, n, days[200], ans = 0; struct cloth{ int a, b, c; }; cloth clothes[200]; int dfs(int day, int point){ if(day == d) return 0; if(~dp[day][point]) return dp[day][point]; int res = 0; for(int i = 0; i < n; i++){ if(clothes[i].a...
You have full control over a robot that walks around in a rectangular field paved with square tiles like a chessboard. There are m columns of tiles from west to east, and n rows of tiles from south to north (1 <= m, n <= 100). Each tile is given a pair of coordinates, such as (i, j), where 1 <= i <= m and 1 <= j <= n. ...
#include <iostream> #include <string> using namespace std; int main() { int s, t, u, d, w, h; string str; while(1){ cin >> w >> h; if(w == 0 && h == 0){ break; } s = t = 1; d = 0; while(1){ cin >> str; if(str == "STOP"){ break; } else if(str == "FORWARD"){ cin >> u; if(d == 0)...
Your company’s next product will be a new game, which is a three-dimensional variant of the classic game “Tic-Tac-Toe”. Two players place balls in a three-dimensional space (board), and try to make a sequence of a certain length. People believe that it is fun to play the game, but they still cannot fix the values of s...
#include <bits/stdc++.h> using namespace std; int a[10][10][10],c[10][10],N; bool visited[10][10][10]; bool valid(int x,int y,int z){ if(0 > x || N <= x) return false; if(0 > y || N <= y) return false; if(0 > z || N <= z) return false; if(a[y][x][z] == -1) return false; return true; } int check(int x,int ...
Problem C Medical Checkup Students of the university have to go for a medical checkup, consisting of lots of checkup items, numbered 1, 2, 3, and so on. Students are now forming a long queue, waiting for the checkup to start. Students are also numbered 1, 2, 3, and so on, from the top of the queue. They have to under...
#include<bits/stdc++.h> using namespace std; #define fs first #define sc second #define mp make_pair #define pb push_back #define eb emplace_back #define ALL(A) A.begin(),A.end() #define RALL(A) A.rbegin(),A.rend() typedef long long LL; typedef pair<int,int> P; const LL mod=1000000007; const LL LINF=1LL<<62; const LL I...
Development of Small Flying Robots <image> You are developing small flying robots in your laboratory. The laboratory is a box-shaped building with K levels, each numbered 1 through K from bottom to top. The floors of all levels are square-shaped with their edges precisely aligned east-west and north-south. Each floo...
#include <bits/stdc++.h> using namespace std; const int INF = INT_MAX; template <class T> pair<vector<T>, map<T, int> > compress(vector<T>& a) { vector<T> v; for(int i = 0; i < a.size(); i++) v.push_back(a[i]); sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); map<T, int> m; for(int i = 0; ...
Advanced Computer Music (ACM) sold a rhythm machine that plays music according to a pre-programmed rhythm. At one point, ACM was trying to develop and sell a new rhythm machine. While ACM's old product could only play one sound at a time, the new product was able to play up to eight sounds at the same time, which was t...
#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 std; long long gc...
You are playing a popular video game which is famous for its depthful story and interesting puzzles. In the game you were locked in a mysterious house alone and there is no way to call for help, so you have to escape on yours own. However, almost every room in the house has some kind of puzzles and you cannot move to n...
#include <iostream> #include <vector> #include <queue> #include <string> #include <algorithm> #include <cstring> using namespace std; // ツサツイツコツδ債づ個姪環づ個遷ツ暗堋表ツ.ツ姪環氾板債づ債,ツ湘」ツ,ツ債カツ,ツ青ウツ姪環,ツ可コツ,ツ右ツ,ツ背ツ姪環づ個渉. char dice[6][4] = { {5,2,1,4}, {1,1,3,0}, {0,3,2,2}, {2,5,4,1}, {4,4,0,3}, {3,0,5,5} }; int main(){ int step[6...
Time passed and Taro became a high school student. Under the influence of my older brother who was a college student, I began to be interested in computer science. Taro read through computer science textbooks and learned that there was a famous problem called the "longest increase subsequence problem." Taro understood ...
#include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) using namespace std; const int64_t INF = INT64_C(100000000000000); int main() { int n; cin>>n; vector<int64_t> a(n); REP(i,n)cin>>a[i]; vector<map<int64_t, pair<int,int>>> dp(n+1); dp[0][-INF] = make_pair(0,0); REP(i,n){ int64_t...
golf Croce is a battle programmer with top-notch skills, and no one in the programming contest neighborhood knows his name. Algorithms, data mining, hacking, AI, ... I've swept all kinds of competitions. The competition that Kurose set as his next goal is "code golf." Code golf is a competition for the "shortness of ...
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll OF_MAX = (1LL<<36)-1; const ll LEN_MAX = 11; ll LENGTH[LEN_MAX+1]; inline ll mul(const ll &a, const ll &b){ if(!a || !b)return 0; if( b > OF_MAX/a )return OF_MAX+1; return a*b; } inline int len(const ll &a){ return upper_bound(LENGTH...
F --Land inheritance Problem Statement One $ N $ brother was discussing the inheritance of his parents. The vast heritage left by their parents included vast lands. The land has a rectangular shape extending $ H $ km from north to south and $ W $ km from east to west. This land is managed in units of 1 km square, 1 k...
#include <bits/stdc++.h> using vi = std::vector<int64_t>; using vvi = std::vector<vi>; int H, W, N; vvi values; int topFind(int, int, int, int, int64_t); int bottomFind(int, int, int, int, int64_t); int leftFind(int, int, int, int, int64_t); int rightFind(int, int, int, int, int64_t); bool condition(int, int, int, i...
problem AOR Co., Ltd. is a $ N $ story building. There is no basement floor. AOR Ika-chan is a squid, so she can go down the stairs, but not up. I decided to install $ M $ elevators in the building because it would be inconvenient if I couldn't climb upstairs. It takes time to install the elevator, and the $ i $ th e...
#ifndef VS #include<bits/stdc++.h> #endif using namespace std; typedef long long LL; #ifdef BTK #define DEBUG if(1) #else #define CIN_ONLY if(1) struct cww {cww() {CIN_ONLY{ios::sync_with_stdio(false); cin.tie(0);}} }star; #define DEBUG if(0) #endif #define ALL(v) (v).begin(),(v).end() #define REC(ret, ...) std::fun...
Problem There are $ N $ balls, each with its own color and value. There are $ C $ types of ball colors from $ 1 $ to $ C $, and each color has an upper limit on the number of balls that can be selected. Maximize the total value you get when choosing at most $ M $ balls in total. Constraints The input satisfies the f...
#include <iostream> #include <algorithm> using namespace std; int N, M, C, l[100009], c[100009], w[100009], p[100009]; int main() { cin >> N >> M >> C; for (int i = 0; i < C; i++) cin >> l[i]; for (int i = 0; i < N; i++) cin >> c[i] >> w[i], p[i] = i, c[i]--; sort(p, p + N, [](int i, int j) { return w[i] > w[j]; })...
Areas on the Cross-Section Diagram Your task is to simulate a flood damage. For a given cross-section diagram, reports areas of flooded sections. <image> Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides. For example, for the abov...
#include <iostream> #include <algorithm> #include <stack> #include <vector> using namespace std; int main(int argc, char* argv[]) { stack<int> s1; stack<pair<int ,int> > s2; char ch; int sum = 0; for (int i = 0; cin >> ch; ++i) { if (ch == '\\') s1.push(i); else if (ch == '/' && s1.size() > 0) { int j = s...
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula: \\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\] where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ res...
n,m,l = map(int,input().split()) A = [list(map(int,input().split())) for i in range(n)] B = [list(map(int,input().split())) for j in range(m)] C = [[0 for k in range(l)]for i in range(n)] for i in range(n) : for k in range(l) : for j in range(m) : C[i][k] = C[i][k] + A[i][j] * B[j][k] for i in range(n): ...
Virat is a guy who likes solving problems very much. Today Virat’s friend Jadega gave him a problem to solve. Jadeja gives Virat three numbers: N, L and R and Virat has to find out the count of numbers between L and R (both inclusive) which are divisible by at least 1 prime number belonging to range 1 to N (inclusive)....
from itertools import combinations as c def primes(n): """ Returns a list of primes < n """ sieve = [True] * n for i in xrange(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] for i in range(input()): ...
Since the finance department of MAKAUT has lots of bills to pass and funds to allocate for puja and freshers so there is a mess in Finance Officer's office. Although he has numbered all type of files from 0-9, all his files got jumbled up. Aaroti Di however arranged all of them to form a big integer n and presented it ...
t=int(raw_input()) for i in range(t): n=raw_input() q=raw_input() print n.count(q)
It was exam time in pesce, mandya and Rubal was feeling hungry.However being late night and exam time he decided to look for snacks in every room.However because of his bad luck he missed the room which actually had snacks.Help him to find the room number which he missed. The rooms in the hostel are in the range 1 to N...
import sys t=int(sys.stdin.readline()) for k in xrange(t): n=int(sys.stdin.readline()) s=(n*(n+1))/2 a=map(int,sys.stdin.readline().split()) s=s-sum(a) sys.stdout.write("%d\n"%s)
You have a matrix of size N * N with rows numbered through 1 to N from top to bottom and columns through 1 to N from left to right. It contains all values from 1 to N^2, i.e. each value from 1 to N^2 occurs exactly once in the matrix. Now, you start from the cell containing value 1, and from there visit the cell with...
t = input() for _ in xrange(t): n = input() loc = {} for i in xrange(n): row = map(int, raw_input().split()) k = 0 for j in row: loc[j] = i, k k += 1 steps = 0 r, c = loc[1] for i in xrange(2, n * n + 1): rw, cl = loc[i] steps += ab...
Little Ron of Byteland was poor at mathematics. He always used to get zero marks in mathematics test. One evening when he showed his result to his father, his father scolded him badly. So, he thought if zeroes were not there in this world how good the world would have been. The next day he was given an assignment by hi...
t=input() while t: x,y=map(int,raw_input().split()) res=x+y res=list(str(res)) while '0' in res: res.remove('0') x=list(str(x)) y=list(str(y)) while '0' in x: x.remove('0') while '0' in y: y.remove('0') res1=int(''.join(x))+int(''.join(y)) res1=str(res1) ...
A version control system(VCS) is a repository of files, often the files for the source code of computer programs, with monitored access. Every change made to the source is tracked, along with who made the change, why they made it, and references to problems fixed, or enhancements introduced, by the change. Version c...
for i in range(input()): a,b,c=map(int,raw_input().split()) count = [0]*(a+1) ar1 = map(int,raw_input().split()) ar2=map(int,raw_input().split()) for i in ar1: count[i]+=1 for i in ar2: count[i]+=1 trig =0 untunig = 0 for i in range(1,a+1): if(count[i]==2): trig+=1 if(count[i]==0): untunig+=1 pr...
By the year 3018, Summer Informatics School has greatly grown. Hotel «Berendeetronik» has been chosen as a location of the school. The camp consists of n houses with n-1 pathways between them. It is possible to reach every house from each other using the pathways. Everything had been perfect until the rains started. T...
#include <bits/stdc++.h> using std::lower_bound; using std::max; using std::min; using std::random_shuffle; using std::reverse; using std::sort; using std::swap; using std::unique; using std::upper_bound; using std::vector; void open(const char *s) {} int rd() { int s = 0, c, b = 0; while (((c = getchar()) < '0' ||...
Petya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array. Now he wonders what is the number of segments in his arra...
import java.util.*; import java.io.*; public class File { public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st =...
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i. Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make towe...
#include <bits/stdc++.h> using namespace std; int a[200005]; const int inf = 0x3f3f3f3f; int main() { int n, m; scanf("%d%d", &n, &m); int mn = inf; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); mn = min(mn, a[i]); } for (int i = 1; i <= n; i++) { a[i] -= mn; } sort(a + 1, a + n + 1, gr...
Given an integer x, find 2 integers a and b such that: * 1 ≤ a,b ≤ x * b divides a (a is divisible by b). * a ⋅ b>x. * a/b<x. Input The only line contains the integer x (1 ≤ x ≤ 100). Output You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in...
#include <bits/stdc++.h> int x; int main() { scanf("%d", &x); if (x != 1) { printf("%d %d", x, x); } else printf("-1"); }
You are given a sequence s consisting of n digits from 1 to 9. You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the ...
for _ in range(int(input())): n = int(input()) z = input() if n==2 and z[0]>=z[1]: print("NO") else: print("YES") print(2) print(z[0],z[1::])
After lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page. Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the fi...
n=int(input()) p=[] for x in range(n): a,b=list(map(int,input().split())) sam=list(range(a,b+1)) p.append(sam) kam=int(input()) for x in p: if kam in x: print(n-p.index(x)) break
There are n students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team. The i-th student has integer programming skill a_i. All programming skills are distinct and between 1 and n, inclusive. Firstly, the first coach will choose ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 5; int n, k, a[MAXN], ans[MAXN], op; int idx[MAXN], pre[MAXN], nex[MAXN]; void del(int x) { int l = x, r = x; for (int i = 1; i <= k + 1; i++) { idx[a[l]] = idx[a[r]] = -1; ans[l] = ans[r] = op; l = pre[l], r = nex[r]; } nex[l] = r...
You are given an array a consisting of n integers. Each a_i is one of the six following numbers: 4, 8, 15, 16, 23, 42. Your task is to remove the minimum number of elements to make this array good. An array of length k is called good if k is divisible by 6 and it is possible to split it into k/6 subsequences 4, 8, 15...
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) { int n=0; Scanner s = new Scanner(System.in); n=s.nextInt(); int A[]= new int[n]; long count4=0; long count8=0; long count15=0; long count16=0;long count23=0;long count42=...
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia. For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remainin...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n, k; cin >> n >> k; for (long long i = 1; i <= n; i++) { if ((i * (i + 1)) / 2 >= k && i + (i * (i + 1)) / 2 - k == n) { cout << (i * (i + 1)) / 2 - k << endl; return ...
You are given a string s consisting of lowercase Latin letters and q queries for this string. Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top". There are two types of queries: ...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 1; const int base = 1e9 + 7; template <typename T> void Read(T& x) { bool Neg = false; char c; for (c = getchar(); c < '0' || c > '9'; c = getchar()) if (c == '-') Neg = !Neg; x = c - '0'; for (c = getchar(); c >= '0' && c <= '9'; c = ge...
Tsumugi brought n delicious sweets to the Light Music Club. They are numbered from 1 to n, where the i-th sweet has a sugar concentration described by an integer a_i. Yui loves sweets, but she can eat at most m sweets each day for health reasons. Days are 1-indexed (numbered 1, 2, 3, …). Eating the sweet i at the d-t...
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitS...
There are n positive integers a_1, a_2, ..., a_n. For the one move you can choose any even value c and divide by two all elements that equal c. For example, if a=[6,8,12,6,3,12] and you choose c=6, and a is transformed into a=[3,8,12,3,3,12] after the move. You need to find the minimal number of moves for transformin...
for _ in range(int(input())): n=int(input()) a=[int(y) for y in input().split()] a=sorted(a) a=a[::-1] d={} count=0 for i in range(n): d[a[i]]=0 for i in range(n): if(d[a[i]] == 0): s=a[i] while(a[i]%2==0): a[i]/=2 ...
Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind. Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense...
#include <bits/stdc++.h> using namespace std; long long int t[4000005], lazy[4000005]; vector<pair<long long int, long long int> > v1; void push(int v) { t[v * 2] += lazy[v]; lazy[v * 2] += lazy[v]; t[v * 2 + 1] += lazy[v]; lazy[v * 2 + 1] += lazy[v]; lazy[v] = 0; } void build(long long int v, long long int t...
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
s=input() flag=0 for i in range(len(s)): if(s[i]=='H' or s[i]=='Q' or s[i]=='9'): print('YES') flag=1 break if flag==0: print('NO')
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. ...
#include <bits/stdc++.h> using namespace std; long long k[1000005]; long long qkm(long long x, long long y, long long mod) { long long ans = 1; for (; y; y >>= 1, x = x * x % mod) if (y & 1) ans = ans * x % mod; return ans; } int main() { long long i, n, p, t, sum1, sum2; cin >> t; while (t--) { cin...
In the game of Mastermind, there are two players — Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive. When Bob guesses a code, Alice tells him some information about ...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int tt; cin >> tt; while (tt--) { int N, X, Y; cin >> N >> X >> Y; vector<int> b(N); vector<int> ans(N, -1); for (int i = 0; i < N; i++) cin >> b[i]; map<int, vector<int>> loc; for ...
You are given a tree that consists of n nodes. You should label each of its n-1 edges with an integer in such way that satisfies the following conditions: * each integer must be greater than 0; * the product of all n-1 numbers should be equal to k; * the number of 1-s among all n-1 integers must be minimum po...
// package Quarantine; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class MaximumDistributedTree { static ArrayList<Integer> tree[]; static ArrayList<Long> compo; ...
Nikola owns a large warehouse which is illuminated by N light bulbs, numbered 1 to N. At the exit of the warehouse, there are S light switches, numbered 1 to S. Each switch swaps the on/off state for some light bulbs, so if a light bulb is off, flipping the switch turns it on, and if the light bulb is on, flipping the ...
#include <bits/stdc++.h> using namespace std; int read() { int x = 0; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) ; for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ 48); return x; } const int LMAX = 12, RMAX = 18; int n, m, q; int L, R; struct Bitset { unsigned long long...
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the ...
n, m = map(int, input().split()) a = input() b = input() res = 0 dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)] for i in range(1, n + 1): for j in range(1, m + 1): if a[i - 1] == b[j - 1]: dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 2) dp[i][j] = max(dp[i][j], max(dp[i - 1][j], d...
Let us call two integers x and y adjacent if (lcm(x, y))/(gcd(x, y)) is a perfect square. For example, 3 and 12 are adjacent, but 6 and 9 are not. Here gcd(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y, and lcm(x, y) denotes the [least comm...
#include <bits/stdc++.h> using namespace std; #define ll long long #define ln "\n" #define pb push_back #define pll pair<ll,ll> #define ppll pair<ll , pll> #define vll vector<ll> #define vs vector<string> #define vpll vector<pll> #define vvll vector<vector<ll>> #define vvpll vector<vpll> #define f first ...
You are given an integer n and an array a_1, a_2, …, a_n. You should reorder the elements of the array a in such way that the sum of MEX on prefixes (i-th prefix is a_1, a_2, …, a_i) is maximized. Formally, you should find an array b_1, b_2, …, b_n, such that the sets of elements of arrays a and b are equal (it is equ...
import com.sun.source.tree.Tree; import java.io.*; import java.util.*; public class TaskA { public static void main(String[] args) { int t = nextInt(); while(t-->0) { int n = nextInt(); int[] a = new int[n]; TreeMap<Integer, Integer> map = new TreeMap<>(); ...
Alice and Bob play a game. Alice has got n treasure chests (the i-th of which contains a_i coins) and m keys (the j-th of which she can sell Bob for b_j coins). Firstly, Alice puts some locks on the chests. There are m types of locks, the locks of the j-th type can only be opened with the j-th key. To put a lock of ty...
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Scanner; public class CF_Edu_108_F { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){...
Cirno gives AquaMoon a problem. There are m people numbered from 0 to m - 1. They are standing on a coordinate axis in points with positive integer coordinates. They are facing right (i.e. in the direction of the coordinate increase). At this moment everyone will start running with the constant speed in the direction o...
#pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,abm,mmx,tune=native") #include<vector> #include<iostream> #include<stack> #include<cmath> #include<algorithm> #include<set> #include<map> #include<string> #include<tuple> #include<bitset> #include<queue> #include<...
Eudokimus, a system administrator is in trouble again. As a result of an error in some script, a list of names of very important files has been damaged. Since they were files in the BerFS file system, it is known that each file name has a form "name.ext", where: * name is a string consisting of lowercase Latin lett...
import java.util.Scanner; public class P174B { public static void main(String[] args) { Scanner inScanner = new Scanner(System.in); String string = inScanner.next(); if (string.charAt(0) == '.' || string.charAt(string.length() - 1) == '.') { System.out.println(...
You've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected. A set of painted squares is called connected, if for every two s...
#include <bits/stdc++.h> using namespace std; int dx[] = {1, -1, 0, 0}; int dy[] = {0, 0, 1, -1}; int n, m, vis[101][101], cnt; string s[101]; int dfs(int x, int y) { if (x < 0 || x >= n || y < 0 || y >= m || vis[x][y] || s[x][y] == '.') return 0; vis[x][y] = 1; for (int i = 0; i < 4; i++) dfs(x + dx[i], y + ...
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves...
import java.util.Scanner; public class e { public static boolean[][] f; public static boolean[] used; public static int n; public static void main(String args[]) { Scanner in = new Scanner(System.in); n = in.nextInt(); int[] x = new int[n]; int[] y = new int[n]; ...
Martha — as a professional problemsetter — proposed a problem for a world-class contest. This is the problem statement: Tomorrow is Nadia's birthday, and Bardia (her brother) is assigned to make the balloons ready! There are n balloons (initially empty) that are tied to a straight line on certain positions x1, x2, .....
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; public class Solution implements Runnable { ArrayList<Integer> s; double [] radius; long x []; void relax (int i, int j) { int t = s.get(j); radius [i] = min (radius[i], (double) (x[i] - x[t]) * (double) (x[i] - x[t]...
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5). You've got some num...
import java.io.*; import java.util.*; /** * Created by madeline on 3/30/17. * Solution to http://codeforces.com/problemset/problem/267/A * Assignment 9 CS104C */ public class CS267A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int num_pairs...
Input The input contains a single integer a (1 ≤ a ≤ 40). Output Output a single string. Examples Input 2 Output Adams Input 8 Output Van Buren Input 29 Output Harding
#include <bits/stdc++.h> using namespace std; int main() { char war[55][20] = { "WASHINGTON", "ADAMS", "JEFFERSON", "MADISON", "MONROE", "ADAMS", "JACKSON", "Van BUREN", "HARRISON", "TYLER", "POLK", "TAYLOR", "FILLMORE", "PIERCE", "BUCHANAN", "LINCOLN", "JOHNSO...
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get th...
def fact(n): if n == 0: return 1 else: return n * fact(n-1) s = raw_input().strip() cnt = dict() for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ?0123456789': cnt[c] = 0 for c in s: cnt[c] += 1 t = 0 for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': if cnt[c] > 0: t += 1 c = s[0] res = 1 if c in 'ABCDEFGHIJKLMNOPQR...
A divisor tree is a rooted tree that meets the following conditions: * Each vertex of the tree contains a positive integer number. * The numbers written in the leaves of the tree are prime numbers. * For any inner vertex, the number within it is equal to the product of the numbers written in its children. ...
#include <bits/stdc++.h> const long double eps = 1e-9; const double pi = acos(-1.0); const long long inf = 1e18; using namespace std; int n, best = 1000000000; long long a[8], mul[256]; int sum[256]; int d[8], lim; int f[9][256]; vector<int> p; int main(int argc, const char* argv[]) { time_t start = clock(); cin >>...
Levko loves sports pathfinding competitions in his city very much. In order to boost his performance, Levko spends his spare time practicing. The practice is a game. The city consists of n intersections connected by m + k directed roads. Two or more roads can connect the same pair of intersections. Besides, there can ...
#include <bits/stdc++.h> using namespace std; const long long inf = 1e18; const double eps = 1e-9; const double INF = inf; const double EPS = eps; int n, m; int L[110], R[110]; vector<pair<int, int> > G[110000], GR[110000]; int Tp[110000]; long long D[110000]; int s1, s2, f; set<pair<long long, int> > S; int Res[110]; ...
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of mi...
#include <bits/stdc++.h> using namespace std; int n; int T[200005]; int t[200005]; void up(int idx, int val) { while (idx <= n) { t[idx] += val; idx += (idx & -idx); } } int que(int idx) { int sum = 0; while (idx > 0) { sum += t[idx]; idx -= (idx & -idx); } return sum; } void update(int idx,...
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show". Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes...
#include <bits/stdc++.h> int main() { int n, i = 0, j = 0, l = 0, r = 0, temp = 0, temp1 = 0, temp2 = 0, temp3 = 0, w = 0; char a[3000]; scanf("%d", &n); scanf("%s", &a); while (a[i] == '.') { r++; i++; } if (a[r] != 'R' && a[r] != 'L') { w = r; } if (a[r] == 'R') { temp = r; ...
You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times): * choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number); * swap the elements on positi...
#include <bits/stdc++.h> using namespace std; const int maxn = 100005; int a[maxn + 5], L[maxn + 5], prime[maxn + 5], numPrime, X[maxn * 5 + 5], Y[maxn * 5 + 5], n, num; bool vis[maxn * 10]; void inti() { int m = (int)sqrt(maxn + 0.5); memset(vis, false, sizeof(vis)); vis[1] = true; for (int i = 2; i <= m; ...
Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration. <im...
#include <bits/stdc++.h> using namespace std; int head[100010]; int nex[200010]; int to[200010]; int cnt = 0; void add(int u, int v) { nex[++cnt] = head[u]; to[cnt] = v; head[u] = cnt; } int vis[100010]; int x[100010]; int temp[400010]; int ans; void dfs(int now, int fa) { vis[now] = 1; temp[ans++] = now; x...
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible. More formally...
#include <bits/stdc++.h> using namespace std; const int MAXS = 2000 + 5; const int MAXP = 500 + 5; const int INF = INT_MAX / 2; vector<int> ans; char s[MAXS], p[MAXP]; int nx[MAXS]; int lens, lenp; bool usd[MAXS][MAXS]; int rec[MAXS][MAXS]; int f(int i, int k) { if (k == 0) return 0; if (i >= lens) return INF; if...
Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A = {a1, a2, ..., an}, where the width and the height of the i-th envelope is strictly higher than the width and the height o...
inputi = [int(i) for i in input().split(" ")] amt = inputi[0] cardW = inputi[1] cardH = inputi[2] envelopes = [] cur_amt = 1 for i in range(amt): inputi = [int(i) for i in input().split(" ")] if inputi[0] > cardW and inputi[1] > cardH: envelopes.append((inputi[0],inputi[1],inputi[0]*inputi[1], cur_amt))...
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li. Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maxi...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream;...
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components. Build a connected undirected k-regular graph containing at least one bridge, or else state that such gra...
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > v; int cnt[110]; void add(int s, int e, int k) { for (int i = s + 1; i <= e - 1; i++) v.push_back(pair<int, int>(i - 1, i)); v.push_back(pair<int, int>(e - 1, s)); for (int i = s + 1; i <= e - 1; i++) v.push_back(pair<int, int>(i, e)); int x ...
On a plane are n points (xi, yi) with integer coordinates between 0 and 106. The distance between the two points with numbers a and b is said to be the following value: <image> (the distance calculated by such formula is called Manhattan distance). We call a hamiltonian path to be some permutation pi of numbers from 1...
#include <bits/stdc++.h> using namespace std; const long long MAXN = 1e6 + 1, SQ = 1200; int n; int x[MAXN], y[MAXN], a[MAXN]; bool cmp(int i, int j) { short int tmp = x[i] / SQ, tmpp = x[j] / SQ; if (tmp ^ tmpp) return x[i] < x[j]; else { if (tmp & 1) return y[i] > y[j]; else return y[i] ...
Vasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first k Latin letters and not contain...
#include <bits/stdc++.h> using namespace std; void normalize(string& str) { int f = 0; int l = (int)str.size() - 1; int cnt; while (f < l) { cnt = 0; cnt = (str[f] == '?') + (str[l] == '?'); if (cnt == 1) { char ch = str[f]; if (ch == '?') ch = str[l]; str[f] = str[l] = ch; } ...
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0. Input The first line of the ...
//package round341x; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); in...
Little Artem is a very smart programmer. He knows many different difficult algorithms. Recently he has mastered in 2-SAT one. In computer science, 2-satisfiability (abbreviated as 2-SAT) is the special case of the problem of determining whether a conjunction (logical AND) of disjunctions (logical OR) have a solution, ...
#include <bits/stdc++.h> int N, M1, M2; inline int inv(int x) { return x <= N ? x + N : x - N; } struct graph { std::bitset<2001> G[2001]; bool no_solution; int f[2001]; void Start(int p) { if (~f[p]) return; f[p] = 1; f[inv(p)] = 0; for (int i = 1; i <= N + N; i++) if (G[p][i]) Start(i); ...
Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n. Let us remind you the definition of the greatest common divisor: GCD(a1, ..., ak) = d, where d represents such a maximal positive number that each ai (1 ≤ i ≤ k) is e...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:32000000") using namespace std; const double pi = 3.1415926535897932384626433832795; template <class T> inline T Sqr(const T &x) { return x * x; } template <class T> inline T Abs(const T &x) { return x >= 0 ? x : -x; } int n; int p[1000]; int k; int res[55]; ...
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open. You are given a jacket with n buttons. Determine if it is fasten...
n = int(input()) a = list(map(int,input().split())) c = a.count(0) if (c>1 or c<1) and n>1 : print('NO') elif n==1 and c==1: print('NO') else: print('YES')
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then ever...
import java.util.Scanner; public class Problem2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] line = input.nextLine().split(" "); int n = Integer.parseInt(line[0]); int c = Integer.parseInt(line[1]); line = input.nextLine().split(" "); int aux =...
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no m...
#include <bits/stdc++.h> using namespace std; const int MAXN = 105; const int MAXK = 42; const int mod = (int)1e9 + 7; int n, k; vector<int> g[MAXN], g2[MAXN]; int dp[MAXN][MAXK + 5][MAXK + 5]; int dp2[MAXN][MAXK + 5][MAXK + 5][MAXN][2]; int NN; void dfs(int v, int p = -1) { for (int i = 0; i < (int)g2[v].size(); i++...
Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction. Pavel has a plan: a permutation p and a sequence b1, b2, ...
#include <bits/stdc++.h> using namespace std; const double PI = 3.141592653589793238; long long powmod(long long a, long long b) { long long res = 1; a %= 1000000007; for (; b; b >>= 1) { if (b & 1) res = res * a % 1000000007; a = a * a % 1000000007; } return res; } vector<int> vec[200005]; bool vis[2...
Andryusha has found a perplexing arcade machine. The machine is a vertically adjusted board divided into square cells. The board has w columns numbered from 1 to w from left to right, and h rows numbered from 1 to h from the bottom to the top. Further, there are barriers in some of board rows. There are n barriers in ...
#include <bits/stdc++.h> using namespace std; struct node { int p, x; node() { ; } node(int a, int b) { p = a, x = b; } }; stack<node> s[100005]; int mx[100005 << 2], n, m, k; struct QaQ { int l, r, f, h; bool operator<(const QaQ &a) const { return h < a.h; } } a[100005]; int cmp(int a, int b) { if (s[a].em...
Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem. We have a forest (acyclic undirected graph) with n vertices and m edges. There are q queries we should answer. In each query two vertices v and u are given. Let V be the ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 5; int N, M, Q; vector<int> G[MAXN]; int CC[MAXN], CCN; vector<int> CCv[MAXN], d[MAXN], dd[MAXN]; int diam[MAXN]; int bfsd[2][MAXN]; int bfs(int v, int di, int cc = -1) { queue<pair<int, int> > q; q.push({v, -1}); bfsd[di][v] = 0; while (!q.em...
The Berland Kingdom is a set of n cities connected with each other with n - 1 railways. Each road connects exactly two different cities. The capital is located in city 1. For each city there is a way to get from there to the capital by rail. In the i-th city there is a soldier division number i, each division is chara...
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > g[5001]; int parent[5000][2]; void set_parent(int x) { int i; for (i = 0; i < g[x].size(); i++) { if (parent[g[x][i].first][0] == -1) { parent[g[x][i].first][0] = x; parent[g[x][i].first][1] = g[x][i].second; set_parent(g[x]...
The presidential election is coming in Bearland next year! Everybody is so excited about this! So far, there are three candidates, Alice, Bob, and Charlie. There are n citizens in Bearland. The election result will determine the life of all citizens of Bearland for many years. Because of this great responsibility, e...
#include <bits/stdc++.h> const int maxn = 1048600; int n, m; char s[maxn]; int a[maxn], bits[maxn]; long long b[maxn], ans; template <typename T> inline void FWT(T *a) noexcept { T *End = a + n; for (register int hl = 1, l = 2; hl < n; hl = l, l <<= 1) { for (register T *i = a; i != End; i += l) { T *tmp ...
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi...
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); vector<int> ans; for (int i = 1; i <= 81; i++) { int p = n - i, s = 0; while (p) { s += (p % 10); p /= 10; } if (s == i) { ans.push_back(n - i); } } sort(ans.begin(), ans.end()); cout <...
Petya has a string of length n consisting of small and large English letters and digits. He performs m operations. Each operation is described with two integers l and r and a character c: Petya removes from the string all characters c on positions between l and r, inclusive. It's obvious that the length of the string ...
import java.util.*; import java.io.IOException; public class Test { Scanner sca = new Scanner(System.in); final int N = 200_001; TreeSet<Integer>[] sets = new TreeSet[128]; int[] cnts = new int[N+N+N]; void build(int ll, int rr, int p) { if (ll == rr) { cnts[p] = 1; ...
Recently n students from city S moved to city P to attend a programming camp. They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea. i-th stude...
if __name__ == '__main__': cin = input t = int(cin()) while t > 0: n = int(cin()) a, cnt = [0] * n, 0 for i in range(n): l, r = map(int, cin().split()) if r >= cnt + max(l - cnt, 1): cnt += max(l - cnt, 1) a[i] += cnt p...
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: * A <image> BC * B <image> AC * C <image> AB * AAA <image> empty string Note that a substring is one or more consecutive characters. For give...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const long long LLinf = 0x3f3f3f3f3f3f3f3f; long long read() { long long x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10l...
Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them: Max owns n creatures, i-th of them can be described with two numbers — its health hpi and its damage dmgi. Max also has two types ...
import java.io.*; import java.util.*; public class Mainn { InputReader scn; PrintWriter out; String INPUT = ""; class pair implements Comparable<pair> { long health = 0, damage = 0, diff = 0; pair(long h, long d) { health = h; damage = d; diff = health - damage; } pair(pair p) { health = p.h...
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 unsigned long long mod = 1e9 + 7; int n, k, emp; int ku[111][111]; struct node { int x, y, id; }; vector<node> ans; void parkin() { for (int i = 0; i < 2 * n; i++) { if (ku[1][i] && ku[1][i] == ku[0][i]) { node car; if (i >= n) car.x = 4, c...
The Bandu of the Hackers' community had a very urgent job to do. He needs to diffuse all the bombs placed by Poker. Poker is extremely clever and cruel. He selected a region of 1000 X 1000 points, chose N center points of the form (X,Y) and placed bombs on every integral point that was on or inside the circular region ...
t = int(input()) mat = [ [0 for i in range(0, 1001)] for j in range(0, 1001)] while(t): val = str(raw_input()) val = val.split(" ") x,y,r = int(val[0]), int(val[1]), int(val[2]) #print("X Y R") #print x,y,r rSquare = r ** 2 #print("rSquare %d"% rSquare) for i in range(1,1001) : for j in range(1,1001) : ...
Fatland is a town with N cities numbered 1, 2, ..., N, connected with 2-way roads. Vincent is a villian who wants to set the entire town ablaze. For each city, there is a certain risk factor E[i] for setting that city ablaze. But once a city c is set ablaze, all cities that can be reached from c will be set ablaze imme...
from collections import defaultdict class Graph(): def __init__(self, connections=[], directed=False): self.status_dict = defaultdict(lambda : 1) self.graph_dict = defaultdict(list) self.is_directed = directed def add_edge(self,node1, node2): s...
An extraterrestrial visit! Remember your childhood friend JAADU from outer space?? Well, he is back again to our mighty Planet Earth. But do you expect us geeks to introduce a character like Rohit Mehra in this story? A Hell No!! Instead, he encounters the creepy Scientists of Planet Earth all the way from S.H.I.E....
def sol(n,k): L = (2**n) - 1 if k > L : return -1 if k == L/2+1 : return 0 if k < L/2+1 : return sol(n-1,k) else: return 1-sol(n-1,L+1-k) #def sol(n,k): # L = (2**n) - 1 ; # if k > L : # return -1 # f=0 # while n>-1 : # if n==1: # if k==1: return f # else: return -1 # if k == L/2 + 1 : # retur...
Protection of the Indian border and safe transport of items from one point to another along the border are the paramount jobs for the Indian army. However they need some information about the protection status along the length of the border. The border can be viewed as the real x-axis. Along the axis, Indian army has N...
N,S,E = map(int, raw_input().split()) data = [] for i in range(N): x,p = map(int, raw_input().split()) data.append([x-p, x+p]) #print 'S is:{0} and E is:{1}'.format(S,E) #print data data.sort() diff = 0 for i in range(len(data)): temp_arr = data[i] temp_start = temp_arr[0] temp_end = temp_arr[1...
Alice is a geeky girl. She has a lot of codes to execute but she always choose a lucky time to execute a code. Time is shown in 24 hour format as hh:mm:ss Time is said to be lucky if all the 6 characters (except ':') are different. Given the time when she completed the code find a lucky time to execute it so that Ali...
import sys class test: def __init__(self): self.s = raw_input() self.ti = self.s.split(':') for i in range(0, 3): self.ti[i] = int(self.ti[i]) if self.ti[0] > 23 or self.ti[1] > 59 or self.ti[2] > 59: raise Exception(str(self.ti[0]) + str(self.ti[1]) + ...
Navi is a famous mathematician. He is working on Division, Multiplication and Addition. He is in need of some hidden patterns to discover some new concepts. He is giving you a task to find that sub-sequence of an array which has the maximum P % mod value, where value of the mod is given below. This sub-sequence shou...
#from math import * def findp(arr , n): m = 10**9 + 7 maximum = -1 for i in range(1 , 1<<n): prod , s = 1 , 0 for j in range(n): if i & (1<<j): s += arr[j] prod = (prod * arr[j]) % m maximum = max( ( prod * pow(s , m-2 , m) ) % m , maximum ) return maximum t = int(raw_input()) for k in range(t...
Aditya is a professor in Engilsh loves to play with words. Today he asks his assistant Abishek to perform an experiment where he wants him to calculate the total number of word that can be formed from a given word such that the characters are arranged lexicographically(in alphabetical order). The words that are to be f...
import collections a=[] t=int(raw_input()) for q in range(0,t): s=raw_input() letters = collections.Counter(s) print(len(letters.values()))
Sherlock has intercepted some encrypted messages, which he suspects are from Professor Moriarty. He found that the number of characters in each message (including spaces) is always a square number. From this he deduces that it must be a Caesar Box Cipher. In a Caesar Box Cipher, suppose the number of characters is L ...
n = input() for _ in xrange(n): s = raw_input() m = int(len(s) ** .5) l = [] for i in xrange(m): v = [] for j in xrange(m): v += [s[i*m+j]] l += [v] print ''.join(map(lambda t: ''.join(list(t)), zip(*l)))
Vinay loves stories on serial killers. He is hypnotized to the stories of The Zodiac Killer. Zodiac was a serial killer in USA in late 1960s and early 1970s. He never revealed his original identity but named himself as Zodiac on the letters he posted to police and news papers. He used to post them about the murders he ...
import sys for t in range(input()): n=int(raw_input()) lst=map(int,raw_input().split()) for i in range(n): sys.stdout.write(chr(255-lst[i])) print
Xenny had N boxes with an integer printed on each of the boxes. He wanted to find out how many distinct pairs of boxes that were at distance k from each other, had an absolute value of difference or sum that was a multiple of k. Help him in this task. (Note: Consider two indices i1 and i2. Pairs (i1, i2) and (i2, i1...
s=map(int,raw_input().split()) n,k=s N=map(int,raw_input().split()) d={} for i in xrange(0,n): if (i+k)<n: if (N[i]+N[i+k])%k==0 or abs(N[i]-N[i+k])%k==0: if (i,i+k) not in d and (i+k,i) not in d: d[(i,i+k)]=1 else: if (i-k)>=0: if (N[i]+N[i-k])%k==0 or ab...
Given are N pairwise distinct non-negative integers A_1,A_2,\ldots,A_N. Find the number of ways to choose a set of between 1 and K numbers (inclusive) from the given numbers so that the following two conditions are satisfied: * The bitwise AND of the chosen numbers is S. * The bitwise OR of the chosen numbers is T. C...
#include <bits/stdc++.h> using namespace std; const int N = 55; int a[N], frq[1 << 18]; long long C[N][N], sum[N][N]; inline int Count(int x) { if (x == 0) return 0; else return 32 - __builtin_clz(x); } int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); ios::sync_with_stdio(0)...
Given is a string S. Replace every character in S with `x` and print the result. Constraints * S is a string consisting of lowercase English letters. * The length of S is between 1 and 100 (inclusive). Input Input is given from Standard Input in the following format: S Output Replace every character in S with ...
s = input() print('x' * (len(s)))
Given is a string S of length N. Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following: ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,a) for(int i=0;i<(a);i++) const ll MOD=1000000007; //const ll MOD=998244353; int dp[5050][5050]; int main(){ int N; cin>>N; string S; cin>>S; int ans=0; for(int i=N-1;i>=0;i--){ for(int j=N-1;j>=0;j--){ if(S[i]==S[j]){...
Snuke has N strings. The i-th string is s_i. Let us concatenate these strings into one string after arranging them in some order. Find the maximum possible number of occurrences of `AB` in the resulting string. Constraints * 1 \leq N \leq 10^{4} * 2 \leq |s_i| \leq 10 * s_i consists of uppercase English letters. In...
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.next()); int sum = 0; String[] s1 = new String[N]; int A = 0; int B = 0; int BA = 0; for(int i=0;i<N;i++) { int t=0; String st = sc...
You are given strings s and t, both of length N. s and t consist of `0` and `1`. Additionally, in these strings, the same character never occurs three or more times in a row. You can modify s by repeatedly performing the following operation: * Choose an index i (1 \leq i \leq N) freely and invert the i-th character i...
#include<bits/stdc++.h> using namespace std; typedef vector<int>V; int n,i,j,ans=1<<30,x; V L,R,S,T; string s,t; int main(){ ios::sync_with_stdio(0);cin.tie(0); cin>>n>>s>>t; if(n<3){for(i=0;i<n;++i)x+=s[i]!=t[i];cout<<x<<endl;return 0;} for(i=0;i+1<n;++i){ if(s[i]!=s[i+1])S.push_back(i+1); if(t[i]!=t[i+1])T.pu...
You are given two integers A and B. Find the largest value among A+B, A-B and A \times B. Constraints * -1000 \leq A,B \leq 1000 * All values in input are integers. Input Input is given from Standard Input in the following format: A B Output Print the largest value among A+B, A-B and A \times B. Examples Inp...
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int A = sc.nextInt(); int B = sc.nextInt(); int max = A + B; max = Math.max(max, A - B); max = Math.max(max, A * B); System.out.println(max)...
Snuke has a rooted tree with N+1 vertices. The vertices are numbered 0 through N, and Vertex 0 is the root of the tree. The parent of Vertex i (1 \leq i \leq N) is Vertex p_i. Besides this tree, Snuke also has an box which is initially empty and many marbles, and playing with them. The play begins with placing one mar...
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt() + 1; ...
Snuke has N sticks. The length of the i-th stick is l_i. Snuke is making a snake toy by joining K of the sticks together. The length of the toy is represented by the sum of the individual sticks that compose it. Find the maximum possible length of the toy. Constraints * 1 \leq K \leq N \leq 50 * 1 \leq l_i \leq 50 ...
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int K = sc.nextInt(); Integer[] cards = new Integer[N]; for (int i = 0; i < cards.length; ...
Snuke has decided to construct a string that starts with `A` and ends with `Z`, by taking out a substring of a string s (that is, a consecutive part of s). Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with `A` and ends w...
#include <iostream> #include <string> using namespace std; int main(){ string S; cin>>S; cout<<S.rfind('Z')-S.find('A')+1<<endl; return 0; }
Eli- 1 started a part-time job handing out leaflets for N seconds. Eli- 1 wants to hand out as many leaflets as possible with her special ability, Cloning. Eli- gen can perform two kinds of actions below. * Clone herself and generate Eli- (gen + 1) . (one Eli- gen (cloning) and one Eli- (gen + 1) (cloned) exist as a r...
#include <iostream> using namespace std; #pragma warning (disable: 4996) int mod = 1000000007; int prev_[100009], dp[100009], dpr[100009]; int mulr[100009]; long long Q; long long N[1 << 18], C[1 << 18], Base[1 << 18]; long long Answer[1 << 18]; void init(int pos) { int lims = (pos - 2) * (pos - 1) / 2; int lim2 =...