input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Two contries A and B have decided to make a meeting to get acquainted with each other. n ambassadors from A and B will attend the meeting in total.
A round table is prepared for in the meeting. The ambassadors are getting seated at the round table, but they have agreed that more than k ambassadors from the same countr... | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-9;
static const double PI = acos(-1.0);
#define REP... |
<image>
One evening. As usual, when you were watching TV in the living room, my sister in fifth grade offered me a consultation. When I listened to the story, I couldn't understand the math problem that was presented at school today, so I want you to teach me how to solve it.
The question that bothers my sister is, "... | #include <bits/stdc++.h>
using namespace std;
#define REP(i,x,y) for(int i=(x);i<(y);++i)
#define MP(a,b) make_pair((a),(b))
#define debug(x) #x << "=" << (x)
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#define dump(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl
#else
#define dump(x)
#endif
typedef long ... |
()
Problem Statement
There is a string S. Initially, S is an empty string.
Perform the following processing in order of n.
* Add x_i p_i (=" (" or") ") to the end of S.
After processing, determine if S is a well-balanced string.
"The string is balanced" is defined as follows.
* The empty string is well-balanced... | #include <iostream>
using namespace std;
int main(){
long long int n,a=0,tmp;
char p;
cin>>n;
for(int i=0;i<n;i++){
cin>>p>>tmp;
if(p=='('){
a+=tmp;
}else{
a-=tmp;
}
if(a<0){
cout<<"NO"<<endl;
return 0;
... |
A connected directed graph without a cycle is given. (A directed graph is concatenated when it is an undirected graph.)
I would like to select one vertex for this graph and determine the capital s.
Let T (v) = "the minimum number of" edge inversion "operations required to make all points reachable from v".
However, ... | #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define eb emplace_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
typedef vector<int>vint;
typedef pair<int,int>pint;
typedef vector<pint>vpint;
template<typename A,typename B>inline... |
A: Taking a Seat-Taking a Seat-
story
Mr. A entered the classroom at the examination site to take an examination. However, Mr. A is a very nervous type. Therefore, depending on the situation, there may be seats that Mr. A does not want to sit in. Therefore, Mr. A decided to find out how many seats he could sit on bas... | #define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include "bits/stdc++.h"
#define REP(i,a,b) for(i=a;i<b;++i)
#define rep(i,n) REP(i,0,n)
#define ll long long
#define ull unsigned ll
typedef long double ld;
#define ALL(a) begin(a),end(a)
#define ifnot(a) if(not a)
#define dump(x) cerr << #x << " = " << (x) <... |
F: Red-Black Soul Gem
problem
Homu-chan has the mysterious power to change the soul game to red or black, and to connect two different soul games with a magic thread. By using this power, Homu-chan can create a magic square by Sorujemu.
Homu-chan was wondering how many different magic squares there were when there w... | #include <bits/stdc++.h>
#define syosu(x) fixed<<setprecision(x)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef pair<double,double> pdd;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd... |
problem
There are $ N $ islands numbered from $ 1 $ to $ N $.
Each island has $ N-1 $ bridges, allowing any $ 2 $ island to move to each other across several bridges.
Each bridge has durability, and the durability of the $ i $ th bridge given the input is $ w_i $.
There are $ 1 $ treasures on each island, and you can ... | #define NAAN_TIKE_PLATYPUS
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <cstring>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <list>
#include <a... |
You have N items that you want to put them into a knapsack. Item i has value vi and weight wi.
You want to find a subset of items to put such that:
* The total value of the items is as large as possible.
* The items have combined weight at most W, that is capacity of the knapsack.
Find the maximum total value of i... | #include <bits/stdc++.h>
#define ll long long
#define INF 999999999
#define MOD 1000000007
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef pair<int,int>P;
typedef pair<ll,ll>pl;
const int MAX_N = 40;
ll v[MAX_N];
ll w[MAX_N];
vector<pl> x,y;
void solve(int s,int t,vector<pl> &x)
{
int z = t-s;
... |
Find the symmetric difference of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$.
Constraints
* $1 \leq n, m \leq 200,000$
* $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$
* $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$
Input
The input is given in the following format.
$n$
$a_0 \; ... | n = int(input())
a = set(map(int, input().split()))
m = int(input())
b = set(map(int, input().split()))
s_union = a | b
s_intersection = a & b
ans = s_union - s_intersection
if ans:
print(*sorted(ans), sep="\n")
|
Little Churu is a naughty child, who likes to play with balls. He has N buckets. Each bucket contains one or more balls. He has numbered his buckets 1 to N (both inclusive). He has an infinite supply of extra balls, apart from the ones already in the buckets. He wants to add zero or more number of balls to each of the ... | T = int(raw_input())
n = []
a = []
m = []
for t in xrange(T):
n.append(int(raw_input()))
a.append(map(int, raw_input().split()))
m.append(max(a[-1]))
M = max(m)
l = [False, False] + [True] * (M-1)
for i in xrange(2,M+1):
if (l[i]):
for j in range(2*i, M+1, i):
l[j]=False
for t in xrange(T):
x = 0
for i i... |
Problem text...
Many persons are familiar with the Roman numerals for relatively small
numbers. The symbols i, v, x, l and c represent the decimal values 1, 5, 10, 50 and
100 respectively. To represent other values, these symbols, and multiples where
necessary, are concatenated, with the smaller valued symbols written ... | def toroman(N):
R = []
for D in [100,50,10,5,1]:
R.append(N / D)
N %= D
R = ''.join(map(lambda x: x[0]*x[1], zip('clxvi', R)))
R = R.replace('lxxxx', 'xc')
R = R.replace('xxxx', 'xl')
R = R.replace('viiii', 'ix')
R = R.replace('iiii', 'iv')
return R
def process(N):
... |
In mathematics, the factorial of a non-negative integer N, denoted by N!, is the product of all positive integers less than or equal to N. The factorial operation is encountered in many areas of mathematics, notably in combinatorics, algebra, and mathematical analysis. Its most basic occurrence is the fact that there a... | import math
t = input();
while(t > 0):
print math.factorial(input());
t -= 1; |
Mike is given a matrix A, N and M are numbers of rows and columns respectively. A1, 1 is the number in the top left corner. All the numbers in A are non-negative integers. He also has L pairs of integers (ik, jk). His task is to calculate Ai1, j1 + Ai2, j2 + ... + AiL, jL.
Unfortunately, Mike forgot if Ai, j was a nu... | # codeChef problem Code: MIKE1
m, n = map(int, raw_input().split() )
Given = []
for i in xrange( m ) :
Given.append( map(int, raw_input().split() ) )
k = int( raw_input() )
flag1 = flag2 = 0
E1 = E2 = 0
for i in xrange( k ) :
point = map(int, raw_input().split() )
if ( flag1 == 1 or point[0] > m or point[1]... |
Problem description
Ravi has fallen in love with Riya. As he is my best friend, I am the only person who knows it and of course I am not going to tell you how this happened :DHe starts messaging Riya as everyone does and soon realizes that his fingers are unable to type any more. He decides to reduce his work from the ... | t=input()
s="abcdefghijklmnopqrstuvwxyz"
d={}
count=1
for i in s:
d[i]=count
count+=1
for kk in range(0,t):
s=raw_input()
ans=0
for i in s:
ans+=d[i]
print ans |
Chef has a binary tree. The binary tree consists of 1 or more nodes. Each node has a unique integer id. Each node has up to 2 children, which are identified by their ids, and each node is the child of at most 1 other node. A node X is considered to be an ancestor of node Y if node Y is a child of node X or if there is ... | t=input()
for i in range(t):
n=input()
a=0
b=0
for j in range(n):
x,y=map(int,raw_input().split())
a+=x
b+=y
print a-b |
There is a light source on the plane. This source is so small that it can be represented as point. The light source is moving from point (a, s_y) to the (b, s_y) (s_y < 0) with speed equal to 1 unit per second. The trajectory of this light source is a straight segment connecting these two points.
There is also a fenc... | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 200000;
pair<double, double> lrs[MAX_N];
int fss[MAX_N + 1];
int main() {
int sy, a, b, n;
scanf("%d%d%d%d", &sy, &a, &b, &n);
for (int i = 0; i < n; i++) {
int l, r;
scanf("%d%d", &l, &r);
lrs[i] = pair<double, double>(l, r);
fss[i +... |
The Hexadecimal virus loves playing with number sets — intersecting them, uniting them. One beautiful day she was surprised to find out that Scuzzy, her spherical pet cat, united all sets in one and ate the result! Something had to be done quickly and Hexadecimal rushed to the market.
The market has n sets of numbers ... | #include <bits/stdc++.h>
using namespace std;
const int Maxn = 605;
int n, s, t, cnt, dis[Maxn], cur[Maxn], head[Maxn];
long long tot, ans, val[Maxn];
struct edg {
int nxt, to;
long long w;
} edge[2 * Maxn * Maxn];
void add(int x, int y, long long w) {
edge[++cnt] = (edg){head[x], y, w};
head[x] = cnt;
edge[+... |
There are n cities in the kingdom X, numbered from 1 through n. People travel between cities by some one-way roads. As a passenger, JATC finds it weird that from any city u, he can't start a trip in it and then return back to it using the roads of the kingdom. That is, the kingdom can be viewed as an acyclic graph.
Be... | #include <bits/stdc++.h>
using namespace std;
const int N = 300010, M = 5 * 300000;
int n, m, val[N], in[N], u, v, idx[N], cnt = 0, cur = 0, tmpin[N], ans = 0,
node, arr[N], seg[4 * N], num[N],
arr2[N];
vector<int> g[N];
int A[N], B[N];
prior... |
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicog... | #include <bits/stdc++.h>
using namespace std;
long long n, k, ans = 0;
string s, t;
int main() {
cin >> n >> k;
cin >> s;
cin >> t;
long long range = 1, l = 0, r = 0;
for (int i = 0; i < n; ++i) {
l = (l << 1) + (s[i] - 'a');
r = (r << 1) + (t[i] - 'a');
if (range < k) {
range = min(k, r - l... |
Two people are playing a game with a string s, consisting of lowercase latin letters.
On a player's turn, he should choose two consecutive equal letters in the string and delete them.
For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A p... | import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void fun(String x) {
Stack A= new Stack();
Stack B= new Stack();
for(int i=0; i<x.length(); i++) {
A.push(x.charAt(i));
}
int c=0;
B.push(A.pop());
while(!A.empty()) {
if(A.peek().equals(B.peek())) {
A.pop();
... |
Semyon participates in the most prestigious competition of the world ocean for the title of the most dangerous shark. During this competition sharks compete in different subjects: speed swimming, masking, map navigation and many others. Now Semyon is taking part in «destruction» contest.
During it, m dominoes are plac... | #include <bits/stdc++.h>
using namespace std;
int k[250005];
vector<int> a[250005], c[250005];
int height[10000005], L[10000005], R[10000005];
long long cost[10000005], dp[10000005];
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", &k[i]);
a[i].resize(k[i] + 1);
... |
Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.
Neko has two integers a and b. His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers k, he needs ... | #include <bits/stdc++.h>
using namespace std;
const int MXN = (int)1e6 + 7;
long long gcd(long long v1, long long v2) {
while (v1) {
long long tmp = v2 % v1;
v2 = v1;
v1 = tmp;
}
return v2;
}
int main() {
long long a, b;
scanf("%lld %lld", &a, &b);
if (a > b) swap(a, b);
if (a == b) {
puts... |
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements?
Input
The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a.
The second line contains 2n space-separat... | import java.util.*;
public class A{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n*2];
boolean flag=false;
int cnt=1;
for(int i=0;i<n*2;i++)
{
a[i]=sc.nextInt();
if(... |
There are n points on the plane, the i-th of which is at (x_i, y_i). Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.
The strange area is enclosed by three lines, x = l, y = a and x = r, as its left side, its bottom side and its right side respectively, where l, r and a can be ... | #include <bits/stdc++.h>
using namespace std;
int n, k, p[(int)2e5 + 5], tree[(int)8e5 + 5];
pair<int, int> inp[(int)2e5 + 5];
long long ans;
int f(int x) { return lower_bound(p + 1, p + 1 + k, x) - p; }
int update(int i, int t, int nl, int nr) {
if (i < nl || nr < i) return tree[t];
if (nl == nr) return tree[t] = ... |
One day mum asked Petya to sort his toys and get rid of some of them. Petya found a whole box of toy spiders. They were quite dear to him and the boy didn't want to throw them away. Petya conjured a cunning plan: he will glue all the spiders together and attach them to the ceiling. Besides, Petya knows that the lower t... | import java.io.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class F120{
static int depth;
static int extremeNode;
static ArrayList<Integer> adj[];
public static void main(String args[]){
// BufferedReader br = new BufferedReader(new InputStreamReader);
// Reader sc = new Reader();
... |
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi ha... | import java.util.*;
import java.io.*;
public class Q2
{
static Print print;
static int max=0;
private static void meth(boolean arr[][],int col[],int i)
{
if(i==col.length)
{
int temp=meth1(arr,col);
max=Math.max(max,temp);
return;
}
for(int j=0;j<6;j++)
{
col[i]=j;
meth(arr, col, i+1);
}... |
Polycarp wants to build a fence near his house. He has n white boards and k red boards he can use to build it. Each board is characterised by its length, which is an integer.
A good fence should consist of exactly one red board and several (possibly zero) white boards. The red board should be the longest one in the fe... | #include <bits/stdc++.h>
#pragma warning(disable : 4996)
using namespace std;
using ld = long double;
template <class T>
using Table = vector<vector<T>>;
const ld eps = 1e-9;
template <class S, class T>
ostream &operator<<(ostream &os, const pair<S, T> v) {
os << "( " << v.first << ", " << v.second << ")";
return o... |
At first, let's define function f(x) as follows: $$$ \begin{matrix} f(x) & = & \left\{ \begin{matrix} x/2 & \mbox{if } x is even \\\ x - 1 & \mbox{otherwise } \end{matrix} \right. \end{matrix} $$$
We can see that if we choose some value v and will apply function f to it, then apply f to f(v), and so on, we'll eventua... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
long long n, k;
cin >> n >> k;
auto count = [&](long long x) {
if (x % 2 == 1) {
long long left = x, right = x;
long long ans = 0;
while (left <= n) {
ans += min(right, n) - left + 1;
... |
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum pos... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const int MOD = 1e9 + 7;
long long qpow(long long a, long long b, long long m) {
long long ans = 1;
while (b) {
if (b & 1) ans = (ans * a) % m;
b /= 2;
a = (a * a) % m;
}
return ans;
}
vector<int> adj[N];
int dep[N];
int par[N];
vo... |
VK just opened its second HQ in St. Petersburg! Side of its office building has a huge string s written on its side. This part of the office is supposed to be split into m meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, bu... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
constexpr int MOD = 1000 * 1000 * 1000 + 7;
constexpr int ALPHABET_SIZE = 26;
constexpr ll INF = 1e18;
bool check(const string& s, ll k, vector<vector<ll>>& dp, vector<int>& cont,
const string& cand, int m) {
... |
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.
<image>
The dragon has a hit p... | import math
t=int(input())
for i in range(t):
x,n,m=map(int,input().split())
if(x-m*10<=0):
print("YES")
else:
s=x
for i in range(n):
j=math.floor(s/2)+10
# print(x," ",j)
if(j>s):
break
else:
s=j
if(s-(m*10)<=0):
print("YES")
else:
print("NO")
|
You know, it's hard to conduct a show with lots of participants and spectators at the same place nowadays. Still, you are not giving up on your dream to make a car crash showcase! You decided to replace the real cars with remote controlled ones, call the event "Remote Control Kaboom Show" and stream everything online.
... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
os << '{';
string sep;
for (const auto &x : v) os << sep << x, sep = ", ";
return os << '}';
}
template <typename T, size_t size>
ostream &operator<<(ostream &os, const array<T, size> &arr)... |
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ... | #include <bits/stdc++.h>
using namespace std;
int cnt[2];
int solve(string &str) {
int ans = 1;
int c = 0, p = 0;
if (str[0] == 'C')
cnt[1]++;
else
cnt[2]++;
for (int i = 1; i < str.size(); i++) {
if (str[i] == str[i - 1]) {
if (str[i] == 'C') {
if (cnt[1] == 5) {
ans++;
... |
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.
Note that all computa... | import math
def sumInBase(num, base):
ans = 0
while num != 0:
ans += num % base
num //= base
return ans
A = int(input())
sumofAll = 0
for i in range(2, A):
sumofAll += sumInBase(A, i)
temp = math.gcd(sumofAll, A - 2)
print('{}/{}'.format(sumofAll // temp, (A - 2) // temp))
|
The Bubble Cup hypothesis stood unsolved for 130 years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem:
Given a number m, how many polynomials P with coefficients in set {\{0,1,2,3,4,5,... | import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.InputMismatchException;
/**
* Built using CHelper plug-in
* Actua... |
Petya is preparing for his birthday. He decided that there would be n different dishes on the dinner table, numbered from 1 to n. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.
Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his ord... | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Map.Entry;
i... |
Suppose you have a sequence of k integers A = [a_1, a_2, ... , a_k] where each a_i ≥ 2. A sequence of prime integers P = [p_1, p_2, ..., p_k] is called suitable for the sequence A if a_1 is divisible by p_1, a_2 is divisible by p_2 and so on.
A sequence of prime integers P is called friendly if there are no unique in... | #ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
//#pragma GCC optimize("O3")
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
typedef long long ll;
int n, k;
const int maxN = 1005;
ll x[maxN];
const int BUBEN2 = 15;
mt19937 rnd(228);
long long multModulo(long long a, long long b, long long m) {
long... |
This is an interactive problem.
There exists a matrix a of size n × m (n rows and m columns), you know only numbers n and m. The rows of the matrix are numbered from 1 to n from top to bottom, and columns of the matrix are numbered from 1 to m from left to right. The cell on the intersection of the x-th row and the y-... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define FOR(i, a, b) for (int (i) = (a); (i) <= (b); (i)++)
#define ROF(i, a, b) for (int (i) = (a); (i) >= (b); (i)--)
#define REP(i, n) FOR(i, 0, (n)-1)
#define sqr(x) ((x) * (x))
#define all(x) (x).begin(), (x).end()
#de... |
Baby Ehab was toying around with arrays. He has an array a of length n. He defines an array to be good if there's no way to partition it into 2 subsequences such that the sum of the elements in the first is equal to the sum of the elements in the second. Now he wants to remove the minimum number of elements in a so tha... | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define mxe(a,n) max_element(a,a+n)-a
#define mne(a,n) min_element(a,a+n)-a
#define mod 1000000007
//#define mod 998244353
ll... |
This is the easy version of the problem. The only difference is that here k=2. You can make hacks only if both the versions of the problem are solved.
This is an interactive problem.
Every decimal number has a base k equivalent. The individual digits of a base k number are called k-its. Let's define the k-itwise XOR ... | #include <iostream>
#include <vector>
#include <unordered_set>
#include <set>
#include <cstring>
#include <map>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
using ll = long long;
const ll INF = 1e18 + 1;
const ll mod = 1e9 + 7;
int main() {
cin.tie(0);
ios_... |
You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language.
Input
This program has only one test, and it's empty (it doesn't give your program anything to rea... | #include <bits/stdc++.h>
using namespace std;
int main() { cout << "INTERCAL"; }
|
They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1;
struct my {
int first, second, col, hld;
} b[N];
int l = 1, C = 1, tin[N], tout[N], timer, n, m, first, second, z, up[N][25],
d[N], sz[N], s, v, ans[N];
pair<int, int> pred[N];
vector<pair<int, int> > a[N];
vector<int> tree[N], hld[N];
void dfs(... |
There is a board with a grid consisting of n rows and m columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number i and column number j as (i, j).
A group of six numbers (a, b, c, d, x0, y0), where 0 ≤ a... | #include <bits/stdc++.h>
using namespace std;
int n, m, s;
long long count(int a, int b, int c, int d) {
long long dx = max(a, c), dy = max(b, d);
long long ret = max(0LL, (n + 1 - (dx * 2 + 1)) * (m + 1 - (dy * 2 + 1)));
return ret;
}
int main() {
cin >> n >> m >> s;
long long num = 0;
for (int a = 0; a * ... |
A sequence of non-negative integers a1, a2, ..., an of length n is called a wool sequence if and only if there exists two integers l and r (1 ≤ l ≤ r ≤ n) such that <image>. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.
The expression <image> means applying the o... |
import java.io.*;
//import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
public class citylights {
public static int[] arr;
public static ArrayList<Integer> p;
public static int[] val;
public static long[] facto;
public static long mod = 1000000007;
public static... |
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.
The stones always fall to the center of Liss's inter... | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Dictionary;
... |
Little penguin Polo adores strings. But most of all he adores strings of length n.
One day he wanted to find a string that meets the following conditions:
1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.
2. No two neighbouring... |
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
... |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | n=int(input())
if n>=0:
print(n)
else:
r=n+(2*n)
n=str(n)
k=len(n)
ones=int(n[k-1])
huns=int(n[k-2])
if ones>=huns:
print(int(n[:k-1]))
else:
f=n[:k-2]+n[k-1]
print(int(f))
|
You are given n rectangles, labeled 1 through n. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).
Your task is to det... | #include <bits/stdc++.h>
using namespace std;
int n, U[100010], D[100010], L[100010], R[100010], s[3010][3010], K,
cl[3010][3010], Le[3010][3010], Up[3010][3010];
int ans[100010];
void read(int &x) {
char ch = getchar();
int mark = 1;
for (; ch != '-' && (ch < '0' || ch > '9'); ch = getchar())
;
if (ch ... |
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more.
Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with c... | #include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
int A[3][N];
for (int i = 0; i < N; i++) cin >> A[0][i];
for (int i = 0; i < N; i++) cin >> A[1][i];
for (int i = 0; i < N; i++) cin >> A[2][i];
long long DP[N][4];
DP[0][0] = A[0][0];
DP[0][1] = A[0][0];
DP[0][2] = A[1][0];... |
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current seq... | #include <bits/stdc++.h>
using namespace std;
const double PI = 3.14159265358979323846;
const double SQRT2 = 1.41421356237;
const double EPS = 1e-9;
const float SQRT2F = (float)SQRT2;
const int INF = 1e9;
const long long INF64 = 1e18;
template <class T>
const T sqr(const T &x) {
return x * x;
}
template <class T>
con... |
The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≤ i ≤ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≤ i < n), ai + 1 - ai = k, where k is the number the Queen... | #include <bits/stdc++.h>
int main() {
int n, k, p;
int tree[1001];
int i, j, b, sum, f, w = 1;
scanf("%d%d", &n, &k);
p = n;
for (i = 1; i <= n; i++) {
scanf("%d", &tree[i]);
}
for (i = 1; i <= n; i++) {
b = tree[i];
sum = 0;
if (b - (i - 1) * k <= 0) continue;
f = b - (i - 1) * k;
... |
Right now you are to solve a very, very simple problem — to crack the safe. Four positive integers stand one by one on a circle protecting the safe. You know that to unlock this striking safe you have to make all four numbers equal to one. Operations are as follows: you may choose two adjacent numbers and increase both... | #include <bits/stdc++.h>
double const PI = 4 * atan(1.0);
using namespace std;
int a[5];
bool toan1() {
for (int i = 1; i <= 4; i++)
if (a[i] != 1) return false;
return true;
}
bool doi2() {
for (int i = 1; i <= 4; i++)
if (a[i] % 2 == 0 && a[i % 4 + 1] % 2 == 0) {
a[i] /= 2;
a[i % 4 + 1] /= 2... |
You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Syl... | var size = readline() - 0;
var line = readline();
var arr = ['Vaporeon', 'Jolteon', 'Flareon', 'Espeon', 'Umbreon', 'Leafeon', 'Glaceon' , 'Sylveon'].sort();
// var size = 7;
// var line = 'j......';
var has_found = 0;
for(var i in arr){
if(arr[i].search(RegExp(line,'i'))==0){
print(arr[i].toLocaleLowerCase... |
Marmot found a row with n pillars. The i-th pillar has the height of hi meters. Starting from one pillar i1, Marmot wants to jump on the pillars i2, ..., ik. (1 ≤ i1 < i2 < ... < ik ≤ n). From a pillar i Marmot can jump on a pillar j only if i < j and |hi - hj| ≥ d, where |x| is the absolute value of the number x.
Now... | #include <bits/stdc++.h>
using namespace std;
template <class T>
struct Seg {
const T ID = {0, -1};
T comb(T a, T b) { return a.first >= b.first ? a : b; }
int n;
vector<T> seg;
Seg(int _n) {
n = _n;
seg.resize(2 * n, ID);
}
void pull(int p) { seg[p] = comb(seg[2 * p], seg[2 * p + 1]); }
void up... |
Some country consists of (n + 1) cities, located along a straight highway. Let's number the cities with consecutive integers from 1 to n + 1 in the order they occur along the highway. Thus, the cities are connected by n segments of the highway, the i-th segment connects cities number i and i + 1. Every segment of the h... | #include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const long long maxn = 1e5 + 100;
const long long mod = 1e9 + 7;
const long double PI = acos((long double)-1);
long long pw(long long a, long long b, long long md = mod) {
long long res = 1;
while (b) ... |
You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself.
You want the race to be open to bot... | #include <bits/stdc++.h>
using namespace std;
const int N = 200010;
struct edge {
int from, to, next;
} e[N * 20], e2[N * 10];
int head[N], ecnt, vis[N], fa[N][18], dep[N], ok[N * 10], ecnt2;
map<pair<int, int>, int> mp;
inline void adde(int from, int to) {
e[++ecnt] = (edge){from, to, head[from]}, head[from] = ecn... |
The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time ... | #include <bits/stdc++.h>
using std::max;
using std::memset;
using std::min;
using std::swap;
using std::vector;
const int maxn = 105;
int n, a[maxn], b[maxn];
vector<int> e[maxn];
vector<int> vis;
bool sol;
char line[maxn];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%s", line + 1);
... |
There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves.
Tablecity can be represented as 1000 × 2 grid, where every cell represents one district. Eac... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n = 1000 + 1000 + 1;
printf("%d\n", n);
for (int i = (int)(1); i <= (int)(1000); ++i)
printf("%d %d %d %d\n", i, 1, i, 2);
puts("1 1 1 2");
for (int i = (int)(1); i <= (int)(1000); ++i)
printf("%d %d %d %d\n", i, 1, i, 2);
return 0;
}
|
A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values — the start time li and the finish time ri (li ≤ ri).
Restaurant management can accept and reject orders. What is the maximal number of orders the ... | #include <bits/stdc++.h>
using namespace std;
bool comp(const pair<long long, long long> &a,
const pair<long long, long long> &b) {
return a.second < b.second;
}
long long bs(pair<long long, long long> a[], long long l, long long r,
long long &srch) {
long long ans = -1, m;
while (l <= r) {... |
A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are <image> roads in total. It takes exactly y seconds to traverse any single road.
A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any t... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200005;
int N;
long long X, Y;
vector<int> G[MAX];
long long dp[MAX][2];
bool is_star() {
for (int i = 0; i < N; i++) {
if (G[i].size() == N - 1) {
return true;
}
}
return false;
}
long long DP(int u, int p, int k) {
if (dp[u][k] != -1)... |
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only th... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, d, h;
scanf("%d %d %d", &n, &d, &h);
if (2 * h < d || (n > 2 && d == 1)) {
printf("-1");
return 0;
}
for (int i = 1; i < h + 1; i++) printf("%d %d\n", i, i + 1);
if (d > h) {
printf("%d %d\n", 1, h + 2);
}
for (int i = h + 3; ... |
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions.
To be precise, researchers introd... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:256000000")
using namespace std;
const int inf = 1000000000;
int x[4], y[4];
int order[4];
int sx[4] = {0, 1, 1, 0};
int sy[4] = {0, 0, 1, 1};
int dx[4] = {-1, 0, 0, 1};
int dy[4] = {0, -1, 1, 0};
int d[4];
bool setValue(int &v, int nv) {
if (v == nv) {
ret... |
Heidi got one brain, thumbs up! But the evening isn't over yet and one more challenge awaits our dauntless agent: after dinner, at precisely midnight, the N attendees love to play a very risky game...
Every zombie gets a number ni (1 ≤ ni ≤ N) written on his forehead. Although no zombie can see his own number, he can ... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:64000000")
using namespace std;
int q;
int main() {
cin >> q;
for (int i = 0; i < q; ++i) {
int gg = 0;
int r, n;
cin >> n >> r;
for (int i = 0; i < n - 1; ++i) {
int ff;
cin >> ff;
gg = (gg + (r - ff + n) % n) % n;
}
... |
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occur... | #include <bits/stdc++.h>
using namespace std;
map<long long, long long> ct;
long long get(long long x) {
long long st = 1;
long long ans = 0;
while (x > 0) {
ans += (x & 1) * st;
x /= 10;
st *= 10;
}
return ans;
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
long long n;
cin >> n;
... |
The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs.
The stairs consists of n steps. The steps are numbered from bottom to top, it means that the lowest ste... | //package que_b;
import java.io.*;
import java.util.*;
import java.math.*;
public class utkarsh {
InputStream is;
PrintWriter out;
long mod = (long) (1e9 + 7), inf = (long) (3e18);
class pair {
int I;
long V;
pair(int i, long v) {
I = i; V = v;
}... |
It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu ... | #include <bits/stdc++.h>
using namespace std;
struct Dominator {
struct min_DSU {
vector<int> par, val;
vector<int> const& semi;
min_DSU(int N, vector<int> const& semi) : par(N, -1), val(N), semi(semi) {
iota(val.begin(), val.end(), 0);
}
void comp(int x) {
if (par[par[x]] != -1) {
... |
Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.
Not all of sellers are honest, so now some products could be more expensive than after a week of discou... | import java.io.*;
import java.util.*;
import java.math.*;
public class utkarsh {
InputStream is;
PrintWriter out;
long maxl = 4L * (long)1e18, mod = (long)1e9 + 7L;
int p[], maxi = 2 * (int)1e9, sz, np = 15485900, modi = (int)1e9 + 7;
boolean b[]; // = isPrime();
class pair{
... |
Thank you for helping Heidi! It is now the second of April, but she has been summoned by Jenny again. The pranks do not seem to end...
In the meantime, Heidi has decided that she does not trust her friends anymore. Not too much, anyway. Her relative lack of trust is manifested as follows: whereas previously she would ... | #include <bits/stdc++.h>
using namespace std;
int n, k;
vector<pair<int, int> > adj[100100];
long long dp[100100][2];
void dfs(int x, int p) {
set<pair<long long, int> > cur;
for (auto i : adj[x]) {
if (i.first != p) {
dfs(i.first, x);
cur.insert(make_pair(-dp[i.first][0] - i.second, i.first));
... |
You are given a tree consisting of n vertices (numbered from 1 to n). Initially all vertices are white. You have to process q queries of two different types:
1. 1 x — change the color of vertex x to black. It is guaranteed that the first query will be of this type.
2. 2 x — for the vertex x, find the minimum inde... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
constexpr int MOD = 1000000007;
constexpr ll INF = (1LL << 61) - 1;
template <class T>
inline bool chmin(T& a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template <class T>
inline bool chmax(T& a, T ... |
The Floral Clock has been standing by the side of Mirror Lake for years. Though unable to keep time, it reminds people of the passage of time and the good old days.
On the rim of the Floral Clock are 2n flowers, numbered from 1 to 2n clockwise, each of which has a colour among all n possible ones. For each colour, the... | #include <bits/stdc++.h>
template <typename T>
inline void read(T& x) {
x = 0;
char s = (char)getchar();
bool f = false;
while (!(s >= '0' && s <= '9')) {
if (s == '-') f = true;
s = (char)getchar();
}
while (s >= '0' && s <= '9') {
x = (x << 1) + (x << 3) + s - '0';
s = (char)getchar();
}... |
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if... | import java.util.*;
//_________________________________________________________________
public class Main {
static boolean prime(int x){
if (x==1||x==2||x==3)return true;
for (int i=3;i<x;i++){
if (x%i==0)return false;
}return true;
}
public static void main(String[] arg... |
— Thanks a lot for today.
— I experienced so many great things.
— You gave me memories like dreams... But I have to leave now...
— One last request, can you...
— Help me solve a Codeforces problem?
— ......
— What?
Chtholly has been thinking about a problem for days:
If a number is palindrome and length of its ... | import itertools as it
k, p = [int(elem) for elem in input().split()]
def build_palindroms(digits):
global k
global val
n = digits // 2
values = [10 ** (digits - 1 - i) + 10 ** i for i in range(n)]
for comb in it.product(range(1, 10), *[range(0, 10) for i in range(n - 1)]):
if not k:
... |
As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him.
<image>
Thus, he came up with a puz... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
string a;
cin >> a;
long long answer = 0;
for (int i = 0; i < a.size(); i++) {
long long open = 0;
long long q = 0;
for (int j = i; j < a.size(); j++) {
if (a[j] == '(') {
open += 1;
} else ... |
And where the are the phone numbers?
You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.
It's guaranteed that the answ... | import java.util.Scanner;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class C {
static SortedSet<Integer> valueSet = new TreeSet<>();
private static int MAX_VALUE;
private static int MIN_VALUE;
public static void main(String[] args) throws InterruptedException {
Integ... |
Indiana Jones found ancient Aztec catacombs containing a golden idol. The catacombs consists of n caves. Each pair of caves is connected with a two-way corridor that can be opened or closed. The entrance to the catacombs is in the cave 1, the idol and the exit are in the cave n.
When Indiana goes from a cave x to a ca... | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> G[300005];
int pre[300005];
int d[300005];
int maxn;
void dfs() {
for (int s = 1; s <= n; s++) {
d[s] = 0x3f3f3f3f;
}
memset(pre, 0, sizeof(pre));
maxn = 0;
queue<int> q;
q.push(1);
d[1] = 0;
pre[1] = 0;
while (!q.empty()) {
i... |
Hibiki and Dita are in love with each other, but belong to communities that are in a long lasting conflict. Hibiki is deeply concerned with the state of affairs, and wants to figure out if his relationship with Dita is an act of love or an act of treason.
<image>
Hibiki prepared several binary features his decision w... | #include <bits/stdc++.h>
using namespace std;
struct op {
string ot;
int conn1, conn2;
int getConn(int idx) { return idx ? conn2 : conn1; }
};
int n, m, k;
int val[2][50];
vector<op> ops[2];
bool occ[50][4];
string neg(string ot) {
if (ot[0] == 'n') return ot.substr(1, ((int)(ot).size()) - 1);
return "n" + ot... |
Rachel, being an awesome android programmer, just finished an App that will let us draw a triangle by selecting three points on the touch-plane.Now She asks her friend Bruce to draw a Right-Angled Triangle (we'll call it RAT) by selecting 3 integral points on the plane.
A RAT is a triangle with Non-Zero area and a rig... | def dist(x1,y1,x2,y2):
return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)
def is_RAT(a):
ab = dist(a[0],a[1],a[2],a[3])
bc = dist(a[4],a[5],a[2],a[3])
ca = dist(a[0],a[1],a[4],a[5])
if ab == bc+ca or ca == bc+ab or bc == ab+ca:
return True
return False
def samepoint(a):
if a[0]==a[2] and a[1] == a[3]:
return True
if ... |
In a coordinate system,There are 3 chocolate which will be placed at three random position (x1,y1),(x2,y2) and (x3,y3).Ramesh loves Chocolates. Ramesh always moves along a straight line. your task is to find out whether he can have all the chocolates.
Input Format :-
The first line of the input contains an integer T d... | for _ in xrange(input()):
ax, ay, bx, by, cx, cy = map(int, raw_input().split())
area = abs(ax*(by-cy) + bx*(cy-ay) + cx*(ay-by))
if area:
print "NO"
else:
print "YES" |
As Valentines Day was approaching, some couples on the campus are upto some mischief and are sneaking around in the Campus Building. But the building has teachers roaming inside it. The teacher both blocks the way and will catch you if you fall into their line of sight. Also, everytime you take a step, each teacher tur... | from collections import *
for T in range(input()):
m,n=map(int,raw_input().split())
board=[list(raw_input()) for i in range(m)]
for i in range(m):
for j in range(n):
if board[i][j] == 'S':
start = i,j
board[i][j] = '.'
elif board[i][j] == 'G':
... |
My good friend Guruji once submitting his code on forum mistakenly forgot to check language option. His code got pasted in general editor. Due to this many portion of his code got changed. One funny thing which happened was that sub-string "<3" got changed into a heart.
Your job is simple, count the number of "<3"(quot... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
s=raw_input()
l=len(s)
c=0
for i in range(0,l-1):
if s[i] == '<':
if s[i+1] == '3':
c=c+1
print c |
Gwen is good in hacking. She helps Ben and Kevin in many missions. This time the boys need CCTV recordings of a particular area. The security network is secured by a special keyless encryption. When she tries to access the tapes remotely, she sees a series of non-negative integers on screen. By stealing security logs a... | t=input()
i=0
while i<t:
n=input()
x=raw_input().split(' ')
cnt=0
j=0
while j<n:
el=int(x[j])
if j==0:
sm=int(x[1])
else:
sm=int(x[0])
k=0
while k<n:
if k!=j:
sm=sm&int(x[k])
k=k+1
if el==... |
Solve the Mystery.
Input :
First line contains T - No. of Test cases.
Each Test case consists of 2 lines.
First line contains K.
Second line contains 3 space separated Integers A1 ,A2 ,A3.
Output :
Print required answers in separate lines.
Constraints :
1 ≤ T ≤ 100
1 ≤ K ≤ 10
0 ≤ Ai ≤10
SAMPLE INPUT
2
2
5 4 3
... | t = input()
while t > 0:
n = input()
a,b,c = map(int,raw_input().split())
print (a+b+c)**n
t = t-1 |
Ted: Robin, get me my legal pad. It's Pros and Cons Time!
There is a long list of n girls in front of Barney, and he is to calculate the optimal "happiness" he can find by selecting exactly 2 girls. (Why 2? No one knows!)
Ted, as a fan of pros and cons, suggests to make a list, a method for estimating the maximum hap... | t = input()
for _ in range(t):
n = input()
h = [0]*n
s = [0]*n
c = []
ans = 0
for i in range(n):
h[i], s[i] = map(int,raw_input().split())
c.append(h[i]+s[i])
for i in range(2):
temp = -1
ind = -1
for j in range(n):
if c[j]>temp:
temp = c[j]
ind = j
ans += h[ind]
h[ind] = -1
s[ind] = -... |
Prateek and Chintu are working on different projects both with equal priority. They both need to run some batches of processes. A batch has processes which need some systems to run them irrespective of the number of process running on each dependent system. If a batch runs then the dependent systems are occupied by its... | '''
# 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!'
nOfS = int(raw_input())
pOnS = raw_input().split()
nOfB = int(raw_input())
bs = []
pOfB = []
count = 0
pbCount = 0
bsset = []
bsCount = []
for i in range(nOfB):
b... |
Today, you have been given the task of handling the entire Taxi Network of Berland City. Berland city has a huge number of taxi travellers, and you need to help them in transportation in the most efficient manner.
To be precise, this city consists of N users who want to travel via a Taxi today. You have a total of M ... | try:
M, N = map(int, raw_input().split())
taxis = [0 for i in range(N)]
users = []
for i in range(M):
S, J = map(int, raw_input().split())
users.append([S,J, i])
users = sorted(users, key = lambda user: user[0])
ans = [0]*M
for user in users:
flag = False
for i in range(N):
if taxis[i] <= user[0... |
Max feels lonely after shifting to a new locality, as he does not have any friend there. So his parents bought him a new number from the Integers SuperMarket! Every child in the locality has bought a number from the same market.
He takes the number to go play with other children in the locality. But to his surprise,... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
from fractions import gcd
a=int(input())
n=int(input())
arr=map(int,raw_input().split())
count=0
for i in arr:
if gcd(i,a)!=1:
count+=1
print count |
How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"?
The answer can be enormous, so print it modulo (10^9+7).
Constraints
* K is an integer between 1 and 10^6 (inclusive).
* S is a string of length between 1... | import sys,queue,math,copy,itertools,bisect,collections,heapq
def main():
MOD = 10**9 + 7
NI = lambda : int(sys.stdin.readline())
SI = lambda : sys.stdin.readline().rstrip()
K = NI()
S = SI()
LS = len(S)
f = [1] * (K+LS)
r = [1] * (K+LS)
c = 1
for i in range(1, K + LS):
... |
You are given a string S of length N consisting of lowercase English letters.
Process Q queries of the following two types:
* Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.)
* Type 2: answer the number of different characters occurring in the substring of S betwee... | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.LongBinaryOperator;
public class Main {
st... |
N friends of Takahashi has come to a theme park.
To ride the most popular roller coaster in the park, you must be at least K centimeters tall.
The i-th friend is h_i centimeters tall.
How many of the Takahashi's friends can ride the roller coaster?
Constraints
* 1 \le N \le 10^5
* 1 \le K \le 500
* 1 \le h_i \le 5... | n, k = map(int, input().split())
h = list(map(int, input().split()))
print(sum(x >= k for x in h)) |
There is an infinitely long street that runs west to east, which we consider as a number line.
There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.
Q people are standing at coordinate 0. The i-th person will start the coordinate 0 ... | from collections import deque, defaultdict
from heapq import heappush, heappop
import sys
input = sys.stdin.readline
N, Q = map(int, input().split())
events = [None] * (2*N)
for i in range(N):
S, T, X = map(int, input().split())
events[2*i] = (S-X, X)
events[2*i+1] = (T-X, -X)
events.sort(key=lambda x: x[0... |
There are N men and N women, both numbered 1, 2, \ldots, N.
For each i, j (1 \leq i, j \leq N), the compatibility of Man i and Woman j is given as an integer a_{i, j}. If a_{i, j} = 1, Man i and Woman j are compatible; if a_{i, j} = 0, they are not.
Taro is trying to make N pairs, each consisting of a man and a woman... | #include <cstdio>
int n;
int A[21];
constexpr int mod = 1000000007;
int dp[1<<21];
int main(){
scanf("%d", &n);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
int x;
scanf("%d", &x);
if(x) A[i] |= 1 << j;
}
}
dp[0] = 1;
for(int x = 1; x < (1<<n); x++){
int i = __bui... |
In Takahashi's mind, there is always an integer sequence of length 2 \times 10^9 + 1: A = (A_{-10^9}, A_{-10^9 + 1}, ..., A_{10^9 - 1}, A_{10^9}) and an integer P.
Initially, all the elements in the sequence A in Takahashi's mind are 0, and the value of the integer P is 0.
When Takahashi eats symbols `+`, `-`, `>` an... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=25e4+10,mo=23333333333333333,M=2e7+3;
ll pw[N],ny[N];
ll n,S,v[N],ans;
char s[N];
ll mul(ll a,ll b){
ll c=(long double)a*b/mo,z=a*b-c*mo;
return z<0?z+mo:z<mo?z:z-mo;
}
ll power(ll a,ll b=mo-2){
ll ans=1;
while (b){
if (b&1)ans=mul(ans... |
We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.
You are given Q queries.
In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i.
Constraints
* 1≤Q≤10^5
* 1≤l_i≤r_i≤10^5
* l_i and r_i are odd.
* All input values ... | #include<bits/stdc++.h>
using namespace std;
#define ran 100001
bool f[ran];int p[ran],s[ran];int lp;
int main(){
f[0] = f[1] = true;
for(int i=2; i<ran; i++){
if(!f[i]){
p[lp++] = i;
}
for(int j=0; j<lp; j++){
int x = i*p[j];
if(x>=ran)break;
f[x] = true;
if(i%p[j]==0)break;
}
}
for(int i=3;... |
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elem... | #include<bits/stdc++.h>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define ll long long
#define pb push_back
#define gcd __gcd
#define For(i,j,k) for(int i=(j);i<k;i++)
#define lowbit(i) (i&(-i))
#define _(x) printf("%d\n",x)
const int maxn = 2e5+100;
int Log[maxn], dp[2][20][maxn],pos[maxn],a[maxn]... |
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered... | N = int(input())
s = input()
for t in ["SS","SW","WS","WW"]:
for i in range(1,N-1):
if (s[i] =="o" and t[i]=="S") or (s[i]=="x" and t[i]=="W"):
t += t[i-1]
else:
if t[i-1] =="S":
t += "W"
else:
t +="S"
if (t[N-2]==t[0] and ((s[N-1]=... |
AtCoDeer the deer and his friend TopCoDeer is playing a game. The game consists of N turns. In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:
(※) After each turn, (the number of times the player has played Paper)≦(the number of times the ... |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next();
int N = s.length();
int count_p = 0, count_g = 0, score = 0;
for (int i = 0; i < N; i++) {
char top = s.charAt(i);
if (count_p < count_g) {
count_p++;
... |
It is known that even numbers greater than or equal to 4 can be represented by the sum of two prime numbers. This is called the Goldbach's conjecture, and computer calculations have confirmed that it is correct up to a fairly large number. For example, 10 can be represented by the sum of two prime numbers, 7 + 3 and 5 ... | #include<iostream>
#include<vector>
using namespace std;
vector<bool> pt;
void MakeTable(int n){
pt.resize(++n);
pt[0] = pt[1] = false;pt[2] = true;
int i = 2;
while(++i<n)pt[i] = i&1;
i = 3;
while(i*i<n){
for(int j=3*i;j<n;j+=2*i)pt[j]=false;
do{i+=2;}while(!pt[i]);
}
}
int main(){
int... |
With the motto "Creating your own path," a shrine created a fortune-telling fortune with its own hands. Ask the person who draws the lottery to throw six stones first, then the line segment connecting the first and second of the thrown stones, the line segment connecting the third and fourth, the fifth and six The fort... | #include <iostream>
#include <cmath>
using namespace std;
#define EPS 1e-8
struct Point{
double x,y;
Point(double x = 0.0, double y = 0.0) : x(x),y(y) {}
Point operator + (Point p){ return Point(x+p.x,y+p.y); }
Point operator - (Point p){ return Point(x-p.x,y-p.y); }
Point operator * (double a){ return Poi... |
N different natural numbers are given. If you select four different ones and set them as $ A $, $ B $, $ C $, $ D $, the following formula
$ \ Frac {A + B} {C --D} $
I want to find the maximum value of.
Given N different natural numbers, choose 4 different from them and create a program to find the maximum valu... | n = int(input())
a = sorted(map(int,input().split()))
b = [(a[i + 1] - a[i], i) for i in range(n -1)]
b.sort(key = lambda x:x[0])
if b[0][1] < n - 2:print((a[-1] + a[-2]) / b[0][0])
elif b[0][1] == n - 3:
if b[1][1] == n - 2:print(max((a[-1] + a[-2]) / b[2][0], (a[-1] + a[-4]) / b[0][0], (a[-3] + a[-4]) / b[1][0]))... |
Carving the cake 2 (Cake 2)
JOI-kun and IOI-chan are twin brothers and sisters. JOI has been enthusiastic about making sweets lately, and JOI tried to bake a cake and eat it today, but when it was baked, IOI who smelled it came, so we decided to divide the cake. became.
The cake is round. We made radial cuts from a p... | #include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#define INF (2 << 28)
#define fr first
#define... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.