input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
In this problem you will have to deal with a very special network.
The network consists of two parts: part A and part B. Each part consists of n vertices; i-th vertex of part A is denoted as Ai, and i-th vertex of part B is denoted as Bi.
For each index i (1 β€ i < n) there is a directed edge from vertex Ai to vertex ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 200020;
int n, m, q;
long long A[maxn], B[maxn], C[maxn];
struct edge {
int a, b;
long long w;
bool operator<(const edge &x) const { return a < x.a; }
} e[maxn];
long long tr[maxn << 2], lz[maxn << 2];
void push_up(int o) { tr[o] = min(tr[o << 1], tr[... |
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.
Determine the number m β the smallest number of points you should add on the line to make the distances between all neighboring points equal.
Input
The first line contains a single integer n (3... | import math
n = int(input())
a = list(map(int, input().split()))
a.sort()
g = 0
for i in range(n - 1):
g = math.gcd(g, a[i + 1] - a[i])
print((a[-1] - a[0]) // g - n + 1) |
Suppose you have two strings s and t, and their length is equal. You may perform the following operation any number of times: choose two different characters c1 and c2, and replace every occurence of c1 in both strings with c2. Let's denote the distance between strings s and t as the minimum number of operations requir... | #include <bits/stdc++.h>
using namespace std;
const int N = 1.25e5 + 10, md = 998244353, G = 3;
char s[N], t[N];
int n, m;
vector<int> rev;
vector<int> w[25];
int c[6][6][N];
int fa[6];
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void merge(int x, int y) {
x = find(x), y = find(y);
if (x == y) ... |
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.
In order to avoid this representatives of both companies decided to make an agreement on the ... | #include <bits/stdc++.h>
using namespace std;
long long n, m, a, b, x, y, res;
map<long long, long long> mp1, mp2;
set<long long> st;
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (long long i = 0; i < n; i++) {
cin >> a >> x;
mp1[a] = x;
st.insert(a);
... |
Problem Statement:
Dom and Brian were trying to evade the truck drivers of Verone's gang. They were too fast, too furious for them, and could get away from the truck drivers easily. They decided to race with each other, and divided the city into N checkpoints for the same. Mia was monitoring Dom and Brian throughout t... | n=input(); D=map(int,raw_input().split()); B=map(int,raw_input().split()); val,val2=0,0;
for i in xrange(n-1):
val=max(val,abs(D[i+1]-D[i]))
for i in xrange(n-1):
val2=max(val2,abs(B[i+1]-B[i]))
if val==val2: print "Tie"; print val;
elif val>val2: print "Dom"; print val;
else: print "Brian"; print val2; |
Mr. Bhulla, now a member of the Mafia, is ordered by his capo Captain Cold to buy guns, ammunition and masks for the organization. Captain Cold is used to playing games with his men and so gives Bhulla some rules regarding the purchase. He says:
There are N different factories in the market of illegal guns and ammo. ... | for t in range(input()):
n = input()
a = [ [] for i in range(n) ]
for i in range(n):
a[i] = map( int, raw_input().split() )
for i in range(1,n):
a[i][0] += min( a[i-1][1], a[i-1][2] )
a[i][1] += min( a[i-1][2], a[i-1][0] )
a[i][2] += min( a[i-1][0], a[i-1][1] )
print min(a[-1]) |
You have been given 3 integers l, r and k. Find how many numbers between l and r (both inclusive) are divisible by k. You do not need to print these numbers, you just have to find their count.
Input Format
The first and only line of input contains 3 space separated integers l, r and k.
Output Format
Print the requ... | s = raw_input()
l,r,k = s.split()
l = int(l)
r = int(r)
k = int(k)
count = 0
for i in range(l,r+1):
if(i%k==0):
count = count +1
print count |
Given a string S made of letters a, b and c, find the number of sub strings that do not contain all the letters a, b and c. That is the number of sub strings that do not contain at least one of the letters a or b or c.
Note that the sub string should contain atleast one letter, that is it should not be empty string.
... | t=int(raw_input())
for w in range(t):
s=raw_input()
l=len(s)
cnt=l*(l+1)/2
a=0
b=0
c=0
for i in range(len(s)):
if s[i]=='a':
a=i+1
cnt-=min(b,c)
if s[i]=='b':
b=i+1
cnt-=min(a,c)
if s[i]=='c':
c=i+1
... |
Soumika has a string S and its starting index is 1. The string S consists of characters from 1-9. As she is very intelligent, she wants to test his brother Vinay Tendulkar. She asked her brother Vinay Tendulkar to count the number of even numbered characters ( i.e 2,4,6,8 ) for every index i (1 β€ i β€ | S|). For an... | x=map(int,' '.join(raw_input()).split())
#print x
s= [0 for i in x]
for i in range(len(x)):
if(x[i]%2==0):
s[i]=1
#print s
ss = [sum(s[i:]) for i in range(len(s)) ]
ss = map(str,ss)
print ' '.join(ss) |
Given N space separated integers. Your task is to arrange them such that the summation M of the absolute differences between every two adjacent numbers is maximum.
Input:
First line of the input contains an integer N.
Second line contains N space separated integers A_i.
Output:
Print the above described ... | import math
n = int(raw_input())
a = map(int,raw_input().split())
a = sorted(a)
b = []
c = []
for i in xrange(n/2):
b.append(a[i])
b.append(a[n-1-i])
c.append(a[n-1-i])
c.append(a[i])
if n%2 != 0 :
b.append(a[n/2])
c.append(a[n/2])
ans = 0
ans1 = 0
#print b,c
for i in xrange(n-1):
ans ... |
The link to the Russian translation.
Stefan is stuck in Marty's body and in order to fix him, Valerie has encountered a problem with dead witches spirits.
In order to allow her to do such magic, the witches gave her a huge grid (10^18 by 10^18, rows numbered from 1 to 10^18, from top to bottom and columns from left ... | def mod(val):
return val%2
def differenceOf(x,y):
if x > y:
return x-y
return y-x
T = int(raw_input())
result = []
for i in xrange(0,T):
n = int(raw_input())
if n==1:
result.append("No")
else:
r_one = 0
c_one = 0
x_one = 0
isPossible = True
for j in xrange(0,n):
inVal = raw_input().split(" ")
... |
In computer Science there is common need to generate random permutation. It can be seen as the shuffle of the numbers. Start with sorted permutation of n, at each step select the random no between 1 to n and put it at front. after doing n steps you can write shuffle sequence like {p1,p2,p3 ,...,pn} where at i th step ... | def bell_seq_generator():
bell = [1]
N = 0
while N<=1000:
yield bell[N]%MOD
x = bell[-1]
bell.append(0)
N += 1
for j in xrange(0, N):
x, bell[j] = (bell[j]+x)%MOD, x%MOD
bell[N] = x
MOD=1000000007
if __name__ == '__main__':
x=list(bell_seq_genera... |
You are given an array of N integers A[1] , A[2] , ... , A[N] . You have to answer Q queries. Each query consists of 3 integers L, R and K. For each query, you have to find the value of the Skipping Sum in the following manner :
def skipping_sum(L,R,K) :
sum = 0
while L β€ R :
... | [N,Q] = [int(i) for i in raw_input().strip().split(" ")]
A = [int(i) for i in raw_input().strip().split(" ")]
dp = [[0 for i in range(len(A))]for i in range(10)]
for i in range(10):
for j in range(len(A)):
if j<=i:
dp[i][j]=A[j]
else:
dp[i][j]=A[j]+dp[i][j-i-1]
for i in range(Q):
[L,R,K] = [int(i) for i in ... |
In vardhaman college of engineering, there is competition with name treasure lock.
To make this competition the key for the lock should satisfy following rules.
1 .3, 5, or both as its digits. No other digit is allowed.
2. Number of times 3 appears is divisible by 5.
3. Number of times 5 appears is divisible by 3.
Rak... | def ans(n):
if(n == 0):
return True
elif(n < 0):
return False
else:
return ans(n-5) or ans(n-3)
for _ in xrange(input()):
n=input()
if ans(n):
if(n%5==0):
print str(3)*n
else:
c = 5*(2*n%3)
print str(5)*(n-c)+str(3)*c
else:
... |
There is a grid with N rows and N columns of squares. Let (i, j) be the square at the i-th row from the top and the j-th column from the left.
Each of the central (N-2) \times (N-2) squares in the grid has a black stone on it. Each of the 2N - 1 squares on the bottom side and the right side has a white stone on it.
Q... | class SegTree():
def __init__(self, initial, operation, identity):
n = len(initial)
self.initial = initial
self.operation = operation
self.identity = identity
self.num = 1 << (len(bin(n - 1)) - 2)
self.tree = [identity] * (2 * self.num - 1)
for i in range(n):
... |
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.
We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?
Constraints
* All values in input are integers.
* 0 \leq A, B, C
* 1 \leq K \l... | #include<iostream>
using namespace std;
int main(){
long long a,b,c,d;
cin>>a>>b>>c>>d;
cout<<max(0LL,min(a,d))-max(0LL,d-b-a);
return 0;
}
|
Niwango bought a piece of land that can be represented as a half-open interval [0, X).
Niwango will lay out N vinyl sheets on this land. The sheets are numbered 1,2, \ldots, N, and they are distinguishable. For Sheet i, he can choose an integer j such that 0 \leq j \leq X - L_i and cover [j, j + L_i) with this sheet.
... | /* cerberus97 - Hanit Banga */
#include <iostream>
#include <iomanip>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
#define pb push_back
#define fa... |
We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.
For example, `greenbin` is an anagram of `beginner`. As seen here, when the same character occurs multiple times, that character must be used that number of times.
Given are N strings s_1, s_2, \ldots, s... | N = int(input())
from collections import Counter
S = [''.join(sorted(input())) for _ in range(N)]
ans = 0
for i in Counter(S).values():
ans += i*(i-1)//2
print(ans) |
Today, Snuke will eat B pieces of black chocolate and W pieces of white chocolate for an afternoon snack.
He will repeat the following procedure until there is no piece left:
* Choose black or white with equal probability, and eat a piece of that color if it exists.
For each integer i from 1 to B+W (inclusive), fi... | #include <stdio.h>
#include <algorithm>
long long ansy, ansx;
long long e, f;
long long b, w;
long long p = 1000 * 1000 * 1000 + 7;
long long beki[200005];
long long kai[200005];
long long rui(long long a, long long b) {
if (b == 0)return 1;
if (b == 1)return a % p;
if (b == 2)return a * a%p;
if (b % 2 == 1) {
re... |
In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi:
* If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other pers... | #include<iostream>
#include<cstdio>
using namespace std;
int main(){
int a,b,k;
cin>>a>>b>>k;
int i;
for(i=0;i<k;i++){
if(i%2==0){
if(a%2==1){
a--;
}
b=b+a/2;
a=a/2;
}else{
if(b%2==1){
b--;
}
a=a+b/2;
b=b/2;
}
}
cout<<a<<" "<<b<<endl;
} |
Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 β€ i β€ N), she needs to consume m_i grams o... | #include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 201;
struct data {
int nt, to;
} a[N << 1];
int head[N], cnt = 0;
void add(int x, int y) {
a[++cnt].to = y;
a[cnt].nt = head[x];
head[x] = cnt;
}
int sz[N], w[N];
ll s[N];
void dfs(int u, int fa) {
sz[u] = 1, s[u] = w[u];
for... |
We call a 4-digit integer with three or more consecutive same digits, such as 1118, good.
You are given a 4-digit integer N. Answer the question: Is N good?
Constraints
* 1000 β€ N β€ 9999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If N is good, print `Yes`; ot... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String N = sc.next();
sc.close();
if(N.charAt(0) == N.charAt(1)) {
if(N.charAt(1) == N.charAt(2)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
... |
You are given two integers A and B as the input. Output the value of A + B.
However, if A + B is 10 or greater, output `error` instead.
Constraints
* A and B are integers.
* 1 β€ A, B β€ 9
Input
Input is given from Standard Input in the following format:
A B
Output
If A + B is 10 or greater, print the string `e... | #include<iostream>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
if(a+b>=10)
cout<<"error"<<endl;
else
cout<<a+b<<endl;
} |
Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: `a`, `e`, `i`, `o` and `u`.
Constraints
* c is a lowercase English letter.
Input
The input is given from Standard Input in the following format:
c
Output
If c is a vowel, print `vowel`. Oth... | print(["consonant","vowel"][input() in "aiueo"]) |
Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip. At the beginning of Day 1, he is at home. His plan is described in a string S of length N. On Day i(1 β¦ i β¦ N), he will travel a positive distance in the following direction:
* North if the i-th letter of S is `N`
* West if the i-th letter... | #include <map>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
string s; cin >> s;
map<char, bool> m;
for (char c : s) m[c] = true;
cout << ((m['N'] == m['S'] && m['E'] == m['W']) ? "Yes" : "No") << endl;
}
|
Ichiro likes baseball and has decided to write a program which simulates baseball.
The program reads events in an inning and prints score in that inning. There are only three events as follows:
Single hit
* put a runner on the first base.
* the runner in the first base advances to the second base and the runner in t... | #include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int main() {
int base = 0;
int out = 0;
int score = 0;
int inning;
string evt;
cin >> inning;
while (inning) {
cin >> evt;
if (evt == "HIT") {
base <<= 1;
base |= 1;
if (base > 7) {
score++;
base &= 7;
}
} el... |
Alien Mr.X left a message for Earthlings to commemorate the arrival of the planet on Earth. Mr.X chose "Tronco Ruins", which is famous as an ancient ruin, as the place to leave a message. This was a mysterious place where strange stone statues were randomly placed in the squares of the grid of various sizes.
As a mess... | #include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<map>
#include<set>
#include<queue>
#include<cstdio>
#include<climits>
#include<cmath>
#include<cstring>
#include<string>
#include<sstream>
#include<numeric>
#include<cassert>
#define f first
#define s second
#define mp make_pair
#define ... |
The Zuia Kingdom has finally emerged through annexation of $N$ cities, which are identified by index from $1$ to $N$. You are appointed the Minister of Transport of the newly born kingdom to construct the inter-city road network.
To simplify the conceptual design planning, you opted to consider each city as a point on... | #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0403"
#include<bits/stdc++.h>
using namespace std;
#define call_from_test
#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
#endif
//BEGIN CUT HERE
struct FastIO{
FastIO(){
cin.tie(0);
ios::syn... |
In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate... | #include<iostream>
using namespace std;
int main()
{
int K,i,c,s;
while(cin>>K,K){
s=0;
for(i=0;i<K*(K-1)/2;i++){cin>>c;s+=c;}
cout<<s/(K-1)<<endl;
}
} |
In 4272 A.D., Master of Programming Literature, Dr. Isaac Cornell Panther-Carol, who has miraculously survived through the three World Computer Virus Wars and reached 90 years old this year, won a Nobel Prize for Literature. Media reported every detail of his life. However, there was one thing they could not report -- ... | #include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#include<ctime>
using namespace std;
#define INF (1<<29)
class PMA{//Aho-Corasick
struct Node{
bool match;
int failure;
int len;
int next[256];
Node(int len):failure(-1),len(len),mat... |
You are given a sequence a0a1...aN-1 digits and a prime number Q. For each i β€ j with ai β 0, the subsequence aiai+1...aj can be read as a decimal representation of a positive integer. Subsequences with leading zeros are not considered. Your task is to count the number of pairs (i, j) such that the corresponding subseq... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
template<class T>
inline bool chmax(T &a, T b) {
if(a < b) {
a = b;
return true;
}
return false;
}
template<class T>
inline bool chmin(T &a, T b) {
if(a > b) {
... |
Boy G was on a voyage with his father to celebrate his 13th birthday. However, during the voyage, unfortunately the ship was hit by a storm and the ship capsized. When he woke up, it was an uninhabited island. Partly due to the influence of the adventurer's father, he decided to live a survival life on an uninhabited i... | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
int N;
ll T[1001];
int main(){
cin>>N;
for(int i=0;i<N;i++)cin>>T[i];
if(N==1)cout<<T[0]<<endl;
else{
sort(T,T+N);
ll res=0;
while(1){
if(N==3){
res+=T[0]+T[1]+T[2];
break;
... |
There is a self-playing game called Gather on the Clock.
At the beginning of a game, a number of cards are placed on a ring. Each card is labeled by a value.
In each step of a game, you pick up any one of the cards on the ring and put it on the next one in clockwise order. You will gain the score by the difference of... | #include<iostream>
#include<algorithm>
#include<vector>
#include<cmath>
#define curr(P, i) P[(i) % P.size()]
#define next(P, i) P[(i+1) % P.size()]
#define prev(P, i) P[(i+P.size()-1) % P.size()]
#define Next(a,i) ((i)+1)%(a).size()
#define Curr(a,i) (i)%(a).size()
#define Prev(a, i) (i+a.size()-1) % a.size()
using n... |
Mary Ice is a member of a spy group. She is about to carry out a secret operation with her colleague.
She has got into a target place just now, but unfortunately the colleague has not reached there yet. She needs to hide from her enemy George Water until the colleague comes. Mary may want to make herself appear in Geo... | #include<bits/stdc++.h>
#define EQ(a,b) (abs((a)-(b)) < EPS)
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define fs first
#define sc second
#define pb push_back
#define sz size()
#define all(a) (a).begin(),(a).end()
using namespace std;
typedef double D;
typedef complex<D> P;
typedef pair<P,P> Line;
typedef vector<P... |
You are a programmer who loves bishojo games (a sub-genre of dating simulation games). A game, which is titled "I * C * P * C!" and was released yesterday, has arrived to you just now. This game has multiple endings. When you complete all of those endings, you can get a special figure of the main heroine, Sakuya. So, y... | #include<stdio.h>
#include<iostream>
#include<cstring>
#include<stdlib.h>
#include<algorithm>
#include<queue>
#define rep(i,s,t) for (i=s;i<=t;i++)
using namespace std;
typedef pair<int,int> PII;
queue <PII> q;
const int maxn = 1000001;
long long depth[maxn];
int l[maxn],r[maxn];
long long dp[maxn];
int qqq[maxn];
long... |
A great king of a certain country suddenly decided to visit the land of a friendly country. The country is famous for trains, and the king visits various stations.
There are 52 train stations, each with a single uppercase or lowercase alphabetic name (no overlapping names). The line of this train is circular, with sta... | #include <iostream>
using namespace std;
int main() {
int n;
int key[100];
while(cin >> n, n) {
for (int i = 0; i < n; i++) {
cin >> key[i];
}
string str;
cin >> str;
for (int i = 0; i < str.size(); i++) {
char c;
if (str[i] >= 'A' && str[i] <= 'Z') {
c = str[i] - 'A';
} else {
... |
B: Cram School Schedule / Cram School Timetable
story
You are the owner of a cram school. Your cram school is a private lesson system with one student and one teacher. The teachers at this cram school are very good and can teach all classes regardless of the subject. Also, because teachers and students are very tough... | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> P;
int main() {
int ck, k, n, m, csh, csm, ceh, cem, cs[100], ce[100];
vector<P> teachers[100], students[100];
cin >> ck;
for(int i = 0; i < ck; ++i){
scanf("%d:%d-%d:%d", &csh, &csm, &ceh, &cem);
cs[i] = csh * 60 + csm;
ce[i] = ceh * 60 +... |
problem
AOR Ika likes rooted trees with a fractal (self-similar) structure. Consider using the weighted rooted tree $ T $ consisting of $ N $ vertices to represent the rooted tree $ T'$ with the following fractal structure.
* $ T'$ is the addition of a tree rooted at $ x $ and having a tree structure similar to $ T $... | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define CIN_ONLY if(1)
struct cww{cww(){
CIN_ONLY{
ios::sync_with_stdio(false);cin.tie(0);
cout<<fixed;
}
}}star;
#define fin "\n"
#define FOR(i,bg,ed) for(int i=(bg);i<(ed);i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).be... |
Poisonous swamp
You are playing a retro role-playing game. The field of this game is a grid of 100 squares vertically and 100 squares horizontally. The cells in the xth column from the left and the yth row from the top of this field are represented as (x, y). The character you control is on one of the squares in the f... | #include<bits/stdc++.h>
using namespace std;
using UL = unsigned int;
using ULL = unsigned long long;
using LL = long long;
#define rep(i, n) for(UL i = 0; i < (n); i++)
struct Problem {
public:
void Solve() {
while (true) {
UL N; scanf("%d", &N);
if (N == 0) break;
int x1, x2, y1, y2;
scanf("%d%d%d%d"... |
G: Restricted DFS
problem
There is an undirected tree G that consists of N vertices N-1 edges and has no self-loops or multiple edges. The vertices are each numbered from 1 to N, the edges are also numbered from 1 to N-1, and the i-th edge connects u_i and v_i. A non-negative integer A_i is assigned to the i-th verte... |
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <stdio.h>
using namespace std;
#define int long long
int MOD = 1000000007;
vector<vector<int> > g;
vector<int> A;
vector<vector<int> > dp;
vector<ve... |
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R.
Constraints
* 1 β€ K β€ N β€ 40
* 1 β€ ai β€ 1016
* 1 β€ L β€ R β€ 1016
* All input values are... | #define _CRT_SECURE_NO_WARNINGS
#include "bits/stdc++.h"
using namespace std;
#define int int64_t
#define CHOOSE(a) CHOOSE2 a
#define CHOOSE2(a0,a1,a2,a3,x,...) x
#define REP1(i, s, cond, cal) for (signed i = signed(s); i cond; i cal)
#define REP2(i, s, n) REP1(i, s, < signed(n), ++)
#define REP3(i, n) REP2(i, 0, n)
... |
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $... | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String str=sc.next();
BigInteger a=new BigInteger(str);
str=sc.next();
BigInteger b=new BigInteger(str);
System.ou... |
A few days ago Chef decided to cook a new dish β chocolate. This must be something amazing. The idea is that chocolate bar will be divided into cells. It must be long, but narrow. To interest customers every bar must be unique. Bar will consist of cells of black or white chocolate. In addition every bar must be good l... | #!/usr/bin/python
mod = 1000000007
#import psyco
#psyco.full()
def matrix_mult(A, B):
C = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(3):
for j in range(3):
for k in range(3):
C[i][k] = (C[i][k] + A[i][j] * B[j][k])
if(C[i][k] > 1000000007):
C[i][k] = C[i][k] % 1000000007
return... |
Given three positive integers N, L and R, find the number of non-decreasing sequences of size at least 1 and at most N, such that each element of the sequence lies between L and R, both inclusive.
Print the answer modulo 10^6+3.
Input
First line of input contains T, the number of the test cases.
Each of next T lines... | p=1000003
'''
calculating modulo inverse of 'a' using Euclid's Extended Lemma
'''
def invert_mod(a):
n=1
old=0
q=p
r=0
h=0
pos=0
while a>0:
r=q%a
q=q/a
h=q*n+old
old=n
n=h
q=a
a=r
if pos==0:
pos=1
else:
pos=0
if(pos):
return old
else:
return p-old
'''
Calculating C(n,k)--- No... |
Chef talks a lot on his mobile phone. As a result he exhausts his talk-value (in Rokdas) very quickly. One day at a mobile recharge shop, he noticed that his service provider gives add-on plans which can lower his calling rates (Rokdas/minute). One of the plans said "Recharge for 28 Rokdas and enjoy call rates of 0.50 ... | #!/usr/bin/env python
import sys
def parse_line(fmt):
args = sys.stdin.readline().split()
rv = []
for v in fmt:
arg = args.pop(0)
if v == 'r':
rv.append(float(arg))
elif v == 'i':
rv.append(int(arg))
else:
rv.append(arg)
if len(rv) ==... |
Many internet protocols these days include the option of associating a
media type with the content being sent.
The type is usually inferred from the file extension.
You are to write a program that facilitates the lookup of media types for
a number of files.
You will be given a table of media type associations that asso... | import os
# print hello
a,b = map(int,raw_input().split())
fileTypeHash = dict()
for i in range(0,a):
line=raw_input().split()
ext=line[0]
filetype=line[1]
fileTypeHash[ext]=filetype
# print hash
for i in range(0,b):
line =raw_input().split()[0]
ind = line.rfind('.')
if(ind == -1):
print("unknown")
elif... |
Santosh has a farm at Byteland. He has a very big family to look after. His life takes a sudden turn and he runs into a financial crisis. After giving all the money he has in his hand, he decides to sell some parts of his plots. The specialty of his plot is that it is rectangular in nature. Santosh comes to know that ... | import sys
import fractions
t=int(sys.stdin.readline())
for tc in xrange(t):
l,m=map(int,sys.stdin.readline().split())
gcd=fractions.gcd(l,m)
l/=gcd
m/=gcd
print l*m |
Chef belongs to a very rich family which owns many gold mines. Today, he brought N gold coins and decided to form a triangle using these coins. Isn't it strange?
Chef has a unusual way of forming a triangle using gold coins, which is described as follows:
He puts 1 coin in the 1^st row.
then puts 2 coins in the 2^nd r... | import math
def CoinsAndTriangle():
for i in xrange(int(raw_input())):
n=int(raw_input())
output=int((-1+math.sqrt((1+(8*n))))/2)
print output
CoinsAndTriangle() |
Since next season are coming, you'd like to form a team from two or three participants. There are n candidates, the i-th candidate has rank a_i. But you have weird requirements for your teammates: if you have rank v and have chosen the i-th and j-th candidate, then GCD(v, a_i) = X and LCM(v, a_j) = Y must be met.
You ... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 30;
const long long int MAX = 1e9 + 7;
void array_show(int *array, int array_n, char middle = ' ') {
for (int i = 0; i < array_n; i++)
printf("%d%c", array[i], (i != array_n - 1 ? middle : '\n'));
}
void array_show(long long int *array, int array_... |
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.
This time Miroslav laid out n skewers parallel to each other, and enumerated them with consecutive integers from 1 to n in order from left to ri... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
int main() {
int n, k;
cin >> n >> k;
if (n <= 2 * k + 1) {
cout << 1 << endl;
cout << n / 2 + 1 << endl;
} else {
int count = n / (2 * k + 1);
int rem = n % (2 * k + 1);
if (rem == 0) {
int mid = k + 1;
co... |
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not o... | /*
Roses are red
Memes are neat
All my test cases time out
Lmao yeet
*/
import java.util.*;
import java.io.*;
public class D3
{
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer... |
Polycarp loves ciphers. He has invented his own cipher called Right-Left.
Right-Left cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{n} Polycarp uses the following algorithm:
* he writes down s_1,
* he appends the current word with s_2 (i.e. writes down s_2 to the right of the current resul... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RightLeftCipher {
public static String decipher(String s){
int n = s.length();
if (n < 3){
return s;
}
int i = 0;
int j = 0;
if (n % 2 == 0){
... |
This is an interactive problem.
Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him:
* "x", if (x mod a) β₯ (y mod a). ... | #!/usr/bin/env python
"""
This file is part of https://github.com/Cheran-Senthil/PyRival.
Copyright 2019 Cheran Senthilkumar <hello@cheran.io>
"""
from __future__ import division, print_function
import itertools
import sys
from io import FileIO
sys.stdin = FileIO(0)
sys.stdout = FileIO(1, 'w')
input = lambda: sys.st... |
You came to a local shop and want to buy some chocolate bars. There are n bars in the shop, i-th of them costs a_i coins (and you want to buy all of them).
You have m different coupons that allow you to buy chocolate bars. i-th coupon allows you to buy q_i chocolate bars while you have to pay only for the q_i - 1 most... | #include <bits/stdc++.h>
namespace FASTIO {
char buf[1 << 21];
char *p1, *p2;
template <typename T>
inline void wt(T x, char c = '\n') {
if (x < 0) {
x = -x;
putchar('-');
}
static char sta[sizeof(T) * 8];
T top = 0;
do {
sta[top++] = x % 10;
x /= 10;
} while (x);
while (top) putchar(sta[-... |
A permutation of length k is a sequence of k integers from 1 to k containing each integer exactly once. For example, the sequence [3, 1, 2] is a permutation of length 3.
When Neko was five, he thought of an array a of n positive integers and a permutation p of length n - 1. Then, he performed the following:
* Const... | #include <bits/stdc++.h>
using namespace std;
long long n, b[100005], c[100005], id[200005], cnt = 0, du[100005], a[100005],
cntt = 0;
multiset<long long> e[200005];
void dfs(long long u) {
if (du[u] == 0) {
a[++cntt] = u;
return;
}
for (multiset<long long>::... |
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold:
* For any pair of integers (i,j), if i and j are coprime, a_i β a_j.
* The maximal value of all a_i should be minimized (that is, as small as possible).
A pair of integers is call... |
def main():
buf = input()
n = int(buf)
prime_map = dict()
a = []
for i in range(2, n+1):
first_prime = first_prime_factor(i)
if first_prime not in prime_map:
prime_map[first_prime] = len(prime_map)+1
a.append(prime_map[first_prime])
print(' '.join(list(map(st... |
You are given a weighted undirected tree on n vertices and a list of q updates. Each update changes the weight of one edge. The task is to output the diameter of the tree after each update.
(The distance between two vertices is the sum of the weights on the unique simple path that connects them. The diameter is the la... | #include <bits/stdc++.h>
using namespace std;
inline void read(int &first) {
register int c = getchar();
first = 0;
int neg = 0;
for (; ((c < 48 || c > 57) && c != '-'); c = getchar())
;
if (c == '-') {
neg = 1;
c = getchar();
}
for (; c > 47 && c < 58; c = getchar()) {
first = (first << 1... |
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 β€ a β€ b β€ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi ha... | #include <bits/stdc++.h>
using namespace std;
inline int mul(int a, int b) { return int(a * 1ll * b % 998244353); }
inline int norm(int a) {
if (a >= 998244353) a -= 998244353;
if (a < 0) a += 998244353;
return a;
}
inline int binPow(int a, int k) {
int ans = 1;
while (k > 0) {
if (k & 1) ans = mul(ans, a... |
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices conne... |
import java.io.*;
import java.util.*;
public class E {
Random random = new Random(751454315315L + System.currentTimeMillis());
long mod = (int) 1e9 + 7;
long[] x;
ArrayList<Integer>[] g;
Map<Long, Integer>[] app;
long ans = 0;
boolean[] used;
long gcd(long a, long b) {
return ... |
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the... | #include <bits/stdc++.h>
using namespace std;
int main() {
int q;
cin >> q;
while (q--) {
long long int a, b, c;
cin >> a >> b >> c;
long long int ans = INT_MAX;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
for (int k = -1; k <= 1; k++) {
long long int pa... |
You are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t = ssss ... For example, if s = 10010, then t = 100101001010010...
Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal... | import math
tt=int(input())
for i in range(tt):
n,x=map(int,input().split())
s=input()
a=1
b={}
def bind(x):
return -((2*x)-1)
if x<0:
a=-1
x=-x
sbal=0
for i in s:
sbal+=(bind(int(i))*a)
b[sbal]=b.get(sbal,0)+1
ans=0
if sbal==0:
if ... |
Vasya has a string s of length n. He decides to make the following modification to the string:
1. Pick an integer k, (1 β€ k β€ n).
2. For i from 1 to n-k+1, reverse the substring s[i:i+k-1] of s. For example, if string s is qwer and k = 2, below is the series of transformations the string goes through:
* qwe... | from sys import stdin, stdout
input = stdin.readline
for _ in " " * int(input()):
n = int(input())
s = list(input())[:-1]
ans = list(s)
ind = 0
for k in range(n):
if (n - k) % 2:
st = s[k:] + s[:k][::-1]
else:
st = s[k:] + s[:k]
if st < ans:
... |
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself.
<image>
Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight.
Now, she is going to pick three gems.
Xenia loves colorful things, ... | import bisect
def nearest_with_leader(reds, greens, blues):
minimum = 10**19*3
for g in greens:
bi = bisect.bisect_left(blues, g)
ri = bisect.bisect_right(reds, g)
if ri == 0 or bi == len(blues):
continue
b = blues[bi]
r = reds[ri-1]
minimum = min(min... |
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the ... | #include <bits/stdc++.h>
using namespace std;
struct point {
int x, y;
};
point p[8];
bool used[8];
int a[8];
bool f;
inline bool plan(point p1, point p2, point p3) {
return ((p1.x - p2.x) * (p2.x - p3.x) + (p1.y - p2.y) * (p2.y - p3.y) == 0);
}
inline bool dist(point p1, point p2, point p3, point p4) {
int d1 = ... |
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.
Everybody knows that the Wo... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000 * 100;
pair<int, int> hap[MAXN];
int main() {
int n, m = 0, index = 0;
cin >> n;
for (int i = 0; i < n; i++) cin >> hap[i].first >> hap[i].second;
sort(hap, hap + n);
m = hap[0].second;
for (int i = 1; i < n; i++) {
if (hap[i].second < ... |
Little Petya likes to play very much. And most of all he likes to play the following game:
He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of ste... | #include <bits/stdc++.h>
using namespace std;
priority_queue<int> pq;
int main() {
int n;
scanf("%d", &n);
long long res = 0;
int x;
scanf("%d", &x);
pq.push(x);
for (int i = 1; i < n; ++i) {
scanf("%d", &x);
pq.push(x);
if (pq.top() > x) {
res += pq.top() - x;
pq.pop();
pq.p... |
Nikola owns a large warehouse which is illuminated by N light bulbs, numbered 1 to N. At the exit of the warehouse, there are S light switches, numbered 1 to S. Each switch swaps the on/off state for some light bulbs, so if a light bulb is off, flipping the switch turns it on, and if the light bulb is on, flipping the ... | #include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
namespace ywy {
inline int get() {
int n = 0;
char c;
while ((c = getchar()) || 23333)
if (c >= '0' && c <= '9') break;
n = c - '0';
while ((c = getchar()) || 233333) {
if (c >= '0' && c <= '9')
n = n * 10 + c - '0';
else
... |
A permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] β are permutations, and [1, 1], [4, 3, 1], [2, 3, 4] β no.
Permutation a is lexicographically smaller than permutation b (they have the same length n), if in the first index... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << "\n";
err(++it, args...);
}
long long powm(long long a, long long b, lo... |
The progress is not standing still in Berland. Recently all garbage containers in Bertown, the capital of Berland, were replaced by differentiated recycling bins, each accepting some category of waste. While this will definitely improve the ecological situation, for some citizens it's difficult to get used to the habit... | #include <bits/stdc++.h>
using namespace std;
int t,c[19],a[19];
string ans="Yes";
int main()
{
cin>>t;
for(int i=0;i<t;i++)
{
for(int i=0;i<3;i++)
cin>>c[i];
for(int i=0;i<5;i++)
cin>>a[i];
if(a[0]<=c[0])
{
c[0]-=a[0];
a[... |
Berland crossword is a puzzle that is solved on a square grid with n rows and n columns. Initially all the cells are white.
To solve the puzzle one has to color some cells on the border of the grid black in such a way that:
* exactly U cells in the top row are black;
* exactly R cells in the rightmost column ar... |
def solve():
n, u, r, d, l = map(int, input().split())
for i in range(16):
ur = i & 1
dr = bool(i & 1<<1)
dl = bool(i & 1<<2)
ul = bool(i & 1<<3)
uu=u
rr=r
dd=d
ll=l
uu -= ur + ul
rr -= ur + dr
dd -= dr + dl
ll -=... |
A number is called 2050-number if it is 2050, 20500, ..., (2050 β
10^k for integer k β₯ 0).
Given a number n, you are asked to represent n as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.
Input
The first line contains a single integer T (1β€ Tβ€ 1... | import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < T; i++) {... |
Finally, you have defeated Razor and now, you are the Most Wanted street racer. Sergeant Cross has sent the full police force after you in a deadly pursuit. Fortunately, you have found a hiding spot but you fear that Cross and his force will eventually find you. To increase your chances of survival, you want to tune an... | // Hypercube Coloring
#include<bits/stdc++.h>
#define P pair<int,int>
#define x first
#define y second
using namespace std;
bool isPowerOfTwo(int n)
{
return n == (n & -n);
}
// Coloring exists if and only if n is a power of two.
vector<int> getSimpleHypercubeColoring(const int n)
{
const int N = 1 << n;
... |
Input
The only line of input contains three integers a1, a2, a3 (1 β€ a1, a2, a3 β€ 20), separated by spaces.
Output
Output a single integer.
Examples
Input
2 3 2
Output
5
Input
13 14 1
Output
14
Input
14 5 9
Output
464
Input
17 18 3
Output
53 | #include <bits/stdc++.h>
using namespace std;
int a0, a1, n, ans, table[500];
int getans(int);
int main() {
scanf("%d%d%d", &a0, &a1, &n);
printf("%d\n", getans(n));
return 0;
}
int getans(int an) {
if (an == 0) return a0;
if (an == 1) return a1;
return getans(an - 1) + getans(an - 2);
}
|
It is dark times in Berland. Berlyand opposition, funded from a neighboring state, has organized a demonstration in Berland capital Bertown. Through the work of intelligence we know that the demonstrations are planned to last for k days.
Fortunately, Berland has a special police unit, which can save the country. It ha... | #include <bits/stdc++.h>
using namespace std;
const int nit = 1 << 18;
int it[2 * nit];
int it_get(int l, int r) {
l += nit, r += nit;
int res = 0;
while (l < r) {
if (l % 2 == 1) res += it[l++];
if (r % 2 == 0) res += it[r--];
l /= 2;
r /= 2;
}
if (l == r) res += it[l];
return res;
}
long l... |
A non-empty string s is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string s from 1 to the string's length and let's denote the i-th character in string s as si.
Binary string s with length n is periodical, if there is an integer 1 β€ k < n such that:
* k is a... | import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class E {
public static void main(String[] args) throws IOException {
new E().run();
}
Map<Integer, Long> shortLen = new Has... |
You must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world.
As you know there are n countries in the world. These countries are connected by n - 1 directed roads. If you don't consider direc... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3000 + 10;
int n;
struct Tside {
int x, y, v;
int num;
Tside *next;
} * h[maxn];
int f[maxn], floors[maxn];
int res = 1000000, res1, res2;
int tx, ty, tv;
void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}
void ins(int x, int y, int num)... |
There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi.
Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximiz... | import java.io.*;
import java.util.*;
//I am fading.......
//read the question correctly (is y a vowel? what are the exact constraints?)
//look out for SPECIAL CASES (n=1?) and overflow (ll vs int?)
//always declare multidimensional arrays as [2][n] not [n][2]
//it can lead to upto 2-3x diff in runtime
public class Mai... |
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.
For permutation p = p0, p1, ..., pn, Polo has defined its beauty β number <image>.
Expression <image> means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in al... | import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
/*
* Simple bitmask code for boolean isset, int set and int clr
*/
public static boolean isset(int n,int i) //returns 1 if the ith bit (from left) of n is set
{
return ((n>>i)&1)==1;
}
public static int set(int n,int i) //make... |
Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.
He's got a square 2n Γ 2n-sized matrix and 4n integers. You need to arrange all these numbers in the matrix (put each number in a single individua... | /*
[ ( ^ _ ^ ) ]
*/
import java.io.*;
import java.util.*;
public class test {
int INF = (int)1e9;
long MOD = 1000000007;
void solve(InputReader in, PrintWriter out) throws IOException {
int n = in.nextInt();
Long[] a = new Long[n];
for(int i=0; i<n; i++)
... |
A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.
Input
Input will begin with an integer n (1 β€ n... | #include <bits/stdc++.h>
using std::greater;
using std::min;
using std::priority_queue;
using std::vector;
const int N = 500005;
int a[N], cnt, n, c[N], sum;
long long st[N], Ans;
priority_queue<long long, vector<long long>, greater<long long> > q;
bool cmp(int x, int y) { return x > y; }
void init() {
std::sort(a + ... |
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1... | n,m=map(int,input().split())
l=[list(map(int,input().split())) for _ in range(n)]
for i in range(n):
if (i==0 or i==n-1) and sum(l[i]): print(2); break
elif l[i][0]==1 or l[i][-1]==1: print(2); break
else: print(4)
|
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".
Sereja needs to answer m queries, each of them is described by two integers li, ri (1 β€ li β€ ri β€ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of... | #include <bits/stdc++.h>
using namespace std;
string str;
struct node_info {
int c, f, s;
} var;
node_info tree[4000001];
inline void build(int node, int start, int end) {
if (start == end) {
tree[node].c = 0;
if (str[start] == '(') {
tree[node].f = 1;
tree[node].s = 0;
} else {
tree[n... |
You have an array of positive integers a[1], a[2], ..., a[n] and a set of bad prime numbers b1, b2, ..., bm. The prime numbers that do not occur in the set b are considered good. The beauty of array a is the sum <image>, where function f(s) is determined as follows:
* f(1) = 0;
* Let's assume that p is the minimu... | #include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int m, a[5005], b[5005], p[10000], k = 0;
bool v[35000];
void make() {
for (int i = 2; i < 35000; i++)
if (!v[i]) {
p[k++] = i;
for (int j = i + i; j < 35000; j += i) v[j] = 1;
}... |
Baldman is a warp master. He possesses a unique ability β creating wormholes! Given two positions in space, Baldman can make a wormhole which makes it possible to move between them in both directions. Unfortunately, such operation isn't free for Baldman: each created wormhole makes him lose plenty of hair from his head... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10, LOG = 20;
pair<int, pair<int, int> > e[N];
int par[N], fat[LOG][N], ed[LOG][N];
long long mst = 0, h[N];
vector<pair<int, int> > adj[N];
int get_par(int v) {
if (par[v] == -1) return v;
return par[v] = get_par(par[v]);
}
void dfs(int v, int p = 0... |
Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but m... | #include <bits/stdc++.h>
using namespace std;
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
double n, m;
cin >> n >> m;
cout.precision(17);
cout << fixed;
if (n == 1 && m == 1)
cout << 1. << endl;
else
cout << (1. + (n - 1.) * (m - 1.) / (n * m - 1.)) / n << endl;
return 0;
}
|
The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.
<image>
The event coordinator has a list of k participants who should be picked up at the airport.... | #include <bits/stdc++.h>
using namespace std;
int main(void) {
int n;
cin >> n;
vector<string> v = {string("+------------------------+"),
string("|O.O.O.#.#.#.#.#.#.#.#.|D|)"),
string("|O.O.O.#.#.#.#.#.#.#.#.|.|"),
string("|O.......................... |
You have decided to watch the best moments of some movie. There are two buttons on your player:
1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.
2. Skip exactly x minutes of the movi... | n,x = map(int,raw_input().split())
l = []
for i in range(n):
l.append(map(int,raw_input().split()))
ans = 0
currTime = 1
i=0
while(i<n):
if(currTime+x <= l[i][0]):
currTime += x
i = i-1
else:
ans += (l[i][1]-currTime + 1)
currTime = l[i][1]+1
i+=1
print ans |
One day n friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together.
Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them occupies the rectangle of... | import java.util.*;
import java.io.*;
public class Random {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] w=new int[n];
int[] h=new int[n];
for(int i=0;i<n;i++){
w[i]=sc.nextInt();
h[i]=sc.nextI... |
The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.
Let's consider a rectangular image that is represent... | #include <bits/stdc++.h>
using namespace std;
const int N = 100 + 5;
long long a[N][N], b[N][N], c[N][N];
int n, m;
char s[N];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%s", s + 1);
for (int j = 1; j <= m; j++) a[i][j] = s[j] == 'W' ? 1 : -1;
}
int ans = 0;
for (int i =... |
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.
In Bananistan people play this crazy game β Bulbo. Thereβs an array of bulbs and player at the position, which represents one of the bulbs. The distance between... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 5011;
int n, xt, nn;
int a[maxn], b[maxn], c[maxn * 2];
const long long inf = 10000000000000;
long long dp[maxn * 2][2];
long long t1[maxn * 2], t2[maxn * 2];
long long ans;
int myabs(int x) {
if (x > 0)
return x;
else
return (-x);
}
int get(int... |
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.
For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.
Calculate the answer for t values of n.
Input
The first line of... | t = int(input())
while(t):
n = int(input())
s = n*(n+1) // 2
k = len(format(n, "b"))
s_pair = 2**k - 1
print(s - 2*s_pair)
t-=1 |
You are given two multisets A and B. Each multiset has exactly n integers each between 1 and n inclusive. Multisets may contain multiple copies of the same number.
You would like to find a nonempty subset of A and a nonempty subset of B such that the sum of elements in these subsets are equal. Subsets are also multise... | #include <bits/stdc++.h>
const long long N = 1000005;
long long n, x, l[N][2], cnt[N], la, lb, ra, rb, rev;
std::vector<long long> a, b;
signed main() {
scanf("%lld", &n);
a.push_back(0), b.push_back(0);
for (long long i = 1; i <= n; i++)
scanf("%lld", &x), a.push_back(a.back() + x);
for (long long i = 1; i... |
Codeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contribution β an integer number, not necessarily positive. There are n registered users and the i-th of them has contribution ti.
Limak is a little polar bear and he's new into competi... | #include <bits/stdc++.h>
using namespace std;
int n, k;
long long b, c;
vector<long long> v[5];
vector<long long> cand[5];
int sz[5];
int st[5];
int en[5];
long long cost(long long x, long long y) {
long long diff = (y - x);
return (diff / 5) * b + (diff % 5) * c;
}
void input() {
scanf("%d%d%lld%lld", &n, &k, &b... |
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything ... | from math import pi
d,h,v,e=map(int,input().split())
v=v/(pi*((d/2)**2))
d=h/(v-e)
if v-e>0 and d<=10000:
print('YES')
print(d)
else:
print('NO') |
Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination β the number of ... | #include <bits/stdc++.h>
using namespace std;
struct Point {
int x;
int y;
Point() { x = y = 0; }
Point(double _x, double _y) {
x = _x;
y = _y;
}
friend Point operator+(const Point &a, const Point &b) {
return Point(b.x + a.x, b.y + a.y);
}
friend Point operator-(const Point &a, const Point ... |
Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operati... | #include <bits/stdc++.h>
using namespace std;
int a[3005], b[3005];
long long f[3005][3005];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i], a[i] -= i, b[i] = a[i];
sort(b + 1, b + n + 1);
int tot = unique(b + 1, b + n + 1) - b - 1;
for (int i = 1; i <= n; ++i) {
long long mn = 0... |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | n=int(input())
s=input()
c=0
c1=0
for i in s:
if i=="D":
c=c+1
else:
c1=c1+1
if c>c1:
print("Danik")
elif c<c1:
print("Anton")
else:
print("Friendship") |
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).
... | n = int(input())
s = 0
mx = 0
a = list((map(int,input().split())))
for i in range(n):
s+=a[i]
mx = max(mx,a[i])
print(mx*n-s) |
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.
Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, ... | #include <bits/stdc++.h>
using namespace std;
using namespace std::chrono;
inline int getint() {
char c = getchar();
int x = 0, mi = 1;
while (c != EOF && c != '-' && !isdigit(c)) c = getchar();
if (c == '-') {
mi = -1;
c = getchar();
}
while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
retur... |
The marmots have prepared a very easy problem for this year's HC2 β this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also rea... | #include <bits/stdc++.h>
int a[10000];
int m, n;
void quicksort(int b[], int low, int high) {
int i = low;
int j = high;
int key = a[i];
if (i < j) {
while (i < j) {
while (a[j] >= key && j > i) j--;
a[i] = a[j];
while (a[i] <= key && i < j) i++;
a[j] = a[i];
}
a[i] = key;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.