input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Example
Input
2 2 2 0 0 0 5
Output
1 3 3 1 0 | #include<bits/stdc++.h>
using namespace std;
typedef long long int64;
int main()
{
int X, Y, Z, A, B, C, N;
int64 a[1000] = {}, b[1000] = {}, c[1000] = {};
cin >> X >> Y >> Z >> A >> B >> C >> N;
for(int i = 0; i < X; i++) ++a[abs(i - A) % N];
for(int i = 0; i < Y; i++) ++b[abs(i - B) % N];
for(int i =... |
A: Alphabet block
Wakana Nakawa loves palindromes. Because my name is also a palindrome.
Wakana got a set with some alphabet blocks. An alphabet block is a block in which one lowercase alphabet is written for each block, and you can create your favorite character string by changing the order of the blocks and combini... | #include <iostream>
#include <algorithm>
#include <utility>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <math.h>
#include <string.h>
#include <iomanip>
#include <numeric>
#include <cstdlib>
#include <cstdint>
#include <cmath>
#include <functional>
#includ... |
C: Skewering
problem
One day, when Homura was playing with blocks, Tempura came. Homura decided to play with blocks with Tempura.
There is a rectangular parallelepiped of A \ times B \ times C, which is made by stacking A \ times B \ times C blocks of cubic blocks with a side length of 1 without any gaps. Each side ... | A,B,C=map(int,input().split())
ANS=0
for i in [A,B,C]:
if i%2==1:
ANS+=1
if ANS>=2:
print("Hom")
else:
print("Tem")
|
Queries with Six Inequeties
Given a set of four integer pairs (a, b, c, d).
The jth query determines if i exists, x_j <a_i <y_j <b_i and z_j <c_i <w_j <d_i.
input
N Q
a_1 b_1 c_1 d_1
a_2 b_2 c_2 d_2
::
a_n b_n c_n d_n
x_1 y_1 z_1 w_1
x_2 y_2 z_2 w_2
::
x_q y_q z_q w_q
output
ans_1
ans_2
::
ans_q
On line j, p... | #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 = {a0, a1, . . . , an−1} with the following operations:
* update(s, t, x): change as, as+1, ..., at to x.
* find(s, t): report the minimum element in as, as+1, ..., at.
Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.
Constraints
* 1 ≤ n ≤ 100000... | #include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
using namespace std;
typedef long long ll;
const ll inf=2147483647;
struct segtree{
private:
ll siz;
vector<ll> node,lazy;
vector<bool> lazyflag;
public:
segtree(ll n){
siz=1;
while(siz<=n) siz*=2;
node.resize(2... |
To attain inner peace Geek Sundaram has to pass through the "Hall of Valley of Death". The floor of this hall is a square with length 100 m. It is laid with square tiles of size 1 X 1 arranged over the entire hall. But, at some places in the hall tiles are broken. The moment a person enters the hall, the underworld... | for _ in range(input()):
n=input()
r,c=[0]*100,[0]*100
for i in range(n):
x,y=map(int,raw_input().split())
r[x]+=1
c[y]+=1
max_x,max_y=0,0
for i in range(100):
if r[i]:
max_x+=1
if c[i]:
max_y+=1
#print max_x,max_y
print min(max_x,max_y) |
Our hardworking chef is bored of sleeping in his restaurants. He has decided to settle down. The first thing he must do is to find a suitable location to build a palatial home.
Think of the city as a two-dimensional grid. There are N restaurants in the city. Each of the chef's restaurant is a point denoted by (X , ... | t = int(raw_input())
while t > 0:
t-=1
n = int(raw_input())
x=[]
y=[]
for i in range(n):
l = map(int,raw_input().split())
x.append(l[0])
y.append(l[1])
if n % 2 == 1:
print 1
else :
x.sort()
y.sort()
print (x[n/2]-x[n/2-1]+1)*(y[n/2]-y[n/2-1]+1) |
You have initially a string of N characters, denoted by A1,A2...AN. You have to print the size of the largest subsequence of string A such that all the characters in that subsequence are distinct ie. no two characters in that subsequence should be same.
A subsequence of string A is a sequence that can be derived from A... | t=int(raw_input())
while(t):
d={}
s=(raw_input())
for i in s:
if i in d :
d[i]+=1
else:
d[i]=1
t-=1
#print d
print len(d.keys()) |
Chef has an array of N integers. He wants to play a special game. In this game he needs to make all the integers in the array greater than or equal to 0.
Chef can use two types of operations. The first type is to increase all the integers of the given array by 1, but it costs X coins. The operation of the second type... | n = input()
a = []
m = raw_input().split()
total = 0
for i in range(n):
k = int(m[i])
if k < 0:
a.append(k)
total += -k
X = input()
if X >= len(a):
print total
else:
a.sort()
ans = bar = 0; last = len(a)-1
while True:
j = None
for i in xrange(last,-1,-1):
... |
There are n points with integer coordinates. We can form different quadrangles out of them by taking four different points and connecting them with lines. Let’s call a quadrangle ABCD nice if and only if:
Ax > 0 and Ay > 0;
Bx > 0 and By < 0;
Cx < 0 and Cy < 0;
Dx < 0 and Dy > 0;
ABCD has an integer area.
Your task i... | for t in range(int(raw_input())):
a = [[0]*4 for x in range(4)]
n = int(raw_input())
for i in range(n):
(x, y) = (int(j) for j in raw_input().split())
index = -1
if x > 0:
if y > 0:
index = 0
elif y < 0:
index = 1
elif x... |
Sereja and Dima play the game. The rules are as follows:
Initially, there are n cards on the table, each card has a positive integer written on it.
At the beginning Sereja writes down the number 0 on the sheet of paper.
Then players pick cards from the table alternately. When a player picks a card, he writes down the g... | from fractions import gcd
a = []
n = 0
dp1 = [[-1 for i in range(101)] for i in range(101)]
dp2 = [[-1.0 for i in range(101)] for i in range(101)]
def iswinning(g,taken):
global n, a, dp1
if dp1[g][taken]!= -1:
return dp1[g][taken]
if g==1:
dp1[g][taken] = 1
elif taken==n:
dp1[g][taken] = 0
else:
... |
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be... | #include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
inline void add(int &a, int b) {
a += b;
if (a >= mod) {
a -= mod;
}
}
inline void sub(int &a, int b) {
a -= b;
if (a < 0) {
a += mod;
}
}
inline int mul(int a, int b) { return (long long)a * b % mod; }
inline int modexp(int a,... |
A point belongs to a triangle if it lies inside the triangle or on one of its sides. Two triangles are disjoint if there is no point on the plane that belongs to both triangles.
You are given n points on the plane. No two points coincide and no three points are collinear.
Find the number of different ways to choose t... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 3030;
const double pi = acos(-1);
struct Point {
int x, y, c, id;
double k;
bool operator<(const Point &b) const { return k < b.k; }
} p[MAXN], o;
int n, cnt[2], bl[MAXN];
long long ans, tmp[2];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n... |
Being bored of exploring the Moon over and over again Wall-B decided to explore something he is made of — binary numbers. He took a binary number and decided to count how many times different substrings of length two appeared. He stored those values in c_{00}, c_{01}, c_{10} and c_{11}, representing how many times subs... | #include <bits/stdc++.h>
using namespace std;
const int MaxN(100003);
const int Mod(1e9 + 7);
int fac[MaxN], inv[MaxN];
char s1[MaxN], s2[MaxN];
int fexp(int x, int k) {
int res = 1;
for (; k; k >>= 1, x = (long long)x * x % Mod)
if (k & 1) res = (long long)res * x % Mod;
return res;
}
inline int C(int n, int... |
Vasya is choosing a laptop. The shop has n laptops to all tastes.
Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.
If all three properties of a laptop are strictly less than those properties ... | #include <bits/stdc++.h>
using namespace std;
struct node {
int a, b, c, d, e;
} s[110], s1[110];
bool cmp(node x, node y) { return x.d < y.d; }
int main() {
int n;
scanf("%d", &n);
int p = 0;
for (int i = 0; i < n; i++) {
int x, y, z, w;
scanf("%d%d%d%d", &x, &y, &z, &w);
s[i].a = x;
s[i].b =... |
Alice and Bob are decorating a Christmas Tree.
Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments.
In Bob's opinion, a Christmas Tree will be beautiful if:
* the number of blue ornaments used is greater b... | #include <bits/stdc++.h>
using namespace std;
const long long MAXN = 2 * 1e5 + 5;
const long long INF = 1e8 + 5;
const long long MOD = 1e9 + 7;
long long N;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long Y, B, R;
cin >> Y >> B >> R;
long long ans = 0;
if (B >= R - 1 and ... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the in... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class CodeG
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokeni... |
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of sp... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
using namespace std;
const long double eps = 1e-7;
const long double pi = 3.1415926535897932384626433832795;
long long pow_mod(long long a, long long n, long long mod) {
long long res = 1;
while (n) {
if (n & 1) res *= a;
res %= mod;
a ... |
You are given a binary matrix a of size n × m. A binary matrix is a matrix where each element is either 0 or 1.
You may perform some (possibly zero) operations with this matrix. During each operation you can inverse the row of this matrix or a column of this matrix. Formally, inverting a row is changing all values in ... | #include <bits/stdc++.h>
using namespace std;
int read() {
int w = 0, f = 1;
char c = ' ';
while (c < '0' || c > '9') c = getchar(), f = c == '-' ? -1 : f;
while (c >= '0' && c <= '9') w = w * 10 + c - 48, c = getchar();
return w * f;
}
int n, m, a[205][205], b[205], c[205];
signed main() {
n = read(), m = ... |
Let a be an array consisting of n numbers. The array's elements are numbered from 1 to n, even is an array consisting of the numerals whose numbers are even in a (eveni = a2i, 1 ≤ 2i ≤ n), odd is an array consisting of the numberals whose numbers are odd in а (oddi = a2i - 1, 1 ≤ 2i - 1 ≤ n). Then let's define the tran... | #include <bits/stdc++.h>
using namespace std;
const int H = 1000000;
template <typename Key, typename Val>
struct Hash {
char *used;
Key *key;
Val *val;
Hash() {
used = new char[H];
key = new Key[H];
val = new Val[H];
memset(used, 0, sizeof(used));
}
int hash_func(const Key &k) { return k % ... |
There is a square grid of size n × n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs min(h, w) to color a rectangle of size h × w. You are to make all cells white for minimum total cost.
The square is large, so... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 10005;
const int inf = 0x3f3f3f3f;
int n, m, cnt = -1, p[maxn], dep[maxn], cur[maxn], s, t, zx[maxn], zy[maxn],
cntx, cnty;
struct kkk {
int lx, ly, rx, ry;
} a[maxn];
struct node {
int v, next, cap, flow;
} e[maxn * 10];
void add(int u, int v... |
Monocarp and Bicarp live in Berland, where every bus ticket consists of n digits (n is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.
Monocarp and Bicarp have decided to play a game with this tic... | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.wr... |
Assume that you have k one-dimensional segments s_1, s_2, ... s_k (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i ≠ j) if and only if the segments s_i and... | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 3e5 + 15;
int q, n, ans;
bool mark[MAX_N];
int d[MAX_N];
vector<int> G[MAX_N];
int dfs(int v, int p = -1) {
int res1 = 0, res2 = 0, ct = 0;
for (int u : G[v])
if (u != p && !mark[u]) {
ct++;
int tmp = dfs(u, v);
if (res1 < tmp) {
... |
You are the gym teacher in the school.
There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right.
Since they are rivals, you want to maximize the distance between them. If students a... | t = int(input())
for i in range(t):
n, x, a, b = map(int, input().split(' '))
if((a==n and b==1)or(b==n and a==1)):
print(n-1)
elif x==0:
print(abs(b-a))
else:
ans=x+abs(b-a)
if(ans>=n):
print(n-1)
else:
print(ans)
|
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r × c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomei... | """
This template is made by Satwik_Tiwari.
python programmers can use this template :)) .
"""
#===============================================================================================
#importing some useful libraries.
import sys
import bisect
import heapq
from math import *
from collections import Cou... |
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
... |
You are given an array a consisting of n integers.
Your task is to determine if a has some subsequence of length at least 3 that is a palindrome.
Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c... | #!/usr/bin/env python
import sys
def main():
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().strip().split()))
d = dict()
didbreak = False
for i in range(n):
if a[i] not in d:
d[a[i]] = [1, i]
else:
... |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | import math
if __name__ == "__main__":
n = int(input())
for i in range(n):
m = int(input())
res = 1
test = 0
while(m > 2**res -1):
res += 1
if m% (2**res -1) == 0:
test = m//(2**res -1)
break
x = test
pri... |
Ashish has n elements arranged in a line.
These elements are represented by two integers a_i — the value of the element and b_i — the type of the element (there are only two possible types: 0 and 1). He wants to sort the elements in non-decreasing values of a_i.
He can perform the following operation any number of t... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void out(T x) {
cout << x << endl;
exit(0);
}
const int maxn = 1e6 + 11;
string solve() {
int n;
cin >> n;
vector<pair<int, int>> v(n);
vector<int> cnt = {0, 0};
vector<int> checksorted(n);
for (int i = 0; i < n; i++) {
cin >> v[i].... |
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not.
There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc... | n=int(input())
b=[]
for i in range(n):
x=int(input())
a=[int(i) for i in input().split()]
d={}
for j in range(len(a)):
if a[j] in d:
d[a[j]]+=1
else:
d[a[j]]=1
b.append(list(d.keys()))
for i in range(len(b)):
for j in range(len(b[i])):
print(b[i][j],end=" ")
print()
|
This is an interactive problem.
There is an unknown integer x (1≤ x≤ n). You want to find x.
At first, you have a set of integers \{1, 2, …, n\}. You can perform the following operations no more than 10000 times:
* A a: find how many numbers are multiples of a in the current set.
* B a: find how many numbers ar... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int SQ = 320;
const int TRES = 100;
int queries = 0;
int ask(int t, int a) {
queries++;
if (t == 1) cout << "A " << a << '\n' << flush;
if (t == 2) cout << "B " << a << '\n' << flush;
int res;
cin >> res;
return res;
}
const int MAXN ... |
When they are bored, Federico and Giada often play the following card game with a deck containing 6n cards.
Each card contains one number between 1 and 6n and each number appears on exactly one card. Initially the deck is sorted, so the first card contains the number 1, the second card contains the number 2, ..., and ... | #include <bits/stdc++.h>
using namespace std;
struct Node {
int cnt;
int cards[3];
int father;
int deg;
int player;
bool used;
};
vector<Node> nodes;
stack<int> S;
int main() {
int n, x;
Node root;
scanf("%d", &n);
vector<int> player(6 * n + 1, 0);
for (int i = 0; i < 3 * n; i++) {
scanf("%d",... |
To help those contestants who struggle a lot in contests, the headquarters of Codeforces are planning to introduce Division 5. In this new division, the tags of all problems will be announced prior to the round to help the contestants.
The contest consists of n problems, where the tag of the i-th problem is denoted by... | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
static FastScanner sc;
static PrintWriter pw;
static final int INF = 1000000000;
static final long MOD = 998244353;
static class A {
int val; int pos;
A(int x, int y) {
this.val = ... |
During cleaning the coast, Alice found n piles of stones. The i-th pile has a_i stones.
Piles i and i + 1 are neighbouring for all 1 ≤ i ≤ n - 1. If pile i becomes empty, piles i - 1 and i + 1 doesn't become neighbouring.
Alice is too lazy to remove these stones, so she asked you to take this duty. She allowed you to... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define forn(i,x,n) for(int i = x;i <= n;++i)
#define forr(i,x,n) for(int i = n;i >= x;--i)
const int N = 2e5+7;
const ll INF = 1e18;
int a[N],b[N];
ll L[N],R[N];
bool check(vector<ll> a)
{
forn(i,1,a.size() - 1)
{
if(a[i] < a[i - 1]) return 0;
... |
A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world... |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int rows = input.nextInt();
int cols = input.nextInt();
String arr[] = new String[rows];
for (int i = 0; i < arr.length; i++) {
arr... |
<image>
After William is done with work for the day, he enjoys playing his favorite video game.
The game happens in a 2D world, starting at turn 0. William can pick any cell in the game world and spawn in it. Then, each turn, William may remain at his current location or move from the current location (x, y) to one o... | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
... |
You have been offered a job in a company developing a large social network. Your first task is connected with searching profiles that most probably belong to the same user.
The social network contains n registered profiles, numbered from 1 to n. Some pairs there are friends (the "friendship" relationship is mutual, th... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int MOD = 1e9 + 7;
const int SEED = 29;
long long int p[N];
long long int h[N];
std::vector<pair<int, int> > v;
map<long long int, long long int> mp;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
c... |
The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet.
The Smart Beaver is going to bring som... | #include <bits/stdc++.h>
using namespace std;
long long a[11111], b[11111], ma;
long long n, c, x, t, i;
long long an_amazing_trip_of_amazing_little_beaver_from_ABBYY(long long x) {
long long k = 0;
for (long long i = 0; i < n; i++) {
k += a[i] * x / b[i] + 1;
if (k > c) return c + 1;
}
return k;
}
int ... |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] Args) {
int n = si();
String f = "I'm too stupid to solve this problem";
if (n == 0)
System.out.println("0 0 0");
... |
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement.
UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in... | #include <bits/stdc++.h>
using namespace std;
int a[1000][1000];
int rr[1000];
int cc[1000];
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < n; ++i) {
rr[i] = i;
}
for (int i = 0; i < m; ++i) {
cc[i] = i;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
... |
You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.
String s[l... r] = slsl + 1... sr ... | #include <bits/stdc++.h>
int dp[5001][5001];
char s[5001];
int main() {
scanf("%s", s);
int n;
scanf("%d", &n);
for (int i = 0; *(s + i); i++) {
dp[i][i] = 1;
for (int j1 = i - 1, j2 = i + 1; j1 >= 0 && *(s + j2); j1--, j2++)
if (s[j1] == s[j2])
dp[j1][j2] = 1;
else
break;
... |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | from collections import Counter
n=int(input())
n1=n+1
while(True):
s=list(str(n1))
c=Counter(s)
if(len(c)==len(s)):
print("".join(s))
break
n1=n1+1 |
There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is alrea... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CodeC
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokeni... |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... |
n, m = map(int, input().split())
print((m * 2) - 1 if m <= n - (n//2) else (m - (n - (n // 2))) * 2)
# UBCF
# CodeForcesian
# ♥
# تو شرایطی که همه درگیر خودشون و کاراشون شدن من بدون اینکه متوجه شم درگیرت شدم |
Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:
* a < b < c;
* a divides b, b divides c.
Naturally, Xenia wants... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class CF199A {
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
... |
You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.
A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the r... | #include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, 1, -1, 1, -1, 1, -1};
int dy[] = {1, -1, 0, 0, -1, 1, 1, -1};
long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); }
long long lcm(long long a, long long b) { return (a / gcd(a, b)) * b; }
void PLAY() {
cout << fixed << setprecision(1... |
Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'.
A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.
<image>
Ciel wants to draw several ... | import sys
n=int(input())
a=[]
for x in range (n):
a.append(list(raw_input().strip()))
ja='YES'
for i in range (n-2):
for j in range(1,n-1):
if a[i][j]=="#":
if a[i+1][j-1]==a[i+1][j]==a[i+1][j+1]==a[i+2][j]=='#':
a[i][j],a[i+1][j-1],a[i+1][j],a[i+1][j+1],a[i+2][j]='.','.'... |
<image>
Input
The input contains a single floating-point number x with exactly 6 decimal places (0 < x < 5).
Output
Output two integers separated by a single space. Each integer should be between 1 and 10, inclusive. If several solutions exist, output any of them. Solution will exist for all tests.
Examples
Input... | #include <bits/stdc++.h>
using namespace std;
int main() {
double rr;
cin >> rr;
for (int a = 1; a <= 10; a++)
for (int h = 1; h <= 10; h++) {
double r = a / 2.0 * h / sqrt(a * a / 4.0 + h * h);
if (fabs(r - rr) < 1e-6) {
cout << a << ' ' << h << endl;
return 0;
}
}
}
|
All modern mobile applications are divided into free and paid. Even a single application developers often release two versions: a paid version without ads and a free version with ads.
<image>
Suppose that a paid version of the app costs p (p is an integer) rubles, and the free version of the application contains c ad... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline void umax(T &a, T b) {
if (a < b) a = b;
}
template <class T>
inline void umin(T &a, T b) {
if (a > b) a = b;
}
template <class T>
inline T abs(T a) {
return a > 0 ? a : -a;
}
template <class T>
inline T gcd(T a, T b) {
return __gcd(a, b);
... |
There are n students studying in the 6th grade, in group "B" of a berland secondary school. Every one of them has exactly one friend whom he calls when he has some news. Let us denote the friend of the person number i by g(i). Note that the friendships are not mutual, i.e. g(g(i)) is not necessarily equal to i.
On day... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int g[100000], cnt[100000];
int v[100000], b[100000];
int s[100005], sc[100005], sz;
bool used[100005] = {}, dead[100005] = {}, marked[100005] = {};
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < (int)(n); ++i) scanf("%d", g + i), --g[i], cnt[i] = 1;
... |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
for (int i = 1; i <= k + 1; i++) {
if (i & 1)
cout << i / 2 + 1 << " ";
else
cout << k + 2 - i / 2 << " ";
}
for (int i = k + 2; i <= n; i++) {
cout << i << " ";
}
return 0;
}
|
The Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are n gems in the Shuseki Islands in total, and the i-th gem is located on island pi.... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solution {
private static int n, d;
private static int[] arr = new int[30001];
private static int[][] res = new int[30001][500];
private s... |
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bi... | #include <bits/stdc++.h>
using namespace std;
int T[5050];
set<pair<int, int> > S;
int main() {
int n, k;
scanf("%d%d", &n, &k);
S.insert(make_pair(0, 0));
for (int i = (0); i <= (int(n) - 1); ++i) {
scanf("%d", &T[i]);
int sum = T[i];
for (int j = (1); j <= (k); ++j) {
S.insert(make_pair(sum,... |
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: ... | #include <bits/stdc++.h>
using namespace std;
struct seg {
long long l, r, id;
bool operator<(const seg &t) const {
if (r != t.r) return r < t.r;
return l < t.l;
}
};
struct my_pair {
long long first;
int second;
bool operator==(const my_pair &t) const { return (first == t.first); }
bool operator<... |
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and ... | a,b=map(int,input().split())
countd=0
counts=0
while a>0 or b>0:
if a>0 and b>0:
countd=countd+1
a=a-1
b=b-1
elif a>=2 and b==0:
counts=counts+1
a=a-2
elif a==0 and b>=2:
counts=counts+1
b=b-2
else:
a=0
b=0
print(countd,counts)
... |
Kleofáš is participating in an n-thlon - a tournament consisting of n different competitions in n different disciplines (numbered 1 through n). There are m participants in the n-thlon and each of them participates in all competitions.
In each of these n competitions, the participants are given ranks from 1 to m in suc... | #include <bits/stdc++.h>
using namespace std;
const int inf = 1 << 29;
const int mod = (int)1e9 + 7;
const double eps = 1e-8;
const double pi = acos(-1.0);
int n, m, k;
double dp[110][100010];
double sum[1010];
int a[110];
int main() {
cin >> n >> m;
int tot = 0;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[... |
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you for... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, i, j, sum = 0, c, t = 0;
cin >> n >> k;
int a[505][505] = {0};
c = n * (k - 1);
for (i = 1; i <= n; i++) {
for (j = 1; j < k; j++) {
t++, a[i][j] = t;
}
for (j = k; j <= n; j++) {
c++, a[i][j] = c;
if (j == k) s... |
Radewoosh is playing a computer game. There are n levels, numbered 1 through n. Levels are divided into k regions (groups). Each region contains some positive number of consecutive levels.
The game repeats the the following process:
1. If all regions are beaten then the game ends immediately. Otherwise, the system ... | import java.util.*;
import java.io.*;
public class a
{
public static void main(String[] arg) throws IOException
{
new a();
}
public a() throws IOException
{
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
double[] ... |
Two positive integers are coprime if and only if they don't have a common divisor greater than 1.
Some bear doesn't want to tell Radewoosh how to solve some algorithmic problem. So, Radewoosh is going to break into that bear's safe with solutions. To pass through the door, he must enter a permutation of numbers 1 thro... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10, mod = 1e9 + 7;
const long long inf = 1e18;
int to[maxn], bp[maxn], cnt[maxn], cnt2[maxn], fac[maxn];
int who[maxn], rwho[maxn], n;
void add(int a, int b) {
if ((n / a) != (n / b)) cout << 0 << endl, exit(0);
if (who[a] == 0) who[a] = b, cnt2[n... |
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from t... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, t;
cin >> n >> k >> t;
double sum = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= k; ++j) {
double up_bd = (double)(j + (i)*k) * 100 / (n * k);
double low_bd = (double)(j + (i)*k + 1) * 100 / (n * k);
if (up_bd <=... |
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the inte... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import ja... |
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some verte... | #include <bits/stdc++.h>
using namespace std;
int dx4[] = {0, 0, 1, -1};
int dy4[] = {1, -1, 0, 0};
int dx8[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dy8[] = {1, -1, 0, 0, 1, -1, 1, -1};
int dxH[] = {2, 2, -2, -2, 1, 1, -1, -1};
int dyH[] = {1, -1, 1, -1, 2, -2, 2, -2};
const double GRS = (1 + sqrt(5)) / 2;
template <typena... |
Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated n Mr. Meeseeks, standing in a line numbered from 1 to n. Each of them has his own color. i-th Mr. Meeseeks' color is ai.
Rick and Morty are gathering their army and they want to divide Mr. Meeseeks into s... | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
const int M = 6000005;
int col[N], rec[N], root[N], cnt = 0;
int lc[M], rc[M], key[M], rightmost[M];
inline void Insert(int x, int y, int l, int r, int pos, int val) {
key[x] = key[y] + val;
if (l == r) {
rightmost[x] = key[x];
return;
}
... |
This is an interactive problem. In the output section below you will see the information about flushing the output.
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the... | // Previous submission was stuck...
import javax.print.DocFlavor;
import java.io.*;
import java.util.*;
public class _809B {
static int n, k;
static boolean le(int a, int b) {
System.out.println(1 + " " + a + " " + b);
System.out.flush();
String s = null;
try {
s =... |
<image>
It is well-known that the best decoration for a flower bed in Sweetland are vanilla muffins. Seedlings of this plant need sun to grow up. Slastyona has m seedlings, and the j-th seedling needs at least kj minutes of sunlight to grow up.
Most of the time it's sunny in Sweetland, but sometimes some caramel clou... | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 35;
struct Interval {
int l, r, c, i;
};
struct Event {
int l, t, i;
Event() {}
Event(int il, int it, int ii) {
l = il;
t = it;
i = ii;
}
};
bool operator<(Interval a, Interval b) {
if (a.c != b.c) return a.c < b.c;
return a.i <... |
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is e... | import heapq
n, k = (int(x) for x in raw_input().split())
costs = [int(x) for x in raw_input().split()]
def solve(n, k, costs):
total_cost = 0
depart = [0] * n
heap = [(-costs[i], i) for i in xrange(k)]
heapq.heapify(heap)
for i in xrange(k, n):
cost, orig = heapq.heappushpop(heap, (-cost... |
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
inline int getint() {
int x;
scanf("%d", &x);
return x;
}
inline long long getlng() {
long long x;
scanf("%lld", &x);
return x;
}
int dx4[] = {-1, 0, 1, 0};
int dy4[] = {0, 1, 0, -1};
int dx8[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy8... |
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of tree... | import java.io.*;
import java.util.*;
public class Main {
public static void functi(int v, int[] mas, int[] masC, int cV, int k, int n){
if(masC[v] != cV)
mas[0]--;
for(int i = 0; i < n; i++){
if(mas[i] == v)
functi(i, mas, masC, masC[v], k, n);
}
... |
Olya wants to buy a custom wardrobe. It should have n boxes with heights a1, a2, ..., an, stacked one on another in some order. In other words, we can represent each box as a vertical segment of length ai, and all these segments should form a single segment from 0 to <image> without any overlaps.
Some of the boxes are... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
long long gcd(long long x, long long y) {
if (y == 0)
return x;
else
return gcd(y, x % y);
}
long long ksm(long long a, long long b) {
long long r = 1;
while (b) {
if (b & 1) r = (r * a) % mod;
a =... |
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usua... | #include <bits/stdc++.h>
std::string s;
char c;
int main() {
std::cin >> s;
for (auto t : s) {
for (; c != t; --c) puts("..\nX.");
puts("X.");
}
}
|
The Professor has lost his home robot yet again. After some thinking Professor understood that he had left the robot in the basement.
The basement in Professor's house is represented by a rectangle n × m, split into 1 × 1 squares. Some squares are walls which are impassable; other squares are passable. You can get fro... | #include <bits/stdc++.h>
using namespace std;
const int EXP = 22505;
const int DIM = 100015;
char str[DIM];
bitset<EXP> wal, rom, ext, cur;
int main(void) {
int n, m, k;
cin >> n >> m >> k;
for (int i = 0; i < n; ++i) {
cin >> str;
for (int j = 0; j < m; ++j) {
if (str[j] == '#') wal[i * m + j] = tr... |
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.
Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, ... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const double eps = 1e-8;
template <class T>
T sqr(T x) {
return x * x;
}
long long gcd(long long a, long long b) { return (b == 0) ? a : gcd(b, a % b); }
int main(int argc, char** argv) {
long long n;
cin >> n;
long long m = 0;
while ... |
View Russian Translation
One day Benny decides to miss lessons. But as she is a very good pig she will do her homework anyway. She doesn't know anything about the content of this lessons. Your task is to help her.
The problem is following: you are given a right triangle with coordinates of vertices (0, 0), (0, a), (b... | a,b,p=map(int,raw_input().split())
print('%.2f' % (b-b*((p**0.5)/10))) |
The Humans are at war against a very powerful alien race that invaded our solar system.
The human army has n soldiers. The soldiers are numbers from 1 to n. The army has a superiority hierarchy. Every soldier has one immediate superior. The superior of a superior of a soldier is also a superior to that soldier. So, a ... | def bfs(x):
b=[False]*(n+1)# an array of false flags to keep track of vertices visited
#memo=[-1]*(n+1)
global memo,component_id,root
#found=False
c=0
q=[]
q.append(x)
component_id[x]=c
#root=0
memo[x]=0
while len(q)!=0 :
#t=s[-1]
top=q.pop()
#print "t... |
You have been given a positive integer N. You need to find and print the Factorial of this number. The Factorial of a positive integer N refers to the product of all number in the range from 1 to N. You can read more about the factorial of a number here.
Input Format:
The first and only line of the input contains a s... | import math
print math.factorial(int(raw_input())) |
Your friend Max has written a string S in your textbook. The string consists of lowercase latin letters. The problem is that Max is not good at writing at all! Especially, you never know if he wanted to write "w" or two consecutive "v". Given the string S, return the minimum and maximum length of a word which can be re... | tc = input()
data = raw_input()
other = ""
max1 = 0
for char in data:
if char == 'w':
max1 += 2
other += 'vv'
elif char == 'v':
max1 += 1
other += 'v'
else:
other += char
max1 += 1
i = 1
min1 = max1
while i < max1:
if other[i-1] == "v" and other[i] =="v":
min1 -= 1
i += 2
else:
i+= 1
#print othe... |
Marut is great warrior. Marut loves his girlfriend Shizuka very much. Being jealous from Marut's love, the Devil kidnaps his girlfriend. Hence, Marut declares a war against the Devil. The devil decides to send his army men one by one to fight with Marut. Marut being a smart person, he has a secret energy booster named... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
t=int(raw_input())
for i in range(t):
a=raw_input().strip().split(" ")
b=raw_input().strip().split(" ")
a=map(int,a)
b=map(int,b)
s=sum(b)
initial_energy=a[1]
code_ras=a[2]
if((... |
After solving Reese's first problem Harold thought he had proven himself. But Reese wasn't convinced so he gave Harold another query. He told Harold to find the nth term of the sequence given by the equation.
a[n]=( f[n] + g[n] ) % n
where, f[n] = f[n-1] + x(n) ; where x(n) = smallest prime factor of n.
and g[n] =... | arr = [0]*100005
f = [0]*100005
ans = [0]*100005
def mark(a):
i = 2
while i*a<=100002:
num = i*a
if arr[num]==0:
arr[num] += a
i += 1
def sieve():
for i in xrange(2,100002):
if arr[i]==0:
arr[i] = arr[i-1]+i
mark(i)
else:
arr[i] += arr[i-1]
sieve()
for i in xrange(1,100002//2+1):
for j in xra... |
Rahul has to buy a few wooden planks ,the shop he visited has 50 different types of wooden planks available.Each type of plank is marked from 1-50.The rate(per square feet) of each plank is calculated as the number marked on the
plank multiplied by sum of the digits of the number marked on the plank.He told the shopkee... | raw_input()
typeofplanks = map(int, raw_input().split())
l,b = map(int, raw_input().split())
def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n / 10
return r
total_price = 0
for p in typeofplanks:
price = (p * sum(int(digit) for digit in str(p)))
#price = (p * sum_digits3(p))
if 1... |
Abhikalpan the tech-fest of IIITDMJ brings an amazing
competition of breaking love triangles. So the coordinators of the
event invite all triples from all over the world.
A triple can have 2 boys and 1 girl or 2 girls and 1 boy =D.
So to break this triangle they have given a task. According to ... | t=int(raw_input())
for sdgdg in xrange(t):
a,b=(int(e) for e in raw_input().split(' '))
print b-1,a-1 |
Robert Frost is standing on a cross-way with six roads diverging out. He decides to choose the road not taken. After travelling the pathway he reaches a similar but yet another cross-way with six another roads diverging out. He keeps on travelling like this from one cross-way to another and keeps discovering that each ... | a = [1, 0, 6, 12, 90, 360, 2040, 10080, 54810, 290640, 1588356, 8676360, 47977776, 266378112, 1488801600, 8355739392, 47104393050, 266482019232, 1512589408044, 8610448069080, 49144928795820, 281164160225520]
t = input()
while t:
n = input()
print a[n]
t -= 1 |
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
... | #ifdef xay5421
#define D(...) fprintf(stderr,__VA_ARGS__)
#else
#define D(...) ((void)0)
#define NDEBUG
#endif
#include<bits/stdc++.h>
#define int long long
#define LL long long
#define MP make_pair
#define PB push_back
#define EB emplace_back
#define fi first
#define se second
#define ALL(x) (x).begin(),(x).end()
#def... |
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2).
The game consists of turns. At each turn you can either end the game, ... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
ll a[400001];
ll b[400001];
ll pb[400001];
ll ppb[400001];
ll s1(int l,int r){
//cout << "s1 " << (ppb[r]-ppb[l])-l*(pb[r]-pb[l]) << ' ' << l << ' ' << r << endl;
return (ppb[r]-ppb[l])-l*(pb[r]-pb[l]);
}
ll s2(int l,int r){
return (r+1)*(pb[r... |
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Example... | #include <stdio.h>
int main ()
{
char K;
scanf ("%c", &K);
K=K+1;
printf("%c", K);
return 0;
} |
Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.
* Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i chara... | s=input()
t=input()
ans=0
s_inx=0
t_inx=0
s_l=len(s)
t_l=len(t)
c=0
while t_inx<=t_l-1:
try:
temp_inx=s[s_inx:].index(t[t_inx])
s_inx+=temp_inx+1
t_inx+=1
c=0
except:
c+=1
s_inx=0
ans+=s_l
if c==2:
print(-1)
exit()
else:
ans+=s_inx
print(ans) |
N people are arranged in a row from left to right.
You are given a string S of length N consisting of `0` and `1`, and a positive integer K.
The i-th person from the left is standing on feet if the i-th character of S is `0`, and standing on hands if that character is `1`.
You will give the following direction at mo... | n, k = map(int, input().split())
s = input()
l = [0] * (k * 2 + 1)
c = '1'
p = 0
ret = 0
for i in range(len(s)):
if s[i] != c:
ret = max(ret, i - l[p])
l.append(i)
if c == '1':
l.pop(0)
l.pop(0)
c = s[i]
ret = max(ret, n - l[p])
print(ret)
|
In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short.
The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string.
Given a string S of length N and an integer k (k \geq 3), he defines the k-DMC number of S as the number o... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper p... |
There are N squares lining up in a row, numbered 1 through N from left to right. Initially, all squares are white. We also have N-1 painting machines, numbered 1 through N-1. When operated, Machine i paints Square i and i+1 black.
Snuke will operate these machines one by one. The order in which he operates them is rep... | #include <iostream>
using namespace std;
constexpr int mod = 1000000007;
int n, inv[1000009];
int main() {
cin >> n;
inv[1] = 1;
int cur = 1;
for (int i = 2; i <= n; i++) {
inv[i] = 1LL * inv[mod % i] * (mod - mod / i) % mod;
cur = 1LL * cur * (i - 1) % mod;
}
int ret = 0;
for (int i = n - 1; cur != 0; i--) ... |
You are given a string S.
Takahashi can insert the character `A` at any position in this string any number of times.
Can he change S into `AKIHABARA`?
Constraints
* 1 \leq |S| \leq 50
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If it i... | import re
s = input()
t = ['KIHBR','AKIHBR','KIHABR','KIHBAR','KIHBRA','AKIHABR','AKIHBAR','AKIHBRA','KIHABAR','KIHABRA','KIHBARA','AKIHABAR','AKIHABRA','AKIHBARA','AKIHABARA']
if s in t:
print('YES')
else:
print('NO') |
There are N cats. We number them from 1 through N.
Each of the cats wears a hat. Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me."
Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats.
Constraints
* 2 ≤ N ... | N = int(input())
hat = list(map(int, input().split()))
hat.sort()
min, max = hat[0], hat[N - 1]
count_min = 0
count_max = N
if max - min > 1:
print("No")
elif max == min:
if max <= N // 2 or max == N-1:
print("Yes")
else:
print("No")
else:
for i in range(N):
if hat[i] < max:
... |
You are given an integer sequence x of length N. Determine if there exists an integer sequence a that satisfies all of the following conditions, and if it exists, construct an instance of a.
* a is N^2 in length, containing N copies of each of the integers 1, 2, ..., N.
* For each 1 ≤ i ≤ N, the i-th occurrence of the... | #
# ⋀_⋀
# (・ω・)
# ./ U ∽ U\
# │* 合 *│
# │* 格 *│
# │* 祈 *│
# │* 願 *│
# │* *│
#  ̄
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないyp
from heapq import heappop, heappush, heappushpop
from collections import Counter,default... |
There are N towns in Snuke Kingdom, conveniently numbered 1 through N. Town 1 is the capital.
Each town in the kingdom has a Teleporter, a facility that instantly transports a person to another place. The destination of the Teleporter of town i is town a_i (1≤a_i≤N). It is guaranteed that one can get to the capital fr... | #include<bits/stdc++.h>
#define rep(i,x,y) for (int i=(x);i<=(y);i++)
using namespace std;
#define N 100005
int n,m,fa[N],cnt,head[N],dep[N],f[N],ans;
struct edge{int to,nxt;}e[N<<1];
void adde(int x,int y){e[++cnt].to=y;e[cnt].nxt=head[x];head[x]=cnt;}
void dfs(int u,int pr){
f[u]=1;
for (int i=head[u];i;i=e[i].nxt)... |
Have you ever heard of the unit "○○ tsubo" that expresses the area of land? Since ancient times, one samurai has said the area for making rice to eat in a day.
There is a land of a [m] x b [m]. Enter a and b and create a program that outputs the tsubo area S [tsubo] of the land. 1 tsubo = 3.305785 [m2], and a and b ... | #include <stdio.h>
int main(void){
int a,b;
scanf("%d %d",&a,&b);
printf("%lf\n",a*b/3.305785);
return 0;
} |
Taro and Hanako decided to play hit-and-blow. The hit-and-blow rules are as follows.
* Separated into questioners and respondents.
* The questioner decides a 4-digit number (correct answer) that does not include duplicate numbers.
* Respondents guess the 4-digit number (answer).
* For the answer, the questioner gives ... | #include <iostream>
#include <string>
using namespace std;
int main()
{
while(1)
{
string r,a;
int hit=0;
int blow=0;
cin>>r>>a;if(r=="0")return 0;
for(int i=0;i<4;++i){
for(int j=0;j<4;++j){
if(r[i]==a[j]){
if(i==j){
... |
Our master carpenter is designing a condominium called Bange Hills Mansion. The condominium is constructed by stacking up floors of the same height. The height of each floor is designed so that the total height of the stacked floors coincides with the predetermined height of the condominium. The height of each floor ca... | #include <iostream>
using namespace std;
int main(void){
int h,a,b,i,I,s;
cin>>h>>a>>b;
i=a;
s=0;
while(1){
if(i>b){break;}
I=h%i;
if(I==0){s++;}
I=0;
i++;
}
cout<<s<<endl;
}
|
Peter loves any kinds of cheating. A week before ICPC, he broke into Doctor's PC and sneaked a look at all the problems that would be given in ICPC. He solved the problems, printed programs out, and brought into ICPC. Since electronic preparation is strictly prohibited, he had to type these programs again during the co... | while 1:
try:
n=input()
p=sorted(map(int,raw_input().split()))
print sum([sum(p[:i+1]) for i in range(n)])
except:
break |
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two ar... | #include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<math.h>
#include<cstring>
using namespace std;
int w,h,c[50][50];
void island(int i,int j){
int x,y;
c[i][j]=0;
for(x=-1;x<=1;x++){
for(y=-1;y<=1;y++){
if(0<=j+x&&j+x<w&&0<=i+y&&i+y<h&&c[i+y][j+x]==1){
island(i+y,j+x);
}... |
The configuration of three circles packed inside a triangle such that each circle is tangent to the other two circles and to two of the edges of the triangle has been studied by many mathematicians for more than two centuries. Existence and uniqueness of such circles for an arbitrary triangle are easy to prove. Many me... | #include<complex>
#include<iostream>
#include<cmath>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<cassert>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-10)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON... |
Problem
A new arcade will open. We decided to set up a completely new prize game to attract a large number of customers.
This prize game consists of an RxC grid. Each square is blank or has a number from 1 to 18. The player can select a blank square and win a prize for that square. However, the prizes in the square c... | #include <bits/stdc++.h>
#define int long long
using namespace std;
int H, W, a[6][6], ans;
int pepi[6][6];
int dy[6] = {-1,0,1,1,1,0};
int dx[6] = {0,1,1,0,-1,-1};
int dy2[6] = {-1,-1,-1,0,1,0};
int dx2[6] = {-1,0,1,1,0,-1};
int XXX_cnt;
int XXX[7][19];
void dfs1(int hako, int tama){
if( hako == 0 ){
i... |
Princess'Gamble
Princess gambling
English text is not available in this practice contest.
One day, a brave princess in a poor country's tomboy broke the walls of her room, escaped from the castle, and entered the gambling hall where horse racing and other gambling were held. However, the princess who had never gambl... |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int n = sc.nextInt();
int m = sc.nextInt();
int p = sc.nextInt();
if(n+m+p==0) break;
int sum = 0;
int win = 0;
boolean winer = true;
for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.