input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
The mayor of the Berland city S sees the beauty differently than other city-dwellers. In particular, he does not understand at all, how antique houses can be nice-looking. So the mayor wants to demolish all ancient buildings in the city.
The city S is going to host the football championship very soon. In order to make... | #include <bits/stdc++.h>
using namespace std;
const long long nn = 100005;
struct Building {
long long ren, dem;
inline bool operator<(const Building &x) const { return ren < x.ren; }
};
Building bui[nn];
priority_queue<long long, vector<long long>, greater<long long> > heap;
long long n, m, money[nn], ans;
long lo... |
Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.
At each step he selects... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 22;
int N, M, aim_state, min_steps, min_pset, edges[MAXN], vis[1 << MAXN];
void DFS(int state, int pset, int steps) {
if (steps >= min_steps) return;
if (vis[pset]) return;
vis[pset] = true;
if (state == aim_state) {
min_steps = steps;
min_p... |
There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.
More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to... | def count_unic_mess(crt, display, array, n, result_arr):
low_bound = 0 if crt - display < 0 else crt - display
high_bound = n if crt + display + 1 > n else crt + display + 1
result = high_bound - low_bound
if array[crt] == 0:
result_arr.append(result)
return result
ref = array[cr... |
Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.
Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water d... | #include <bits/stdc++.h>
using namespace std;
int n, m[100005], a[100005];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
m[i] = a[i] + 1;
}
long long ans = 0;
for (int i = n - 1; i >= 1; --i) m[i] = max(m[i], m[i + 1] - 1);
for (int i = 1; i <= n; ++i) m[i] = max(m... |
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.
Max is a young biologist. For n days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the dis... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 5;
struct p {
int x, id;
bool operator<(const p &a) const { return x < a.x; }
} a[MAX];
int n, ans, K;
int fa[MAX], siz[MAX], tot[MAX], b[MAX];
set<int> S;
int find(int x) {
if (fa[x] != x) fa[x] = find(fa[x]);
return fa[x];
}
int main() {
sc... |
Two sweet dogs, Bernard and Havanese, play the following game.
There are P sticks, each of exactly Q meters in length. The dogs move in turns. For each move a dog chooses a stick and splits it into two or more equal parts each having integer length greater than or equal to S meters. Each resulting part is also a stick.... | def divisors(n):
from math import sqrt
s = int(sqrt(n + 0.0))
for i in xrange(1, s + 1):
if n % i == 0:
yield i
yield (n / i)
def winning(p, q, s):
if p % 2 == 0:
return False
for d in divisors(q):
if d >= 2 and q / d >= s and not winning(d, q / d, s):
return True
return False
def main():
... |
Description
You are tasked to determine the kth term of the binomial expansion of the expression (x + y)^n.
Input Format
The input starts with an integer M > 0, followed by M pairs of integers k, n, where 1 ≤ k ≤ n+1 and 0 < n < 1000.
Output Format
For every pair of integers k, n, output the correct kth term of th... | import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
t = int(raw_input())
while t>0:
a = raw_input().split(' ')
a = [int(x) for x in a]
c = nCr(a[1],a[0]-1)
x = a[1]-a[0]+1
y = a[0]-1
if(c!=1):
print c,
if(x!=0):
print "x^%d"%x,
if(y==1):
print "y"
elif(y==0):
print ""... |
You have an n by m grid. Each grid square has a certain value associated with it. This is given by the numbers vi,j.
You can capture grid squares in two different ways.
You can directly capture a grid square. This costs ci,j.
You can indirectly capture a grid square. You can only do this if we have already captured a... | import sys
from collections import deque
from collections import OrderedDict as dict
INFINITE = 999999999999
global_edges = set()
def solve():
r, c = map(int, sys.stdin.readline().split())
val = []
indirect = []
direct = []
for array in [val, indirect, direct]:
for row in range(r):
... |
Daenerys Targaryen has set her eyes on The kingdom of Dorne. Dornishmen, known for their strong sense of national identity, have refused to surrender to the whims of Daenerys. Fearing the imminent attack on their kingdom and knowing their strength as Spearmen, they have devised a battle plan which they think will give ... | t = input();
for qq in range(t):
n = input();
ans = 0.0;
ans += ((5.0*n - 2) * (2.0*n - 1)) / (3.0 * n);
print '%.6f' % ans |
Quan_Lank loves awsome numbers. Awsome numbers are the positive integers whose decimal representations contain only the awsome digits 4 and 7. For example, numbers 7, 74, 4 are awsome and 5, 137, 4467 are not. Unfortunately, not all numbers are awsome. Quan_Lank calls a number nearly awsome if the number of awsome digi... | for i in range(int(raw_input())):
s=raw_input()
S=0
S=s.count("4")+s.count("7")
if str(S).count("4")+str(S).count("7")==len(str(S)):
print("YES")
else:
print("NO") |
Micro's friend Ravi gifted him a game called Array on his birthday. The game involves an array of distinct numbers of size N . The game follows 1-based indexing of array. Player has to perform Q operation on the array. The operation can be of following two types:
1. 0 x y : Update the xth element of array to y.
2. 1 v:... | import sys
'''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
array = []
class InvalidInput(Exception):
pass
def _read_operation(string):
splits = map(int, string.split())
code = splits[0]
if code == 0:
x, ... |
Today Oz wants to play with Lucky strings. A string S is called Lucky string if there exists a non-negative integer m such that S is composed of m consecutive 'R' characters followed by m consecutive 'K' characters. Empty string is also a Lucky string i.e for m=0
Now Oz has a string STR. Each character of STR is either... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
t = int(raw_input())
strings = []
for i in range(0,t):
strings.append(raw_input())
for i in range(len(strings)):
count = 0
start = 0
end = len(strings[i])
while(start < end)... |
Ravi is very tensed nowadays because of the design project. He has not even decided the topic yet. Micro feels very bad for Ravi, so to help Ravi take his mind off from design project for sometime he gave him a problem. He gave him two strings S and P. Now Ravi has to tell if S can be converted to P by deleting some ch... | try:
t = int(input())
for i in xrange(t):
s = list(raw_input())
p = list(raw_input())
i = 0
flag = 0
for j in s:
if(p[i] == j):
i += 1
if(i == len(p)):
flag = 1
break
if(flag == 1)... |
Tom is off to a school Annual Day and is searching for a matching pair of socks. His drawer is filled with socks, each pair of a different color. In its worst case scenario, how many socks (x) should Tom remove from his drawer until he finds a matching pair?
Input Format
The first line contains the number of test ca... | n = input()
while(n>0):
n-=1
k = input()
print k+1 |
You are enthusiastically participating in Virtual Boot Camp-14 and want to seriously learn programming. To be a good programmer you not only need to solve a problem, but also need to solve it as quickly as possible.
You are participating in this "Week02 Contest" and want to win it. You are sure that you will be able ... | s=raw_input()
d,h,m,w=s.split(' ')
d=int(d)
h=int(h)
m=int(m)
w=int(w)
print (d-1)*24*60+h*60+m+w*20 |
You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j). Some of the squares contain an object. All the remaining squares are empty. The state of the grid is represented by strings S_1,S_2,\cdots,S_N. The square (i,j) contains an object if S_{i,j}= `#` and is em... | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
struct edge {
int to, cap;
char flag; // 0: r -> l 1: u -> d
edge(): flag(-1) {}
edge(const int &t, const int &c, const char &f): to(t), cap(c), flag(f) {}
} ge[60000];
int n, m;
vector <int> gl[10010];
int depth[10010], q[10010];
int i... |
There is a game that involves three variables, denoted A, B, and C.
As the game progresses, there will be N events where you are asked to make a choice. Each of these choices is represented by a string s_i. If s_i is `AB`, you must add 1 to A or B then subtract 1 from the other; if s_i is `AC`, you must add 1 to A or ... | #from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
def ddprint(x):
if DBG:
print(x... |
Takahashi has come to a party as a special guest. There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.
Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0). A handshake will be performed as follows:
* Takahashi chooses o... | #include <bits/stdc++.h>
using namespace std;
int main(){
int64_t N, M;
cin >> N >> M;
vector<int64_t> A(N), S(N+1);
for(int i=0; i<N; i++) cin >> A[i];
sort(A.begin(), A.end());
for(int i=0; i<N; i++) S[i+1] = S[i] + A[i];
// ok : ok以上がM回以上
int64_t ok = 0, ng = 1e6;
while(ng-ok>1)... |
We have two distinct integers A and B.
Print the integer K such that |A - K| = |B - K|.
If such an integer does not exist, print `IMPOSSIBLE` instead.
Constraints
* All values in input are integers.
* 0 \leq A,\ B \leq 10^9
* A and B are distinct.
Input
Input is given from Standard Input in the following format:
... | #include<iostream>
using namespace std;
int main() {
int A, B; cin >> A >> B;
if ((A - B) % 2) cout << "IMPOSSIBLE" << endl;
else cout << (A + B) / 2 << endl;
} |
Let M be a positive integer.
You are given 2 N integers a_1, a_2, \ldots, a_{2 N}, where 0 \leq a_i < M for each i.
Consider dividing the 2 N integers into N pairs. Here, each integer must belong to exactly one pair.
We define the ugliness of a pair (x, y) as (x + y) \mod M. Let Z be the largest ugliness of the N pa... | #include <algorithm>
#include <cstdio>
int arr[200005];
int main()
{
// freopen("AGC032-E.in", "r", stdin);
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < n << 1; i++)
scanf("%d", arr + i);
std::sort(arr, arr + (n << 1));
int l = 0, r = n, res = -1;
while (l <= r)
{
int x = l + r >> 1;
bool flg = tr... |
When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.
You, the smartwatch, has found N routes to his home.
If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.
Find the smallest cost of a route that takes not l... | using namespace std;
#include<iostream>
int main(){
int n,tl,c,t,cm=1001;
cin>>n>>tl;
for(int i=0;i<n;i++){
cin>>c>>t;
if(c<cm && t<=tl)cm=c;
}
if(cm>1000)cout<<"TLE"<<endl;
else cout <<cm<<endl;
return 0;
}
|
You are given a string S consisting of `a`,`b` and `c`. Find the number of strings that can be possibly obtained by repeatedly performing the following operation zero or more times, modulo 998244353:
* Choose an integer i such that 1\leq i\leq |S|-1 and the i-th and (i+1)-th characters in S are different. Replace each... | #include <bits/stdc++.h>
#define dbg(x) cerr<<#x": "<<x<<"\n"
#define dbg_p(x) cerr<<#x": "<<x.first<<","<<x.second<<"\n"
#define dbg_v(x, n) do{cerr<<#x"[]: ";for(long long _=0;_<n;++_)cerr<<x[_]<<" ";cerr<<'\n';}while(0)
#define dbg_ok cerr<<"OK!\n"
#define st first
#define nd second
#define DMAX 200100
#define MO... |
You are given a grid with 2 rows and 3 columns of squares. The color of the square at the i-th row and j-th column is represented by the character C_{ij}.
Write a program that prints `YES` if this grid remains the same when rotated 180 degrees, and prints `NO` otherwise.
Constraints
* C_{i,j}(1 \leq i \leq 2, 1 \leq... | e=input()
f=input()
if e[::-1]==f:
print('YES')
else:
print('NO') |
Kenus, the organizer of International Euclidean Olympiad, is seeking a pair of two integers that requires many steps to find its greatest common divisor using the Euclidean algorithm.
You are given Q queries. The i-th query is represented as a pair of two integers X_i and Y_i, and asks you the following: among all pai... | #include <cstdio>
#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;
#define iter(i, n) for (int i = 1; i <= n; ++i)
const int mod = 1e9 + 7;
typedef long long i64;
typedef pair<i64, i64> pii;
#define fi first
#define se second
vector<pii> vec[100];
i64 f[100];
int F(i64 a, i64 b) {
i... |
On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t). He can move in arbitrary directions with speed 1. Here, we will consider him as a point without size.
There are N circular barriers deployed on the plane. The center and the radius of the i-th barrier are (x_i, y_i) and r_i, r... | #include <bits/stdc++.h>
using namespace std;
typedef double dbl;
struct vec { dbl x, y; };
vec operator-(vec v1, vec v2) { return { v1.x - v2.x, v1.y - v2.y }; }
dbl len(vec v) { return hypot(v.x, v.y); }
dbl dis(vec v1, vec v2) { return len(v2 - v1); }
struct cir { vec v; dbl r; };
const int N = 1002;
cir c[N];
db... |
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the `0` key, the `1` key and the backspace key.
To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this stri... | #include <bits/stdc++.h>
using namespace std;
int main(){
char c;
string s;
while(~scanf("%c",&c)){
if(c=='B'){
if(!s.empty())
s.pop_back();
}
else s+=c;
}
cout<<s<<endl;
return 0;
}
|
A calculator scholar has discovered a strange life form called an electronic fly that lives in electronic space. While observing the behavior of the electronic flies, the electronic flies at the (x, y, z) point in this space then move to (x', y', z') indicated by the following rules. I found out.
<image>
However, a1... | import fractions
def func(a,m):
x,n=1,1
x=(a*x)%m
while x!=1:
x=(a*x)%m
n+=1
return n
def lcm(a,b):
return a*b/fractions.gcd(a,b)
while True:
a1,m1,a2,m2,a3,m3=map(int,raw_input().split())
if a1==m1==a2==m2==a3==m3==0:break
x,y,z=func(a1,m1),func(a2,m2),func(a3,m3)
... |
There is a rectangular maze with square squares lined up vertically and horizontally. In this maze, while moving to the adjacent squares in the north, south, east and west, the starting square S departs and the goal square G is aimed at. There are three types of trout: plain, mountain, and ice. S and G are located in t... | #include <iostream>
#include <algorithm>
using namespace std;
#define rep(i,n) for(int i = 0 ; i < n ; i++)
char c[14][14];
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
int belong[14][14];
int ok[10000];
int gx,gy;
int ans = 0;
int ccc = 0;
void dfs(int x,int y,int C,int px,int py){
if( c[y][x] == '#' || c[y][x] ... |
I have a plan to go on a school trip at a school. I conducted a questionnaire survey for that purpose. Students have student numbers from 1 to n, and the locations of travel candidates are represented by numbers from 1 to m, and where they want to go ○ , Mark the places you don't want to go with a cross and submit.
At... | #include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
pair<int, int>x[8000000]; int n, m, s;
int main() {
while (true) {
for (int i = 0; i < 8000000; i++) { x[i].first = 1000000; }
cin >> n >> m;
if (!n) { break; }
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >... |
Dr. Nakamura is a great inventor, and he is still working on a new invention that ordinary people cannot think of. Now he is inventing a new security system and container.
The security system is a panel that identifies the person who rides on it and stuns it by passing an electric current if it is an uninvited guest. ... |
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
private void run() throws IOException {
Scanner scann... |
ICPC Ranking
Your mission in this problem is to write a program which, given the submission log of an ICPC (International Collegiate Programming Contest), determines team rankings.
The log is a sequence of records of program submission in the order of submission. A record has four fields: elapsed time, team number, p... | import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(true){
int M = sc.nextInt();
int T = sc.nextInt();
... |
Recent improvements in information and communication technology have made it possible to provide municipal service to a wider area more quickly and with less costs. Stimulated by this, and probably for saving their not sufficient funds, mayors of many cities started to discuss on mergers of their cities.
There are, of... | #include <bits/stdc++.h>
using namespace std;
using vi=vector<int>;
using vvi=vector<vi>;
#define rep(i,n) for(int i=0;i<n;i++)
#define all(a) a.begin(),a.end()
#define INF 10000
int main(){
int n;
while(cin>>n,n){
vector<string> s(n);
set<string> s_set;
for(auto&i:s)cin>>i;
rep(i,n){
bool ok=true;
rep... |
Problem
Multiple rooted trees are given as the initial state. Alice and Bob, on the other hand, play the game. The game is played alternately by two players, with Alice on the play and Bob on the play. The player whose turn has turned takes the following actions.
1. Select one root (vertex that has no parent). Let th... | #include <bits/stdc++.h>
#define MOD 1000000007LL
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
int n,m;
vector<int> G[1005];
vector<int> rG[1005];
bool used[1005];
int gr[1005];
int cnt[10000];
void dfs2(int v,int g){
int su=0;
for(int i=0;i<G[v].size();i++){
su^=gr[G[v][i]];
}
cnt[g^su]+... |
There was an explorer Henry Nelson traveling all over the world. One day he reached an ancient building. He decided to enter this building for his interest, but its entrance seemed to be locked by a strange security system.
There were some black and white panels placed on a line at equal intervals in front of the entr... | #include <iostream>
#include <iomanip>
#include <vector>
#include <bitset>
#include <string>
#include <map>
#include <queue>
#include <functional>
#include <assert.h>
using namespace std;
inline int pack(int p, int ps, int n) {
return (p << n) | ps;
}
int main(int argc, char *argv[])
{
for(;;) {
int n;
cin ... |
Mike Smith is a man exploring caves all over the world.
One day, he faced a scaring creature blocking his way. He got scared, but in short time he took his knife and then slashed it to attempt to kill it. Then they were split into parts, which soon died out but the largest one. He slashed the creature a couple of time... | #include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <ctime>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <deque>
#include <complex>
#include <string>
#include <iomanip>... |
Problem statement
Real variables $ x_1, x_2, ..., x_N $ satisfy the following conditions.
1. $ 0 \ leq x_i \ leq 1 $ ($ 1 \ leq i \ leq N $)
2. $ w_1x_1 + w_2x_2 + ... + w_Nx_N \ leq W $
At this time, find the maximum value that $ v_1x_1 + v_2x_2 + ... + v_Nx_N $ can take. It is known that such a maximum actually ... | #include<stdio.h>
#include<algorithm>
using namespace std;
pair<double,pair<int,int> > p[110000];
pair<double,pair<int,int> > q[110000];
int main(){
int a,b;
scanf("%d%d",&a,&b);
int sz=0;
int s2=0;
double val=0;
for(int i=0;i<a;i++){
int w,v;
scanf("%d%d",&w,&v);
if(v>=0&&w<=0){
val+=v;
b-=w;
}else... |
Problem Statement
Mr. Takatsuki, who is planning to participate in the Aizu training camp, is enthusiastic about studying and has been studying English recently. She tries to learn as many English words as possible by playing the following games on her mobile phone. The mobile phone she has is a touch panel type that ... | #include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<complex>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<utility>
usi... |
Example
Input
R?????,2?)
Output
29 | #include <iostream>
#include <cstdio>
#include <string>
using namespace std;
// s の方が大きいときに true
string max_s(const string &s, const string &t) {
if(s.length() != t.length()) return (s.length() > t.length() ? s : t);
else return (s > t ? s : t);
}
string min_s(const string &s, const string &t) {
if(s.leng... |
C: Imagawayaki Man-Imagawayaki Man-
story
Imagawayaki Man is a hero of justice. The face is Imagawayaki with a diameter of 1 meter (mainly a food made by filling a dough made of wheat flour with a generous amount of bean paste, and it looks round and delicious. In Hokkaido, it is simply called "yaki". In addition to ... | #include<bits/stdc++.h>
using namespace std;
template<class T = int> using V = vector<T>;
int main() {
int n; cin >> n;
if (n == 1) {
cout << "! 1" << endl;
return 0;
}
int mx = -1, mi = -1;
for (int i = 2; i <= n; ++i) {
cout << "? 1 " << i << endl;
int x; cin >> x;... |
E: Jam
problem
There are N cities in a country, numbered 1, \ 2, \ ..., \ N. These cities are connected in both directions by M roads, and the i-th road allows you to travel between the cities u_i and v_i in time t_i. Also, any two cities can be reached by using several roads.
Bread is sold in each town, and the del... | #include <bits/stdc++.h>
#pragma GCC Optimize("Ofast")
using namespace std;
#define int long long
#define impl(x, last) x == last ? 0 : 63 - __builtin_clz(x ^ last)
struct RadixHeap {
int last, size_;
vector<tuple<int, int, bool>> bucket_[64];
RadixHeap() : last(0), size_(0){}
void emplace(int x, int ... |
Oranges on Cans
square1001 You put a $ N $ can of aluminum on the table.
E869120 You put $ M $ of oranges on each aluminum can on the table.
How many oranges are on the aluminum can?
input
Input is given from standard input in the following format.
$ N $ $ M $
output
Output the number of oranges on the alumin... | #include "bits/stdc++.h"
using namespace std;
using i64 = long long;
const i64 MOD = 1e9+7;
const i64 INF = 1e18+7;
template <typename T = i64>
bool chmax(T& a, T b){
if(a < b){
a = b;
return true;
}
return false;
}
template <typename T = i64>
bool chmin(T& a, T b){
if(a > b){
... |
Write a program which manipulates a sequence $A$ = {$a_0, a_1, ..., a_{n-1}$} with the following operations:
* $add(s, t, x)$ : add $x$ to $a_s, a_{s+1}, ..., a_t$.
* $find(s, t)$ : report the minimum value in $a_s, a_{s+1}, ..., a_t$.
Note that the initial values of $a_i ( i = 0, 1, ..., n-1 )$ are 0.
Constraints... | #include "bits/stdc++.h"
using namespace std;
using ll = long long;
#define rep(i,n) for (int i=0;i<(n);i++)
#define rep2(i,a,b) for (int i=(a);i<(b);i++)
template<class T, class E>
struct SegTree{
typedef function<T(T,T)> F;
typedef function<T(T,E)> G;
typedef function<E(E,E)> H;
typedef function<E(E,int)> P;... |
Suraj, the Chief Prankster is back in action now and this time he has stolen the valentine's day gift given by Ashi (the love of Chef) to the Chef and ran away with it to Byteland.
Byteland is a not a regular place like Chef's town. The safest way from Chef's town to Byteland is through the path of tasty dishes. The pa... | arr = []
def check(ppl):
for i in range(0,len(arr)):
if(arr[i][2]==-1):#magic dish
ppl -= arr[i][1]
elif(ppl>=arr[i][1]):#clan - applicable
ppl += arr[i][2]
return ppl
def binary_search(low,high):
while True:
#print low,high
if(low+1==high):
break
if (low==high):
return low
mid = (low+high... |
After a long and successful day of preparing food for the banquet, it is time to clean up. There is a list of n jobs to do before the kitchen can be closed for the night. These jobs are indexed from 1 to n.
Most of the cooks have already left and only the Chef and his assistant are left to clean up. Thankfully, some ... | t=int(raw_input())
for i in range(0,t):
lis=map(int,raw_input().split())
lis1=map(int,raw_input().split())
l=[]
for j in range(0,lis[0]):
l.append(j+1)
l=set(l)
lis1=set(lis1)
m=list(set(l)-set(lis1))
m.sort()
if len(m)==0:
print
print
elif len(m)==1:
print m[0]
print
else:
for j in range(0,len(m... |
Write a program to find the remainder when two given numbers are divided.
Input
The first line contains an integer T, total number of test cases. Then follow T lines, each line contains two Integers A and B.
Output
Find remainder when A is divided by B.
Constraints
1 ≤ T ≤ 1000
1 ≤ A,B ≤ 10000
Example
Input
3... | from sys import stdin, stdout
t=int(input())
for i in range(t):
A,B = map( int, stdin.readline().rstrip().split() )
c=A%B
print(c) |
Little Elephant from the Zoo of Lviv likes cards. He has N cards, each of which has one of 1000 colors. The colors are numbered from 1 to 1000.
Little Elephant and Big Hippo are playing the following game. At first Little Elephant takes some subset of cards, and Big Hippo takes the rest of them. Here, Little Elephant c... | '''
Created on Feb 22, 2013
@author: anuvrat
'''
import sys
MODULATOR = 1000000007
class Memoize( object ):
def __init__( self, f ):
self.f, self.cache = f, {}
def __call__( self, *args ):
if not args in self.cache: self.cache[args] = self.f( *args )
return self.cache[args]
@Memoiz... |
In this problem, you will be given a polynomial, you have to print what it becomes after differentiation.
Following are the rules for differentiation:
For a polynomial f(x), its differentiation is defined as f'(x).
If a is a constant, then differentiation of af(x) is af'(x).
If f(x) = h(x) + g(x) , then f'(x) = h'(x... | # your code goes here
from sys import stdin, stdout
t = int(stdin.readline())
while t:
t -= 1
n = int(stdin.readline())
d = []
for _ in xrange(n):
a, p = map(int, stdin.readline().strip().split(' '))
d.append([p,a])
if n>1 and p == 0:
d.pop()
n -= 1
ans = ""
for i in range(len(d)):
if i < n-1:
if... |
Given an array A1,A2...AN, you have to print the size of the largest contiguous subarray such that
GCD of all integers in that subarray is 1.
Formally, For a subarray Ai,Ai+1...Aj where 1 ≤ i < j ≤ N to be valid: GCD(Ai,Ai+1...Aj) should be 1. You have to print the size of the largest valid subarray.
If no valid subarr... | """
http://www.codechef.com/COOK50/problems/SUBGCD
"""
from fractions import gcd
def GCD(L) :
"""GCD of list L. length of list L is at least 2."""
ans = L[0]
for i in xrange(1,len(L)) :
ans = gcd(ans,L[i])
if ans == 1 : break
return ans
T = int(raw_input())
for _ in xrange(T) :
N = int(raw_input())
A = map(... |
Alice and Bob are playing chess on a huge chessboard with dimensions n × n. Alice has a single piece left — a queen, located at (a_x, a_y), while Bob has only the king standing at (b_x, b_y). Alice thinks that as her queen is dominating the chessboard, victory is hers.
But Bob has made a devious plan to seize the vic... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream... |
You are given a connected undirected graph without cycles (that is, a tree) of n vertices, moreover, there is a non-negative integer written on every edge.
Consider all pairs of vertices (v, u) (that is, there are exactly n^2 such pairs) and for each pair calculate the bitwise exclusive or (xor) of all integers on edg... | #include <bits/stdc++.h>
using namespace std;
long long int x[1000000];
struct inter {
int l1, r1, l2, r2;
};
vector<inter> vv, vv2;
int main() {
int i;
int n, p;
long long int kk, w;
scanf("%d %I64d", &n, &kk);
for (i = 1; i < n; i++) scanf("%d %I64d", &p, &w), x[i] = x[p - 1] ^ w;
sort(x, x + n);
int ... |
The only difference between easy and hard versions is the constraints.
Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of n consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the i-th p... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 5e3 + 70;
const int INF = 2.1e9;
const long long inf = 1e18;
const int MOD = 1e9 + 7;
int n, m, k, x;
int a[maxn];
long long dp[maxn][maxn];
int Q[maxn], front, tail;
long long solve() {
for (int i = 1; i <= n; i++) dp[i][1] = (i > k ? -inf : a[i]);
for... |
The length of the longest common prefix of two strings s=s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum k ≤ min(n, m) such that s_1 s_2 … s_k equals t_1 t_2 … t_k. Let's denote the longest common prefix of two strings s and t as lcp(s,t).
Z-function of a string s_1 s_2 ... s_n is a sequence of integers ... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, q, i, l[N], r[N], s1[N];
long long s2[N];
template <typename T>
struct BIT {
T bi[N];
inline void add(int x, int v) {
for (; x <= n; x += x & -x) bi[x] += v;
}
inline T ask(int x) {
T ans = 0;
for (; x; x -= x & -x) ans += b... |
Recently Evlampy installed one interesting computer game, one of aspects of which is to split army into several groups and then fight with enemy's groups. Let us consider a simplified version of the battle.
In the nearest battle Evlampy should fight an enemy army that consists of m groups, the i-th of which has hp_i h... | #include <bits/stdc++.h>
using std::sort;
const int MAXM = 1000011;
int N, M;
int A[MAXM];
int T;
int L[MAXM];
int C[MAXM];
int Aim[MAXM];
struct Pair {
int *p, v;
Pair() {}
Pair(int *_p, int _v) {
p = _p;
v = _v;
}
} P[MAXM];
inline bool operator<(const Pair &A, const Pair &B) { return A.v < B.v; }
voi... |
A frog is initially at position 0 on the number line. The frog has two positive integers a and b. From a position k, it can either jump to position k+a or k-b.
Let f(x) be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval [0, x]. The frog doesn't need to visit all ... | import java.io.*;
import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class P1146D {
public static void main(String[] args) {
SimpleScanner scanner = new SimpleScanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
int m = sc... |
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
int d = 0;
while (n--) {
char e;
cin >> e;
if (e == '(') {
cout << d % 2;
d++;
} else {
d--;
cout << d % 2;
}
}
cout << end... |
The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is... | //package cf568d2;
import java.util.*;
public class G {
static int n,t;
static int[]a;
static int[]g;
static long[][][]dp;
static final long MOD=1000000007;
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
t=sc.nextInt();
a... |
The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary str... | pp = input()
if len(pp) == 1:
print('0')
exit(0)
z = 1 if pp[0]=='0' else 0
zc = [z]
l = 1
lndl = [l]
for p in pp[1:]:
l = max(z + 1, l + (1 if p == '1' else 0))
z += 1 if p == '0' else 0
lndl.append(l)
zc.append(z)
lnda = lndl[-1]
o = 1 if pp[-1]=='1' else 0
oc = [o]
l = 1
lndr = [l]
for p in r... |
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.
So the team is considered perfect if it includ... | q = int(input())
for i in range(q):
k = 0
c, m, x = [int(s) for s in input().split()]
if min(c, m, x) != x:
print(min(c, m))
else:
k += x
z = (c + m - 2 * x) // 3
print(k + min(z, c - x, m - x))
|
There is a string s of lowercase English letters. A cursor is positioned on one of the characters. The cursor can be moved with the following operation: choose a letter c and a direction (left or right). The cursor is then moved to the closest occurence of c in the chosen direction. If there is no letter c in that dire... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void debug_out(T t) {
cerr << t;
}
template <typename A, typename B>
void debug_out(pair<A, B> u) {
cerr << "(" << u.first << " " << u.second << ")";
}
template <typename T>
void debug_out(vector<T> t) {
int sz = t.size();
for (int i = 0; i < s... |
There are n people in this world, conveniently numbered 1 through n. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let d(a,b) deno... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll n, m;
cin >> n >> m;
vector<vector<ll>> d(n);
vector<ll> debt(n);
for (int i = 0; i < m; i++) {
ll u, v, c;
cin >> u >> v >> c;
u--;
v-... |
This problem is different with easy version only by constraints on total answers length
It is an interactive problem
Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask tw... | #include <bits/stdc++.h>
inline long long read() {
long long x = 0, f = 1;
char c = getchar();
for (; c > '9' || c < '0'; c = getchar()) {
if (c == '-') f = -1;
}
for (; c >= '0' && c <= '9'; c = getchar()) {
x = x * 10 + c - '0';
}
return x * f;
}
int cnt[27][105];
char s[105], s1[105];
std::stri... |
Bessie is planning a vacation! In Cow-lifornia, there are n cities, with n-1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city.
Bessie is considering v possible vacation plans, with the i-th one consisting of a start city a_i and destination city b_i.
It is known t... | #include <bits/stdc++.h>
using namespace std;
const int N = 4e5 + 69, L = 20;
int n, k, r, qu, t, dist[N], dep[N], lift[N][L];
vector<int> adj[N];
int par[N], sz[N];
int find(int v) { return (v == par[v] ? v : par[v] = find(par[v])); }
bool merge(int u, int v) {
if ((u = find(u)) == (v = find(v))) return 0;
if (sz[... |
There was once young lass called Mary,
Whose jokes were occasionally scary.
On this April's Fool
Fixed limerick rules
Allowed her to trip the unwary.
Can she fill all the lines
To work at all times?
On juggling the words
Right around two-thirds
Sh... | n = int(input())
res = ''
while n != 1:
for i in range(2,n+1):
if n % i == 0:
res += str(i)
n //= i
break
print(res) |
Note that the only differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if all versions are solved.
Slime is interested in sequences. He defined good positive integer sequences p of length n as follows:
* For each k>1 that presents in p, there should be at ... | #include <bits/stdc++.h>
using namespace std;
inline bool cmin(int &x, int y) { return x > y ? x = y, 1 : 0; }
inline bool cmax(int &x, int y) { return x < y ? x = y, 1 : 0; }
const int _ = 5055, mod = 998244353;
int N, fac[_], inv[_];
int f[_][_];
int ans[_];
inline int dec(int x) { return x >= mod ? x - mod : x; }
in... |
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week.
Alice is going to paint some n... | import sys;
import math;
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_string(): return sys.stdin.readline().strip()
t = int(input());
for test in range(t):
n,k = get_ints();
ans=0;
if(n<=k):
... |
This is an easier version of the problem E with smaller constraints.
Twilight Sparkle has received a new task from Princess Celestia. This time she asked to decipher the ancient scroll containing important knowledge of pony origin.
To hide the crucial information from evil eyes, pony elders cast a spell on the scroll... | #include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 5, P = 131, mod = 1e9 + 7;
vector<int> vec, rk[N], dp[N];
vector<unsigned long long> hs[N];
int n, len[N], nxt[N * 10];
char s[N * 10];
unsigned long long bin[N * 10];
inline unsigned long long getHash(int x, int at, int l) {
if (at > l) return hs[x... |
Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates.
Let's define a total cleanup as the following process. The goal of this process is to collect all the pile... | #include <bits/stdc++.h>
using namespace std;
const long double pi = 3.141592653589793238462643383279502884;
const long long xd[] = {-1, 0, 1, 0};
const long long yd[] = {0, -1, 0, 1};
long long XX[] = {-1, -1, -1, 0, 0, 1, 1, 1};
long long YY[] = {-1, 0, 1, -1, 1, -1, 0, 1};
long long expo(long long a, long long b, lo... |
Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode o... | f, t = -1, 0
INT = 10 ** 9 + 7
def mult(a, b):
ans = 1
for i in range(b):
ans *= a - i
ans %= INT
return ans
def fact(a):
ans = 1
for i in range(a):
ans *= i + 1
ans %= INT
return ans
L = []
def BinarySearch(num, pos):
global f, t
a = [i for i in range(num)]
left = 0
right = num
while left < right:
... |
One fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length n to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules:
* the string may only contain characters 'a', 'b', or 'c... |
import java.util.Scanner;
public class StringGeneration {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tc = 0; tc < t; tc++) {
int n = sc.nextInt();
int l = sc.nextInt();
int m = n / 3;
... |
You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with intege... | def f(n,houses):
xs=[x for (x,y) in houses]
ys=[y for (x,y) in houses]
xs.sort(); ys.sort()
width =(1 if n%2 else xs[n/2]-xs[n/2-1]+1)
height=(1 if n%2 else ys[n/2]-ys[n/2-1]+1)
return width*height
for t in xrange(int(raw_input())):
n=int(raw_input())
houses=[tuple(map(int,raw_input().split())) for i in xrange... |
You are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has d buttons with digits from 0 to d - 1. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a "RESET" button — pressi... | #include<bits/stdc++.h>
using namespace std;
const long long inf=1000000000000000000ll;
int q[2000200],l,r,cnt,n,d,x,hd[2200],la[2200],f[2200],lo[2200];
struct node{int to,next,c,val;}e[2000010];
char s[1100];
bool inq[2200];
long long dis[2200];
vector<int> pa;
void add(int x,int y,int c,int val)
{
e[++cnt]=(node){... |
Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. O... | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
//#include <sstream>
#include <vector>
#include <set>
#include <string>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
#include <iomanip>
#include <cstring>
#include <stdio.h>
#include <cassert>
using namespace std;
void s... |
Anton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end.
The conveyor is a looped belt with a total length of 2l meters, of which l meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any moment (... | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class C {
private static void solve() throws IOException {
int n = nextInt();
int length = nextInt();
int v1 = nextInt(), v2 = nextInt();
int[] candy = new int[n];
for (int i = 0; i < n; i++) {
candy[i] = nextInt();
}
Rationa... |
You are going to work in Codeforces as an intern in a team of n engineers, numbered 1 through n. You want to give each engineer a souvenir: a T-shirt from your country (T-shirts are highly desirable in Codeforces). Unfortunately you don't know the size of the T-shirt each engineer fits in. There are m different sizes, ... | #include <bits/stdc++.h>
using namespace std;
const int N = 3100, M = 310;
int n, m;
double f[M][N], tmp[N], delt[M], p[N][M], ans;
void upd(int x) {
for (int j = 0; j <= n; ++j) tmp[j] = f[x][j], f[x][j] = 0;
for (int j = 1; j <= n; ++j)
f[x][j] = tmp[j - 1] * p[j][x] + f[x][j - 1] * (1 - p[j][x]);
delt[x] -... |
The Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows.
Initially, the ... | #include <bits/stdc++.h>
using namespace std;
const int SIZE = 1 << 19;
const int LOGS = 19;
int n;
int arr[SIZE];
pair<int, int> rmq[2 * SIZE];
int nxt[LOGS + 1][SIZE];
pair<int, int> RMQMin(int left, int right) {
left += SIZE - 1;
right += SIZE - 1;
pair<int, int> res = min(rmq[left], rmq[right]);
if (left ==... |
Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with n vertices, chooses some m edges and keeps them. Bob gets the <image> remaining edges.
Alice and Bob are fond of "triangles" in graphs, that i... | #include <bits/stdc++.h>
using namespace std;
long long deg[1000011];
signed main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n, m;
cin >> n >> m;
long long ans = n * (n - 1) * (n - 2) / 6;
for (long long i = 0; i < n; i++) deg[i]++;
while (m--) {
long long u, v;
ci... |
There are n people, sitting in a line at the table. For each person we know that he always tells either the truth or lies.
Little Serge asked them: how many of you always tell the truth? Each of the people at the table knows everything (who is an honest person and who is a liar) about all the people at the table. The ... | //package round156;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class D2 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int[][] ret = new ... |
It is well known that Berland has n cities, which form the Silver ring — cities i and i + 1 (1 ≤ i < n) are connected by a road, as well as the cities n and 1. The goverment have decided to build m new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve whi... | #include <bits/stdc++.h>
using namespace std;
struct Edge {
int a, b;
} edges[101];
vector<int> adj[101];
int n, m, a, b;
bool res = true;
short int mark[101] = {0};
void DFS(int node) {
int size = adj[node].size();
if (mark[node] == 0) mark[node] = 1;
for (__typeof(size) i = 0; i < size; i++) {
if (!res) r... |
Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.
Yaroslav is now wondering: what maximum sum of array elements c... | n = int(input())
a = list(map(int, input().split()))
c = list(map(abs, a))
if len(list(filter(lambda x: x < 0, a))) & 1 and n + 1 & 1:
print(sum(c) - 2 * min(c))
else:
print(sum(c))
# Made By Mostafa_Khaled |
Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming ... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline T sqr(T x) {
return x * x;
}
const double EPS = 1e-6;
const int INF = 0x3fffffff;
const long long LINF = INF * 1ll * INF;
const double PI = acos(-1.0);
using namespace std;
char ans[101][101];
int main(void) {
int n, x;
scanf("%d %d", &n, &x)... |
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each obje... | #include <bits/stdc++.h>
const int maxn = 1e5 + 9;
using namespace std;
int n, a[maxn], pre[maxn], cnt[maxn], res = -1, c, j, ans[maxn];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= n; i++) {
scanf("%d", &pre[i]);
if (pre[i]) cnt[pre[i]]++;
}
for ... |
Inna and Dima bought a table of size n × m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A".
Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows:
1. initially, Inna chooses some cell of the tabl... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class InnaAndDima {
static int[] dr = { 0, 0, -1, 1 };
static int[] dc = { -1, 1, 0, 0 };
static char[] map = new char[256];
static {
map['D'] = 'I';
map['I'] = 'M';
map['M... |
Of course, many of you can calculate φ(n) — the number of positive integers that are less than or equal to n, that are coprime with n. But what if we need to calculate φ(φ(...φ(n))), where function φ is taken k times and n is given in the canonical decomposition into prime factors?
You are given n and k, calculate th... | #include <bits/stdc++.h>
using namespace std;
const long long INF = (long long)9e18 + 7LL;
struct event {
long long sta, dur, per;
event() {
sta = 0;
dur = 0;
per = 0;
}
event(long long s, long long d, long long p) {
sta = s;
dur = d;
per = p;
}
long long value(void) const {
asse... |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | #41A
print("YES" if input()==input()[::-1] else "NO") |
DZY loves Fast Fourier Transformation, and he enjoys using it.
Fast Fourier Transformation is an algorithm used to calculate convolution. Specifically, if a, b and c are sequences with length n, which are indexed from 0 to n - 1, and
<image>
We can calculate c fast using Fast Fourier Transformation.
DZY made a litt... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1E-9;
const double Exp = 2.718281828459045;
const double Pi = 3.1415926535897932;
const int Max_Bit = 63;
const int INF = 2000000000;
const long long LINF = 1000000000000000007ll;
const int MOD = 1000000007;
const int NMAX = 100005;
const int MMAX = 505;
... |
After you have read all the problems, probably, you think Alex is genius person. That's true! One day he came up with the following task.
Given a sequence of integer numbers a1, a2, ..., an. You are to find a longest sequence b1, b2, ..., b4m, that satisfies the following conditions:
* b4k + 1 = b4k + 3 for all val... | #include <bits/stdc++.h>
using namespace std;
int a[500005];
map<int, int> pre;
map<int, int> num;
vector<int> ans;
stack<int> st;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
while (cin >> n) {
for (int i = 1; i <= n; i++) {
cin >> a[i];
num[a[i]] = 0;
}
for (int k ... |
According to the legends the king of Berland Berl I was noted for his love of beauty and order. One day he ordered to tile the palace hall's floor where balls and receptions used to take place with black and white tiles according to a regular geometrical pattern invented by him. However, as is after the case, due to lo... | #include <bits/stdc++.h>
using namespace std;
inline void read(int &x) {
char c;
int f = 1;
while (!isdigit(c = getchar()))
if (c == '-') f = -1;
x = (c & 15);
while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + (c & 15);
x *= f;
}
int n, m, i, j, a, b, c, s[105][105], le[105][105], up[105][105];
c... |
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
In... | #include <bits/stdc++.h>
using namespace std;
const int N = 105;
int n, K, p[N];
double odp[N][N], dp[N][N];
int calc(int x) { return x * (x + 1) / 2; }
int main() {
scanf("%d%d", &n, &K), K = min(K, 1000);
const int tot = n * (n + 1) / 2;
for (int i = (1); i <= (n); ++i) scanf("%d", &p[i]);
for (int i = (1); i... |
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | n=int(input())
s=input()
s=list(s)
s1=input()
s1=list(s1)
c=0
for i in range(n):
if abs(int(s[i])-int(s1[i]))>5:
c+=10-abs(int(s[i])-int(s1[i]))
else:
c+=abs(int(s[i])-int(s1[i]))
print(c)
|
Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.
A set ρ of pairs (a, b) of elements ... | #include <bits/stdc++.h>
using namespace std;
long long int choose[4001][4001];
long long int f[4001], g[4001];
int main() {
int n;
cin >> n;
for (int i = 0; i < (int)4001; ++i) choose[i][i] = choose[i][0] = 1;
for (int i = 0; i < (int)n + 1; ++i)
if (i)
for (int j = 0; j < (int)i; ++j)
if (j)... |
Today Berland holds a lottery with a prize — a huge sum of money! There are k persons, who attend the lottery. Each of them will receive a unique integer from 1 to k.
The organizers bought n balls to organize the lottery, each of them is painted some color, the colors are numbered from 1 to k. A ball of color c corresp... | n,m=raw_input().split()
n=int(n);m=int(m)
a=[int(i) for i in raw_input().split()]
div = n/m
res=0
s=set(a)
for i in s:
if (a.count(i) > div):
res+=a.count(i)-div
print res |
The year 2015 is almost over.
Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.
Limak... | a ,b = map(int,raw_input().split())
s=bin(a)[2:]
s1 = bin(b)[2:]
i=0
for x in xrange(len(s)):
if s[x]=="0":
ss="1"*x+"0"+"1"*(len(s)-x-1)
i=x
break
if i==0:
i=1
ss="10"+"1"*(len(s)-1)
c=int(ss,2)
if c<=b and c>=a:
count=0
while c<=b and c>=a:
count+=1
... |
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of co... | #include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 5;
const int nax = 1e6 + 5;
int main() {
double a, b, c;
scanf("%lf%lf%lf", &a, &b, &c);
printf("%.18lf\n", a * a * a * sqrt(2) / 12 + b * b * b / 3 / sqrt(2) +
c * c * c * 0.301502832395831588);
return 0;
}
|
The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class P4 {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader... |
Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:
<image>
Where <image> represents logical OR and <image> represents logical exclusive OR (XOR), and vi,... | import java.io.*;
import java.util.*;
public class C {
static final int P = 1_000_000_007;
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
static class Edge {
int from, to;
int signFrom, signTo, id;
public Edge(int signFrom, int signTo, int id) {
this.signFrom = signFrom;
thi... |
Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the fou... | "use strict";
/*
var write = console.log.bind();
var k = 0;
var readline = function() {
switch ( k++ ) {
case 0: return '4 4'
case 1: return '0 0 0 0'
case 2: return '1 0 0 1'
case 3: return '0 1 1 0'
case 4: return '0 1 0 0'
}
};
*/
let input = readline().split(' ').map(e => +e);
let n = input[0],
m = ... |
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions o... | n=int(input())
s=input()
t=[]
d=r=0
for i in s:
t.append(i)
while len(t)!=1:
for i in range(len(t)):
if t[i]=="R" and d==0:
r+=1
elif t[i]=="D" and r==0:
d+=1
elif t[i]=="R" and d!=0:
d-=1
t[i]=0
else:
r-=1
t... |
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.
You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.
Find the maximum value ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 100;
struct Point {
double x, y;
Point(double _x = 0, double _y = 0) {
x = _x;
y = _y;
}
} point[maxn];
Point operator-(const Point &a, const Point &b) {
return Point(a.x - b.x, a.y - b.y);
}
Point operator+(const Point &a, const Point... |
You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.
Subsequence is a sequence that can be derived from another sequence by deletin... | n = int(raw_input())
l = map(int, raw_input().split())
s = reduce(lambda x,y: x + y, filter(lambda x: x > 0, l), 0)
print s if s%2 == 1 else s - min(map(abs, filter(lambda x: x%2==1, l)))
|
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.
For example, the imbalance value of arra... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
const int MAXN = 1e6 + 10;
pair<int, int> st1[21][MAXN];
int query_min(int l, int r) {
int k = 32 - __builtin_clz(r - l + 1) - 1;
return min(st1[k][l], st1[k][r - (1 << k) + 1]).second;
}
int query_max(int l, int r) {
int k = 32 - __built... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.