input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
problem
AOR Ika is studying to pass the test.
AOR Ika-chan solved the $ N $ question. After that, round the solved problem according to the following procedure.
1. Check the correctness of the answer.
2. If the answer is correct, write a circle mark, and if it is incorrect, write a cross mark on the answer sheet.
... | #include<iostream>
#include<string>
using namespace std;
int main(){
int N,i=0;
string s;
cin>>N>>s;
for(i=1;i<N;i++){
if(s[i]=='x'&&s[i-1]=='x') break;
}
cout << i << endl;
return 0;
} |
Problem Statement
You are given a list of $N$ intervals. The $i$-th interval is $[l_i, r_i)$, which denotes a range of numbers greater than or equal to $l_i$ and strictly less than $r_i$. In this task, you consider the following two numbers:
* The minimum integer $x$ such that you can select $x$ intervals from the gi... | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <iomanip>
#include <set>
#include <tuple>
#define mkp make_pair
#define mkt make_tuple
#define rep(i,n) for(int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
const ll ... |
Apple adventure
square1001 and E869120 got lost in the grid world of $ H $ rows and $ W $ rows!
Said the god of this world.
"When you collect $ K $ apples and they meet, you'll be back in the original world."
Upon hearing this word, square1001 decided to collect more than $ K $ of apples and head to the square wher... | #include <bits/stdc++.h>
int ri() {
int n;
scanf("%d", &n);
return n;
}
std::pair<int, int> d[] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int main() {
int h = ri(), w = ri(), k = ri();
std::string a[h];
for (auto &i : a) std::cin >> i;
int gx, gy, sx, sy;
std::vector<std::pair<int, int> > apples;
for (int i = 0;... |
Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E).
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 1,000
* 0 ≤ wi ≤ 10,000
* G has arborescence(s) with the root r
Input
|V| |E| r
s0 t0 w0
s1 t1 w1
:
s|E|-1 t|E|-1 w|E|-1
, where |V| is the... | #include <bits/stdc++.h>
using namespace std;
struct StronglyConnectedComponents
{
vector< vector< int > > gg, rg;
vector< pair< int, int > > edges;
vector< int > comp, order, used;
StronglyConnectedComponents(size_t v) : gg(v), rg(v), comp(v, -1), used(v, 0) {}
void add_edge(int x, int y)
{
gg[x].p... |
Sherlock Holmes has decided to start a new academy to some of the young lads. He has conducted several tests and finally selected N equally brilliant
students.Now he don't know whether to train all the N students or not. Now since Holmes was in a confusion, Watson came up with an idea. He wanted to
test the obedience o... | # your code goes here
from sys import stdin, stdout
t = int(stdin.readline())
while t:
t -= 1
n = int(stdin.readline())
a = map(int, stdin.readline().strip().split(' '))
if n <= 2:
stdout.write(str(n)+"\n")
else:
m = 2
c = 2
i = 2
while i < n:
if a[i] != a[i-1] + a[i-2]:
m = max(c, m)
c = 2
... |
Rupsa recently started to intern under Chef. He gave her N type of ingredients of varying quantity A1, A2, ..., AN respectively to store it. But as she is lazy to arrange them she puts them all in a storage box.
Chef comes up with a new recipe and decides to prepare it. He asks Rupsa to get two units of each type ingr... | _ = int(raw_input())
for __ in range(_):
N = int(raw_input())
arr = map(int,raw_input().split())
ans = 0
mx = 10**4 + 10
for num in arr :
if num < 2:
ans = -1
break
ans = ans + num
if num < mx:
mx = num
if ans != -1:
ans = ans -... |
There is new delicious item in Chef's menu - a doughnut chain. Doughnuts connected successively in line forming a chain.
Chain of 3 doughnuts
Chef has received an urgent order for making a chain of N doughnuts. He noticed that there are exactly N cooked doughnuts in the kitchen, some of which are already connected i... | for t in xrange(input()):
n, m = map(int, raw_input().strip().split())
arr = map(int, raw_input().strip().split())
arr.sort()
cuts = 0
for i in xrange(m):
k = m - i - cuts - 1
if k <= arr[i]:
ans = cuts + k
break
cuts += arr[i]
print ans |
Hackers! Hackers! Everywhere!
Some days back your email ID was hacked. Some one read the personal messages and Love Letters you sent to your girl friend. That's a terrible thing, well, you know how are the boys at ISM. So, you have decided that from now onwards you will write Love Letters to your girlfriend in a differ... | t=input()
while t>0:
b=[]
a=raw_input().split()
for i in range(len(a)):
str=a[i]
rev=str[::-1]
b.append(rev)
for i in range(len(b)):
print b[i],
print "\n"
t=t-1 |
Computation of the date either previous or forthcoming dates is quiet easy. But it is quiet difficult to calculate the day from a particular given date.
You are required to find a day from a particular date given to you.
Input
It consists of a single line entry consisting of date in format dd mm yyyy.
i.e. the input... | import datetime
dt='21/03/2012'
day, month, year = (int(x) for x in dt.split('/'))
ans=datetime.date(year,month,day)
print (ans.strftime("%A")) |
Problem description.
The problem statement is simple , you are given an array and you have to perform two types of operation on it.
Type 1 : update the value of array at the given index.
Type 2 : find the maximum sum you can obtained in the given range ( L , R ) by taking any two index i and j , such that ( L <=... | # your code goes here
from math import ceil, log
from sys import stdin, stdout
st = []
def getMid(s, e):
return s + (e-s) / 2
def construct(st, arr, ss, se, si, type):
if se == ss:
if se%2 == type:
st[si] = arr[ss]
else:
st[si] = 0
return st[si]
m = getMid(ss, se)
st[si] = max(construct(st, arr, ss, m,... |
Polycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d).
Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, q;
map<int, int> coins;
cin >> n >> q;
int queries[q];
for (int i = 0; i < n; i++) {
int val;
cin >> val;
coins[val]++;
}
for (int i = 0; i < q; i++) {
cin >> queries[i];
}
for (int i = 0; i < q; i++) {
int counter =... |
You are given a square board, consisting of n rows and n columns. Each tile in it should be colored either white or black.
Let's call some coloring beautiful if each pair of adjacent rows are either the same or different in every position. The same condition should be held for the columns as well.
Let's call some col... | #include <bits/stdc++.h>
using namespace std;
long long mod = 998244353, dpp[510][510][4], dpc[510][510][4], f[510], g[510];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long tp2, i, j, n, k, cnt = 0, tp;
cin >> n >> tp2;
tp2--;
dpp[1][1][1] = 1;
dpp[1][1][2] = 1;
for (... |
In the intergalactic empire Bubbledom there are N planets, of which some pairs are directly connected by two-way wormholes. There are N-1 wormholes. The wormholes are of extreme religious importance in Bubbledom, a set of planets in Bubbledom consider themselves one intergalactic kingdom if and only if any two planets ... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int x, y;
double a[100005];
struct Edge {
int v;
Edge *next;
} * h[100005], pool[100005 << 1];
int tot;
void addEdge(int u, int v) {
Edge *p = &pool[tot++];
p->v = v;
p->next = h[u];
h[u] = p;
}
double ans;
int um;
double r;
int fa[100005];
double son[... |
Buber is a Berland technology company that specializes in waste of investor's money. Recently Buber decided to transfer its infrastructure to a cloud. The company decided to rent CPU cores in the cloud for n consecutive days, which are numbered from 1 to n. Buber requires k CPU cores each day.
The cloud provider offer... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
using namespace std;
const int N = 200005;
long long int tree[2 * N];
long long int tree1[2 * N];
vector<long long int> e(N, 0);
vector<long long int> cos1(N, 0);
int m;
vector<pair<pair<in... |
Integer factorisation is hard. The RSA Factoring Challenge offered $100 000 for factoring RSA-1024, a 1024-bit long product of two prime numbers. To this date, nobody was able to claim the prize. We want you to factorise a 1024-bit number.
Since your programming language of choice might not offer facilities for handli... | import sys
import random
def gcd(x, y):
return x if y == 0 else gcd(y, x % y)
def isPrime(n):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
if n!=int(n):
return False
n=int(n)... |
Grigory has n magic stones, conveniently numbered from 1 to n. The charge of the i-th stone is equal to c_i.
Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index i, where 2 ≤ i ≤ n - 1), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
int t, c;
vector<int> T(N - 1);
vector<int> C(N - 1);
cin >> t;
int a = t;
for (int i = 0; i < N - 1; i++) {
int b;
cin >> b;
T[i] = abs(b - a);
a = b;
}
cin >> c;
int w = c;
for (int i = 0; i < N - 1; i+... |
You have a string s of length n consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the l... | import java.util.Scanner;
public class good_string {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int t=s.nextInt()... |
Let c be some positive integer. Let's call an array a_1, a_2, …, a_n of positive integers c-array, if for all i condition 1 ≤ a_i ≤ c is satisfied. Let's call c-array b_1, b_2, …, b_k a subarray of c-array a_1, a_2, …, a_n, if there exists such set of k indices 1 ≤ i_1 < i_2 < … < i_k ≤ n that b_j = a_{i_j} for all 1 ≤... | #include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
int n, c, m, a[3010];
int ksm(int x, int y = mod - 2) {
int z = 1;
for (; y; y >>= 1, x = 1ll * x * x % mod)
if (y & 1) z = 1ll * z * x % mod;
return z;
}
void ADD(int &x, int y) {
x += y;
if (x >= mod) x -= mod;
}
int SUM(int x, int... |
Serge came to the school dining room and discovered that there is a big queue here. There are m pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him.
Initially t... | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e6, big = 1e18;
long long val[maxn], t[4 * maxn + 5], sum[4 * maxn + 5];
void build(long long v, long long l, long long r) {
if (l == r - 1) {
sum[v] = 0;
t[v] = val[l];
return;
}
long long m = (l + r) / 2;
build(2 * v, l, m);
b... |
You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices.
A set of edges is called a matching if no two edges share an endpoint.
A set of vertices is called an independent set if no two vertices are connected with an edge.
Input
The first line... | #include <bits/stdc++.h>
using namespace std;
const long long N = 3e5 + 5, inf = 1e18 + 100;
vector<long long> g[N];
long long used[N];
void solve() {
long long n, m;
cin >> n >> m;
for (long long i = 1; i <= 3 * n; ++i) g[i].clear(), used[i] = 0;
vector<long long> seq;
for (long long i = 1; i <= m; ++i) {
... |
There were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swo... | n= int(input())
s = list(map(int,input().split()))
s.sort()
maxm = s[n-1]
ans = 0
def computeGCD(x, y):
while(y):
x, y = y, x % y
return x
a = maxm-s[0]
for i in range(1,n-1):
a = computeGCD(a,maxm-s[i])
for i in range(0,n-1):
ans += maxm - s[i]
print(ans//a,a)
|
Kolya has a turtle and a field of size 2 × n. The field rows are numbered from 1 to 2 from top to bottom, while the columns are numbered from 1 to n from left to right.
Suppose in each cell of the field there is a lettuce leaf. The energy value of lettuce leaf in row i and column j is equal to a_{i,j}. The turtle is i... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast,unroll-loops,fast-math")
using namespace std;
long long poww(long long a, long long b, long long md) {
return (!b ? 1
: (b & 1 ? a * poww(a * a % md, b / 2, md) % md
: poww(a * a % md, b / 2, md) % md));
}
const int maxn = 27;
con... |
You are given an integer x represented as a product of n its prime divisors p_1 ⋅ p_2, ⋅ … ⋅ p_n. Let S be the set of all positive integer divisors of x (including 1 and x itself).
We call a set of integers D good if (and only if) there is no pair a ∈ D, b ∈ D such that a ≠ b and a divides b.
Find a good subset of S ... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
long long MOD = 1000000007;
long double EPS = 1e-9;
long long binpow(long long b, long long p, long long mod) {
long long ans =... |
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better ... | import java.io.*;
import java.util.*;
@SuppressWarnings("unused")
public class Main {
FastScanner in;
PrintWriter out;
int MOD = (int)1e9+7;
long ceil(long a, long b){return (a + b - 1) / b;}
long gcd(long a, long b){return b == 0 ? a : gcd(b, a % b);}
long lcm(long a, long b){return a / gcd(a,... |
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers.
Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high... | # import sys
# file = open('test1')
# sys.stdin = file
def ii(): return int(input())
def ai(): return list(map(int, input().split()))
def mi(): return map(int, input().split())
for _ in range(int(input())):
n = ii()
lst = ai()
nlst = []
for ind, ele in enumerate(lst):
if ele==-1:
if ind!=0 and lst[ind-1]!=-1:... |
Ehab has an array a of length n. He has just enough free time to make a new array consisting of n copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?
A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (pos... | t = int(input())
for i in range(t):
n = int(input())
a = input().split()
s_a = set(a)
print(f"{len(s_a)}\n")
|
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void input(vector<T>& v, T n) {
for (T i = 0; i < n; i++) {
cin >> v[i];
}
}
int main() {
int t;
long long n;
cin >> t;
int Case = 0;
while (t--) {
cin >> n;
map<long long, long long> mp1;
vector<long long> v(n), v2(n);
... |
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.
Each tool can be sold for exactly one emerald. How many... | import math
t=int(input())
for i in range(t):
a,b=map(int,input().split())
m=min(a,b,(a+b)/3)
print(math.floor(m))
|
Linda likes to change her hair color from time to time, and would be pleased if her boyfriend Archie would notice the difference between the previous and the new color. Archie always comments on Linda's hair color if and only if he notices a difference — so Linda always knows whether Archie has spotted the difference o... | #include <bits/stdc++.h>
using namespace std;
const int Inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3fll;
const long double inF = 11451419198101145141919810.1145141919810;
const long double pi = acosl(-1);
long long n;
int ask(long long x) {
printf("? %lld\n", x);
fflush(stdout);
int res;
scanf("%d"... |
You are given three sequences: a_1, a_2, …, a_n; b_1, b_2, …, b_n; c_1, c_2, …, c_n.
For each i, a_i ≠ b_i, a_i ≠ c_i, b_i ≠ c_i.
Find a sequence p_1, p_2, …, p_n, that satisfy the following conditions:
* p_i ∈ \\{a_i, b_i, c_i\}
* p_i ≠ p_{(i mod n) + 1}.
In other words, for each element, you need to choose ... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
void solve();
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long t;
cin >> t;
while (t--) {
solve();
cout << "\n";
}
cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;
... |
To improve the boomerang throwing skills of the animals, Zookeeper has set up an n × n grid with some targets, where each row and each column has at most 2 targets each. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right.
For each column, Zookeeper will t... | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fcking inter... |
Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.
Consider the 2D plane. There is a token which is initially at (0,0). In one move a player must increase either the x coordinate or the y coordinate of the token by exactly k. In doing so, the... | #include<iostream>
#include<cstdio>
#include<cmath>
#define int long long
using namespace std;
inline int read()
{
int n=0,f=1,ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
n=n*10+ch-'0';
ch=getchar();
}
return n*f;
}
signed main()
{
int t,d,k;
bool f... |
Polycarp often uses his smartphone. He has already installed n applications on it. Application with number i takes up a_i units of memory.
Polycarp wants to free at least m units of memory (by removing some applications).
Of course, some applications are more important to Polycarp than others. He came up with the fol... | #lösningsmängd är nedåtbegränsad och ordnad. -> optimal minsta existerar i kontext.
#Vet att det är sant att lösning består av x stna 1-cost x tillhör [0..all(1-cost)]
#för x stna 1-cost bestäms y stna 2-cost entydligt.
#itererar alla x, försök i varje steg reducera y från mx(2-cost)
#same hold tru if conv points 1 an... |
Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: r... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;
public class TwoChandeliers {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedRea... |
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th ... | import javax.print.DocFlavor;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static int N = 5005;
static int[] arr = new int[N];
static long[][] memo = new long[N][N];
static List<Integer> occupiedSeats = new ArrayList<>();
static List<Integer> emptySeats = new Ar... |
Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number... | n = int(input())
r = lambda : list(map(int, input().split()))
arr = []
for i in range(n):
a = r()
arr.append(a)
row = [sum(i) for i in arr]
col = []
for i in range(n):
c = 0
for j in range(n): c+=arr[j][i]
col.append(c)
ans = 0
for i in range(n):
for j in range(n):
if row[i] < col[j... |
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.
The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequenc... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
long long ans = 0;
for (int i = 0; i < n - 1; ++i) {
int j = 0;
while (i + (1 << (j + 1)) < n) ++j;
a[i + (1 << j)] += a[i];
ans += a[i];
cout << ans << ... |
Bob came to a cash & carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. ... | import java.io.*;
import java.util.*;
public class Answer19B{
public static void main(String[] args){
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
new Kai(reader).solve();
}
}
class Kai{
BufferedReader reader;
public Kai(BufferedReader reader){
this.reader=reader;
}... |
You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that:
1. First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals <image>. The operation x mod y means that ... | //package round138;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), K = ni();
int mod = 1000000007;
int[] v = ... |
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on n wooden ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j, a, b, k, p;
pair<int, int> cell[1001];
cin >> n;
k = 0;
p = 0;
for ((i) = (0); (i) < (int)(n); (i)++) {
cin >> a >> b;
if (a == 0) k++;
if (b == 0) p++;
}
int sum;
sum = 0;
sum += min(k, n - k);
sum += min(p, n - p... |
Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:
* f(0) = 0;
* f(2·x) = f(x);
* f(2·x + 1) = f(x) + 1.
Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤... | #include <bits/stdc++.h>
using namespace std;
vector<int> f(100001);
int comp(int i) {
int b = 0, d = 0;
while (i > 0) {
if (i & 1 == 1) b++;
i = i >> 1;
}
return b;
}
int main() {
int m, i, n;
int h[65];
long long j, s;
for (i = 0; i < 65; i += 2) {
h[i] = 0;
h[i + 1] = 0;
}
cin >> ... |
Greg has a pad. The pad's screen is an n × m rectangle, each cell can be either black or white. We'll consider the pad rows to be numbered with integers from 1 to n from top to bottom. Similarly, the pad's columns are numbered with integers from 1 to m from left to right.
Greg thinks that the pad's screen displays a c... | #include <bits/stdc++.h>
using namespace std;
int n, m;
long long res, c[2005][2005];
int main() {
cin >> n >> m;
long long p, q, s;
for (int i = 1; i <= n; i++) {
p = 1, q = 0;
for (int j = 2; j <= m; j++) {
q = (q + c[i - 1][j]) % 1000000007;
p = (p + q) % 1000000007;
c[i][j] = p;
... |
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangeme... | #include <bits/stdc++.h>
using namespace std;
int n, m[100005], x, k[100005], res, last;
stack<int> s;
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
if (s.empty() || x > s.top()) {
s.push(x);
} else {
if (last > x) {
m[x] = 1;
k[x] = last;
} else {
... |
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u... | #include <bits/stdc++.h>
using namespace std;
const int INF = ~(1 << 31);
const double eps = 1e-6;
const long double PI = 3.1415926535;
const int MOD = 1e9 + 7;
int n, m;
int main() {
string s;
cin >> s;
stack<int> st;
for (int(i) = 0; (i) < (s.size()); ++(i)) {
int g = s[i] == '+';
if (st.size() && st.... |
Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal...
Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate inter... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 10;
const int maxm = 3000 + 10;
struct Edge {
int v, l, r, next;
Edge(int v = 0, int l = 0, int r = 0, int next = 0)
: v(v), l(l), r(r), next(next) {}
} edges[maxm << 1];
int head[maxn], nEdge, n, m;
int a[maxm], b[maxm];
int vis[maxn], cnt... |
The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they ma... | #include <bits/stdc++.h>
using namespace std;
int n, l;
vector<int> v;
int main() {
scanf("%d %d", &n, &l);
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
if (x >= l) v.push_back(x);
}
sort(v.begin(), v.end());
int ms = 0;
for (int i = 0; i < v.size(); i++) {
int count = 0;
for (i... |
A chessboard n × m in size is given. During the zero minute we repaint all the black squares to the 0 color. During the i-th minute we repaint to the i color the initially black squares that have exactly four corner-adjacent squares painted i - 1 (all such squares are repainted simultaneously). This process continues a... | #include <bits/stdc++.h>
using namespace std;
int perimeter(int w, int h) {
if (w == 1) return h;
if (h == 1) return w;
return 2 * w + 2 * (h - 2);
}
int main() {
int n, m, x;
cin >> n >> m >> x;
int res = 0;
while (true) {
int border = (perimeter(n, m) + 1) / 2;
--x;
if (!x) {
res = bor... |
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
int cost[MAXN];
char used[MAXN];
vector<int> g[MAXN];
int main() {
ios_base::sync_with_stdio(false);
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> cost[i];
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
x--;... |
The Berland capital (as you very well know) contains n junctions, some pairs of which are connected by two-way roads. Unfortunately, the number of traffic jams in the capital has increased dramatically, that's why it was decided to build several new roads. Every road should connect two junctions.
The city administrat... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
const long double eps = 1e-7;
const int inf = 1000000010;
const long long INF = 10000000000000010LL;
const int mod = 1000000007;
const int MAXN = 100010, LOG = 20;
struct DSU {
int par[901];
vector<int> vec[901];
DSU() {
for (int i = ... |
You have two friends. You want to present each of them several positive integers. You want to present cnt1 numbers to the first friend and cnt2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.
In addition, the fir... | def solve(c1, c2, x, y):
l, h = 0, 10**18
while l < h:
m = l+(h-l)/2
if m-m/x >= c1 and m-m/y >= c2 and m-m/x/y >= c1+c2:
h = m
else:
l = m+1
return h
c1, c2, x, y = map(int, raw_input().split())
print solve(c1, c2, x, y)
|
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int r, x, y, x1, y1;
cin >> r >> x >> y >> x1 >> y1;
int ans;
ans = ceil(sqrt(pow(x - x1, 2) + pow(y - y1, 2)) / (2 * r));
cout << ans;
return 0;
}
|
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.
The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be ... | I = lambda:map(int,raw_input().split())
n,k = I()
x = k
s = 0
for i in range(k):
lst = list(I())
s = s + len(lst) - 2
x = x + len(lst) - 2
if lst[1] == 1:
for j in range(2,len(lst)):
if lst[j] == j:
x = x - 1
s = s - 1
print x+s-1
... |
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula
<image>
Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6,... | import os
import sys
from io import BytesIO, IOBase
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.write if self.wri... |
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd a... | #include <bits/stdc++.h>
using namespace std;
int main() {
int m[5], w[5], h[2], score[5] = {500, 1000, 1500, 2000, 2500};
for (int i = 0; i < 5; i++) cin >> m[i];
for (int i = 0; i < 5; i++) cin >> w[i];
cin >> h[0] >> h[1];
int ans = 0;
for (int i = 0; i < 5; i++) {
int mx = (3 * score[i]) / 10;
i... |
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to t... | import java.util.*;
public class JerrysProtest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] array = new int[n];
for(int x = 0; x < n; x++)
{
array[x] = in.nextInt();
}
Arrays.sort(array);
long[] freq = new long[5000];
for(... |
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a sec... | def main():
n, a, b, t = map(int, raw_input().split())
b += 1
l = [b if char == "w" else 1 for char in raw_input()]
t -= sum(l) - a * (n + 2)
hi, n2 = n, n * 2
n3 = n2 + 1
lo = res = 0
l *= 2
while lo <= n and hi < n2:
t -= l[hi]
hi += 1
b = hi - n
whi... |
Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station.
Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j.... | /*-
* Codeforces problem :
* http://codeforces.com/problemset/problem/675/E
*
* Print the sum of ρi,j among all pairs of 1 ≤ i < j ≤ n.
*/
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Inp... |
Bearland is a dangerous place. Limak can’t travel on foot. Instead, he has k magic teleportation stones. Each stone can be used at most once. The i-th stone allows to teleport to a point (axi, ayi). Limak can use stones in any order.
There are n monsters in Bearland. The i-th of them stands at (mxi, myi).
The given k... | #include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void smin(T &a, U b) {
if (a > b) a = b;
}
template <typename T, typename U>
inline void smax(T &a, U b) {
if (a < b) a = b;
}
int power(int a, int b, int m, int ans = 1) {
for (; b; b >>= 1, a = 1LL * a * a % m)
if (b & 1)... |
Today Peter has got an additional homework for tomorrow. The teacher has given three integers to him: n, m and k, and asked him to mark one or more squares on a square grid of size n × m.
The marked squares must form a connected figure, and there must be exactly k triples of marked squares that form an L-shaped tromi... | #include <bits/stdc++.h>
using namespace std;
const int N = 41414;
bool a[N][320], as[N][320];
int n, m, k, ty, tl, t, z, mx;
bool pd(int k) {
if (k < 0 || k == 1 || k == 2 || k == 5 || k == 4 ||
k == 8 && n != 3 && m != 3)
return 1;
return 0;
}
void dfs(int x, int y, int ct) {
if (tl) return;
if ((x ... |
All of us know that girls in Arpa’s land are... ok, you’ve got the idea :D
Anyone knows that Arpa isn't a normal man, he is ... well, sorry, I can't explain it more. Mehrdad is interested about the reason, so he asked Sipa, one of the best biology scientists in Arpa's land, for help. Sipa has a DNA editor.
<image>
S... | #include <bits/stdc++.h>
static const int MAXN = 200007;
static const int MAXQ = 100003;
static const int LOGN = 18;
static const int ALPHA_SZ = 29;
static const char ALPHA_OFFSET = '_';
static const int SOLANUM_TUBEROSUM = 128;
namespace sfx {
char *s;
int n;
int sa[MAXN], rk[MAXN], lcp[MAXN], nw[MAXN];
int st[MAXN][L... |
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.
Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.
Now then, you are given a function f: [... | n = int(raw_input())
data = map(int, raw_input().split())
inPlace = 0
values = set()
for i in range(len(data)):
values.add(data[i])
if data[i] == i + 1:
inPlace += 1
if inPlace != len(values):
print -1
else:
h = [0] * len(values)
ind = 0
hi = {}
for v in values:
h[ind] = v
hi[v] = ind
ind += 1
g = [... |
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most k pebbles in each pocket at the same time.... | import math
n,k = map(int,input().split())
stones = list(map(int, input().split()))
days = 0
for i in range(n):
days += math.ceil(stones[i]/k)
print(math.ceil(days/2)) |
The year of 2012 is coming...
According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us... | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jtimv
*/
import java.util.*;
public class Task {
public static void main(String[] args) {
new Task().main();
}
Scanner in = new Scanner(System.in);
String[] heores = {"Anka",... |
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis... | s, v1, v2, t1, t2 = list(map(int, input().split()))
a = 2*t1 + s*v1
b = 2*t2 + s*v2
if a > b:
print("Second")
elif a < b:
print("First")
else:
print("Friendship")
|
Harry, upon inquiring Helena Ravenclaw's ghost, came to know that she told Tom Riddle or You-know-who about Rowena Ravenclaw's diadem and that he stole it from her.
Harry thought that Riddle would have assumed that he was the only one to discover the Room of Requirement and thus, would have hidden it there. So Harry ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
const int LG = 17;
int anc[N][LG];
int sum[N][LG];
int depth[N];
vector<pair<int, int>> chld[N];
int parent[N], type[N];
int n;
void build(int now, int par, int val) {
anc[now][0] = par;
sum[now][0] = val;
depth[now] = depth[par] + 1;
for (int... |
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below... | #include <bits/stdc++.h>
using namespace std;
int n, v[100];
string s[100], c;
int def() {
string s1, s2, s3;
cin >> s1 >> s2;
int p = s1.rfind("&") + 1, q = s1.find("*"), v1;
if (q < 0) {
v1 = 0 - p;
q = 1000;
} else
v1 = (s1.size() - q) - p;
s3 = s1.substr(p, q - p);
if (s3 == "void") {
... |
Let's denote a function
<image>
You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
Input
The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.
The second line contains n integers a1, a2, ..., ... | from sys import stdin, stdout
n = int(stdin.readline())
a = [int(i) for i in stdin.readline().split()]
d = dict()
ans, sm = 0, 0
for i in range(n):
if a[i] not in d.keys():
d[a[i]] = 0
d[a[i]] += 1
ans += i * a[i] - sm
if (a[i] + 1) in d.keys():
ans += 1 * d[a[i] + 1]
if (a[i] - 1) i... |
It's May in Flatland, and there are m days in this month. Despite the fact that May Holidays are canceled long time ago, employees of some software company still have a habit of taking short or long vacations in May.
Of course, not all managers of the company like this. There are n employees in the company that form a... | #include <bits/stdc++.h>
using namespace std;
int a14;
inline int rd(int l, int r) { return rand() % (r - l + 1) + l; }
const int mxn = 1e5 + 3, sq = 333;
int to[mxn], nxt[mxn], fir[mxn],
gn = 1, n, fa[mxn], dep[mxn], siz[mxn], dfn[mxn], dn, top[mxn], zs[mxn],
dfa[mxn], va[mxn], m, xw[mxn], ans, ux[mxn], un, st... |
You are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column.
You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to:
* (i - 1, j + 1) — only if i > 1,
* (i, ... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
long long add(long long a, long long b) {
long long res = a + b;
return res >= mod ? res - mod : res;
}
long long mul(long long a, long long b) { return a * b % mod; }
vector<vector<long long>> matmul(const vector<vector<long long>>& a,
... |
The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.
The nation has n districts numbered from 1 to n, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district i is equ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 100;
long long tree[N];
bool a[N];
int sz[N];
int mapping[N];
int par[N];
long long n;
void print() {
for (int i = 1; i <= n; i++) {
if (a[i] == false) printf("%d ", i);
}
}
long long query(int idx) {
long long sum = 0;
while (idx > 0) {
... |
Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A f... | #include <bits/stdc++.h>
using namespace std;
void fun() {}
long long int __gcd(long long int a, long long int b) {
if (b == 0) return a;
return __gcd(b, a % b);
}
long long int poww(long long int a, long long int b, long long int md) {
if (b < 0) return 0;
if (a == 0) return 0;
long long int res = 1;
while... |
Bhavana and Bhuvana place bet every time they see something interesting that can occur with a probability 0.5.
Both of them place a bet for a higher amount which they don’t posses at that time. But when one wins she demands other for the bet amount. For example if Bhuvana wins she asks bhavana for the bet amount.
But... | from sys import stdin
t=stdin.readline()
a=stdin.readlines()
for i in a:
n = int(i)
cur = 1
ans = 0
while cur<=n:
cur = cur*2
ans+=1
ans-=1
if n==0:
ans = 0
if ans==0:
ans = -2147483648
print ans |
Strings can be efficiently stored as a data structure, to have efficient searching methods.
A new startup is going to use this method, but they don't have much space. So they want to check beforehand how much memory will be required for their data.
Following method describes the way in which this startup's engineers s... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
class Node():
def __init__(self,alphabet):
self.value = alphabet
self.children = []
class Trie():
def __init__(self):
self.root = Node("root")
def insertWord(self,word):
le... |
Given the value of n, print the n'th prime number.
Input : A single integer n.
Output : A single number which is the n'th prime number.
Constraints :
1 ≤ n ≤ 1000
SAMPLE INPUT
2
SAMPLE OUTPUT
3
Explanation
The first few prime numbers are:
2,3,5,7. So, the answer is 3. | no = input()
c = 0
for pk in range(2,7920):
am = 0
for qd in range(2,(pk/2)+1):
if (pk % qd == 0):
am = 1
break
if (am == 0):
c = c + 1
if(c == no):
print pk
break |
Yesterday Oz heard a story about insect colony. The specialty of insects is that they splits sometimes i.e an insect of size A can split into two insects of positive integral sizes B and C such that A = B + C. Also sometimes they attack each other i.e. two insects of sizes P and Q will become R = P XOR Q .
You are give... | t = int(raw_input())
for i in range(t):
arr = list(map(int,raw_input().split()))
arr = arr[1:]
ans = sum(arr)
if ans%2 == 1:
print 'No'
else:
print 'Yes' |
you are given an array of size N. You need to select K elements from the array such that the difference between the max number among selected and the min number among selected array elements should be minimum. Print the minimum difference.
INPUT:
First line N number i.e., length of array
Second line K number
Next N l... | a=[]
t,k=input(),input()
for _ in xrange(t):
a.append(input())
a.sort()
t=[a[x+k-1]-a[x] for x in xrange(0,len(a)-k) ]
print min(t) |
In a mystical TimeLand, a person's health and wealth is measured in terms of time(seconds) left.
Suppose a person there has 24x60x60 = 86400 seconds left, then he would live for another 1 day.
A person dies when his time left becomes 0. Some time-amount can be borrowed from other person, or time-banks.
Some time-amoun... | def solve():
n,k=[int(x) for x in raw_input().split()]
nums =[0]
nums.extend( [int(x) for x in raw_input().split()])
for i in xrange(1,1+k+1):
nums[i] = max(nums[i-1],nums[i])
for i in xrange(1+k+1,n+1):
nums[i] = max(nums[i-1],nums[i-k-1]+nums[i])
print nums[n]
def main():
for _ in xrange(input()... |
Sita loves chocolate and Ram being his boyfriend wants to give Sita as many chocolates as he can. So, he goes to a chocolate store with Rs. N in his pocket. The price of each chocolate is Rs. C. The store offers a discount that for every M wrappers he gives to the store, he gets one chocolate for free. How many chocola... | for _ in xrange(input()):
n,c,m=map(int,raw_input().split())
nc=n/c
nw=nc
if nw>=m:
while True:
c=nw/m
nc+=c
nw=nw%m+c
if nw<m:
break
print nc |
Surya loves to play with primes. One day, he asked his friend don to print any number in the form of multiple of prime factors. Help don in solving the problem.
Input
The first line will contain an integer t (1 ≤ t ≤ 10^6) denoting number of test case.
For each test case, you will be given an integer n (2 ≤ n ≤ 10^6... | def CheckIfProbablyPrime(x):
return (2 << x - 2) % x
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d)
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
for i in range(input()):
a=input()
s=""
s1=""
... |
Maga and Alex are good at string manipulation problems. Just now they have faced a problem related to string. But it is not a standard string problem. They have no idea to solve it. They need your help.
A string is called unique if all characters of string are distinct.
String s_1 is called subsequence of string s_2 ... | input()
ans=''
inp=raw_input()
init=0
for j in xrange(ord('z'),ord('a')-1,-1):
a=chr(j)
for k in xrange(init,len(inp)):
if inp[k]==a:
ans+=a
init=k+1
break
print ans |
Given is a positive integer N. How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?
Constraints
* 2 \leq N \leq 10^6
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer.
Examples
Input
3
Output
3
Input
100
... | N = int(input())
ans = 0
for i in range(1, N):
ans += (N - 1) // i
print(ans) |
We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.
We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.
The i-th and j-th sardines (i \neq j) are on bad terms if and o... | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main {
static Input in = new Input(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int N = in.nextInt();
Map<Long, Map<Lon... |
There are N slimes standing on a number line. The i-th slime from the left is at position x_i.
It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}.
Niwango will perform N-1 operations. The i-th operation consists of the following procedures:
* Choose an integer k between 1 and N-i (inclusive) with equ... | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL mod = 1000000007;
LL mi (LL x, LL m) {
// compute pow(x, m-2)
LL acc = 1;
LL p = m-2;
while (p) {
if (p%2 == 1) {
acc *= x;
acc %= m;
}
x *= x % m;
x %= m;
p >>= 1;
}
return acc;
}
int main()
{
LL n;
cin >> n;
vect... |
Takahashi has a string S of length N consisting of lowercase English letters. On this string, he will perform the following operation K times:
* Let T be the string obtained by reversing S, and U be the string obtained by concatenating S and T in this order.
* Let S' be some contiguous substring of U with length N, an... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
final int N = sc.nextInt();
int K = sc.nextInt();
StringBuilder S = new StringBuilder(sc.next());
boolean firstTime = true;
int step = 1;
... |
There are N people numbered 1 to N. Each person wears a red hat or a blue hat.
You are given a string s representing the colors of the people. Person i wears a red hat if s_i is `R`, and a blue hat if s_i is `B`.
Determine if there are more people wearing a red hat than people wearing a blue hat.
Constraints
* 1 \l... | import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String s = sc.next();
Main redOrBlue = new Main();
System.out.println(redOrBlue.judgeRedOrBlue(N, s));
}
private String judgeRedOrBlue(int n, String s) {... |
There are some coins in the xy-plane. The positions of the coins are represented by a grid of characters with H rows and W columns. If the character at the i-th row and j-th column, s_{ij}, is `#`, there is one coin at point (i,j); if that character is `.`, there is no coin at point (i,j). There are no other coins in t... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 305;
int N, M, ps[3*MAXN][3*MAXN], ps2[3*MAXN][3*MAXN];
char arr[MAXN][MAXN];
vector<pair<int, int>> utama[2*MAXN], lain[2*MAXN];
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; ... |
"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the curr... | a, b, c, x, y = map(int, input().split())
print(min(a*x+b*y, c*2*max(x,y), c*2*min(x,y)+abs(x-y)*(a if x>y else b))) |
Snuke has a string S consisting of three kinds of letters: `a`, `b` and `c`.
He has a phobia for palindromes, and wants to permute the characters in S so that S will not contain a palindrome of length 2 or more as a substring. Determine whether this is possible.
Constraints
* 1 \leq |S| \leq 10^5
* S consists of `a`... | s=input()
from collections import defaultdict
d=defaultdict(int)
for c in s:
d[c]+=1
a,b,c=d["a"],d["b"],d["c"]
mx=max(a,b,c)
mn=min(a,b,c)
#a,b,c = map(lambda x:x-mn, [a,b,c])
if mx-mn >=2:
print("NO")
else:
print("YES") |
It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.
There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.
Find the minimum distance to be traveled when AtCoDeer can start and ... | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
int A = cin.nextInt();
int list[] = new int[A];
int tmp;
for(int i=0;i<A;i++){
list[i] = cin.nextInt();
}
Arrays.sort(list);
tmp = list[0];
int s... |
You are given a positive integer N. Find the number of the pairs of integers u and v (0≦u,v≦N) such that there exist two non-negative integers a and b satisfying a xor b=u and a+b=v. Here, xor denotes the bitwise exclusive OR. Since it can be extremely large, compute the answer modulo 10^9+7.
Constraints
* 1≦N≦10^{18... | #include <bits/stdc++.h>
using namespace std;
const int64_t MOD = 1e9+7;
void add(int64_t& a, int64_t b){
a = (a+b)%MOD;
}
int nth_bit(int64_t num , int n) {
return (num >> n) & 1;
}
int main() {
int64_t N;
cin >> N;
int64_t dp[61][3] = {0};
dp[60][0] = 1;
for(int d = 59; d >= 0; d--) {... |
Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i. He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A. In how many ways can he make his selection?
Constraints
* 1 \leq N \leq 50
* 1 \leq A \leq 50
* 1 \leq x_... | #include <cstdio>
#include <algorithm>
using namespace std;
long long int knapsack[51][3000]={};
long long int ans=0;
int main(){
int n,a,t;
knapsack[0][0]=1;
scanf("%d %d",&n,&a);
for(int i=1;i<=n;i++){
scanf("%d",&t);
for(int k=i-1;k>=0;k--){
for(int j=2500;j>=t;j--){
knapsack[k+1][j]+=knapsack[k][j-t]... |
There is data on sales of your company. Your task is to write a program which identifies good workers.
The program should read a list of data where each item includes the employee ID i, the amount of sales q and the corresponding unit price p. Then, the program should print IDs of employees whose total sales proceeds ... | while True:
n = int(raw_input())
if n == 0:
break
data = {}
order = []
for i in range(n):
id,price,quant = map(int, raw_input().split())
if id in data:
data[id] += price*quant
else:
data[id] = price*quant
order.append(id)
if max(data.values()) < 1000000:
print "NA"
else:
for k in order:
... |
Taro went to a toy store to buy a game of life made by Aizu Hobby. Life games are played using a board with squares and roulette. As shown in the figure, the board has one start point and one goal point, which are connected by a single grid. First, the pieces are placed in the square at the starting point, and the piec... | #include <bits/stdc++.h>
using namespace std;
double mem[51][5001];
int x,y,z,v[100],used[51][5001];
struct po{int e,a;};
po E[101];
double dfs(int pos,int mo){
if(pos==y) return mo;
if(used[pos][mo]) return mem[pos][mo];
used[pos][mo]=1;
for(int i=0;i<x;i++) {
int npos=min(y,pos+v[i]),nmo=mo;
int e... |
Maze & Items is a puzzle game in which the player tries to reach the goal while collecting items. The maze consists of $W \times H$ grids, and some of them are inaccessible to the player depending on the items he/she has now. The score the player earns is defined according to the order of collecting items. The objectiv... | #include <iostream>
#include <queue>
using namespace std;
int H, W, sx[32], sy[32], s[10][10], idx[1009][1009];
char c[1009][1009];
int t[32][32], u[1009][1009];
pair<int, int> dp[1 << 10][32];
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int main() {
cin >> W >> H;
for (int i = 1; i <= H; i++) {
fo... |
Dr. Asimov, a robotics researcher, released cleaning robots he developed (see Problem B). His robots soon became very popular and he got much income. Now he is pretty rich. Wonderful.
First, he renovated his house. Once his house had 9 rooms that were arranged in a square, but now his house has N × N rooms arranged in... | def checkback(B,i,j):
samesum= (B[i][j]==B[i][j-1]) +(B[i][j]==B[i][j+1]) +(B[i][j]==B[i-1][j])
if samesum==2:
return not B[i][j]
else:
return B[i][j]
while(1):
[N,K]=map(int,raw_input().split())
if N==0:
break
if N%2 or K>2**(N/2):
print "No\n"
else:
... |
The nth triangular number is defined as the sum of the first n positive integers. The nth tetrahedral number is defined as the sum of the first n triangular numbers. It is easy to show that the nth tetrahedral number is equal to n(n+1)(n+2) ⁄ 6. For example, the 5th tetrahedral number is 1+(1+2)+(1+2+3)+(1+2+3+4)+(1+2+... | import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int[] simen=new int[1000];
static int[] kisu_simen=new int[48];
static int INF=1000000007;
public static void main(String[] args) {
for(int i=0; i<200; i++) {
int tmp=(i+1)*(i+2)*(i+3)/6;
for(int j=0; j<5; j++) {
simen[i*5+j]... |
There are several towns on a highway. The highway has no forks. Given the distances between the neighboring towns, we can calculate all distances from any town to others. For example, given five towns (A, B, C, D and E) and the distances between neighboring towns like in Figure C.1, we can calculate the distance matrix... | #include<stdio.h>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
int d[310];
int c[510];
int v[310];
int at[30];
int n;
int tmp[30];
int sz;
set<vector<int> >S;
inline int ABS(int a){return max(a,-a);}
void solve(int a,int b){
if(a==n){
for(int i=0;i<n;i++)tmp[i]=at[i];
std::sort(tmp,tm... |
Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves rectangles as much as programming. Yu-kun decided to write a program to calculate the maximum score that can be obtained, thinking of a new play to ge... | #include <iostream>
#include <cstdio>
using namespace std;
#define rep(i,n) for(int i=0;i<n;++i)
#define REP1(i,n) for(int i=1;i<=n;++i)
#define ALL(c) (c).begin(),(c).end()
int a[50][50],b[50][50],c[50][50];
int main(){
int ha,wa,hc,wc;
cin >> ha >> wa;
rep(i,ha) rep(j,wa) cin >> a[i][j];
rep(i,ha) rep(j,wa) cin >... |
Once upon a time in a kingdom far, far away, there lived eight princes. Sadly they were on very bad terms so they began to quarrel every time they met.
One day, the princes needed to seat at the same round table as a party was held. Since they were always in bad mood, a quarrel would begin whenever:
* A prince took t... | #include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
int sum=0;
vector<int> solve(bitset<13>&used, vector<int>&nums) {
if (used.count() == 13) {
return vector<int>{-1};
}
else {
for (int i = 0; i < 13; ++i) {
if (!used[i]) {
if (sum ... |
Alice and Bob are going to drive from their home to a theater for a date. They are very challenging - they have no maps with them even though they don’t know the route at all (since they have just moved to their new home). Yes, they will be going just by their feeling.
The town they drive can be considered as an undir... | #include <cmath>
#include <queue>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
typedef pair<int, int> pii;
const int maxn = 105;
const int inf = 1e9;
const double eps = 1e-12;
int n, s, t, flag[maxn];
vector<pii> mp[maxn];
void add_edge(int u, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.