input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins from Y of the people and bronze coins from Z of the people. It is not possible to get two or more different col... | #include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn=1e5+5;
struct node
{
LL a, b, c;
bool operator <(const node & A) const
{
return (a-b)<A.a-A.b;
}
}p[maxn];
LL lef[maxn];
priority_queue<LL, vector<LL>, greater<LL> >q;
int main()
{
int x, y, z;
cin>>x>... |
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation:
* Select a pair of different... | import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Ar... |
A professor invented Cookie Breeding Machine for his students who like cookies very much.
When one cookie with the taste of x is put into the machine and a non-negative integer y less than or equal to 127 is input on the machine, it consumes the cookie and generates two cookies with the taste of y and (x XOR y).
Here... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int te; cin >> te;
while (te--){
int n, x; cin >> n >> x;
ll ans = 127 * (n - 1);
if (n & 1)
ans += x;
else
ans += 127 ^ x;
cout << ans << "\n";
}
return 0;
}
|
Tic-tac-toe is a game in which you win when you put ○ and × alternately in the 3 × 3 squares and line up ○ or × in one of the vertical, horizontal, and diagonal lines (Fig.). 1 to Fig. 3)
<image> | <image> | <image>
--- | --- | ---
Figure 1: ○ wins | Figure 2: × wins | Figure 3: Draw
In tic-tac-toe, ○ and × alterna... | #include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const double EPS = 1e-9;
bool check(char a, char b, char c){
if(a == 's') return false;
return (a == b && b == c);
}
int main(){... |
Artist Shinagawa was asked to exhibit n works. Therefore, I decided to exhibit the six sides of the cube colored with paint as a work. The work uses all six colors, Red, Yellow, Blue, Magenta, Green, and Cyan, and each side is filled with one color. Shinagawa changed the arrangement of colors even for cubic works with ... | D = [
(1, 5, 2, 3, 0, 4), # 'U'
(3, 1, 0, 5, 4, 2), # 'R'
(4, 0, 2, 3, 5, 1), # 'D'
(2, 1, 5, 0, 4, 3), # 'L'
]
p_dice = (0, 0, 0, 1, 1, 2, 2, 3)*3
def rotate_dice(L0):
L = L0[:]
for k in p_dice:
yield L
L[:] = (L[e] for e in D[k])
while 1:
N = int(input())
if N == 0:
... |
Alice and Brown are brothers in a family and each receives pocket money in celebration of the coming year. They are very close and share the total amount of the money fifty-fifty. The pocket money each receives is a multiple of 1,000 yen.
Write a program to calculate each one’s share given the amount of money Alice an... | #include<iostream>
#include<cmath>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
cout << (a+b)/2 << endl;
return 0;
}
|
In the Kingdom of IOI, the wind always blows from sea to land. There are $N + 1$ spots numbered from $0$ to $N$. The wind from Spot $0$ to Spot $N$ in order. Mr. JOI has a house at Spot $N$. The altitude of Spot $0$ is $A_0 = 0$, and the altitude of Spot $i$ ($1 \leq i \leq N$) is $A_i$.
The wind blows on the surface ... | #include<iostream>
#include<algorithm>
using namespace std;
int n,q,r,l;
long long s,t,a[200010],d[200010],x;
int main(){
cin>>n>>q>>s>>t;
for(int i=0;i<=n;i++)cin>>a[i];
long long cnt=0;
for(int i=0;i<n;i++){
d[i]=a[i+1]-a[i];
if(d[i]<0)cnt-=t*d[i];
if(d[i]>0)cnt-=s*d[i];
}
while(q--){
cin>>l>>r>>x;l--... |
A fraction whose numerator is 1 and whose denominator is a positive integer is called a unit fraction. A representation of a positive rational number p/q as the sum of finitely many unit fractions is called a partition of p/q into unit fractions. For example, 1/2 + 1/6 is a partition of 2/3 into unit fractions. The dif... | #include <bits/stdc++.h>
#define PB push_back
#define MP make_pair
#define REP(i,n) for (int i=0;i<(n);i++)
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define ALL(a) (a).begin(),(a).end()
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;
double EPS=1e-10;
int p,q,a,n;
... |
In the year 29XX, the government of a small country somewhere on the earth introduced a law restricting first names of the people only to traditional names in their culture, in order to preserve their cultural uniqueness. The linguists of the country specifies a set of rules once every year, and only names conforming t... | #include <string.h>
#include <ctype.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
inline void cmin(string &a, const string& b) { if (a > b) a = b; }
inline void cmin(string &a, const string& b, const string& c) {
if (a.size() ... |
Reordering the Documents
Susan is good at arranging her dining table for convenience, but not her office desk.
Susan has just finished the paperwork on a set of documents, which are still piled on her desk. They have serial numbers and were stacked in order when her boss brought them in. The ordering, however, is not... | #include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<db,db> pdb;
typedef tuple<int,int,int> tii;
typedef tuple<ll,ll,ll> tll;
typedef vector<vector<ll>> mat;
const ll mod=1e9+7;
const in... |
Expression Mining
Consider an arithmetic expression built by combining single-digit positive integers with addition symbols `+`, multiplication symbols `*`, and parentheses `(` `)`, defined by the following grammar rules with the start symbol `E`.
E ::= T | E '+' T
T ::= F | T '*' F
F ::= '1' | '2' | '3' | '4' | '5'... | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#define ALL(v) begin(v),end(v)
typedef long long LL;
const LL INF = 1010101010;
struct solver{
enum nodetype{
CON, PAR, ADD, MUL
};
struct node{
nodetype tp;
LL val;
vector<int> child;
vector<LL> psum;
}... |
T.I. Financial Group, a world-famous group of finance companies, has decided to hold an evil gambling game in which insolvent debtors compete for special treatment of exemption from their debts.
In this game, each debtor starts from one cell on the stage called the Deadly Ring. The Deadly Ring consists of N cells and ... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string mp;
int n,T;
double mem[2001][2001];
bool used[2001][2001];
double dfs(int t,int pos){
if(t==T)return mem[t][pos]=(mp[pos]=='R');
if(used[t][pos])return mem[t][pos];
used[t][pos]=1;
double res=0;
for(int i=1;i<=6;i++)res+=dfs(t+1,(po... |
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well.
Today's training is to increase creativity by drawing pictures. Let's draw a pattern well using a square stamp.
I want to use stamps of various sizes to complete the picture of the red, ... | #include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <numeric>
#include <utility>
#include <iomanip>... |
In the International City of Pipe Construction, it is planned to repair the water pipe at a certain point in the water pipe network. The network consists of water pipe segments, stop valves and source point. A water pipe is represented by a segment on a 2D-plane and intersected pair of water pipe segments are connected... | #include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-12)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
class Point{
public:
do... |
The city of Kyoto is a famous tourist destination for old temples and shrines.
Ikta came to Kyoto sightseeing with a few friends, but as a result of all acting freely, they all got lost.
So Ikta decided to think about where to meet in order to meet everyone as soon as possible.
Kyoto's roads run innumerably at inter... | #include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
... |
Problem statement
Here are $ N $ sheets of paper. You want to scan all paper by using $ 3 $ scanners in parallel. Each piece of paper has a fixed scanning time, and the time it takes to scan the $ i $ th paper is $ T_i $. You can scan the paper in any order, but you cannot scan multiple papers at the same time with a ... | #define _USE_MATH_DEFINES
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
using namespace std;
typedef pair<long long int, long long int> P;
long long int INF = 1e18;
long long int MOD = 1e9 + 7;
boo... |
In the Jambo Amusement Garden (JAG), you sell colorful drinks consisting of multiple color layers. This colorful drink can be made by pouring multiple colored liquids of different density from the bottom in order.
You have already prepared several colored liquids with various colors and densities. You will receive a d... | #include<iostream>
#include<map>
#include<algorithm>
#include<queue>
using namespace std;
int n,m;
map<string,priority_queue<int,vector<int>,greater<int> > >M;
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
string s;int a;cin>>s>>a;
M[s].push(a);
}
cin>>m;
int now=0;
for(;m--;)
{
string s;cin>>s;
while(M[s... |
Problem
One day, Kawabayashi is about to have lunch at the school cafeteria. There are three types of daily lunch menus for school cafeterias: A lunch, B lunch, and C lunch.
Kawabayashi is a glutton, so I would like to eat all three types of daily lunch menus one by one.
However, Kawabayashi decided to put up with one... | #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
if(a > b && a > c) cout << "A" << endl;
else if(b > c) cout << "B" << endl;
else cout << "C" << endl;
return 0;
}
|
For given three points p1, p2, p, find the projection point x of p onto p1p2.
<image>
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xi, yi ≤ 10000
* p1 and p2 are not identical.
Input
xp1 yp1 xp2 yp2
q
xp0 yp0
xp1 yp1
...
xpq−1 ypq−1
In the first line, integer coordinates of p1 and p2 are given. Then, q queries are giv... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
0 0 3 4
1
2 5
output:
3.1200000000 4.1600000000
"""
import sys
class Segment(object):
__slots__ = ('source', 'target')
def __init__(self, source, target):
self.source = complex(source)
self.target = complex(target)
def dot(a, b):
... |
Priority queue is a container of elements which the element with the highest priority should be extracted first.
For $n$ priority queues $Q_i$ ($i = 0, 1, ..., n-1$) of integers, perform a sequence of the following operations.
* insert($t$, $x$): Insert $x$ to $Q_t$.
* getMax($t$): Report the maximum value in $Q_t$. ... | #include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define il inline
#define db double
#define ls rt << 1
#define rs rt << 1 | 1
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define pll pair<ll, ll>
#define X first
#define Y second
#define pcc pair<char, char>
#define v... |
Nanu, a Clash of Clans player is so much obsessed with the game and its new update.
She wants to win as much battles as she can. Each of the enemy clan has N troops of lowercase letters.
And for the attack she takes an army of length M.
In the new update win is given when first k troops she takes, can kill any of the k... | from sys import stdin, stdout
t = int(stdin.readline())
while t:
t -= 1
n, m, k = map(int, stdin.readline().strip().split(' '))
N = stdin.readline().strip()
M = stdin.readline().strip()
M = M[:k]
count = 0
for i in range(len(N)-k+1):
s = N[i:i+k]
if s == M:
count += 1
if count == 0:
count = -1
stdout.... |
The captain of the ship TITANIC is a little .... off the track. He needs to select the crew for the ship. But everyone seems to be eligible. So to test their intelligence, he plays a game.
The contestants have to stand in a line. They are given the numbers in the order in which they stand, starting from 1. The captai... | from math import floor
from math import log
n = int(raw_input());
while n > 0:
no = int(raw_input());
print int(2**floor(log(no, 2)));
n -= 1; |
Freakin' news has recently claimed that they have discovered a civilization on mars and that they have established contact with the martians. Following is a summary of the dawn hour breakin' news on freakin' news :
Occassionally, the martian ministers feel the need to please their king. For this purpose, they give th... | l = raw_input().split()
n, k = int(l[0]), int(l[1])
l = raw_input().split()
l = [int(i) for i in l]
a, b = 1, -1
ans = -1*sum(l[:n-k])+sum(l[n-k:])
print ans |
There is a line with 1000 cells numbered from 1 to 1000 from left to right and N coins placed on it. Coin i is placed at cell Xi, and no two coins are placed at the same cell.
Bob would like to move the coins to the N leftmost cells of the line. To do this, he is allowed to take a coin from any cell T and move it to c... | for _ in xrange(int(raw_input())):
N, K = map(int, raw_input().split())
coins = map(int, raw_input().split())
if coins[-1] == N:
print 0
continue
seconds = 0
count = 0
for __ in xrange(coins[-1], 0, -1):
if __ in coins:
count += 1
else:
seconds += ((count - 1) / K + 1)
print seconds |
You are playing following game: given an array A of N natural numbers. All numbers in the array A are at most M. On every turn you may pick any two different elements Ai and Aj (i≠j), such that Ai, Aj ≤ M, and add K to both. The game ends when you are not able to continue. That is, when there is no pair (i,j) left such... | import sys
N, M, K = map(lambda x: int(x), sys.stdin.readline().split())
A = map(lambda x: int(x), sys.stdin.readline().split())
moves = map(lambda x: (M - x) / K + 1, A)
moves_sum = sum(moves)
moves_max = max(moves)
moves.remove(moves_max)
moves_max2 = max(moves)
min_moves = max((moves_sum - moves_max + 1) / 2, mov... |
Witua is a little student from the University of Lviv. He enjoys studying math. Witua knows a lot of famous mathematicians like Eratosthenes, Pythagoras, Fermat, Diophantus, Furko, Gauss and so on. However, his favorite one is Euler. The only thing Witua likes more than Euler is Euler’s totient function φ. He is explor... | import random
def modulo(a,b,c):
x = 1
y = a
while b>0:
if b%2==1:
x = (x*y)%c
y = (y*y)%c
b = b/2
return x%c
def millerRabin(N,iteration):
if N<2:
return 0
if N!=2 and N%2==0:
... |
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick.
Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ... | #include <bits/stdc++.h>
using namespace std;
void dfs(vector<int> adj[], int i, vector<bool> &vis) {
vis[i] = 1;
for (auto it : adj[i]) {
if (!vis[it])
dfs(adj, it, vis);
else {
cout << it << " ";
return;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout... |
Zibi is a competitive programming coach. There are n competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.
Rules of scoring also are... | import sys
s = sys.stdin.read()
n = m = -1
numb = 0
for i in range(len(s)):
if ord(s[i])>=48:
numb = 10*numb + ord(s[i])-48
else:
if n==-1:
n = numb
else:
m = numb
break
numb = 0
inp = []
numb = 0
sign = 1
for i in range(i+1,len(s)):
i... |
You have got a shelf and want to put some books on it.
You are given q queries of three types:
1. L id — put a book having index id on the shelf to the left from the leftmost existing book;
2. R id — put a book having index id on the shelf to the right from the rightmost existing book;
3. ? id — calculate the... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException ... |
You are given a positive integer n.
Find a sequence of fractions (a_i)/(b_i), i = 1 … k (where a_i and b_i are positive integers) for some k such that:
$$$ \begin{cases} $b_i$ divides $n$, $1 < b_i < n$ for $i = 1 … k$ \\\ $1 ≤ a_i < b_i$ for $i = 1 … k$ \\\ \text{$∑_{i=1}^k (a_i)/(b_i) = 1 - 1/n$} \end{cases} $$$
I... | #include <bits/stdc++.h>
using namespace std;
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie();
int n;
cin >> n;
int p = n;
for (long long i = 2; i * i < n; ++i) {
n = p;
if (n % i == 0) {
long long d1 = 1;
while (n % i == 0) {
n /= i;
d... |
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other.
<image> The example of two segments on the x-axis.
Your problem is to find two integers a and b such that l_1 ≤ a ≤ r_1, l_2 ≤ b ≤ r_2 an... | qry=int(input())
for _ in range(qry):
lrs=list(map(int,input().split()))
if lrs[0]==lrs[2]:
print(lrs[0],lrs[3])
else:
print(lrs[0],lrs[2]) |
In the country N, there are n cities connected by m one-way roads. Although this country seems unremarkable, there are two interesting facts about it. At first, a week lasts d days here. At second, there is exactly one museum in each city of the country N.
Travel agency "Open museums" is developing a new program for t... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
static PrintWriter out = new PrintWriter(System.out);
/*
3 3 7
1 2
1 3
2 3
0111111
0000000
0... |
Jury picked a polynomial f(x) = a_0 + a_1 ⋅ x + a_2 ⋅ x^2 + ... + a_k ⋅ x^k. k ≤ 10 and all a_i are integer numbers and 0 ≤ a_i < 10^6 + 3. It's guaranteed that there is at least one i such that a_i > 0.
Now jury wants you to find such an integer x_0 that f(x_0) ≡ 0 mod (10^6 + 3) or report that there is not such x_0.... | #include <bits/stdc++.h>
using namespace std;
const long long int mod = 1e6 + 3;
long long int query(int x) {
printf("? %d\n", x);
fflush(stdout);
long long int r;
scanf("%lld", &r);
return r;
}
void ex_(long long int x) {
printf("! %lld", x);
exit(0);
}
long long int pows(long long int now, int num) {
... |
Recall that string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly zero or all) characters. For example, for the string a="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", ... | s = input()
n = len(s)
count_o = []
count_w = 0
count = 0
for i in range(1, n):
if s[i] == 'v' and s[i-1] == 'v':
count_w += 1
elif s[i] == 'o':
count_o.append(count_w)
for c in count_o:
count += c * (count_w-c)
print(count)
|
You are given an array a consisting of n integers a_1, a_2, ..., a_n. You want to split it into exactly k non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the e... | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
InputReader in = new InputReader(inpu... |
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibl... | #include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f3f3f3f3fll;
long long cnt[200005];
long long cost[200005];
set<pair<long long, long long>> primeset;
void SieveOfEratosthenes(long long n) {
bool prime[n + 1];
memset(prime, true, sizeof(prime));
for (long long p = 2; p * p <= n; p++) {... |
Alice is playing a game with her good friend, Marisa.
There are n boxes arranged in a line, numbered with integers from 1 to n from left to right. Marisa will hide a doll in one of the boxes. Then Alice will have m chances to guess where the doll is. If Alice will correctly guess the number of box, where doll is now, ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5;
int n, m, a[maxn], l[maxn], r[maxn];
long long ans = 0;
int main() {
scanf("%d%d", &n, &m);
if (n == 1) {
printf("0\n");
return 0;
}
memset(l, 0, sizeof(l));
memset(r, 0, sizeof(r));
for (int i = 1; i <= m; i++) {
scanf("%d", &a... |
This is an interactive problem.
Khanh has n points on the Cartesian plane, denoted by a_1, a_2, …, a_n. All points' coordinates are integers between -10^9 and 10^9, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a permutation p_1, p_2,... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
using namespace std;
int a, b, c, d, n, m, k;
long long sq[1002];
bool uu[1002];
inline void sr(vector<int>& a) {
sort(a.begin(), a.end(),
[](const int& a, const int& b) { return sq[a] < sq[b];... |
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were 2n jars of strawberry and blueberry jam.
All the 2n jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exa... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 10;
int a[maxn * 2];
int main() {
int T;
scanf("%d", &T);
while (T--) {
int n;
scanf("%d", &n);
int red = 0, blue = 0;
map<int, int> m;
for (int i = 1; i <= n * 2; i++) {
int color;
scanf("%d", &color);
i... |
The map of Bertown can be represented as a set of n intersections, numbered from 1 to n and connected by m one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along... | import java.io.*;
import java.lang.Math;
import java.util.*;
public class Main {
public BufferedReader in;
public PrintStream out;
public boolean log_enabled = false;
public boolean multiply_tests = false;
public static boolean do_gen_test = false;
public void gen_test() {
... |
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place s... | import java.io.*;
import java.util.*;
public class Main{
static int pairToNum(int i,int j) {
return i*m+j;
}
static int[] numToPair(int num) {
return new int[] {num/m,num%m};
}
static long INF=(long)1e15;
static int n,m;
public static void main(String[] args) throws Exception{
PrintWriter pw=new P... |
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participan... | #include <bits/stdc++.h>
using namespace std;
const long long inf = 1e9;
const double eps = 1e-1;
const long long mod = 1e9 + 7;
bool check_pow_2(long long n) { return (n & (n - 1) == 0); }
bool is_prime(long long a, long long p) {
for (long long i = 2; i <= sqrt(a) && i <= p; i++)
if (a % i == 0) return false;
... |
Let a and b be two arrays of lengths n and m, respectively, with no elements in common. We can define a new array merge(a,b) of length n+m recursively as follows:
* If one of the arrays is empty, the result is the other array. That is, merge(∅,b)=b and merge(a,∅)=a. In particular, merge(∅,∅)=∅.
* If both arrays a... | import java.util.*;
import java.io.*;
/*
-> Written by <-
-----------
|J_O_B_E_E_L|
|___________|
| ___ |
| (^_^) |
| /( | )\ |
|____|_|____|
*/
public class Test{
static int x;
static Boolean [][] memo;
static ArrayList<Integer> list;
static boolean dp(int idx,int n) {
if(idx==list.size... |
Mr. Chanek The Ninja is one day tasked with a mission to handle mad snakes that are attacking a site. Now, Mr. Chanek already arrived at the hills where the destination is right below these hills. The mission area can be divided into a grid of size 1000 × 1000 squares. There are N mad snakes on the site, the i'th mad s... | #include <bits/stdc++.h>
using namespace std;
const long long MAXN = 2e3 + 5;
const long long MOD = 1e9 + 7;
long long n, m, R, x[MAXN], y[MAXN], T[MAXN][MAXN], W[MAXN][MAXN],
U[MAXN][MAXN], V[MAXN][MAXN];
long long c[MAXN], inve[MAXN], fact[MAXN];
void read_input() {
cin >> n >> m >> R;
for (long long i = 0; i... |
You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it.
You can perform the following operation any number of times (possibly zero):
* Choose any two adjacent cells and multiply the values in them b... | import java.io.*;
import java.util.StringTokenizer;
public class Cft {
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
int t = in.nextInt();
while (t-- > 0) {
int sum=0, min = Integer.MAX_VALUE;
int n = in.nex... |
For the New Year, Polycarp decided to send postcards to all his n friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size w × h, which can be cut into pieces.
Polycarp can cut any sheet of paper w × h that he has in only two cases:
* If w is even, then he can cut t... | import sys
def cardsForFriends():
for _ in range(int(input())):
w, h, n = map(int, input().split())
ans, tmp = 1, 1
while not w & 1:
w //= 2
ans += tmp
tmp *= 2
while not h & 1:
h //= 2
ans += tmp
tmp *= 2
if ans >= n:
print('YES')
else: print('NO')
def main():
cardsForFriends()
... |
Gaurang has grown up in a mystical universe. He is faced by n consecutive 2D planes. He shoots a particle of decay age k at the planes.
A particle can pass through a plane directly, however, every plane produces an identical copy of the particle going in the opposite direction with a decay age k-1. If a particle has d... | import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
//import javafx.util.*;
public final class B
{
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
static ArrayList<ArrayList<Integer>> g,CARS,intersection;
static long mod=1000000007;
sta... |
Let's call a positive integer n ordinary if in the decimal notation all its digits are the same. For example, 1, 2 and 99 are ordinary numbers, but 719 and 2021 are not ordinary numbers.
For a given number n, find the number of ordinary numbers among the numbers from 1 to n.
Input
The first line contains one integer... | """
Don't see the standings during the contest!!! you will lose motivation.
"""
# ---------------------------------------------------Import Libraries---------------------------------------------------
import sys
import time
import os
from math import sqrt, log, log2, ceil, log10, gcd, floor, pow, sin, cos, tan, pi... |
You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n.
A path from u to v is a sequence of edges such that:
* vertex u is the start of ... | #include <bits/stdc++.h>
#define forn(i,n) for(ll i=0; i<n; i++)
#define pb push_back
#define ll long long int
#define mp make_pair
#define sz(arr) (ll)arr.size()
#define MOD 998244353
using namespace std;
vector< vector<ll> > tree;
vector<ll> ans,used;
void dfs(ll nd){
used[nd]=1;
//cout<<nd<<" ";
for(ll nxt: tre... |
Vasya plays the Plane of Tanks.
Tanks are described with the following attributes:
* the number of hit points;
* the interval between two gun shots (the time required to recharge the gun);
* the probability that the gun shot will not pierce armor of the enemy tank;
* the damage to the enemy's tank.
Th... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-10;
int hp1, hp2;
int dt1, dt2;
int L1, R1;
int L2, R2;
double p1, p2;
double frac1, frac2;
const int MAXH = 200;
const int D = 5000;
double dp1[MAXH + 1][D + 1];
double dp2[MAXH + 1][D + 1];
double sum1[D + 1];
double sum2[D + 1];
void calcDp(int i, d... |
An oriented weighted forest is an acyclic weighted digraph in which from each vertex at most one edge goes.
The root of vertex v of an oriented weighted forest is a vertex from which no edge goes and which can be reached from vertex v moving along the edges of the weighted oriented forest. We denote the root of vertex... | #include <bits/stdc++.h>
using namespace std;
const int Maxn = 100 * 1000 + 10;
const long long D = 1000ll * 1000 * 1000 + 7;
pair<int, long long> par[Maxn];
pair<int, long long> find(int v) {
if (v == par[v].first) return par[v];
pair<int, long long> ret = find(par[v].first);
par[v] = pair<int, long long>(ret.fi... |
A parking lot in the City consists of n parking spaces, standing in a line. The parking spaces are numbered from 1 to n from left to right.
When a car arrives at the lot, the operator determines an empty parking space for it. For the safety's sake the chosen place should be located as far from the already occupied pl... | #include <bits/stdc++.h>
using namespace std;
int n, q, lt, rt, a, b, place, arabayeri[1000009], sol[1000009], sag[1000009],
temp2;
set<pair<int, pair<int, int> > > A;
pair<int, int> temp;
pair<int, pair<int, int> > f(int l, int r) {
if (!l and r == n + 1) return make_pair(-1e9, make_pair(1, n + 1));
if (!l) re... |
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.
A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's c... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
vector<int> e[N], e1[N];
int used[N], n, m, h, t;
void check(int v, int u) {
int k1, k2, k3 = k1 = k2 = 0;
static int timer = 10;
timer++;
for (int to : e[v]) {
if (to == u) {
continue;
}
used[to] = timer;
k1++;
}
for (in... |
Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs.
Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure... | #include <bits/stdc++.h>
using namespace std;
const int maxN = 5 * 10000 + 10, mod = (int)1e9 + 7;
int n;
long double k = 0, s = 0, lll, pp;
int p[maxN], l[maxN];
pair<int, int> c[maxN];
bool cmp(pair<int, int> x, pair<int, int> y) {
double xxx, yyy;
if (x.second != 100)
xxx = (double)(x.first * x.second) / (10... |
The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.
In the Pindows operating system a strings ... |
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class _B implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
S... |
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning.... | #include <bits/stdc++.h>
using namespace std;
long long n, m, x, mod = 1e9 + 7, ans = 1, f[3];
signed main() {
scanf("%lld", &n);
for (long long i = 1; i <= n; i++) {
scanf("%lld", &x);
if (x == 1) m++;
}
f[0] = f[1] = 1;
for (long long i = 2; i <= m; i++)
f[i % 3] = (f[(i - 2) % 3] * (i - 1) + f[... |
Xenia the horse breeder has n (n > 1) horses that stand in a row. Each horse has its own unique number. Initially, the i-th left horse has number i. That is, the sequence of numbers of horses in a row looks as follows (from left to right): 1, 2, 3, ..., n.
Xenia trains horses before the performance. During the practic... | #include <bits/stdc++.h>
const long long MOD = 1e9 + 7;
const long long MAXN = 1e6 + 1;
using namespace std;
long long readInt() {
bool minus1 = false;
long long result = 0;
char ch;
ch = getchar();
while (true) {
if (ch == '-') break;
if (ch >= '0' && ch <= '9') break;
ch = getchar();
}
if (c... |
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.
No... | import sys
n, m = map(int, input().split())
if m != 0:
data = [int(el) for el in input().split()]
data.sort()
if data[0] == 1 or data[-1] == n:
print('NO')
sys.exit()
for e in range(m - 2):
if data[e] + data[e + 1] + data[e + 2] == data[e] * 3 + 3:
print('NO')
... |
Our bear's forest has a checkered field. The checkered field is an n × n table, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. Let's denote a cell of the field on the intersection of row x and column y by record (x, y). Each cell of the field contains grow... | public class E {
private final static boolean autoflush = false;
long [][] A = {
{ 1, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 0, 0 },
{ 2, 1, 2, 1, 1, 0 },
{ 2, 1, 1, 2, 0, 1 },
{ 2, 1, 1, 1, 1, 0 },
{ 2, 1, 1, 1, 0, 1 }
};
public E () {
int N = sc.nextInt();
int X = sc.nextInt() - 1;
int Y = sc.n... |
This problem has nothing to do with Little Chris. It is about hill climbers instead (and Chris definitely isn't one).
There are n hills arranged on a line, each in the form of a vertical line segment with one endpoint on the ground. The hills are numbered with numbers from 1 to n from left to right. The i-th hill stan... | #include <bits/stdc++.h>
using namespace std;
struct point {
long long x, y;
point() {}
point(long long _x, long long _y) {
x = _x;
y = _y;
}
};
inline long long CCW(point a, point b, point c) {
long long a1 = b.x - a.x, b1 = b.y - a.y;
long long a2 = c.x - b.x, b2 = c.y - b.y;
return a1 * b2 - a2... |
Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu.
Each piece of tofu in the canteen is given a m-based number, all numbers are in the range [l, r] (l and r being m-based numbers), and for ev... | #include <bits/stdc++.h>
using namespace std;
template <typename F, typename U>
ostream& operator<<(ostream& os, const pair<F, U>& p) {
os << "(" << p.first << "," << p.second << ")";
return os;
}
template <typename F>
ostream& operator<<(ostream& os, const vector<F>& v) {
os << "[";
for (__typeof((v).begin()) ... |
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
(1n + 2n + 3n + 4n) mod 5
for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).
Input
The si... | n=int(input())
if n==0:
answer=4
else:
a=1
if n%4==0:
a+=6+1
elif n%4==1:
a+=2+3
elif n%4==2:
a+=4+9
else:
a+=8+7
if n%2==0:
a+=6
else:
a+=4
answer=a%5
print(answer)
|
A wavy number is such positive integer that for any digit of its decimal representation except for the first one and the last one following condition holds: the digit is either strictly larger than both its adjacent digits or strictly less than both its adjacent digits. For example, numbers 35270, 102, 747, 20 and 3 ar... | #include <bits/stdc++.h>
using namespace std;
const int maxs = 1000050, maxss = maxs * 10, mm = 1e7, mm1 = 1e6, mm2 = 1e5;
long long n, K, ans = -1;
int num1[maxs], s1 = 0, num2[maxs], s2 = 0;
int hs = 0, he[maxss], ne[maxs], cnt[maxs];
long long st[maxs];
long long chg(int x, int y, long long z) { return (z * 10 + x) ... |
New Year is coming in Tree Island! In this island, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists exactly one path between them. For every person in Tree Island, it takes exactly one minute to pass by exactly one road.
There is a weird New Year tra... | #include <bits/stdc++.h>
using namespace std;
struct node {
long long y, nex;
} a[2 * 210000];
struct node1 {
long long dep, par[20];
} t[210000];
long long fir[210000], len, n, m, z;
long long inf = 1ll << 60;
bool bo;
void ins(long long x, long long y) {
a[++len].y = y;
a[len].nex = fir[x];
fir[x] = len;
}
... |
Optimizing the amount of data transmitted via a network is an important and interesting part of developing any network application.
<image>
In one secret game developed deep in the ZeptoLab company, the game universe consists of n levels, located in a circle. You can get from level i to levels i - 1 and i + 1, also y... | import java.io.*;
import java.util.*;
public class E {
void solve() throws IOException {
int n = nextInt();
int q = nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
long[] sum = new long[n + 1];
for (int i = n - 1; i >= 0; i--) {
sum[i] = a[i] + sum[i + 1];
... |
Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right.
In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur mult... | #include <bits/stdc++.h>
using namespace std;
long long V[101][101];
int main() {
long long a, b, c, d, T;
cin >> T;
long long sum = 0;
while (T--) {
cin >> a >> b >> c >> d;
for (int i = a; i <= c; i++) {
for (int j = b; j <= d; j++) {
sum++;
}
}
}
cout << sum;
}
|
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimu... | from __future__ import division
from collections import Counter as ctr
from math import ceil, log, factorial
# reads a line of input and converts into a list of ints
# 1 1 3 => [1, 1, 3]
def rl():
return [int(i) for i in raw_input().split()]
# reads n lines of input (if n defined) and returns a list of strings
# w... |
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman coul... | #include <bits/stdc++.h>
using namespace std;
void file() {
freopen("std.in", "r", stdin);
freopen("wa.out", "w", stdout);
}
const long long N = 1e6 + 10, M = 2e6 + 10, inf = 1e9;
inline long long read() {
bool sym = 0;
long long res = 0;
char ch = getchar();
while (!isdigit(ch)) sym |= (ch == '-'), ch = ge... |
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.
For the i-th query find any position pi (li ≤ pi ≤ ri) so that api ≠ xi.
Input
The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the number of elements in a and the number of queries.
The second... | #include <bits/stdc++.h>
using namespace std;
int N, M, a[200010], dp[200010];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
int i, l, r, x;
for (i = 1; i <= N; i++) cin >> a[i];
for (i = N; i > 0; i--) {
dp[i] = i;
if (a[i + 1] == a[i]) dp[i] = dp[i + 1];
}
while (M--) {
... |
There are n bears in the inn and p places to sleep. Bears will party together for some number of nights (and days).
Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.
A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking... | #include <bits/stdc++.h>
using namespace std;
int n, q, p;
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
inline unsigned int C(int n, int r) {
vector<int> tmp;
for (int i = 1; i <= r; i++) tmp.push_back(n - i + 1);
for (int i = 1; i <= r; i++) {
int zjk = i;
for (auto &t : tmp)
if (t != 1)... |
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, ... | #include <bits/stdc++.h>
using namespace std;
int pre[500500], nex[500500], p[500500];
stack<int> s;
void connect(int x, int y) {
nex[x] = y;
pre[y] = x;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m, c, i;
string b, o;
cin >> n >> m >> c >> b;
c--;
s.push(0);
connect(n, 0);
fo... |
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city h... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, x, y, si[N];
double ans[N];
int tot, fi[N], a[N], ne[N];
inline void add(int x, int y) {
a[++tot] = y;
ne[tot] = fi[x];
fi[x] = tot;
}
inline void pre(int x) {
si[x] = 1;
for (int i = fi[x]; i; i = ne[i]) pre(a[i]), si[x] += si[a[i]]... |
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe ... | #include <bits/stdc++.h>
const int MOD = 10007;
const int MAXN = 110001;
int n, a[MAXN];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", a + i);
std::sort(a + 1, a + n + 1);
int answer = 0;
for (int i = 1; i <= n; i++) {
answer = (answer + 1ll * a[i] * a[n - i + 1] % MOD) % MOD;
}... |
Tanya is now five so all her friends gathered together to celebrate her birthday. There are n children on the celebration, including Tanya.
The celebration is close to its end, and the last planned attraction is gaming machines. There are m machines in the hall, they are numbered 1 through m. Each of the children has ... | #include <bits/stdc++.h>
using namespace std;
const int N = 70;
int gi() {
int x = 0, o = 1;
char ch = getchar();
while (!isdigit(ch) && ch != '-') ch = getchar();
if (ch == '-') o = -1, ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
return x * o;
}
struct dat {
int i, j, s, d;... |
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.
About sequences a and b we know that their elements are in the range from l to... | #include <bits/stdc++.h>
void probs();
int main() {
probs();
return 0;
}
void probs() {
int n, l, r, *a, *b;
scanf("%d%d%d", &n, &l, &r);
int k, max;
a = (int*)malloc(n * sizeof(int));
b = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
for (int i = 0; i < n; i++) {
... |
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...
You are given an array of integers. Sort it in non-descending order.
Input
The input consists of a single line... | a = input()[2:]
n = [0 for i in range(1000000)]
g = 123
for i in range(130000):
g *= 3
a = list(map(int, a.split()))
x = [0 for _ in range(len(a))]
for i in range(len(x)):
x[i] = min(a)
a.remove(x[i])
for o in x:
print(o, end=' ')
|
Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?"
We have a tree T with n vertices and m types of ice cream numerated from 1 to m. Each vertex i has a set of si types of ice cream. Vertices which have the i-t... | #include <bits/stdc++.h>
using namespace std;
int col[300010], flag[300010];
vector<int> ice[300010];
vector<int> edge[300010];
int dfn;
void dfs(int u, int f) {
for (int ic : ice[u]) {
if (col[ic]) {
flag[col[ic]] = dfn;
}
}
int cur = 1;
for (int ic : ice[u]) {
if (!col[ic]) {
while (fl... |
Developer Petr thinks that he invented a perpetual motion machine. Namely, he has a lot of elements, which work in the following way.
Each element has one controller that can be set to any non-negative real value. If a controller is set on some value x, then the controller consumes x2 energy units per second. At the s... | #include <bits/stdc++.h>
using namespace std;
vector<int> v[111111];
int n, m, s[111111], vis[111111], b[111111];
int l, p[111111], f, ans[111111];
void print() {
f = 1;
printf("YES\n");
int i;
for (i = 1; i < n; i = i + 1) printf("%d ", ans[i]);
printf("%d\n", ans[n]);
}
void s4(int x) {
int i;
ans[x] = ... |
John gave Jack a very hard problem. He wrote a very big positive integer A0 on a piece of paper. The number is less than 10200000 . In each step, Jack is allowed to put ' + ' signs in between some of the digits (maybe none) of the current number and calculate the sum of the expression. He can perform the same procedure... | #include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
class CerrDummy {
} cerrDummy;
template <class T>
CerrDummy& operator<<(CerrDummy& cd, const T&) {
return cd;
}
using charTDummy = char;
using traitsDummy = char_traits<charTDummy>;
CerrDummy& operator<<(CerrDummy& cd,
basic_ostre... |
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.
Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in mu... |
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author tula4
*/
public class C00441D2PB {
public static void main(String[] args) {
... |
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a ... | /* start initial cell as (0,0)
The main idea is that :
1)a cell can not repeat.
2)if 2 cell are adjacent then absolute difference between steps taken to reach these cells should be one
*/
import java.io.*;
import java.util.*;
public class pt
{
static class pair{
int x,... |
Imp likes his plush toy a lot.
<image>
Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.
Initially, Imp has only on... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int copies, original;
cin >> copies >> original;
if (copies == 0 && original == 1) {
cout << "Yes" << endl;
exit(0);
}
if (copies >= original - 1) {
if ((copies - original + 1) % 2 == 0 && original > 1) {
cout << "Yes" << e... |
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something.
The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people"
Igor just c... | e = [[False] * 5 for i in range(5)]
for i in range(int(input())):
a, b = map(int, input().split())
e[a - 1][b - 1] = e[b - 1][a - 1] = True
for a in range(3):
for b in range(a + 1, 4):
for c in range(b + 1, 5):
if len({e[a][b], e[a][c], e[b][c]}) == 1:
print('WIN')
... |
You are given an integer array of length n.
You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to [x, x + 1, ..., x + k - 1] for some value x and length k.
Subsequence ... | #include <bits/stdc++.h>
using namespace std;
void printReverse(int u, vector<int> &tr) {
if (u == -1) {
return;
}
printReverse(tr[u] - 1, tr);
cout << u + 1 << ' ';
}
int main() {
ios_base::sync_with_stdio(0);
int n;
cin >> n;
vector<int> a(n), tr(n);
pair<int, int> mx = {0, 0};
for (int i = 0;... |
Consider a tree (that is, an undirected connected graph without loops) T_1 and a tree T_2. Let's define their cartesian product T_1 × T_2 in a following way.
Let V be the set of vertices in T_1 and U be the set of vertices in T_2.
Then the set of vertices of graph T_1 × T_2 is V × U, that is, a set of ordered pairs o... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 4001, mod = 998244353;
vector<int> g[maxn];
int n, m, k, c[80][80];
int sz[maxn], used[maxn];
int dp1[maxn][80], dp2[maxn][80];
int ANS, ans[80], ans1[80], ans2[80];
void add(int &a, int b) {
a += b;
if (a >= mod) a -= mod;
}
void dfs(int v, int p) {
... |
Limak is an old brown bear.
He often goes bowling with his friends.
For rolling a ball one gets a score - a non-negative integer number of points.
Score for the i-th roll is multiplied by i and scores are summed up.
For example, for rolls with scores 7, 10, 5 the total score is equal to 7×1 + 10×2 + 5×3 = 42.
Limak m... | s=0
mod=(10**9)+7
n=input()
c=pow(2,n-1,mod)
d=pow(2,abs(n-2),mod)
arr=map(int,raw_input().split())
for i in xrange(n):
s=((s%mod)+((arr[i]*c)%mod))%mod
c=((c%mod)+(d%mod))%mod
print s%mod |
In PIET's CS Deparment there is a contest of Geometry. In this contest students are told to find minimum angle between hour and minute hand.
Input:
The first line contains the number of test cases, T. T lines follow, each of which contains two integer Hour hand H and minute hand M .
Output:
Print the minimum angle be... | for _ in xrange(input()):
hr,mn=map(int,raw_input().split())
if hr==12:
hr=0
ahr=int(hr*30)+int(mn*0.5)
amn=int(mn*6)
angle=abs(ahr-amn)
if angle>180:
angle=360-angle
print angle |
Ma5termind and Subway are bored of their normal life.They want to do something interesting so that they can enjoy their last sem of college life.As usual Ma5termind comes up with a simple and interesting game.
Ma5termind gives Subway a compressed string. A compressed String is composed of characters and numbers.Every ... | import re
S = str(raw_input())
pairs = re.findall(r'([a-z])([0-9]+)', S)
alphabets_count = [0] * 26
for pair in pairs:
alphabets_count[ord(pair[0])-97] += int(pair[1])
for Q_I in range(int(raw_input())):
K = int(raw_input())
res = -1
for i in range(26):
if K <= alphabets_count[i]:
res = chr(i+97)
break
... |
Himu wants to go on a long drive with his girlfriend. There are N cities numbered from 1 to N, and every city is connected to every other city with bidirectional road. The length of a road is equal to XOR of the city numbers it is connecting. For example the length of road connecting city numbers 8 and 4 is 12. Himu wa... | t = int(raw_input())
while t:
a=1
n =int(raw_input())
n = n^1
while(n):
n/=2
a=a*2
a-=1
print a
t-=1 |
We have a FULL binary tree i.e. each node except leaves has two children.
The magic sum between any two leaf nodes (both possibly same) is the number obtained after adding values of all the nodes (including starting and ending nodes) in a unique path from first leaf to the later one.
Your task is to find the maximu... | def tlnr(i):
global lis
if 2*i+1 > len(lis)-1: return lis[i],lis[i]
ldia=tlnr(2*i+1)
rdia=tlnr(2*i+2)
return max(ldia[0],rdia[0],ldia[1]+rdia[1]+lis[i]),max(ldia[1],rdia[1])+lis[i]
T = int(raw_input())
for _ in xrange(T):
N = int(raw_input())
lis = [int(e) for e in raw_input().split()]
print tlnr(0)[0] |
A Nice-P sequence is defined as a sequence such that a1 x a2=1 (mod p), a2 x a3=1 (mod p) ..., an-1 x an = 1 (mod p). In addition, a1, a 2, a 3, ... an must be less than p and greater than or equal to 0. Given one element, a1, find the sum of the entire Nice-P sequence of length n. If, for any ai, where i ≥ 1, there ex... | #import sys
#sys.stdin = open("input.txt","r")
from fractions import gcd
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
g = b
return g, x, y
for testCases in range(input()):
a,p,n = map(int,raw_input().spli... |
You are given two circles C1 & C2 (centers , and radii are given), if area of circle-1 is A1 and that of circle-2 is A2 , you have to find whether area of union of these circle is the larger circle and area of intersection of these circle is smaller circle simultaneously , otherwise print "NOT SATISFIED".
Input
firs... | import math
T = int(input())
for t in range(T):
x1,y1,r1 = map(int, raw_input().split())
x2,y2,r2 = map(int, raw_input().split())
d = math.sqrt((x1-x2)**2 + (y1-y2)**2)
if d==0 and r1==r2:
print "C2~C1"
elif d>abs(r1-r2):
print "NOT SATISFIED"
elif r1>r2:
print "C1CC2"
else:
print "C2CC1" |
There is a mysterious temple in Mysteryland. The door of the temple is always closed.It can only be opened by a unique procedure.There are two boxes and N items outside the temple.Sherlock holmes visits the temple many times.Each time Sherlock holmes visits the temple,the number of items N outside the door of the templ... | def isSubSetSum(sett, n, summ):
subset = []
for i in range(summ+1):
a = []
for j in range(n+1):
a.append(True)
subset.append(a)
for i in range(n):
subset[0][i] = True;
for i in range(summ):
subset[i][0] = False;
for i in range(summ):
for i in range(n):
subset[i][j] = subset[i][j-1];
if ... |
As predicted by the great Gods, Little Arjit has got nothing to do this summer. (Are you surprised?) But, he's not one of those people to lose hope... not so easily. He decided to work hard this summer on the two things he wants the most, as of now: "Dual degree work", and "an internship!"
So, following the signs from... | from math import factorial
t = int(raw_input())
while t > 0:
t -= 1
n = input()
print factorial(2*n)/(factorial(n)**2 * (n + 1)) |
Xsquare got bored playing with the arrays all the time. Therefore, he has decided to play with the strings. Xsquare called a string P a "double string" if string P is not empty and can be broken into two strings A and B such that A + B = P and A = B. for eg : strings like "baba" , "blabla" , "lolo" are all double strin... | from collections import Counter
for _ in range(int(raw_input())):
s=Counter(raw_input())
f=0
for i in s.values():
if i>1:
f=1
break
if f:
print "Yes"
else:
print "No" |
Snuke has X+Y balls. X of them have an integer A written on them, and the other Y of them have an integer B written on them.
Snuke will divide these balls into some number of groups. Here, every ball should be contained in exactly one group, and every group should contain one or more balls.
A group is said to be good... | #include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
typedef long long ll;
inline int read(){
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c=='-')f=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
x=(x<<1)+(x<<3)+c-'0';
c=getchar();
}
return x*f;
}
int T,A,X,B,Y,... |
Fennec is fighting with N monsters.
The health of the i-th monster is H_i.
Fennec can do the following two actions:
* Attack: Fennec chooses one monster. That monster's health will decrease by 1.
* Special Move: Fennec chooses one monster. That monster's health will become 0.
There is no way other than Attack and... | R = lambda: map(int, input().split())
n, k = R()
print(sum(sorted(R())[:n - k]) if k < n else 0) |
You will be given a string S of length 3 representing the weather forecast for three days in the past.
The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. `S`, `C`, and `R` stand for sunny, cloudy, and rainy, respectively.
You will also be given a string T of length 3 representing the ... | #include<iostream>
using namespace std;
int ans;
char s[10],t[10];
int main()
{
cin>>s>>t;
for(int i=0;i<3;++i)
ans+=(s[i]==t[i]);
cout<<ans<<endl;
return 0;
} |
Note the unusual memory limit.
For a rectangular grid where each square is painted white or black, we define its complexity as follows:
* If all the squares are black or all the squares are white, the complexity is 0.
* Otherwise, divide the grid into two subgrids by a line parallel to one of the sides of the grid, a... | #include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
#define M 187
#define P 16
int mark[M][M];
int dp[M][M][P][M]; //y1 y2 x1
int cut[M][M][M];
int H, W;
int main() {
cin >> H >> W;
for (int i = 0; i < H; i++)
{
string S;
cin >> S;
for (int j = 0; j < W; j++)
... |
There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.) The state of each piece is represented by a string S of length N. If S_i=`B`, the i-th piece from the left is showing black; If S_i=`W`, the i-th piece from the left is showing white.
Consider performing the f... | #include<iostream>
#include<string>
using namespace std;
int main(){
string S;
long long cnt=0,sum=0;
cin >> S;
for(int i=0;i<S.size();i++){
if(S[i]=='B')cnt++;
else sum+=cnt;
}
cout << sum << endl;
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.