input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Polycarp wrote on the board a string s containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.
After that, he erased some letters from the string s, and he rewrote the remaining letters in any order. As a result, he got some new string t. You have to find it with some ad... | t=int(input())
for i in range(t):
s=input()
b=[]
d=dict()
for j in s:
if j in d.keys():
d[j]+=1
else:
b.append(j)
d[j]=1
b.sort(reverse=True)
n=int(input())
a=list(map(int,input().split()))
c=["a"]*(n)
m=1
f=dict()
p=0
w... |
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like t... | #include <bits/stdc++.h>
using namespace std;
int cnt[200200];
long long a[200202];
int b[200200];
int vis[200020];
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
cin >> b[i];
if (b[i]... |
You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times:
* Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.
Your task is to fi... | for _ in range(int(input())):
a,b,x,y,n=map(int,input().split())
if n>=((a-x)+(b-y)):
print(x*y)
else:
if a>=b and n<=(b-y):
print(a*(b-n))
elif b>a and n<=(a-x):
print((a-n)*b)
elif n<=(a-x) and n<=(b-y):
print(min((a-n)*b,a*(b-n)))
else:
if n>(a-x):
... |
Greg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. T... | #include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void smin(T &a, const U &b) {
if (a > b) a = b;
}
struct point {
double x, y, z;
inline double al() { return atan2(y, x); }
inline double nor() { return sqrt(nor2()); }
inline double nor2() { return *this * *this; }
inlin... |
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. I... | #include <iostream>
using namespace std;
#include<bits/stdc++.h>
typedef long long ll;
int main() {
int t;cin>>t;
while(t--){
int n;cin>>n;
int i,j,k,x;
vector<ll>a(n+2);
vector<ll>ans(n+2,0);
for(i=0;i<n;i++)
cin>>a[i];
int pos=... |
You are given an integer array a of size n.
You have to perform m queries. Each query has one of two types:
* "1 l r k" — calculate the minimum value dif such that there are exist k distinct integers x_1, x_2, ..., x_k such that cnt_i > 0 (for every i ∈ [1, k]) and |cnt_i - cnt_j| ≤ dif (for every i ∈ [1, k], j ∈ ... | #include "bits/stdc++.h"
using namespace std;
#define for_(i, s, e) for (int i = s; i < (int) e; i++)
#define for__(i, s, e) for (ll i = s; i < e; i++)
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
#define endl '\n'
int n, m;
const int MXN = 1e5, INF = 1e9;
const int block_size = 2000, block... |
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i... | #pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<string.h>
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define NDEBUG
#define eprintf(...) do {} while (0)
#endif
#include<cassert>
using ... |
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is n... | import java.io.*;
import java.util.*;
public class B {
public static int countBitFlips(int n,char[] arr){
int r=0;
int l=n-1;
int ans=0;
while(r<l){
// out.println("hetetefte "+r+" "+l);
if(arr[l]!=arr[r]){
ans++;
}
... |
Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that ... | import java.io.*;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
public class CodeForces {
public void solve() throws IOException {
int n = nextInt();
int d = nextInt();
List<String> friends = new ArrayList<String>();
List<String[]> st = new ArrayList<String[]>();
for (int i = 0, l = ... |
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size n × n. The elements of this matrix are integers.... | #include <bits/stdc++.h>
using namespace std;
int N, M, S;
int x[20];
int a[10][10];
int func(int mask, int val) {
int i;
for ((i) = 0; (i) < (int)(M); (i)++)
if (((mask) & (1 << (i))))
if (x[i] == val) return i;
return -1;
}
bool dfs(int pos, int mask) {
int i, j;
if (pos == 8) {
for ((i) = 0; ... |
Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, de... | #include <bits/stdc++.h>
using namespace std;
const long long MAX = 2500000000;
const int inf = 0x3f3f3f3f;
const double EPS = 1e-9;
const double PII = 2 * asin(1.0);
const long long mod = 1e9 + 7;
int double_cmp(double x, double y = 0, double tol = EPS) {
return (x <= y + tol) ? (x + tol < y) ? -1 : 0 : 1;
}
multima... |
You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.
A picture is a barcode if the following conditions are fulfilled:
* All pixels in each column are of the same color.
* The width of each monochrome ver... | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Barcode {
static class Solver {
int n, m, x, y;
int[] arr;
int[][][] mem;
public void solve(MyReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
... |
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two ot... | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
int n;
struct node {
int v, w;
node() {}
node(int _v, int _w) : v(_v), w(_w) {}
};
vector<node> ve[110];
int ans;
bool flag;
void dfs(int fa, int u) {
if (u == 1 && fa != -1) flag = true;
if (flag) return;
for (int i = 0; i < ve[u].si... |
A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tr... | import static java.lang.Math.*;
import java.io.*;
import java.util.*;
public class Template {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() {
while (st==null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (Exception e) {}
}
return st.... |
Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height h and width w. Then the grid is divided into h × w squares. Alice is going to assign one of k different colors to each square. The colors are numbered from 1 to k. Sh... | #include <bits/stdc++.h>
using namespace std;
const int N = 1000 + 5;
vector<int> vl[N], v[N];
int n, m, k, g[N][N];
void done() {
long double s = n * (m - 1) + (n - 1) * m, a = 0;
char c;
for (int i = 0; i < s; ++i) {
cin >> c;
if (c == 'E') a += 1;
}
if ((a / s) >= (3. / 4.)) {
cout << "YES" << ... |
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so ... | //import java.io.File;
//import java.io.FileNotFoundException;
import java.util.*;
public class Intervals
{
public static void main(String[] args) //throws FileNotFoundException
{
Scanner reader = new Scanner(System.in);
// Scanner reader = new Scanner(new File("test.txt"));
int numQueries = reader.nextInt();
... |
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained... | import java.util.*;
import java.io.*;
public class D215 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int p = sc.nextInt();
int[] a = new int[n];
int[] b = new int[m];
for(in... |
Inna loves sweets very much. That's why she wants to play the "Sweet Matrix" game with Dima and Sereja. But Sereja is a large person, so the game proved small for him. Sereja suggested playing the "Large Sweet Matrix" game.
The "Large Sweet Matrix" playing field is an n × m matrix. Let's number the rows of the matrix ... | #include <bits/stdc++.h>
using namespace std;
const int N = 4000009;
struct tree {
long long Mul[4000009];
long long Sub[4000009];
void update(int left, int right, long long by) {
internalUpdate(left, by, by * (left - 1));
internalUpdate(right + 1, -by, -by * right);
}
void internalUpdate(int at, long... |
The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.
Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one ... | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> g[30005];
int vis[30005];
void euler(int u) {
if (vis[u]) return;
vis[u] = 1;
for (int v = 0; v < g[u].size(); v++) {
euler(g[u][v]);
}
printf("%d ", u);
}
int main() {
memset(vis, 0, sizeof(vis));
scanf("%d %d", &n, &m);
while (m--... |
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve... | n=int(input())
a,b=input(),""
x,y=1,0
for i in range(n-1):
s=input()
if a==s:
x+=1
else:
b=s
y+=1
print([b,a][x>y]) |
Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types:
1. Fold the sheet of paper at position pi. After this query the leftmost... | import java.util.*;
import java.io.*;
public class _0461_C_ApplemanAndASheetOfPaper {
static class Node{
int l, r, val;
public Node(int l, int r) {
this.l = l; this.r =r;
}
}
static Node seg[];
static int build(int l, int r, int idx) {
seg[idx] = new Node(l, r);
if(l == r) {
seg[idx].val = 1;
... |
Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.
Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes.... | #include <bits/stdc++.h>
using namespace std;
int x[1005], y[1005];
int main(void) {
memset(x, 0, sizeof(x));
memset(y, 0, sizeof(y));
int n, i;
scanf("%d", &n);
for (i = 0; i < n; i++) scanf("%d%d", &x[i], &y[i]);
long long dx, dy, d;
sort(x, x + n);
sort(y, y + n);
dx = x[n - 1] - x[0];
dy = y[n -... |
There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.
... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j, k, p, t, ij, r;
int a[101], b[101][101] = {0};
cin >> n >> k;
for (i = 1; i <= n; i++) cin >> a[i];
for (i = 1; i <= n; i++) {
t = a[i] / k;
r = a[i] % k;
for (j = 1; j <= r; j++) b[i][j] = t + 1;
for (j = r + 1; j <= a[i]... |
We have an old building with n + 2 columns in a row. These columns support the ceiling. These columns are located in points with coordinates 0 = x0 < x1 < ... < xn < xn + 1. The leftmost and the rightmost columns are special, we will call them bearing, the other columns are ordinary.
For each column we know its durab... | #include <bits/stdc++.h>
using namespace std;
const int md = 1000000007;
const int maxn = 101010;
const int maxn4 = 4 * maxn;
const long long inf = 2020202020202020202LL;
int n;
double x[maxn], d[maxn];
double dr[maxn], dl[maxn];
vector<pair<int, int>> rf(maxn);
double poly[maxn];
void dodo(double dr[]) {
dr[0] = x[n... |
Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.
Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his t... | import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.IOExc... |
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.
Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1.
Input
T... | #include <bits/stdc++.h>
using namespace std;
const int maxN = 100005;
const int mod = (int)1e9 + 7;
char a[maxN];
int main() {
int n, t;
cin >> n >> t;
if (n == 1) {
if (t <= 9) {
cout << t << endl;
} else {
cout << -1 << endl;
}
return 0;
}
int mod = 0;
for (int i = 0; i < n - ... |
Carl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color. To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple... | have = list(map(int, input().split()))
goal = list(map(int, input().split()))
deficit = 0
makeable = 0
for i in range(3):
if have[i] < goal[i]:
deficit += goal[i] - have[i]
else:
makeable += (have[i] - goal[i]) // 2
print('Yes' if makeable >= deficit else 'No')
|
A tennis tournament with n participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.
The tournament takes place in the following way (below, m is the number of the participants of the current round):
* let k be the maximal power of the number 2 such ... | /**
* Created by KamnaYadav on 1/19/2017.
*/
import java.util.*;
public class tennisTournament {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int numCandidate = sc.nextInt();
int numBottles = sc.nextInt();
int numTowels = sc.nextInt();
int nu... |
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:
1. ai ≥ ai - 1 for all even i,
2. ai ≤ ai - 1 for all odd i > 1.
For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.
Can you make the... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, a[1005], k = 0, b[1005];
bool flag = 0;
scanf("%d", &n);
for (i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
sort(a, a + n);
for (i = 0; i < n / 2; ++i) {
b[k] = a[i];
b[k + 1] = a[n - 1 - i];
k += 2;
}
if (n % 2 == 1) {
... |
Vanya plays a game of balloons on the field of size n × n, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:
... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
char maze[1010][1010];
int no[1010][1010];
int s[1010][1010];
int w[1010][1010];
int e[1010][1010];
int a[1010][1010];
int b[1010][1010];
int c[1010][1010];
int d[1010][1010];
double mul1[1010][1010];
double mul2[1010][1010];
double mul3[1010][1010]... |
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were pub... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, i, h[100005], st = 1, ed, mid, cnt, a, b;
multiset<int> s;
scanf("%d %d", &n, &k);
for (i = 0; i < n; i++) {
scanf("%d", h + i);
}
ed = n;
while (st <= ed) {
mid = (st + ed) / 2;
cnt = 0;
s.clear();
for (i = 0; i < mi... |
You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels:... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int n, a[105];
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
string t;
getline(cin, t);
for (int ii = 1; ii <= n; ii++) {
string s;
getline(cin, s);
int m = s.length(), c = 0;
for (int i = 0;... |
Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions:
* the number of occ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1000, C = 8;
int arr[N], n, mid;
int dp[N][1 << C];
bool visit[N][1 << C];
int solve(int startIdx, int canNotPickMask) {
if (canNotPickMask == (1 << C) - 1) return 0;
if (startIdx >= n) return -N;
int &ans = dp[startIdx][canNotPickMask];
if (visit[star... |
Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.
He know... | ##n = int(input())
##a = list(map(int, input().split()))
##print(' '.join(map(str, res)))
[ts , tf, t] = list(map(int, input().split()))
n = int(input())
if n == 0:
print(ts)
exit(0)
a = list(map(int, input().split()))
if a[0] > ts:
print(ts)
exit(0)
min_wait = 1e18
tbest = a[0]-1
tnow = ts
twai... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | #include <bits/stdc++.h>
using namespace std;
int a, b;
int y = 0;
int main() {
cin >> a >> b;
while (a <= b) {
a = a * 3;
b = b * 2;
y++;
}
cout << y;
return 0;
}
|
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is know... | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int n;
static int[] a;
static int[] first = new int[5003];
static int[] last = new int[5003];
static boolean[] ap = new boolean[5003];
s... |
Vasya is studying number theory. He has denoted a function f(a, b) such that:
* f(a, 0) = 0;
* f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b.
Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calcul... | #include <bits/stdc++.h>
using namespace std;
long long a, b;
vector<long long> vect;
long long gcd(long long a, long long b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int main() {
ios_base::sync_with_stdio(0);
int i;
long long ans = 0;
cin >> a >> b;
for (i = 1; i * 1ll * i <= a; i++)
... |
For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.
For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program... | def nok(a, b):
c = a*b
while (a!=0) and (b!=0):
if a>b: a%=b;
else: b%=a;
return c//(a+b);
nk = input().split()
n, k = int(nk[0]), int(nk[1])
print (nok(10**k, n)) |
Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.
Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans:
1. to orient each undirected edge in one of two possible directions to maximize... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
pair<int, int> edges[N];
int type[N];
bool inv[N];
vector<int> e[N];
int vis[N];
int used[N];
inline int other(int id, int u) {
return edges[id].first == u ? edges[id].second : edges[id].first;
}
int ans1 = 0, ans2 = 0;
void dfs(int u) {
vis[u] = ... |
Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.
The game is played on the following field.
<image>
Players are making moves by turns. At first move a player can put his chip in any cell of any sm... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io... |
Polycarp has a strict daily schedule. He has n alarms set for each day, and the i-th alarm rings each day at the same time during exactly one minute.
Determine the longest time segment when Polycarp can sleep, i. e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in... | n = int(input())
a = []
for i in range(n):
str = input()
h = int(str[0:2]) * 60
m = int(str[3:5])
a.append(h + m)
a.sort()
mx = 0
for i in range(n - 1):
if mx < ((-a[i] + a[i + 1]) - 1):
mx = ((-a[i] + a[i + 1]) - 1)
if mx < (1440 + a[0] - a[n - 1] - 1):
mx = 1440 + a[0] - a[n - 1] -... |
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.
Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colo... | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
String s = scn.next();
boolean flag = false;
if(s.charAt(0) == '?' || s.contains("??") || s.charAt(n - 1) == '?')
... |
You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold:
1. There are no neighbors adjacent to anyone seated.
2. It's impossible to seat one more person without violating the first rule.
The seating is given as a string consisting of zeros and ones (0 means... | n = int(input())
l = '0' + input() +'0'
o = 0
z = 0
flag = True
for i in l:
if i == "0" and z < 2:
z += 1
o = 0
elif i == "1" and o != 1:
o = 1
z = 0
else:
flag = False
break
if flag:
print("Yes")
else:
print("No")
|
SKIT's Chemistry Department found some liquid containing a precious chemical which can be separated out of the liquid using centrifugation.
This liquid need to be centrifuged for 5 minutes continuously after that some another facilitating chemical is mixed in the liquid and it is again centrifuged for 5 minutes.
It is... | times=input()
for _ in range(times):
inp=raw_input()
lst=inp.split()
capa=int(lst[0])
num=int(lst[1])
if num==0:
print 0
elif num<capa:
print 10
else:
mult=num/capa
diff=num%capa
if diff==0:
extra=0
elif diff<=int(capa/2):
extra=5
else:
extra=10
time=10*mult+extra
print time |
Golu hates odd numbers. When he learns about binary strings he wants to find out how many binary strings of given length N exist without an odd number of consecutive 1's.
For example: For N=4 1001,1010,1110,0001 are strings which contain odd number of 1's where 1100,1111 are not. Leading zeros are allowed.
This task ... | a = [0]*(1000005)
b = [0]*(1000005)
def cstr():
a[0] = 1
for i in range(1, 1000000+1):
a[i] = (a[i-1] + b[i-1]) % 1000000007
b[i] = a[i-1] % 1000000007
# return (a[n-1] + b[n-1]) % 1000000007
t = input()
cstr()
while t>0:
t-=1
n = input()
# cnt = cstr(n)
print (a[n-1] + b[n-1]) % 1000000007 |
Alice got a message M. It is in an alien language. A string in an alien language is said to be valid if it contains the letter a or z. Alice decided to count the number of valid substrings of the message M. Help him to do this. Two substrings are different if it occurs at different positions in the message.
Input
... | t = int(raw_input())
while t:
t-=1
s = raw_input().strip()
count = 0
prev = 0
curr = 0
l = len(s)
s = s.replace("a", "z")
if "z" in s:
for i, v in enumerate(s):
if v == "z":
count += l - i
prev += curr
count += prev
curr = 0
else:
count += prev
curr += 1
print co... |
You are given two very large numbers made up of 1 or 0 only. You have to find the digit by digit XOR of the two numbers, i.e., the i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ otherwise the i-th digit of the answer is 0. The number of digits in both the numbers is same.
I... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
t=input('');
for i in range(t):
number1=raw_input('');
number2=raw_input('');
number3='';
for j in range(len(number1)):
if(number1[j]!=number2[j]):
number3=number3+'1';
else:
... |
Good news , You have a chance to work in IRCTC as a software developer . Applications are required with a program for railway sites . sid of a station is a something which uniquely defines it . Given N station's sid from 1 to N and distance between any two stations , if any person wants to go from station having sid A... | import heapq
INF = 1 + 25 * 10**9
def dijkstra(G, n, s,de):
dist = [INF] * (n+1)
#path=[]
dist[s] = 0
heap = []
heapq.heappush(heap, (0,s))
while heap:
d, u = heapq.heappop(heap)
if dist[u] < d:
continue
#path.append(u)
if u==de:
break... |
Mehta is a forever alone and desperate guy. He has a crush on N girls of his society. He wants to impress them all and so he needs to do their task collectively.All the girls give him a number which he stores in an array named A of size N. To do their task, he has to report the number of triplets (i,j,k) in the array A... | '''
Project name : Mehta_and_the_Tricky_Triplets
Created on : Tue Aug 26 23:19:11 2014
Author : Anant Pushkar
'''
import sys
debug_mode = len(sys.argv)>1 and sys.argv[1]=="DEBUG"
def debug(msg):
if debug_mode:
print msg
class Solver:
def __init__(self , n):
self.create_masks()
for i in xrange(n):
a = int(ra... |
After the huge success of Hero ISL this season our friend is planning to play in the next season. He already has a team which contains some good players but they not so good. He wants his team to qualify for the next season but the coach is worried as they don't have a good player.
Being a huge a fan of Lionel Messi h... | from sys import stdin
for i in xrange(int(stdin.readline())):
a=map(int, stdin.readline().split())
print pow(a[0],a[1],1000000007) |
Ravi, a student of a primary class, is unable to understand the ranking system of his school.
The ranking system is as:
If two students of the class get equal marks, they are given the same rank but students with different marks are given the rank as the (number of students above him + 1). See the example for more cla... | t = int(raw_input())
for i in range(t):
n = int(raw_input())
out = [0]*n
s = raw_input().split()
s = [int(num) for num in s]
s2 = []
for j in range(len(s)):
s2.append((j, s[j]))
s2 = sorted(s2, key = lambda x: x[1], reverse = True)
prev = -1
pos = 1
s3 = []
same = 0
for j in range(len(s2)):
if ( prev !=... |
In India IPL is on full swing now. Fans of cricket love watching the game and seeing ball by ball with having Snacks. Yummy, crispy snacks. Ankit and his friends are one of them.
One night, while watching his Favourite team's Match he is eating Snacks. His team is leading the game and so his enjoyment growing ball by ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
t=int(raw_input())
while t:
t=t-1
n=int(raw_input())
d=list(map(float,raw_input().split()))
f=list(map(float,raw_input().split()))
sum=0
for i in range(0,n):... |
Tic-Tac-Toe are three cousins. They planned to play cricket this afternoon but got stuck in their homework. Mrs. Jaime assigned them a task to arrange all the letters in a scrambled word in the order of their appearance in english alphabets. All the letters are in upper-case. Help Tic-Tac-Toe to solve their homework so... | t = int(raw_input())
while(t>0):
string = raw_input()
a = ''.join(sorted(string))
print a
t -= 1 |
You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.
* `0 u v`: Add an edge (u, v).
* `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise.
Constraints
* 1 \leq N \leq 200,000
* 1 \leq Q \leq 200,000
* 0 \leq u_i, v_i \lt N
Input
Input is ... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.i... |
There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.
Obs. i is said to be good when its elevation is higher than those of all observatories that can be r... | #include<bits/stdc++.h>
using namespace std;
int main(){
int N, M;
cin >> N >> M;
vector<int> H(N);
int A, B;
vector<bool> X(N,true);
for(int i=0; i<N; i++) cin >> H[i];
for(int i=0; i<M; i++){
cin >> A >> B;
if(H[A-1]>=H[B-1]) X[B-1]=false;
if(H[B-1]>=H[A-1]) X[A-1]=false;
}
int cnt=0;
... |
Takahashi has A cookies, and Aoki has B cookies. Takahashi will do the following action K times:
* If Takahashi has one or more cookies, eat one of his cookies.
* Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies.
* If they both have no cookies, do nothing.
In the end, how many cookies will Taka... | A, B, K = map(int, input().split())
print(max(0, A - K), max(0, min(A + B -K, B))) |
Given is a string S consisting of `L` and `R`.
Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.
The character written on the leftmost square is always `R`, and the character written on the rightmost square... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(void){
string s;
cin>>s;
int n=s.size();
int a[100010];
for(int i=0;i<n;i++) a[i]=1;
for(int i=0;i+2<n;i++){
if(s[i]=='R'&&s[i+1]=='R'){
a[i+2]+=a[i];
a[i]=0;
}
}
for(int ... |
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved t... | N = int(input())
M = N*(N-1)//2-N//2
print(M)
if N%2 ==0:
rem = N+1
else:
rem = N
#print(rem)
for i in range(N):
i +=1 #1index
for j in range(i,N):
j +=1 #1index
temp = [i,j]
if i+j != rem:
print(*temp) |
You are given P, a permutation of (1,\ 2,\ ...\ N).
A string S of length N consisting of `0` and `1` is a good string when it meets the following criterion:
* The sequences X and Y are constructed as follows:
* First, let X and Y be empty sequences.
* For each i=1,\ 2,\ ...\ N, in this order, append P_i to the end of... | #include<cstdio>
#include<algorithm>
using namespace std;
int gi(){
int x=0,w=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')w=0,ch=getchar();
while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return w?x:-x;
}
const int N=2e5+5;
int n,q,a[N],b[N];
struct fenwick{
int c[N],... |
Print all the integers that satisfies the following in ascending order:
* Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.
Constraints
* 1 \leq A \leq B \leq 10^9
* 1 \leq K \leq 100
* All values in input are integers.
Input
Input is give... | #include <iostream>
using namespace std;
int main()
{
int a, b, k;
cin >> a >> b >> k;
for(int i = a; i <= b; i++)
{
if(i < (a+k) || i > (b-k))
{
cout << i << endl;
}
}
return 0;
}
|
We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i.
Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they w... | import sys
n,z,w=map(int,input().split())
a=list(map(int,input().split()))
if n==1: print(abs(a[0]-w));sys.exit()
x,y=[-1]*n,[-1]*n
x[n-1]=abs(a[n-1]-w)
y[n-2]=abs(a[n-1]-a[n-2])
for i in range(n-2,-1,-1):
x[i]=abs(a[i]-a[n-1])
for j in range(i+1,n-1):
x[i]=min(x[i],y[j])
y[i]=abs(a[n-1]-a[i])
... |
Nuske has a grid with N rows and M columns of squares. The rows are numbered 1 through N from top to bottom, and the columns are numbered 1 through M from left to right. Each square in the grid is painted in either blue or white. If S_{i,j} is 1, the square at the i-th row and j-th column is blue; if S_{i,j} is 0, the ... | import java.io.*;
import java.util.*;
import java.math.*;
// import java.awt.Point;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
static int mod = 1_000_000_007;
// int mod = 998244353;
long inf = Long.MAX_VALUE/2;
void solve(){
int n = ni();
i... |
You are given nonnegative integers a and b (a ≤ b), and a positive integer x. Among the integers between a and b, inclusive, how many are divisible by x?
Constraints
* 0 ≤ a ≤ b ≤ 10^{18}
* 1 ≤ x ≤ 10^{18}
Input
The input is given from Standard Input in the following format:
a b x
Output
Print the number of th... | #include <iostream>
using namespace std;
int main() {
long long int a,b,x;
cin >> a >> b >> x;
cout << b / x - a / x + (a % x == 0 ? 1 : 0) << endl;
} |
12:17 (UTC): The sample input 1 and 2 were swapped. The error is now fixed. We are very sorry for your inconvenience.
There are N children in AtCoder Kindergarten, conveniently numbered 1 through N. Mr. Evi will distribute C indistinguishable candies to the children.
If child i is given a candies, the child's happine... | #include <bits/stdc++.h>
using namespace std;
const int N = (int)400 + 7;
const int mod = (int)1e9 + 7;
int add(int a, int b) {
a += b;
if (a > mod) a -= mod;
return a;
}
int mul(int a, int b) {
return (a * 1LL * b) % mod;
}
int n, c;
int a[N], b[N];
int sum[N][N];
int s[N][N];
int dp[N][N];
int main() {
sca... |
The problem of hiding a part of a formula and searching for the hidden number is called verbal arithmetic. This time, I'm dealing with an expression in which some numbers in the expression are hidden by X. Enter the following formula and create a program that outputs the result.
Formula
* A simple one-line addition e... | import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws java.io.IOException {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String fm[] = sc.nextLine().split("\\+|=");
int init = 0;
if (fm[0].charAt(0) == 'X' && fm[0].length()... |
Takeshi, who loves hot springs, is planning a trip to a hot spring resort on his next long vacation. I would like to travel by connecting to a long-distance bus and reach my destination with as little money as possible. Takeshi, who has savings but is unwilling to pay, decided to consult with his grandfather. The grand... | #include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using nam... |
The dice are placed in the orientation shown in the figure below.
<image>
As shown in this figure, the dice used here have 1 on the upper side and 2 on the south side, and 3 on the east side. Since the sum of the facing faces of the dice is always 7, the invisible faces are 5 on the north side, 4 on the west side, a... | #include<stdio.h>
int m[]={2189,89,1232,866,1796,2603},a,b,c,d,r;int main(){for(char s[9];~scanf("%s",s);r+=a%3?b%3?(b+6-a)%6<3?2:5:3+!b:a?6:1)*s<65?r&&printf("%d\n",r),a=c=r=0,b=1:*s%6-4?d=(*s-78?*s%5-1:0)+c&3,a=m[a]>>3*d&7,b=m[b]>>3*d&7:c+=3+*s;} |
Let's solve the puzzle by programming.
The numbers n x n are arranged in a grid pattern. Some of the numbers are circled and we will call them the starting point. The rules of the puzzle are as follows:
* Draw one line that goes vertically and horizontally from each starting point (cannot be drawn diagonally).
* Exte... |
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
private void run() throws IOException {
Scanner scanner = new Scanner(System.in);
while (true) {
n = scanner.nextInt();
if (n == 0)
break;
... |
There is a chain consisting of multiple circles on a plane. The first (last) circle of the chain only intersects with the next (previous) circle, and each intermediate circle intersects only with the two neighboring circles.
Your task is to find the shortest path that satisfies the following conditions.
* The path co... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pa... |
The committee members of the Kitoshima programming contest had decided to use crypto-graphic software for their secret communication. They had asked a company, Kodai Software, to develop cryptographic software that employed a cipher based on highly sophisticated mathematics.
According to reports on IT projects, many p... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
while(cin >> n, n) {
vector<string> ws(n);
for(auto& w : ws) cin >> w;
vector<string> ss = {""};
while(cin >> ss.back()) {
if(ss.back().back() == '.') break;
ss.push_back("");
}
... |
Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves lowercase letters as much as programming. Yu-kun decided to write a scoring program for a new play that uses paper, circles, lines, and lowercase lett... | #include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm> // require sort next_permutation count __gcd reverse etc.
#include <cstdlib> // require abs exit
#include <cstdio> // require scanf printf
#include <functional>
#... |
You are a member of a secret society named Japanese Abekobe Group, which is called J. A. G. for short. Those who belong to this society often exchange encrypted messages. You received lots of encrypted messages this morning, and you tried to decrypt them as usual. However, because you received so many and long messages... | #include <bits/stdc++.h>
using namespace std;
#define repi(i,a,b) for(int i = (int)(a); i < (int)(b); i++)
#define rep(i,n) repi(i,0,n)
string S;
int dp[2222][2222];
int trans[2222][2222];
int rec(int L, int R) {
int& ret = dp[L][R];
if(ret + 1) return ret;
int& recons = trans[L][R];
if(L > R) return ret = 0... |
Maki is a house cat. One day she fortunately came at a wonderful-looking dried fish. Since she felt not hungry on that day, she put it up in her bed. However there was a problem; a rat was living in her house, and he was watching for a chance to steal her food. To secure the fish during the time she is asleep, she deci... | #include <iostream>
#include <fstream>
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iomanip>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <s... |
Problem statement
$ N $ Line segments $ s_1, s_2, ..., s_N $ are given. At this time, find the minimum possible value of dist $ (s_i, s_j) $, ($ 1 \ leq i, j \ leq N, i \ ne j $). dist $ (s_i, s_j) $ is
* $ \ sqrt {(x_i-x_j) ^ 2 + (y_i-y_j) ^ 2} $, ($ (x_i, y_i) $ is the point above $ s_i $, $ (x_j, y_j) $ is $ s_j $... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef complex<double> P;
typedef pair<int,int> pii;
#define REP(i,n) for(ll i=0;i<n;++i)
#define REPR(i,n) for(ll i=1;i<n;++i)
#define FOR(i,a,b) for(ll i=a;i<b;++i)
#define DEBUG(x) cout<<#x<<": "<<x... |
Problem Statement
Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and always tries to save as much paper as possible. She decided to play a ghost leg with other participants to decide the team for the Aizu training camp.
How to make Amidakuji for this training camp is as foll... | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int INF = 1e9;
int N, M;
vector<int> res;
vector<int> simu(const vector<vector<bool>> &A){
vector<int> ret(N+1);
for(int i = 0; i < N+1; ++i) ret[i] = i;
for(size_t j = 0; j < A[0].size(); ++j){
for(size_t i = 0; i < ret.si... |
Example
Input
4
1 1 2
Output
6 | #include <bits/stdc++.h>
using namespace std;
#define INF (1<<29)
#define MAX_V 100010
#define MAX_LOG_V 110
typedef long long ll;
vector<int> G[MAX_V];
int root;
int deg[MAX_V];
int parent[MAX_LOG_V][MAX_V];
int depth[MAX_V];
void dfs(int v, int p, int d)
{
parent[0][v] = p;
depth[v] = d;
for (int i... |
problem
AOR Ika-chan is taking a class where grades are determined only by the score of the $ N $ report. AOR Ika-chan has $ M $ friends who are taking the same class, and if you have a report on a theme that you are not good at, you can get the same score as that friend by copying the report of a friend who is good a... | // ?????¬???????????¬??????
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#inclu... |
B: Hokkaido University Hard
Note
Please note that the question settings are the same as question A, except for the constraints.
story
Homura-chan, who passed Hokkaido University and is excited about the beginning of a new life. But in front of her, a huge campus awaits ...
"Eh ... I'm not in time for the next clas... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
H,W = map(int, input().split())
builds = []
for h in range(H):
l = str(input())
for w in range(W):
if l[w] == "B":
builds.append([h,w])
# [min,max]
lu = [H+W,0]
ld = [H+W,0]
for h,w in builds:
lu = [min(lu[0],h+w),max(lu[1],h+w)]
ld = [min(ld[0],H-h+w),ma... |
Bichrome Tree Connectivity
Given a tree.
Initially, all vertices are white.
Inverting the color of the white vertices makes it black, and inverting the color of the black vertices makes it white.
Handle two types of queries.
The first type of query inverts the color of vertex v.
The second type of query answers t... | #include <bits/stdc++.h>
using namespace std;
using ll=long long;
//#define int ll
#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rep(i,b) rng(i,0,b)
#define gnr(i,a,b) for(int i=int(b)-1;i>=int(a);i--)
#define per(i,b) gnr(i,0,b)
#define pb push_back
#define eb emplace_back
#define a first
#define b secon... |
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* get(i): output the value of ai.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ s ≤ t ≤ n
* 1 ≤ i ≤... | # -*- coding: utf-8 -*-
"""
Range Add Query (RAQ)
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_E&lang=ja
"""
import sys
def main(args):
def add(b, k, x):
while k <= n:
b[k] += x
k += k & -k
def get(b, k):
s = 0
while k > 0:
s += b... |
At the legendary times of Nonsenso wars in ISM Dhanbad, there was a neck to neck competition between Barney Stinson and Sheldon Cooper. They both were on level 19. After trying too hard both of them could not decipher the nonsense, so they decided to play alongside. Sheldon Cooper had to pass a message to Barney Stinso... | t=input()
for _ in xrange(t):
s=raw_input()
l=len(s)-1
i=0;
ss=""
while(i<l):
n=int(s[i:i+2])
if(n<20):
n=int(s[i:i+3])
i+=1
i+=2
ss+=chr(n)
print ss |
Ayan's favourite musical instrument is the keyboard. He practices regularly as well, you can hear him playing even at 3 or 4 in the night.
Unfortunately, he got into a fight in his room and his keyboard was damaged beyond repair. However, being a rich fellow he quickly ordered another one.
But this time he felt a bit a... | a = 'CcDdEFfGgABS' * 3;
T = int(input());
while T:
T -= 1
s = raw_input().split();
pos1 = a.find(s[0])
pos2 = a.find(s[1], pos1 + 1)
print 'Major' if pos2 - pos1 == 4 else 'Minor' |
Sorting is considered to be one of the most important skills to be learned in computer science and has it's applications in real product building.
The problem has arised to the team of PcCube.They need to sort the set of alphanumeric strings in such a way that the positions of alphabets and numbers remains unchanged.
... | T = int(raw_input())
for i in xrange(T):
S = raw_input()
numLst = []
charLst = []
ansLst = []
for i in S:
if (ord(i) > 47 and ord(i) < 58):
numLst.append(i)
else:
charLst.append(i)
numLst.sort(reverse=True)
charLst.sort(reverse=True)
for i in xrange(S.__len__()):
if (ord(S[i]) > 47 and ord(S[i]) <... |
Given an input sequence. You have to write a program to sort it in non decreasing order.
Input
First line of input T has number of test cases followed by T test cases.
Each test case has two lines. First line has a number N. The second line has N space separated elements as an input sequence
Output
Output has T lines... | t=input()
while(t):
t=t-1
n=input()
x=raw_input()
a=[]
u=0
v=0
for i in range(0,len(x)):
if(x[i]==" "):
v=i
a.append(int(x[u:v]))
u=v+1
a.append(int(x[v:len(x)]))
a.sort()
s=""
for i in range(0,n):
s=s+str(a[i])
s=s+" "... |
Chef taught his brother Chefu about right angled triangle and its properties. Chefu says that he has understood everything about right angled triangles. Chef wants to check learning of his brother by asking the following question "Can you find a right angled triangle whose length of hypotenuse is H and its area is S?"... | from math import sqrt
from __builtin__ import long
t = int(raw_input())
while t > 0:
t = t-1
h,s = [long(i) for i in raw_input().split()]
k = (h**4-16*s**2)
if k < 0:
print -1
else :
k = sqrt(k)
p = (h**2 + k)/2
p = sqrt(p)
b = sqrt(h**2-p**2)
if p > b:
print b,p,h
else:
print p,b,h |
The University management meets every semester to discuss about the issues of the University in a round table conference. Therefore new proposals are made to the present academic curriculum. However whenever a new proposal comes from a member, all the members of the round table, except the adjacent members , throws his... | t=input()
m=1000000007
for i in range(0,t):
n=input()
if n<=3:
print "0"
else :
print (n*(n-3)/2)%m |
There is a strange peculiarity: if you connect the cities of Rostov, Taganrog and Shakhty, peculiarly, you get a triangle
«Unbelievable But True»
Students from many different parts of Russia and abroad come to Summer Informatics School. You marked the hometowns of the SIS participants on a map.
Now you decided to pr... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D {
static PrintWriter out = new PrintWriter(System.out);
static int N;
static long GOAL;
static Vec ar[];
static Vec pnts[];
public static void ma... |
You are given an array a consisting of n integers. You can perform the following operations with it:
1. Choose some positions i and j (1 ≤ i, j ≤ n, i ≠ j), write the value of a_i ⋅ a_j into the j-th cell and remove the number from the i-th cell;
2. Choose some position i and remove the number from the i-th cell... | #include <bits/stdc++.h>
using namespace std;
struct node {
int w, id;
} a[1000010], b[1000010], d[1000010];
bool cmp(node x, node y) { return x.w < y.w; }
int main() {
int n, s1 = 0, s2 = 0, s3 = 0, x;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
if (x < 0)
a[++s1].w = x, a[s1... |
Vasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (... | n, m = map(int, input().split())
print(max(n-2*m, 0), end=' ')
for i in range(0, n+1):
if i*(i-1)/2>=m: break
print(n-i) |
Berland forest was planted several decades ago in a formation of an infinite grid with a single tree in every cell. Now the trees are grown up and they form a pretty dense structure.
So dense, actually, that the fire became a real danger for the forest. This season had been abnormally hot in Berland and some trees got... | #include <bits/stdc++.h>
using namespace std;
const int mo = 998244353, N = 55, iv6 = 166374059, iv2 = 499122177;
int n, t, x[N], y[N], ans, i, ii, j;
int ad[N * 5], T[N * 5], s[N * 5], M;
inline void upd(int x) {
if (ad[x] > 0)
T[x] = s[x];
else
T[x] = x < M ? T[x << 1] + T[x << 1 | 1] : 0;
}
inline void m... |
Lunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it.
Let f_1, f_2, …, f_i, … be an infinite sequence of positive integers. Bob knows that for i > k, f_i can be obtained by the following recursive equation:
$... | #include <bits/stdc++.h>
using namespace std;
const long long p = 998244353;
const long long g = 3;
int k;
long long n, m, b[210];
struct Matrix {
int n;
long long mat[210][210];
Matrix() {
n = 0;
memset(mat, 0, sizeof(mat));
}
Matrix(int _n, long long diag) {
n = _n;
memset(mat, 0, sizeof(mat... |
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to find any spanning tree of this graph such that the degree of the first vertex (vertex with label 1 on it) is equal to D (or sa... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.Set;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
im... |
There is a robot staying at X=0 on the Ox axis. He has to walk to X=n. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.
The i-th segment of the path (from X=i-1 to X=i) can be exposed to sunlight or not. The array s denotes which segments are ex... | n,b,a=map(int,input().split())
s=list(map(int,input().split()))
maxa=a
cnt=0
for i in range(n):
if(s[i]==0):
if(a>0):
a-=1
cnt+=1
elif(b>0):
b-=1
cnt+=1
else:
if(a<maxa and b>0):
b-=1
a+=1
cnt+=1
elif(a>0):
a-=1
cnt+=1
if(b==0 and a==0):
break
print(cnt) |
You are given an array a consisting of n integers a_1, a_2, ... , a_n.
In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n, t, a;
cin >> t;
while (t--) {
cin >> n;
int arr[3] = {0};
for (int i = 0; i < n; i++) {
cin >> a;
arr[a % 3]++;
}
if (arr[1] == 0) {
... |
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are n students living in a building, and for each of them the favorite drink a_i is known. So you know n integer... | from math import ceil
n, k = map(int, input().split())
bev = [0] * k
for i in range(n):
x = int(input())
bev[x-1] += 1
bad = 0
good = 0
for i in range(k):
bad += bev[i] & 1
good += bev[i] - (bev[i] & 1)
# print(good, bad)
bad = ceil(bad / 2)
print(good + bad) |
You are given a system of pipes. It consists of two rows, each row consists of n pipes. The top left pipe has the coordinates (1, 1) and the bottom right — (2, n).
There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:
<image> Types of pipes
... | //package cf590d3;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class C {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int q = sc.nextInt();
for(int w = 0; w < q; w++) {
int n = sc.nextInt();
char[]top = sc.nextLine().toCharArray();
char[]bot ... |
The Central Company has an office with a sophisticated security system. There are 10^6 employees, numbered from 1 to 10^6.
The security system logs entrances and departures. The entrance of the i-th employee is denoted by the integer i, while the departure of the i-th employee is denoted by the integer -i.
The compan... | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e5 + 10;
long long N, arr[maxn];
signed main() {
ios::sync_with_stdio(false);
cin >> N;
set<long long> st, today;
vector<long long> v;
long long h = 1;
for (register long long i = 1; i <= N; ++i) {
cin >> arr[i];
if (arr[i] < 0) {... |
Hooray! Polycarp turned n years old! The Technocup Team sincerely congratulates Polycarp!
Polycarp celebrated all of his n birthdays: from the 1-th to the n-th. At the moment, he is wondering: how many times he turned beautiful number of years?
According to Polycarp, a positive integer is beautiful if it consists of ... | for _ in range(int(input())):
x = input()
now = len(x)
ans = (now-1) * 9
ans += (int(x[0]))
flag = 0
for j in range(1,len(x)):
if(x[j] > x[j-1]):
break
elif(x[j] < x[j-1]):
flag = 1
break
ans -= flag
print(ans) |
The map of Bertown can be represented as a set of n intersections, numbered from 1 to n and connected by m one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.StringTokenizer;
/*
*/
public class B {
public static void main(String[] args) {
FastScanner fs = new FastScanner();
int n=fs.nextInt(), m=fs.ne... |
Consider the infinite sequence s of positive integers, created by repeating the following steps:
1. Find the lexicographically smallest triple of positive integers (a, b, c) such that
* a ⊕ b ⊕ c = 0, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
* a, b, ... | from __future__ import division,print_function
#from sortedcontainers import SortedList
import sys
#sys.__stdout__.flush()
le = sys.__stdin__.read().split("\n")
l = map(int,le[1:-1])
def f(n):
if n%3==1:
n//=3
po=1
while n>=po:
n-=po
po*=4
return po+n
if n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.