input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v.
It is expected that one of the vertices will be invaded by ... | #include <bits/stdc++.h>
using namespace std;
#define MP make_pair
#define FF first
#define SS second
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pie;
const int MOD = 1e9 + 7;
const int INF = 2e9;
const ll LINF = 4e18;
const ll delta = 96181;
const int N = 1e5 + 20;
vector<int> G[N];
int n, d... |
Snuke is making sugar water in a beaker. Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.
* Operation 1: Pour 100A grams of water into the beaker.
* Operation 2: Pour 100B grams of water into the beaker.... | #include<bits/stdc++.h>
using namespace std;
int A,B,C,D,E,F;
int w,s;
int ans,anss;
double maxn=-1;
int main() {
scanf("%d%d%d%d%d%d",&A,&B,&C,&D,&E,&F);
A*=100;B*=100;
for(int a=0;a<=F/A;a++)
for(int b=0;b<=(F-a*A)/B;b++)
for(int c=0;c<=(F-a*A-b*B)/C;c++)
for(int d=0;d<=(F-a*A-b*B-c*C)/D;d++) {
w=a*A... |
Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the... | a = raw_input()
b = raw_input()
c = ""
count = 0
while count < len(b) :
c += a[count]+b[count]
count += 1
try:
c += a[count]
except:
pass
print c |
Takahashi is playing with N cards.
The i-th card has an integer X_i on it.
Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:
* The integers on the two cards are the same.
* The sum of the integers on the two cards is a multiple of M.
Find the maximum numb... | #include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<map>
#include<vector>
#include<math.h>
#include<stdio.h>
#include<stack>
#include<queue>
#include<tuple>
#include<cassert>
#include<set>
#include<functional>
//#include<bits/stdc++.h>
#define int long long
using namespace std;
const in... |
You are given circle $A$ with radius $r_a$ and with central coordinate $(x_a, y_a)$ and circle $B$ with radius $r_b$ and with central coordinate $(x_b, y_b)$.
Write a program which prints:
* "2" if $B$ is in $A$,
* "-2" if $A$ is in $B$,
* "1" if circumference of $A$ and $B$ intersect, and
* "0" if $A$ and $B$ do not... | from decimal import Decimal
def dist(x1, y1, x2, y2):
return ((x1 - x2)**2 + (y1 - y2)**2)**Decimal('0.5')
N = int(raw_input())
while (N):
N -= 1
xa, ya, ra, xb, yb, rb = map(Decimal, raw_input().split())
d = dist(xa, ya, xb, yb)
sr = ra + rb
dr = abs(ra - rb)
if d > sr:
s = 0
... |
Let's play the game using a bag containing several cards with integers written on it. In each game, participants first declare one of their favorite number n. Then, take out an appropriate number of cards from the bag at a time, and if the sum of the numbers written on those cards is equal to n, you will receive a luxu... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
int m = sc.nextInt();
if(m==0)break;
int[] a = new int[m+1];
int[] b = new int[m+1];
for(int i=1;i<=m;i++){
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
int... |
The brothers Hiroshi and Kenjiro came to Lake Inawashiro for fishing. The two decided to score as follows and compete with the total score of the fish they caught.
* One char is a point
* One yamame trout b points
* Add c points for every 10 chars
* Add d points for every 20 yamame trout
Create a program to determi... | #include<stdio.h>
int main(void)
{
int h1,h2,k1,k2,a,b,c,d,x,y;
scanf("%d %d",&h1,&h2);
scanf("%d %d",&k1,&k2);
scanf("%d %d %d %d",&a,&b,&c,&d);
x=(h1*a)+(h2*b)+((h1/10)*c)+((h2/20)*d);
y=(k1*a)+(k2*b)+((k1/10)*c)+((k2/20)*d);
if(x>y){
printf("hiroshi\n");
}
if(x<y){
printf("kenjiro\n");
}
if(x==y){
... |
problem
JOI City will hold a large-scale exposition.
There are two themes for this exposition, and each of the N exhibition facilities in JOI City will exhibit on one of the two themes.
The location of the facility is represented by plane coordinates (x, y). To move from the facility at position (x, y) to the facili... | #include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
#include<string>
#include<map>
#include<set>
using namespace std;
typedef pair<int,int> P;
typedef pair<int,P> PP;
#define F first
#define S second
#define INF (10000000)
int N;
int X[100001];
int Y[100001];
int m... |
My arm is stuck and I can't pull it out.
I tried to pick up something that had rolled over to the back of my desk, and I inserted my arm while illuminating it with the screen of my cell phone instead of a flashlight, but I accidentally got caught in something and couldn't pull it out. It hurts if you move it forcibly.... | import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
static String line;
static final int MOD = 100000007;
static long solve(int len, int loop) {
long ret = 0;
long[] dp = new long[len + 1];
dp[0] = 1;
for (int i = 1; i <= len; ++i) {
for (int j = 1; j <= Math.min(... |
During a voyage of the starship Hakodate-maru (see Problem A), researchers found strange synchronized movements of stars. Having heard these observations, Dr. Extreme proposed a theory of "super stars". Do not take this term as a description of actors or singers. It is a revolutionary theory in astronomy.
According to... | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include... |
Example
Input
crc
1
Output
crc | #include <bits/stdc++.h>
#define ll long long
#define INF (1LL << 60)
#define MOD 1000000007
#define EPS 1e-10
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i)
#define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i)
#define each(a,b) for(auto& (a): (b))
#define all(v) (v).beg... |
Problem
Yamano Mifune Gakuen's 1st grade G group is a class where female students carrying misfortune gather. They face various challenges every day with the goal of being happy.
In their class, they can take practical happiness courses as part of the test of happiness.
From Monday to Friday, there are classes from 1... | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <cassert>
typedef long long ll;
using namespace std;
#define debug(x) c... |
Taro got a driver’s license with a great effort in his campus days, but unfortunately there had been no opportunities for him to drive. He ended up obtaining a gold license.
One day, he and his friends made a plan to go on a trip to Kyoto with you. At the end of their meeting, they agreed to go around by car, but ther... | #include<bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<int,int> P;
vector<P> G[1111];
struct st{
int prev,curr,dist,pass;
st(){}
st(int prev,int curr,int dist,int pass):prev(prev),curr(curr),dist(dist),pass(pass){}
bool operator<(const st &a) const{
return dist!=a.dist?dist>a.dist:p... |
Bouldering is a style of rock climbing. Boulderers are to climb up the rock with bare hands without supporting ropes. Your friend supposed that it should be interesting and exciting, so he decided to come to bouldering gymnasium to practice bouldering. Since your friend has not tried bouldering yet, he chose beginner’s... | #include<cstdio>
#include<cmath>
#include<utility>
#include<vector>
#include<queue>
#include<complex>
#include<iostream>
#include<set>
#include<algorithm>
using namespace std;
typedef double Real;
typedef complex<Real> Point;
const Real PI=acos(-1.0);
const Real eps=1e-10;
template<class T> bool eq(T a,T b){
retur... |
A tree is one of the most popular data structures in computer science. Tree itself is very elegant, but it is incompatible with current computer architecture. In the current architecture, memory can be regarded as a one-dimensional array. Since a tree is not a one-dimensional structure, cache efficiency may come into q... | #include<iomanip>
#include<limits>
#include<thread>
#include<utility>
#include<iostream>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<numeric>
#include<cassert>
#include<random>
#include<chrono>
#include<unordered_set>
#includ... |
Problem Statement
Dr. Suposupo developed a programming language called Shipura. Shipura supports only one binary operator ${\tt >>}$ and only one unary function ${\tt S<\ >}$.
$x {\tt >>} y$ is evaluated to $\lfloor x / 2^y \rfloor$ (that is, the greatest integer not exceeding $x / 2^y$), and ${\tt S<} x {\tt >}$ is ... | #include <iostream>
#include <string>
#include <cctype>
using namespace std;
typedef string::const_iterator State;
typedef long long ll;
ll mod=1000000007;
string s;
ll expression(State &begin); //term or expr >> term
ll term(State &begin); //num or S<expr>
ll number(State &begin); //
string as(State &begin){
... |
Example
Input
2 10
10 200 1
10 100 100
Output
200 | #include <bits/stdc++.h>
using namespace std;
#define GET_MACRO(_1, _2, _3, NAME, ...) NAME
#define _repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define _rep(i,n) _repl(i,0,n)
#define rep(...) GET_MACRO(__VA_ARGS__, _repl, _rep)(__VA_ARGS__)
#define mp(a,b) make_pair((a),(b))
#define pb(a) push_back((a))
#define all... |
You are planning to create a map of an RPG. This map is represented by a grid whose size is $H \times W$. Each cell in this grid is either '@', '*', '#', or '.'. The meanings of the symbols are as follows.
* '@': The start cell. The story should start from this cell.
* '*': A city cell. The story goes through or ends ... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 100000... |
Problem
Lahuy had no time off and was free, and somehow wanted to eat donuts, so he decided to go around the store and buy donuts.
There is one donut shop in each city, and all donut shops are closed on odd days.
Lahuy has a taste for donuts, so the degree of satisfaction you get depends on the store.
So Lahuy decided... | #include<bits/stdc++.h>
using namespace std;
typedef vector<int> vec;
typedef vector<vec> mat;
void dfs(mat &G,vec &vd,int pos){
if(vd[pos])return;
vd[pos]=1;
for(int i=0;i<(int)G[pos].size();i++){
dfs(G,vd,G[pos][i]);
}
}
void solve(mat &G,vec &c){
int V=G.size();
vec vd(V, 0);
dfs(G,vd,0);
... |
Find places where a string P is found within a text T. Print all indices of T where P found. The indices of T start with 0.
Constraints
* 1 ≤ length of T ≤ 1000000
* 1 ≤ length of P ≤ 10000
* The input consists of alphabetical characters and digits
Input
In the first line, a text T is given. In the second line, a s... | #include <iostream>
#include <string>
using namespace std;
#define STRMAXT 1000000
#define STRMAXP 10000
void KMP(const string T, const string P){
int tcur = 0;
int pcur = 2;
int tablecur = 0;
int plen = P.length();
int tlen = T.length();
int* Table = new int[plen + 1];
Table[0] = -1;
if (plen >= 2){
Table[... |
In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.
Write a program which reads an integer x and print it as is. Note that multiple datasets are give... | i = 0
while True:
n = int(input())
i += 1
if n == 0:
break
print("Case {}: {}".format(i, n)) |
The Chef is having a dinner party and invited over all his friends. His guests
being fairly health conscious have exact protein requirements, and The Chef wishes to oblige them all.
The Chef will cook dishes for each individual guest using the ingredients in his kitchen. Each ingredient has a specific amount of pro... | import sys
def create_meal_from_rawinput():
temp = sys.stdin.readline()
proteinsStr = temp.split()[1:]
proteins = [int(i) for i in proteinsStr]
ingredients = sys.stdin.readline().strip()
desiredProteins = int(sys.stdin.readline())
return Meal(
proteins,
ingredients,
desiredProteins
)
class Meal(object)... |
Bala's room is in a mess. He's been so busy doing research that he hasn't bothered to clean out his room for months. Now he has decided to sort out all the items in his room and keep only the essential ones. He knows the usefulness of each of the 'N' items that he has, and wants to keep only the 'K' most useful items. ... | test=input()
for i in range(test):
x=[]
while len(x)==0:
x=raw_input().split()
y=raw_input().split()
for k in range(int (x[0])):
y[k]=int(y[k])
y.sort()
k=len(y)
sum=0
s=int(x[1])
for j in range (s):
sum=sum+int(y[k-j-1])
print sum |
Aniket Verma aka Math Bond flaunts his mathematics skill whenever he gets the opportunity. But this time he gets into trouble when he meets Sakshi, another mathematician. Sakshi gave him a problem and asked him to solve. Help Aniket to solve the problem.
Given a number N, find the sum of all products x*y such that N/x... | mod = 10**9+7
t = input()
while t > 0:
n = input()
ans = 0
for i in range(1,n+1):
res = int(n/i)
ans += i*res
print ans%mod
t -= 1 |
The following problem appeared in the CodeChef March '09 Challenge. A discussion of possible approaches to solving this problem can be found in our blog.
One evening Johnny found some funny looking beens in his grandfather's garden shed, and decided to plant one of them. Next morning, to his surprise he found an enorm... | n = int(raw_input())
import sys
for _ in xrange(n):
raw_input()
n = 1.0
for l in map(int, raw_input().split()):
n = (n - l) * 2
print "No" if n else "Yes" |
Smaug, the dragon, rules under The Mountain, Erabor which was originally the ruling place of Dwarf King. King Thorin, who is the rightful heir to the throne is on his way to take back his kingdom from Smaug. With the help of a map, King Thorin is able to find a secret entry into the mountain. But now when he has reache... | lis=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
a=raw_input().strip()
leng=len(a)
count=0
if(leng%2==1):
count+=1
flag=1
for i in lis:
k=a.count(i)
if(k%2==1):
if(count>0):
count-=1
else:
flag=0
break
if(flag==1):
print "YES"
else:
print "N... |
Jerry is not good in studies, but he likes to solve puzzles and always challenges his friend Tom. Today Jerry challenged Tom to solve a new riddle. He says "You are given a Pascal's triangle of infinite height, and you are supposed to find the sum of all the integers present at the given height." As usual Tom is conf... | t=int(raw_input())
for i in xrange(t):
n=int(raw_input())
print (2**(n-1))%1000 |
You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n.
You can successively perform the following move any number of times (possibly, zero):
* swap any two adjacent (neighboring) characters of s (i.e. for any i = ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
string a, b, result;
int nb = 0;
cin >> t >> a >> b;
for (int i = b.size() - 1; i >= 0; i--) {
int j = 0;
for (; j <= i && b[i] != a[j]; j++)
;
if (j == i + 1) {
nb = -1;
break;
}
for (; j < i; j++) {
... |
You are given a binary string s.
Find the number of distinct cyclical binary strings of length n which contain s as a substring.
The cyclical string t contains s as a substring if there is some cyclical shift of string t, such that s is a substring of this cyclical shift of t.
For example, the cyclical string "00011... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 42;
const int INF = INT_MAX / 2;
const int MOD = 1e9 + 7;
struct suffix_automaton {
struct node {
int len, link;
bool end;
map<char, int> next;
};
vector<node> sa;
int last;
suffix_automaton() {}
suffix_automaton(string s) {
sa.r... |
You came to the exhibition and one exhibit has drawn your attention. It consists of n stacks of blocks, where the i-th stack consists of a_i blocks resting on the surface.
The height of the exhibit is equal to m. Consequently, the number of blocks in each stack is less than or equal to m.
There is a camera on the cei... | n,m=map(int,input().split(' '))
a=list(map(int,input().split(' ')))
a.sort()
count=0
prev=0
for i in range(n):
count+=1
if a[i]>prev:
prev+=1
count+=a[n-1]-prev
print(sum(a)-count)
|
The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the pat... | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 300000;
int wis[MAX_N], ps[MAX_N], pes[MAX_N], cis[MAX_N];
vector<pair<int, int> > nbrs[MAX_N];
long long dp0[MAX_N], dp1[MAX_N];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", wis + i);
for (int i = 1; i < n; i++) {
... |
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.
There are n doors, the i-th door initially has durability equal to a_i.
During your move you can try to br... | n, x, y = map(int, input().split())
a = list(map(int,input().split()))
if x > y:
print( n )
else:
m = 0
for i in a:
if i <= x:
m += 1
print( m - m // 2 )
|
Alice lives on a flat planet that can be modeled as a square grid of size n × n, with rows and columns enumerated from 1 to n. We represent the cell at the intersection of row r and column c with ordered pair (r, c). Each cell in the grid is either land or water.
<image> An example planet with n = 5. It also appears i... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 100;
struct node {
int x, y;
};
int mov[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
string mapa[MaxN];
int flood[MaxN][MaxN];
int vis[MaxN][MaxN];
int N;
queue<node> cola;
int dist(pair<int, int> a, pair<int, int> b) {
return (a.first - b.first) * (a.fi... |
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.
The Word of Uni... | #include <bits/stdc++.h>
using namespace std;
int n, q;
char cc[100001];
int nxt[100001][26], nx[26];
int dp[251][251][251];
int st1[251], st2[251], st3[251];
int trans(int k, int d) { return k == -1 ? -1 : nxt[k][d]; }
int better(int a, int b) {
if (a == -1) {
return b;
}
if (b == -1) {
return a;
}
r... |
Nauuo is a girl who loves playing games related to portals.
One day she was playing a game as follows.
In an n× n grid, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. We denote a cell on the intersection of the r-th row and c-th column as (r,c).
A porta... | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int w = 1, s = 0;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') w = -1;
ch = getchar();
}
while (isdigit(ch)) {
s = s * 10 + ch - '0';
ch = getchar();
}
return w * s;
}
int R[1010], C[1010], n, cnt, pos1[1010], ... |
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed o... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("fast-math")
#pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native")
using namespace std;
template <typename T>
void uin(T &a, T b) {
if (b < a) {
... |
This is an easier version of the next problem. The difference is only in constraints.
You are given a rectangular n × m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation ... | #include <bits/stdc++.h>
using namespace std;
vector<pair<int, vector<int>>> a;
int n;
int m;
int mdp[5000][14];
int tE[12] = {2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
int cost[13][5000][13];
int dp(int tt, int i) {
if (i == m) return 0;
if (tE[n - 1] == (tt + 1)) return 0;
if (mdp[tt][i] != -1) ret... |
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}... |
/**
* Date: 29 Sep, 2019
* Link: https://codeforces.com/contest/1228/problem/D
*
* @author Prasad Chaudhari
* @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/
* @git: https://github.com/Prasad-Chaudhari
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException... |
This problem is interactive.
We have hidden an array a of n pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon.
This device can answer queries of the following form: in response to the positions of k diffe... | import sys
input = sys.stdin.readline
N, K = map(int, input().split())
def inout(A):
print("?", end=" ")
print(*A)
sys.stdout.flush()
pos, a = map(int, input().split())
return pos, a
dic = {}
for k in range(1, K+2):
A = list(range(1,k)) + list(range(k+1, K+2))
pos, a = inout(A)
if a ... |
[3R2 - Standby for Action](https://www.youtube.com/watch?v=P2ZVC9aoiKo)
Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. n"!
The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The sho... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamW... |
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be n participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest numb... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper p... |
The only difference between easy and hard versions is constraints.
You are given a sequence a consisting of n positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ... | def max_tbp(xs, a, b, O, C):
m = 1
occs = O[a]
b_cnts = C[b]
for i in range(len(occs)//2):
st = occs[i]
en = occs[len(occs)-1-i]
cnt = b_cnts[en-1] - b_cnts[st]
m = max(m, (i+1)*2 + cnt)
return m
t = int(input())
for _ in range(t):
n = int(input... |
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.
She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t... |
t = int(input())
for i in range(t):
n = int(input())
nums = list(map(int, input().split()))
ans = False
nums.sort()
for j in range(n-1, -1,-1):
if nums[j] <= j+1:
print(j+2)
ans = True
break
if not ans:
print(1)
... |
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add t... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
int n;
int cnt[2];
vector<int> Adj[MAXN];
void DFS(int node, int p, int c) {
cnt[c]++;
for (auto x : Adj[node]) {
if (x == p) {
continue;
}
DFS(x, node, 1 - c);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(... |
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.
So, if there are k teams (a_1, b_1), (a_2, b_2)... | from collections import Counter
def solve():
n=int(input())
A=list(map(int,input().split()))
if n==1:
return 0
A.sort()
mi=A[0]+A[1]
ma=A[-1]+A[-2]
a=Counter(A)
t=0
q=-1
for i in range(mi,ma+1):
t=0
for j in a:
if i-j in a:
# pr... |
Yura owns a quite ordinary and boring array a of length n. You think there is nothing more boring than that, but Vladik doesn't agree!
In order to make Yura's array even more boring, Vladik makes q boring queries. Each query consists of two integers x and y. Before answering a query, the bounds l and r for this query ... | #include <bits/stdc++.h>
template <class T>
inline void readInt(T &w) {
char c, p = 0;
while (!isdigit(c = getchar())) p = c == '-';
for (w = c & 15; isdigit(c = getchar()); w = w * 10 + (c & 15))
;
if (p) w = -w;
}
template <class T, class... Args>
inline void readInt(T &w, Args &...args) {
readInt(w), r... |
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices ... | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m, k;
cin >> n >> m >> k;
set<int> adj[n + 1];
unordered_set<int> check[n + 1];
for (long long i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].insert(b);
adj[b].insert(a);
check[a].insert(b);
check[b].insert(a);
... |
Let's call a sequence b_1, b_2, b_3 ..., b_{k - 1}, b_k almost increasing if $$$min(b_1, b_2) ≤ min(b_2, b_3) ≤ ... ≤ min(b_{k - 1}, b_k).$$$ In particular, any sequence with no more than two elements is almost increasing.
You are given a sequence of integers a_1, a_2, ..., a_n. Calculate the length of its longest alm... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const int maxn = 5e5 + 10;
const int mod = 1e9 + 7;
int dp[maxn], a[maxn], fen[maxn];
int n;
void add(int idx, int x){
idx ++;
for (; idx <= n+1; idx += idx & -idx)
fen[idx] = max(fen[idx],x);
}
int get(int idx){
idx ++;... |
After realizing that Zookeeper is just a duck, the animals have overthrown Zookeeper. They now have to decide a new ruler among themselves through a fighting tournament of the following format:
Initially, animal 0 is king, while everyone else queues up with animal 1 at the front of the queue and animal n-1 at the back... | #include <bits/stdc++.h>
const int red = 0;
const int blue = 1;
const int green = 2;
const long long inf = 1e16;
typedef std::pair<long long, long long> ii;
typedef std::pair<long long, ii> iii;
struct animal
{
long a, b, c;
int id, pos, color, redHere;
};
long long moves = 0;
std::vector<animal> belt;
std::vec... |
Phoenix has collected n pieces of gold, and he wants to weigh them together so he can feel rich. The i-th piece of gold has weight w_i. All weights are distinct. He will put his n pieces of gold on a weight scale, one piece at a time.
The scale has an unusual defect: if the total weight on it is exactly x, it will ex... | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
while (n--)
{
long long int a, x, s = 0, d = 0, k;
cin >> a >> x;
int arr[a];
for (int i = 0; i < a; i++)
{
cin >> arr[i];
s = s + arr[i];
}
if (s =... |
This is the hard version of the problem. The only difference is that in this version 1 ≤ q ≤ 10^5. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each... | #include<bits/stdc++.h>
using namespace std;
const int N = 105;
const int MOD = 1000000007;
int c[N], b[N];
int bs[N], bp[N];
int dp[N][N * N];
int n, q;
int rlt[N];
int main() {
cin >> n;
int M = 0, res = 1;
for (int i = 1; i <= n; i ++) {
cin >> c[i];
if (c[i] > M) M = c[i];
res = 1LL * res * (c[i] + 1... |
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 (... | #include <bits/stdc++.h>
using namespace std;
const double eps = 0.0001;
int n, il, ir, m;
double L, v1, v2, l, r, rr;
double a[200001];
double answ[100001] = {0};
void answout() {
int i;
for (i = 0; i <= n; ++i) printf("%.15lf\n", answ[i]);
}
int main(void) {
int i;
scanf("%d%lf%lf%lf", &n, &L, &v1, &v2);
fo... |
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, an... | #coding: utf-8
tam = int(raw_input())
strip = map(int, raw_input().split())
sum_right = [0] * tam
sum_left = [0] * tam
aux = 0
for i in xrange(tam):
aux += strip[i]
sum_right[i] = aux
aux = 0
for i in xrange(tam - 1, -1, -1):
aux += strip[i]
sum_left[i] = aux
count = 0
for i in xrange(tam - 1):
if sum_right[i]... |
Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number.
At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell wi... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long double E = 1e-17;
char ccc;
inline void read(int &n) {
n = 0;
while (true) {
ccc = getchar();
if (ccc == ' ' || ccc == '\n') break;
n = n * 10 + ccc - '0';
}
}
template <typename T>
inline T sqr(T t) {
return t *... |
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.
Consider positive integers a, a + 1, ..., b (a ≤ b). You want to find the minimum integer l (1 ≤ l ≤ b - a + 1) such that for any int... | #include <bits/stdc++.h>
using namespace std;
const int M = 1e6 + 5;
int a, b, k, t, p[M], mark[M], sum[M];
void init() {
int N = 1e6;
for (int i = 2; i <= N; i++) {
if (mark[i] == 0) p[++t] = i;
for (int j = 1; p[j] * i <= N; j++) {
mark[p[j] * i] = 1;
if (i % p[j] == 0) break;
}
}
for ... |
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.
Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Roma's got n positive integers.... | n, k = map(int,input().split())
l = list(map(int,input().split()))
a = 0
for i in range(len(l)):
c = list(str(l[i]))
s = 0
for j in range(len(c)):
if c[j] == "7" or c[j] == "4":
s += 1
if s <= k:
a += 1
print(a)
|
A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≤ pi ≤ n).
A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition ppi = n - i + 1.
You have integer n. Find some lucky permutation p of size n.
Input
T... | import java.util.Comparator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.StringTokenizer;
im... |
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.
The problem is the follows. Given n points in the plane, find a pair of points between... | r = input().split(' ')
n = int( r[ 0 ] )
k = int( r[ 1 ] )
if n * ( n - 1 ) >> 1 <= k:
print( 'no solution' )
else:
for i in range( 0 , n ):
print( 0 , i + 1 )
|
Gerald found a table consisting of n rows and m columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value — it seemed to be too small. And to mak... | #include <bits/stdc++.h>
using namespace std;
int fastMax(int x, int y) { return (((y - x) >> (32 - 1)) & (x ^ y)) ^ y; }
int fastMin(int x, int y) { return (((y - x) >> (32 - 1)) & (x ^ y)) ^ x; }
const int N = 50010;
const int M = 1e6 + 5;
int res[1010][1010];
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (... |
When you were a child you must have been told a puzzle of bags and coins. Anyway, here's one of its versions:
A horse has three bags. The first bag has one coin, the second bag has one coin and the third bag has three coins. In total, the horse has three coins in the bags. How is that possible?
The answer is quite s... | #include <bits/stdc++.h>
using namespace std;
const int N = 77777;
unsigned int f[2][N], *cur, *nex;
pair<int, int> a[N];
int n, s, last[N], ans[N], belong[N], child[N];
map<unsigned int, int> mp;
void show() {
while (last[s] != -1) {
belong[last[s]] = 1;
s -= a[last[s]].first;
}
for (int i = n - 1; i >= ... |
Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfect... | #include <bits/stdc++.h>
using namespace std;
void add(string &s) {
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '0') {
s[i] = '1';
return;
} else {
s[i] = '0';
}
}
s = "";
}
int main() {
int n;
while (cin >> n) {
vector<pair<int, int> > vp;
string ans[1000];
... |
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".
The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game la... | #!/usr/bin/env python2
def main():
n, m = map(int, raw_input().split())
differences = set()
for x in xrange(n):
line = raw_input()
g = line.index('G')
s = line.find('S', g + 1)
if -1 == s:
print -1
return
differences.add(s - g)
print len(... |
Your city has n junctions. There are m one-way roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions.
To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction i can protect junction j if eit... | import sys
#sys.stdin = open('inputfile.txt')
def solve():
"""def FindRings():
S = []
v = set(range(1,n+1))
visited = set()
while len(v) > 0:
vertex = v.pop()
Queue = [vertex]
while len(Queue) > 0:
vertex = Queue.pop()
... |
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies.
Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. ... | import math
n,k=map(int,input().split())
l=list(map(int,input().split()))
for i in range(n):
l[i]=math.ceil(l[i]/k)
f=max(l)
for i in range(n-1,-1,-1):
if f==l[i]:
print(i+1)
break
|
One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.
Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
*
* @author Bassem
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new... |
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd
edfg
hijk
... | #include <bits/stdc++.h>
int main() {
int a, b, c, d, e, f, i, j, k, p, q, sum = 0, flag = 0, ct1 = -1, ct2 = 0;
char x[110][110];
int y[110];
scanf("%d %d", &a, &b);
for (i = 0; i < a; i++) {
scanf("%s", x[i]);
}
for (j = 0; j < b; j++) {
flag = 0;
ct2 = 0;
for (i = 1; i < a; i++) {
... |
An undirected graph is called a caterpillar if it is a connected graph without cycles and it has such a path p that any vertex is located at a distance of at most 1 from the path p. The caterpillar can contain loops (edges from a vertex to itself) but cannot contain multiple (parallel) edges.
The picture contains an e... | #include <bits/stdc++.h>
using namespace std;
vector<vector<int> > G, F;
vector<int> visited, explored, V, dp1, dp2, cat, childs, dsu, par, nodes,
leaves;
int dfs_contract(int v, int p) {
par[v] = p;
nodes.push_back(v);
++visited[v];
int ans = 0;
for (int u : G[v]) {
if (u == p) continue;
if (visi... |
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high.
<image>
A group of bears is a non-empty contiguous segment of the line. The size of ... | import math
import random
class AVLTree():
def __init__(self, x):
self.left = None
self.rght = None
self.val = x
self.height = 1
def getHeight0(root):
if root==None: return 0
return max(getHeight0(root.left), getHeight0(root.rght))+1
def getHeight(root):
if roo... |
Would you want to fight against bears riding horses? Me neither.
Limak is a grizzly bear. He is general of the dreadful army of Bearland. The most important part of an army is cavalry of course.
Cavalry of Bearland consists of n warriors and n horses. i-th warrior has strength wi and i-th horse has strength hi. Warri... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
int q;
scanf("%d", &n);
scanf("%d", &q);
vector<pair<int, int> > w(n);
vector<pair<int, int> > h(n);
for (int i = 0; i < n; ++i) {
scanf("%d", &(w[i].first));
w[i].second = i;
}
for (int i = 0; i < n; ++i) {
scanf("%d", &(h[... |
Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.
Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, ..., an / k and b1, b2, ..., bn / k. Let's split the phone number into blocks of le... | #! /usr/bin/env python
mod=1000000007
n,k=map(int,raw_input().split())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
val=n/k
res=1
x=10**(k-1)
for i in range(val):
cnt=0
if b[i]!=0:
cnt=(x-1)/a[i]+1
for j in range(1,10):
if j!=b[i]:
start=((j*x-1)/a[i])+1
... |
Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 109 + 7 (the remainder when divided by 109 + 7).
The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1.
Input
The only line co... | //package educational.round05;
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 E {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
out.prin... |
For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree.
Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to ... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, sz[N], a[N], c, ret, dp[N];
pair<int, int> m[N][2];
vector<int> adj[N];
void dfs(int x, int p) {
int f = 0, u, i, d;
dp[x] = 0;
if (!sz[x]) f = 1, ++sz[x];
d = a[x] >= c ? 1 : 0;
for (i = 0; i < adj[x].size(); ++i) {
u = adj[x][i]... |
Consider a regular Codeforces round consisting of three problems that uses dynamic scoring.
You are given an almost final scoreboard. For each participant (including yourself), the time of the accepted submission for each of the problems is given. Also, for each solution you already know whether you are able to hack i... | #include <bits/stdc++.h>
using namespace std;
int ololo[5000][3], n, solved[3], canHack[3], score[3], willHack[3], bestPlace,
dp[2][90][90][90], ci, li;
int submissionScore(int sc, int tm) {
if (tm == 0) return 0;
return sc * (250 - abs(tm)) / 250;
}
int calcScore(int p) {
int sum = 0;
for (int i = 0; i < 3... |
Bad news came to Mike's village, some thieves stole a bunch of chocolates from the local factory! Horrible!
Aside from loving sweet things, thieves from this area are known to be very greedy. So after a thief takes his number of chocolates for himself, the next thief will take exactly k times more than the previous o... | n = int(input())
be, en, ans = 8, 8 * 10 ** 15, float('inf')
all = [x * x * x for x in range(2, 200001)]
while be <= en:
cur, md, k = 0, (be + en) >> 1, 0
while all[k] <= md:
cur += md // all[k]
k += 1
if cur < n:
be = md + 1
else:
if cur == n:
ans = min(an... |
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are... | n=int(raw_input())
arr=[]
flag=0
for i in xrange(n):
x=list(raw_input())
if flag==0 and x[0]=='O' and x[1]=='O':
flag=1
x[0]='+'
x[1]='+'
arr.append(x)
elif flag==0 and x[3]=='O' and x[4]=='O':
flag=1
x[3]='+'
x[4]='+'
arr.append(x)
else:
... |
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ... | price, change = map(int, input().split())
ans = 1
total = price
while not((total % 10 != 0 and change == total % 10) or (total % 10 == 0)):
total += price
ans += 1
print(ans)
|
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare.
The fare is constructed in the following manner. There are three types of tickets:
1. a tic... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n;
cin >> n;
vector<long long int> times(n + 1), prefix_time(n + 1);
times[0] = 0;
prefix_time[0] = 0;
for (int i = 1; i <= n; i++) cin >> prefix_time[i];
vector<long long int> dp(n + 1);
dp[0] = 0;
for (int i = 1; i <= n; i++) {... |
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.
Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in... | #include <bits/stdc++.h>
using namespace std;
void fast() {
ios::sync_with_stdio(0);
cin.tie(0);
}
int main() {
fast();
int n, m;
cin >> n >> m;
int last[100005] = {0}, c[100005] = {0};
int mx[100005];
for (int i = 0; i < n; i++) {
mx[i] = 0;
for (int j = 0; j < m; j++) {
int x;
cin ... |
Your search for Heidi is over – you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are n different books, numbered 1 through n.
We will look... | import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numCha... |
It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha.
So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly x days. You... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Codeforces822C {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));... |
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send ai requests.
Polycarp plans to test Fakebook under a special kind of... | #include <bits/stdc++.h>
using namespace std;
int32_t main() {
long long n;
cin >> n;
vector<long long> v(n);
for (long long i = 0; i < n; i++) {
cin >> v[i];
}
pair<long long, long long> prefix[n], suffix[n];
prefix[0] = make_pair(0, v[0]);
suffix[n - 1] = make_pair(0, v[n - 1]);
for (long long i... |
— This is not playing but duty as allies of justice, Nii-chan!
— Not allies but justice itself, Onii-chan!
With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands!
There are three... | #include <bits/stdc++.h>
using namespace std;
long long dp[5007];
long long dp2[5007][5007];
long long a, b, c;
long long chooseSum(long long c1, long long c2) {
long long ans = 0;
for (int i = 0; i <= min(c1, c2); i++) {
long long aux = dp[i];
aux = (aux * dp2[c1][i]) % 998244353;
aux = (aux * dp2[c2][... |
While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i, j) such that ai ≤ aj and there are exactly ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CodeForces {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String... |
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The su... | #include <bits/stdc++.h>
using namespace std;
int dx[8] = {0, 0, -1, 1, 1, 1, -1, -1};
int dy[8] = {-1, 1, 0, 0, 1, -1, 1, -1};
const int SIZE = 450;
int main() {
int N, M;
cin >> N >> M;
int E = 0;
if (N == 2)
cout << 103733951 << " " << 103733951 << endl;
else
cout << 2 << " " << 103733951 << endl;
... |
Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.
This story c... | length=int(input())
s1=input()
s2=input()
connect=[{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25}]
tot=0
spells=[]
for i in range(0, length):
l1=ord(s1[i])-97
l2=ord(s2[i])-97
if not (l1 in connect[l2]):
tot=tot+1
spell... |
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes.
A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each pe... | #include <bits/stdc++.h>
using namespace std;
int main() {
float k, n, s, p;
cin >> k >> n >> s >> p;
int reqSheet = ceil(n / s);
int total = reqSheet * k;
int ans = ceil(total / p);
cout << ans;
}
|
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:
* In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to z... | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
int main() {
int i, j, k;
int n, m;
cin >> n;
set<int> s;
for (i = 0; i < n; i++) {
cin >> m;
if (m) s.insert(m);
}
cout << s.size() << endl;
}
|
Arrow is getting paranoid about Malcom merlyn, his arch-enemy. All his efforts to subdue Merlyn have been in vain. These days Arrow is working on a problem with John Diggle. Diggle mentioned that the Felicity has been facing weird problem with their supercomputer, 'The ECHELON', recently.
This afternoon, Arrow receive... | t=input()
for i in range(0,t):
n=input()
if(n%3==0):
s="5"*n
print s
else:
if((n-5)%3==0 and (n-5)>=0):
s="5"*(n-5)
s=s+"3"*5
print s
else:
k=5
cnt=1
f=0
while(((n-k)%3)!=0):
cnt=cnt+1
k=5*cnt
if(k<=n):
f=1
else:
f=0
if(f==0):
print -1
else:
s="5"*... |
Russian Translation Available
You have a graph with N vertices and M edges. Someone has chosen N-1 edges of these M and claims that they form a spanning tree. Just check whether it's true or not.
Input
The first line contains one integer T denoting the number of test cases.
Each test case starts with a line containi... | try:
num_testcases=int(raw_input())
for tstcs in range(num_testcases):
vertex_edges=raw_input().split(' ')
num_vertices=int(vertex_edges[0])
num_edges=int(vertex_edges[1])
edges=[]
graph=[[]for i in range(num_vertices+1)]
for each_edg in range(num_edges):
... |
Chandu and Kundu are bored of dramatic games around. As they are very good friends and scholars they decided to discover a new game.
In total they had N number of marbles with value inscribed on each of them from 1 to N.
Chandu being from royal family has a treasure box. He emptied the box for the game to proceed. ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
import sys
while True:
line = sys.stdin.readline()
if not line:
break
marble_num = int(line.strip())
marble_stack = []
cont_stack = []
for i in range(1, marble_num):
marble_st... |
On the eve of New Year in Dholakpur, Chota Bheem and Chutki are playing a game, described as follows.
There are two plates full of Laddus. Both can eat 'L' (L ≥ 1) laddus from any one plate or 'L' laddus from both the plates in each step. They play the game alternatively and the last one to eat the laddu will be the ... | ans = [0]*1000002
idx = 0
for i in xrange(1000001):
if ans[i]==0:
ans[i] = i + idx
if i + idx <= 1000000:
ans[i+idx] = i
idx = idx + 1
tc = int(raw_input())
while tc>0:
tc = tc - 1
a, b = map(int, raw_input().split())
if a>b:
a, b = b, a
if ans[a] != b:
print "Chutki"
else:
print "Bheem" |
Little Jhool was was the most intelligent kid of his school. But he did NOT like his class teacher, his school, and the way he was taught things in school. Well, he was a rebel, to say the least. Like most of us, he hated being punished by his teacher - specially, when the punishment was to sit beside someone of the o... | for i in range(int(raw_input())):
n = int(raw_input())
b, c = sorted([int(i) for i in raw_input().split()])
diff = c-b
if diff>1:
print "Little Jhool wins!"
else:
print "The teacher wins!" |
Mid semester exams are approaching and 'IDC' wants to study with the toppers of the batch.
So he decide to take a temporary room near all the toppers of the computer science batch.
All room are on a straight line and room numbers are integers.
Since he is very lazy and doesnt want to walk. He wants to visit all the t... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
for tc in xrange(input()):
k = input()
n = map(int,raw_input().split())
n.sort()
ans=0
for i in range(1,k):
ans += n[i]-n[i-1]
print ans*2 |
Pravin and Saddam are room-mates.They always solve aptitude questions together. Once, they came across a problem stated as:
"Find the digit at the unit place that appears in sum of factorials of all numbers between A and B (both inclusive)."
Though they are good at mathematics ,but this time they are scratching their... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
from math import factorial as fact
t=int(raw_input())
while(t):
sum=0
a,b=map(int,raw_input().split())
for i in range(a,b+1):
sum=sum+fact(i)
print sum%10
... |
Samu is playing a shooting game in play station. There are two apples to aim in this shooting game. Hitting first apple will provide her X points and hitting second apple will provide her Y points. And if she misses the apple she chose to hit, she wont get any point.
Now she is having N coins and each shoot will cost... | # def score_enough(x, y, n, w, p1, p2):
# if not p1 and not p2: return
# if not p1:
# val = w / y + (1 if w % y else 0)
# if val <= n: yield (0, val)
# return
# if not p2:
# val = w / x + (1 if w % x else 0)
# if val <= n: yield (val, 0)
# return
# for i i... |
Sunny, Arpit and Kunal are playing a game. All three of them are standing on a number line, each occupying a different integer.
The rules are as follows:
Two of them cannot be at the same integer at same time.
In one move, one of them, who is not between the other two, can jump to a integer ( if there is any space )... | t=int(raw_input())
while t:
t-=1
l=[int(i) for i in raw_input().split()]
l.sort()
if(l[1]-l[0] > l[2]-l[1]):
print(l[1]-l[0]-1)
else:
print(l[2]-l[1]-1) |
You have to go on a trip in your car which can hold a limited amount of fuel. You know how many liters of fuel your car uses per hour for certain speeds and you have to find out how far a certain amount of fuel will take you when travelling at the optimal speed.
You will be given a set of speeds, a corresponding set ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def find_max_fuel():
t= int(raw_input())
speed_arr= map(float,raw_input().split()[:t])
fuel_arr= map(float,raw_input().split()[:t])
max_fuel = int(raw_input())
max_... |
Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.
Operation: Choose one character of S and replace it with a different character.
Constraints
* S and T have lengths between 1 and 2\times 10^5 (inclusive).
* S and T consists ... | S=input()
T=input()
cc=0
for i in range(len(S)):
cc+=int(S[i]!=T[i])
print(cc) |
In AtCoder City, there are three stations numbered 1, 2, and 3.
Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is `A`, Company A operates Station i; if S_i is `B`, Company B operates Station i.
To improve t... | #include <bits/stdc++.h>
using namespace std;
string s;
int main() {
cin >> s;
if (s == "BBB" or s == "AAA") cout << "No";
else cout << "Yes";
} |
Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.
He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:
* a < b + c
* b < c + a
* c < a + b
How... | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
int ans=0;
for(int i=0;i<n-2;i++)
{
for(int j=i+1;j<n-1;j++)
{
for(int k=j+1;k<n;k++)
{
if(a[i]+a[j]>a[k])
{
ans++;
}
else
{
break;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.