input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \l... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct SCC {
public:
SCC(vector<vector<int>>& G) : G(G), comp(G.size(), -1), visited(G.size()), G_rev(G.size()) {
for (int u = 0; u < G.size(); u++) {
for (int v : G[u]) G_rev[v].push_back(u);
}
for (int v = 0;... |
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are i... | #include <bits/stdc++.h>
using namespace std;
int main(){
long long A,B,N; cin>>A>>B>>N;
cout<<(A*min(B-1,N))/B<<endl;
} |
Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at le... | // :(
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
if(n == 2){
cout << -1 << endl;
return 0;
}
if(n == 3){
cout << "a..\na..\n.aa" << endl;
return 0;
}
char mat[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){... |
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, N) for (int i = 0; i < (int)N; i++)
#define all(a) (a).begin(), (a).end()
string s, t;
int n, m;
const int R = 256;
vector<vector<int>> dfa;
vector<int> match;
vector<int> L;
void kmp() {
dfa.resize(R, vector<int>(m+1));
dfa[t[0]][... |
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} ... | #include<iostream>
using namespace std;
int n,nr,nra,nrb,i,a,b,Viz[20];
void solve(int n, int a, int b)
{
if(n==1)
{
cout<<a<<" "<<b<<" ";
return;
}
int i,fb=0,sb=0;
for(i=0; i<nr; i++)
if(((((1<<i)&a)!=0)^(((1<<i)&b)!=0))==1)
{
fb=i;
break;
... |
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N... | #include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
cout << (N - 1 - (N - 1) % 111) + 111 << endl;
} |
Yui loves shopping. She lives in Yamaboshi City and there is a train service in the city. The city can be modelled as a very long number line. Yui's house is at coordinate 0.
There are N shopping centres in the city, located at coordinates x_{1}, x_{2}, ..., x_{N} respectively. There are N + 2 train stations, one loca... | #include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<cstdio>
#include<queue>
#include<map>
#include<set>
#define MN 300000
#define ll long long
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getcha... |
In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicograph... | //2017-11-5
//miaomiao
//
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define pb push_back
#define ppb pop_back
#define For(i, a, b) for(int i = (a); i <= (int)(b); ++i)
#define N (300000+5)
vector<int> ans;... |
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements. Here, the score of a' is defined as follows: (the sum of the elements ... | def f(x):
y=x[:n];heapify(y);z=sum(y);s=[z]
for i in x[n:n*2]:z+=i-heappushpop(y,i);s+=[z]
return s
from heapq import*;n,*a=map(int,open(0).read().split());print(max(map(sum,zip(f([-i for i in a[n:][::-1]]),f(a)[::-1])))) |
Snuke received two matrices A and B as birthday presents. Each of the matrices is an N by N matrix that consists of only 0 and 1.
Then he computed the product of the two matrices, C = AB. Since he performed all computations in modulo two, C was also an N by N matrix that consists of only 0 and 1. For each 1 ≤ i, j ≤ N... | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
typedef vector<int>vint;
typedef pair<int,int>pint;
typedef vector<pint>vpint;
template<typename A,typename B>inline ... |
There are N piles of candies on the table. The piles are numbered 1 through N. At first, pile i contains a_i candies.
Snuke and Ciel are playing a game. They take alternating turns. Snuke goes first. In each turn, the current player must perform one of the following two operations:
1. Choose a pile with the largest n... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5;
int n, a[maxn + 3];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
sort(a + 1, a + n + 1);
int x = n, y = 1;
while (x > 1 && y + 1 <= a[x - 1]) {
x--, y++;
}
if (y > a[x - 1]) {
puts((a[x] - y) & 1 ? ... |
Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will.
Divide the orchard into as many relatives as possible on a parcel basis. However, if the same k... | import java.util.Scanner;
public class Main {
char[][] map;
int h, w;
char c;
void run() {
Scanner scan = new Scanner(System.in);
while (true) {
h = scan.nextInt();
w = scan.nextInt();
if (w == 0 && h == 0) break;
map = new char[h][];
int section = 0;
scan.nextLine();
for (int i = 0; i <... |
Welcome to PC Koshien, players. This year marks the 10th anniversary of Computer Koshien, but the number of questions and the total score will vary from year to year. Scores are set for each question according to the difficulty level. When the number of questions is 10 and the score of each question is given, create a ... | #include <iostream>
using namespace std;
int main()
{
int sum = 0, n;
for (int i = 0; i < 10; i++){
cin >> n;
sum += n;
}
cout << sum << endl;
return (0);
} |
There are several rectangular sheets placed on a flat surface. Create a program to find the area and perimeter of the part covered by these sheets.
However, when the plane is regarded as the coordinate plane, the arrangement of the sheets shall satisfy the following conditions (1) and (2).
(1) The x and y coordinates... | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#define F first
#define S second
using namespace std;
typedef pair<int,int> P;
int n,r;
vector<P> x[10002];
vector<P> xx[10002];
int main(void){
while(cin >> n >> r && n){
for(int i = 0; i < 10002; i++){
x[i].clear()... |
Dr .: Peter, do you know "Yes, I have a number"?
Peter: I used to do it on TV the other day. You remember something by the number of characters in each word contained in a sentence. "Yes, I have a number", so it means "the number 3.14" and is a keyword for remembering pi.
Dr .: Peter, that's not the case. This should... | import sys
sys.setrecursionlimit(10**6)
def main():
s = input()
if s == "END OF INPUT":
return False
if s[0] == " ":
s[0] = "."
for _ in range(100):
s = s.replace(" ", " . ")
lst = s.split()
ans = []
for i in lst:
if i == ".":
ans += [0]
e... |
Rotate and Rewrite
Two sequences of integers A: A1 A2 ... An and B: B1 B2 ... Bm and a set of rewriting rules of the form "x1 x2 ... xk -> y" are given. The following transformations on each of the sequences are allowed an arbitrary number of times in an arbitrary order independently.
* Rotate: Moving the first eleme... | #include<cstdio>
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
using namespace std;
#define reps(i,f,n) for(int i=f;i<int(n);i++)
#define rep(i,n) reps(i,0,n)
class Rule{
public:
vector<int> x;
int y;
};
vector<int> A;
vector<int> B;
const ... |
Jim is planning to visit one of his best friends in a town in the mountain area. First, he leaves his hometown and goes to the destination town. This is called the go phase. Then, he comes back to his hometown. This is called the return phase. You are expected to write a program to find the minimum total cost of this t... | #include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
#include <sstream>
using namespace std;
typedef long long ll;
typedef pair<int,int> PI;
const double EPS=1e-6;
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define F first
#define S second
#define mp(a,b) make_pair(a,b)... |
Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves darts as much as programming. Yu-kun was addicted to darts recently, but he got tired of ordinary darts, so he decided to make his own darts board.
S... | #include <cmath>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
constexpr double EPS = 1e-9;
struct point {
double x, y;
explicit point(double x_ = 0.0, double y_ = 0.0):x(x_), y(y_) {}
point(const point &p):x(p.x), y(p.y) {}
point operator+ (const point &p) const {
return point(... |
Prof. Jenifer A. Gibson is carrying out experiments with many robots. Since those robots are expensive, she wants to avoid their crashes during her experiments at her all effort. So she asked you, her assistant, as follows.
“Suppose that we have n (2 ≤ n ≤ 100000) robots of the circular shape with the radius of r, and... | #include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef complex<double> Point;
namespace std{
bool operator < (const Point& p1, const Point& p2){
if(p1.real() != p2.real()) return p1.real() < p2.real();
return p1.imag() < p2.imag();
}
};
struct Even... |
In the International System of Units (SI), various physical quantities are expressed in the form of "numerical value + prefix + unit" using prefixes such as kilo, mega, and giga. For example, "3.5 kilometers", "5.1 milligrams", and so on.
On the other hand, these physical quantities can be expressed as "3.5 * 10 ^ 3 m... | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
//Unit Converter
public class Main{
void run(){
Map<String, Integer> ref = new HashMap<String, Integer>();
ref.put("yotta", 24); ref.put("zetta", 21); ref.put("exa", 18); ref.put("peta", 15); ref.put("tera", 12);
ref.put("giga", 9); ref.... |
Problem statement
The curve given by one implicit function $ Ax ^ 2 + Bxy + Cy ^ 2 + Dx + Ey + F = 0 $ and the straight line given by $ N $ implicit functions $ A_ix + B_iy + C_i = 0 $ is there. Find out how many regions the plane is divided by these curves and straight lines.
The following is a diagram of the Sample... | #include<cmath>
#include<cstdio>
#include<vector>
#include<algorithm>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
const double EPS=1e-5;
struct point{
double x,y;
point():x(0),y(0){}
point(double x,double y):x(x),y(y){}
point operator+(const point &a)const{ return point(x+a.x,y+a.y); }
point o... |
ICPC World Finals Day 1
In programming contests, it is important to know the execution time of the program. If you make a mistake in estimating the execution time and write code that exceeds the time limit, you will lose that much time. This is especially true in team battles where only one computer can be used, such ... | #include <bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define all(a) a.begin(),a.end()
#define o(a) cout<<a<<endl
#define int long long
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> pii;
const int TLE=1000000000;
signed main(){
int n,t;
cin>>n>>t;
string s;
... |
H - RLE Replacement
Problem Statement
In JAG Kingdom, ICPC (Intentionally Compressible Programming Code) is one of the common programming languages. Programs in this language only contain uppercase English letters and the same letters often appear repeatedly in ICPC programs. Thus, programmers in JAG Kingdom prefer t... | #include<cstdio>
using namespace std;
#define MOD 1000000007
typedef long long LL;
struct node{
char c;
LL l;
};
node a[2005],b[1005],c[1005],d[2005];
int na,nb,nc,nd;
int main(){
char e;
int i,j,k;
while(scanf(" %c",&e)&&e!='$'){
a[na].c=e;
scanf("%lld",&a[na++].l);
}
while(scanf(" %c",&e)&&e!='$'){
... |
G: Koi no Junretsu Run! Run! Run! --Love Permutation, Run run run! -
story
Big Junretsu Ranran Randebu ♪ Hello, Hoshizora Ran Nya! My favorite data structure is Starry Sky Tree Nya!
Ran recently enrolled in the Department of Physics, but apparently he has to do programming there as well. Orchids, I like the theory o... | #include <bits/stdc++.h>
using namespace std;
int N,M;
int q[100005];
int p[100005];
const int MAX = (1<<17);
struct seg {
int d[2*MAX];
int n = 0;
void init(int _n){
memset( d,0,sizeof(d) );
n = 1;
while( n < _n ) n*=2;
}
void set(int k,int x){
k += n-1;
d[k] = x;
while( k ){
... |
A: four tea
problem
Tea is indispensable for programming contests. Tea has the effect of relieving constant tension [citation needed]
There are N players participating in the contest, so I would like to prepare tea for this number of people. There are four types of tea packages, A, B, C, and D, all of which are the ... | #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int (i)=(0);(i)<(int)(n);++(i))
using ll = long long;
using P = pair<int, int>;
using namespace std;
int main() {
int N;
cin >> N;
int p[4], t[4];
rep(i, 4) cin >> p[i];
rep(i, 4) cin >> t[i];
int ans = 1e8;
rep(a, 101) r... |
Gag
Segtree has $ N $ of "gags", each with a value of $ V_i $.
Segtree decided to publish all the gags in any order.
Here, the "joy" you get when you publish the $ i $ th gag to the $ j $ th is expressed as $ V_i --j $.
Find the maximum sum of the "joy" you can get.
input
Input is given from standard input in the... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, a, b) for(int i = a; i < b; i++)
int main(){
ll N; cin >> N;
ll ans = 0;
vector<ll> V(N);
rep(i, 0, N) cin >> V[i];
rep(i, 0, N) ans += V[i] - (i + 1);
cout << ans << endl;
}
|
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and $Q$ integers $x_i$ as queries, for each query, print the number of combinations of two integers $(l, r)$ which satisfies the condition: $1 \leq l \leq r \leq N$ and $a_l + a_{l+1} + ... + a_{r-1} + a_r \leq x_i$.
Constraints
* $1 \leq N \leq 10^5$
* $1 ... | import java.util.*;
import java.io.*;
public class Main {
void solve (FastScanner in, PrintWriter out, Methods ms) {
int n = in.nextInt(), q = in.nextInt();
int[] a = in.nextIntArray(n);
for (int i=0; i<q; i++) {
long x = in.nextLong();
int R = 0;
long sum = 0;
long count = 0;
for (int... |
Do you like Treasure Hunts? I like treasure hunts. Love ‘em. And TROIKA 2013 has the best one ever in ‘MIST’ (apps.facebook.com/mist_troika).
Just like a normal treasure hunt, you are given several clues and you have to get the right answer to progress to the next level and so on, until you reach the ultimate prize! B... | import string
s = raw_input().split()
l = len(s)
for i in range(l):
s[i] = string.lower(s[i])
while True:
p = raw_input().split()
l1 = len(p)
a = 1
for i in range(l1):
if string.lower(p[i]) not in s:
a = 0
break
if a:
break
else:
print "No"
pri... |
The chef has just finished baking several pies, and it's time to place them on cooling racks.
The chef has exactly as many cooling racks as pies. Each cooling rack can only hold one pie, and each pie may only be held by one cooling rack,
but the chef isn't confident that the cooling racks can support the weight of the... | #codechef problem Code: cooling pies
for testcases in xrange(int(raw_input())):
n = int(raw_input() )
pies = map(int, raw_input().split() )
trays = map(int, raw_input().split() )
pies = sorted(pies, reverse = True)
trays = sorted(trays, reverse = True)
wastepies = 0
wastetrays = 0
while ... |
All of us must have played the game of jumping monkeys in our childhood. It was a simple game where one had to put a monkey on a tree using a catapult. The catapult threw the monkey into a specific height in the air such that it may landed on an artificial tree.
This summer one of your cousin visited you during your va... | t=input()
for ti in range(t):
hn=map(int,raw_input().split())
h=hn[0]
a=map(int,raw_input().split())
b=sorted(a)
boolean=True
for i in range(len(b)):
if (i!=0 and b[i]-b[i-1]>h) or (i==0 and b[i]>h):
print "No"
boolean=False
break
if boolean==True:... |
A tutorial for this problem is now available on our blog. Click here to read it.
The following problem appeared in the CodeChef March '09 Challenge
In the mysterious country of Byteland, everything is quite different from what you'd
normally expect. In most places, if you were approached by two mobsters in a dark al... | #codechef problem Code: cooling pies
import itertools
for testcases in xrange(int(raw_input())):
n, tot = map(int, raw_input().split() )
L = []
for i in xrange(n) :
L.append(int(raw_input()))
L = sorted(L)
purse = []
for item in L:
if item > tot:
break
purse.a... |
STATEMENT
You are sitting in your class getting bored and wondering how long will it be before you can get back to your room and contine solving the
current long challenge @ codechef. You look at the clock and it shows the time as HH:MM (24-hour format). Just to pass the time you
consider the problem of what maximal... | import math
t=input()
while t>0:
t-=1
time=raw_input()
hrs=int(time[0:2])
mint=int(time[2:4])
#print hrs," ",mint
p=input()
mi=p/60
sec=p%60
hs=0
if mi>=60:
hs+=(mi/60)
mi%=60
hrs=(hrs+hs)%24
mint=(mint+mi)
if mint>=60:
hrs+=1
hrs%=24
mint%=60
if(sec >0):
if(not(hrs==23 and mint=... |
Teacher Suki loves her students very much. Now, she wants to distribute toffees among her students. She has a bag full of toffees. Since, she doesn't have time for counting, each time she randomly picks up some toffees from the bag and gives them to a student. Now, she doesn't want to be called a bad teacher, so she wa... | tc=int(raw_input())
for i in xrange(tc):
n=int(raw_input())
choco=map(int,raw_input().split())
mi=min(choco)
ma=max(choco)
if ma-mi >=2:
print "BAD"
else:
print "GOOD" |
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints.
Consider... |
import java.util.Scanner;
import java.util.TreeSet;
public class ProblemA {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
TreeSet<Integer> set = new TreeSet<>();
for(int i = 1; i <= m; i++) {
set.add(i);
}
for(int i = 0... |
You are given n blocks, each of them is of the form [color_1|value|color_2], where the block can also be flipped to get [color_2|value|color_1].
A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if th... | #include <bits/stdc++.h>
const int INF = 1e9;
int idx[4][4];
int n;
int cnt[10], min_[10], val[10];
int find(int *f, int x) {
if (f[x] != x) f[x] = find(f, f[x]);
return f[x];
}
int main() {
for (int i = 0, k = 0; i < 4; i++)
for (int j = i; j < 4; j++) {
min_[k] = INF;
idx[i][j] = idx[j][i] = k++... |
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?
Input
The only line of the input contains two integers n and S ... | import java.util.Scanner;
public class Terst{
public static void main(String[ ] args){
Scanner in = new Scanner(System.in);
double a = in.nextInt();
double b = in.nextInt();
System.out.println((int)Math.ceil(b/a));
}
}
|
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int MN = 1e4 + 11;
struct edge {
int u, v, c, f;
edge(){};
edge(int u, int v, int c) : u(u), v(v), c(c), f(0){};
};
int s,... |
You are given an array a consisting of n integer numbers.
You have to color this array in k colors in such a way that:
* Each element of the array should be colored in some color;
* For each i from 1 to k there should be at least one element colored in the i-th color in the array;
* For each i from 1 to k al... | import java.io.*;
import java.util.*;
public class div531B
{
BufferedReader in;
PrintWriter ob;
StringTokenizer st;
public static void main(String[] args) throws IOException {
new div531B().run();
}
void run() throws IOException {
in=new BufferedReader(new InputStreamReader(System.in));
ob=new PrintWriter(... |
Sasha and Dima want to buy two n-tier cakes. Each cake should consist of n different tiers: from the size of 1 to the size of n. Tiers should go in order from the smallest to the biggest (from top to bottom).
They live on the same street, there are 2 ⋅ n houses in a row from left to right. Each house has a pastry shop... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
vector<long long> v(n * 2 + 1), kal1((n * 2)), kal2(n * 2 + 1);
for (long long i = 1; i <= n * 2; i++) {
cin >> v[i];
if (kal1[v[i]] == 0) {
kal1[v[i]] = i;
} else {
kal2[v[i]] = i;
}
}
long long x ... |
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in a... | n=int(input())
l=list(map(int,input().split()))
n1,n2=0,0
for i in l:
if i==1:
n1+=1
else:
n2+=1
r=[]
if n1==0 or n2==0:
r=l
else:
r.append(2)
r.append(1)
n1-=1
n2-=1
while n2!=0:
r.append(2)
n2-=1
while n1!=0:
r.append(1)
n1-=1
for ... |
The only difference between easy and hard versions is constraints.
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes n pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal proba... | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 300007;
const long long maxm = 5007;
const long long mod = 998244353;
long long n, m, l[maxn], w[maxn], yes = 0, no = 0;
long long dp[maxm][maxm];
inline long long exgcd(long long a, long long b, long long &x, long long &y) {
if (!b) {
x = 1, y ... |
Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads,... | // package com.company.codeforces;
import java.io.*;
import java.util.*;
public class Solution {
static ArrayList<Integer> tree[];
static int in[],low[],timer=0,vis[];
static PrintWriter pw = new PrintWriter(System.out);
static class Pair{
int x;
int y;
Pair(int a,int b){
... |
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!
There are n snacks flavors, numbered with integers 1, 2, …, n. Bessie has n snacks, one snack of each flavor. Every g... | import java.io.*;
import java.math.*;
import java.util.*;
/**
*
* @author Saju
*
*/
public class Main {
private static int dx[] = { 1, 0, -1, 0 };
private static int dy[] = { 0, -1, 0, 1 };
private static final long INF = Long.MAX_VALUE;
private static final int INT_INF = Integer.MAX_VALUE;
... |
Let's introduce some definitions that will be needed later.
Let prime(x) be the set of prime divisors of x. For example, prime(140) = \{ 2, 5, 7 \}, prime(169) = \{ 13 \}.
Let g(x, p) be the maximum possible integer p^k where k is an integer such that x is divisible by p^k. For example:
* g(45, 3) = 9 (45 is divis... | """
import math
MOD=1000000007
def powr(n,N):
temp=1
while(N>0):
if(N%2!=0):
temp=(temp*n)%MOD
n=(n*n)%MOD
N=N//2
return (temp%MOD)
x,n=map(int,input().split())
n1=x
L=[]
while(n1%2==0):
L.append(2)
n1=n1//2
for i in range(3,int(math.sqrt(n1))+1,2):
... |
Let's call an array a_1, a_2, ..., a_m of nonnegative integer numbers good if a_1 + a_2 + ... + a_m = 2⋅(a_1 ⊕ a_2 ⊕ ... ⊕ a_m), where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, array [1, 2, 3, 6] is good, as 1 + 2 + 3 + 6 = 12 = 2⋅ 6 = 2⋅ (1⊕ 2 ⊕ 3 ⊕ 6). A... | import java.io.*;
import java.util.*;
//import javafx.util.*;
import java.math.*;
//import java.lang.*;
public class Main
{
//static int n;
// static ArrayList<Integer> adj[];
// static boolean vis[];
// static long ans[];
static final long oo=(long)1e18;
public static vo... |
[Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY)
A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them.
It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location... | t = int(input())
for _ in range(t):
variables = [int(_) for _ in input().split()]
n = variables[0]
s = variables[1]
k = variables[2]
closed = set([int(i) for i in input().split()])
minimum = n
tmp = n
for x in range(s, 0, -1):
if x not in closed:
tmp = abs(s-x)
... |
Tired of boring office work, Denis decided to open a fast food restaurant.
On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.
The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes... | import os
import sys
from io import BytesIO, IOBase
def solution(a, b, c):
if a == 0 and b == 0 and c == 0:
print(0)
return
res = 0
comb = ['001', '010', '100', '011', '101', '110', '111']
comb2 = ['01', '10', '11']
a, b, c = sorted([a, b, c])
if a == 0 and b == 0:
pr... |
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, ... | import java.io.*;
import java.util.*;
public class Main implements Runnable {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int t = scn.nextInt();
while (t-- > 0) {
int n = scn.nextInt();
int[] arr = scn.nextIntArray(n);
for (int i = 0; i < n; i++) {
arr[i]--;
}
int ma... |
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | import math
t=int(input())
while(t>0):
t-=1
n,m=map(int,input().split())
print(math.floor((n*m+1)/2)) |
This is an interactive problem.
Anton and Harris are playing a game to decide which of them is the king of problemsetting.
There are three piles of stones, initially containing a, b, and c stones, where a, b, and c are distinct positive integers. On each turn of the game, the following sequence of events takes place:... | import java.io.*;
import java.util.*;
/*
polyakoff
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int oo = (int) 2e9;
static final long OO = (long) 4e18;
static final int MOD = (int) 1e9 + 7;
static void solve() {
... |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly... | # Gifts Fixing
# https://codeforces.com/problemset/problem/1399/B
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
min_a = min(a)
min_b = min(b)
count = 0
for i in range(n):
diff_a = a[i] - min_a
diff_b = b[i] - min_b
... |
Some time ago Lesha found an entertaining string s consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.
Lesha chooses an arbitrary (possibly zero) number of pairs on positions (i, i + 1) in such a way that the foll... | #include <bits/stdc++.h>
using namespace std;
void test() {
string s;
cin >> s;
42;
int n;
n = s.size();
vector<pair<int, string>> ans;
string cur = "";
vector<pair<int, pair<char, char>>> history;
auto add = [&]() {
if (cur.size() > 10) {
string temp = "";
for (int i = 0; i < 2; ++i) ... |
This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operat... | import sys
input=sys.stdin.readline
def change(x1,x2,x3,y1,y2,y3,ll):
ll[x1][y1]=1-ll[x1][y1]
ll[x2][y2]=1-ll[x2][y2]
#print(x3,y3,ll)
ll[x3][y3]=1-ll[x3][y3]
t=int(input())
while t:
n,m=map(int,input().split())
ll=[]
for i in range(n):
l=list(map(int,input().strip()))
... |
You are given a tree with n vertices. Each vertex i has a value a_i associated with it.
Let us root the tree at some vertex v. The vertex v is called a distinctive root if the following holds: in all paths that start at v and end at some other node, all the values encountered are distinct. Two different paths may have... | #include <iostream>
#include <cstdio>
#include <vector>
#include <map>
using namespace std;
const int maxn = 2e5+5;
vector<int> mp[maxn]; int a[maxn];
map<int,int> num;
map<int,int> * hush[maxn]; int sz[maxn];
int ans , fr , fpa; bool tag[maxn];
bool dfs(int id,int pa)
{
if(id==0) return true;
int son = 0; sz[id] = 1... |
Yuezheng Ling gives Luo Tianyi a tree which has n nodes, rooted at 1.
Luo Tianyi will tell you that the parent of the i-th node is a_i (1 ≤ a_i<i for 2 ≤ i ≤ n), and she will ask you to perform q queries of 2 types:
1. She'll give you three integers l, r and x (2 ≤ l ≤ r ≤ n, 1 ≤ x ≤ 10^5). You need to replace a_i... | #include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e5+1e3+7;
int n,q,a[N],fa[N],tag[N],st[N],ed[N],ok[N],B;
void update(int x)
{
for(int i=st[x];i<=ed[x];i++)
a[i]=max(a[i]-tag[x],1ll);
tag[x]=0;
ok[x]=1;
for(int i=st[x];i<=ed[x];i++)
{
fa[i]=a[i]/B==... |
This is an interactive problem.
Baby Ehab loves crawling around his apartment. It has n rooms numbered from 0 to n-1. For every pair of rooms, a and b, there's either a direct passage from room a to room b, or from room b to room a, but never both.
Baby Ehab wants to go play with Baby Badawy. He wants to know if he c... | #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int N = 105;
mt19937 rng(2333);
bool ask(in... |
This is the easy version of the problem. The only difference is that in this version q = 1. 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 operat... | #pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,abm,mmx,tune=native")
#include<vector>
#include<iostream>
#include<stack>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<string>
#include<tuple>
#include<bitset>
#include<queue>
#include<... |
As you know, lemmings like jumping. For the next spectacular group jump n lemmings gathered near a high rock with k comfortable ledges on it. The first ledge is situated at the height of h meters, the second one is at the height of 2h meters, and so on (the i-th ledge is at the height of i·h meters). The lemmings are g... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct Node {
int m, v, id;
bool operator<(const Node& P) const {
if (m != P.m) return m < P.m;
return v < P.v;
}
} A[maxn];
int n, k, h, tmp[maxn], ans[maxn];
inline bool check(double M) {
int cnt = k;
for (int i = n; i; i--) {
... |
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l < m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the poin... | import java.util.Scanner;
public class Platforms18B {
public static void main(String[] args) {
long n,d,m,l;
Scanner scanner = new Scanner(System.in);
n = scanner.nextLong();
d = scanner.nextLong();
m = scanner.nextLong();
l = scanner.nextLong();
if (m-l == ... |
Furik loves writing all sorts of problems, especially such that he can't solve himself. You've got one of his problems, the one Furik gave to Rubik. And Rubik asks you to solve it.
There is integer n and array a, consisting of ten integers, indexed by numbers from 0 to 9. Your task is to count the number of positive i... | #include <bits/stdc++.h>
using namespace std;
using namespace std;
struct sch {
long long int s, e, t;
};
bool sortinrev(const struct sch &a, const struct sch &b) { return (a.s < b.s); }
long long int gcd(long long int a, long long int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
long long int lcm(long long... |
You've got table a, consisting of n rows, numbered from 1 to n. The i-th line of table a contains ci cells, at that for all i (1 < i ≤ n) holds ci ≤ ci - 1.
Let's denote s as the total number of cells of table a, that is, <image>. We know that each cell of the table contains a single integer from 1 to s, at that all ... | import java.io.*;
import java.math.*;
import java.util.*;
public class Main implements Runnable {
// Variable declarations
int r;
int[] c;
int[][] g, s;
// End of declarations
private void read() throws IOException {
// Read input here
r = nextInt();
c = new int[r + 1]... |
Maxim has got a calculator. The calculator has two integer cells. Initially, the first cell contains number 1, and the second cell contains number 0. In one move you can perform one of the following operations:
1. Let's assume that at the current time the first cell contains number a, and the second cell contains nu... | #include <bits/stdc++.h>
using namespace std;
int l, r, p, ans, n, tot;
int prime[30];
int pr[35];
int tmp[35];
int f[3000005];
vector<int> cdt;
bool mark[3000005];
void dfs(int a, int b) {
if (a > r || b > p) return;
dfs(a, b + 1);
if (mark[b]) return;
if (a > r / b) return;
cdt.push_back(a * b);
dfs(a * b... |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
We'll call position i (1 ≤ i ≤ n) in permutation p1, p... | #include <bits/stdc++.h>
using namespace std;
const int M = 1000000007;
const int MaxN = 1000;
const int MaxG = 1000;
inline int &modaddto(int &a, const int &b) {
a = (a + b) % M;
return a;
}
int main() {
int n, nG;
cin >> n >> nG;
static int f[MaxN + 1][MaxG + 1][3][3];
f[1][0][0][0] = 1;
for (int i = 1;... |
In his very young years the hero of our story, king Copa, decided that his private data was hidden not enough securely, what is unacceptable for the king. That's why he invented tricky and clever password (later he learned that his password is a palindrome of odd length), and coded all his data using it.
Copa is afra... | #include <bits/stdc++.h>
const int max_N = 1e5;
template <size_t size>
struct Kmp {
int fail[size];
template <typename T>
inline void get_fail(T S, int len) {
fail[1] = 0;
for (int i = 2, j; i <= len; ++i) {
for (j = fail[i - 1]; j && S[j + 1] != S[i]; j = fail[j])
;
fail[i] = S[j + 1]... |
Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such ... | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Set;
public class E {
static Set<String> ans;
static int m;
public static void main(String[] ar... |
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they ge... | #include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
inline void chmin(A &a, B b) {
if (a > b) a = b;
}
template <typename A, typename B>
inline void chmax(A &a, B b) {
if (a < b) a = b;
}
signed main() {
long long N;
cin >> N;
vector<long long> cnt(5);
long long sum = 0;
for (l... |
Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.
While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:
1) The boss has t... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, mx, reg;
cin >> n >> mx >> reg;
pair<pair<int, int>, int> aa[n];
for (int i = 0; i < n; i++) {
cin >> aa[i].first.first >> aa[i].first.second;
aa[i].second = i;
}
sort(a... |
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:
There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X"... | import java.io.*;
import java.util.*;
public class C234A
{
public static StringTokenizer st;
public static void nextLine(BufferedReader br) throws IOException
{
st = new StringTokenizer(br.readLine());
}
public static String next()
{
return st.nextToken();
}
pu... |
The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.
For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crim... | import java.io.BufferedInputStream;
import java.rmi.StubNotFoundException;
import java.util.Collections.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
impor... |
There are many interesting tasks on domino tilings. For example, an interesting fact is known. Let us take a standard chessboard (8 × 8) and cut exactly two squares out of it. It turns out that the resulting board can always be tiled using dominoes 1 × 2, if the two cut out squares are of the same color, otherwise it i... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n, m;
cin >> n >> m;
vector<string> g(n);
bool p = true;
for (int i = 0; i < n; ++i) cin >> g[i];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (g... |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | def is_simple(n):
for i in xrange(2, n):
if n % i == 0:
return False
return True
n = int(raw_input())
b = 4
a = n - b
while is_simple(a) or is_simple(b):
a -= 1
b += 1
print a, b |
You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the displ... | input()
n = raw_input()
R = [int(ii) for ii in list(n)]
P = []
for ii in range(10):
R = [(mm+1)%10 for mm in R]
P.append([str(mm) for mm in R])
ans = -1
for ii in P:
# print ii
for jj in range(len(ii)):
k = ''.join(ii[jj:] + ii[:jj])
if ans == -1:
ans = k
if int(k) < int(ans):
ans = k
print ans
|
According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no m... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:836777216")
using namespace std;
bool a[705][705];
int b[705][705];
int cnt[705];
int main(void) {
int n, m;
scanf("%d%d", &n, &m);
memset((cnt), (0), sizeof((cnt)));
memset((a), (0), sizeof((a)));
memset((b), (0), sizeof((b)));
for (int(i) = 0; (i) <... |
Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar.
<image>
So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become <image> an... | #include <bits/stdc++.h>
using namespace std;
int record[1000010], record2[1000010];
long long m, hh1, hh2, aa1, aa2, xx1, xx2, yy1, yy2;
long long A1, A2, B1, B2, D1, D2;
inline void solve() {
scanf("%d%d%d%d%d%d%d%d%d", &m, &hh1, &aa1, &xx1, &yy1, &hh2, &aa2, &xx2,
&yy2);
long long tmp = hh1, tmp2 = hh2, ... |
Limak is a little bear who learns to draw. People usually start with houses, fences and flowers but why would bears do it? Limak lives in the forest and he decides to draw a tree.
Recall that tree is a connected graph consisting of n vertices and n - 1 edges.
Limak chose a tree with n vertices. He has infinite strip ... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1000001000;
const long long INFL = 2000000000000001000;
int solve();
int main() {
srand(2317);
cout.precision(10);
cout.setf(ios::fixed);
int tn = 1;
for (int i = 0; i < tn; ++i) solve();
}
const int maxn = 2e5;
vector<int> g[maxn];
bool del[maxn];... |
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.
Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered ... | etaj, kvart = map(int, input().split())
Okna = []
notsleep = 0
for i in range(0, etaj):
Okna.append(list(map(int, input().split())))
for i in range(0, etaj):
for j in range(0, (kvart*2)-1, 2):
if Okna[i][j] or Okna[i][j+1] == 1:
notsleep += 1
print(notsleep)
|
The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.
Find any longest k-good segment.
As the input/output can reach huge size it is recommended to use fast input/output methods... | import java.io.*;
import java.util.*;
public class cfkGood {
public static void main(String[] args) throws IOException {
Kattio io = new Kattio();
int N = io.nextInt();
int K = io.nextInt();
int[] A = new int[N];
int difVal = 0; // Number of different values in the window.... |
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.
Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes ... | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A {
static final int INF = Integer.MAX_VALUE;
public static void m... |
You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edge... | #include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > g[100005];
int a[100005], b[100005];
char s[2];
int vis[100005];
vector<int> com;
bool dfs(int u, int cc) {
com.push_back(u);
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i].first, c = g[u][i].second;
if (vis[v]) {
if (c == ... |
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking... | n = int(raw_input())
a = map(lambda x:int(x) - 1, raw_input().split(' '))
b = [-1 for i in xrange(n)]
l, r = [0], []
b[0] = 0
while l:
while l:
i = l.pop()
if i + 1 < n and b[i + 1] < 0:
b[i + 1] = b[i] + 1
r.append(i + 1)
if i - 1 > 0 and b[i - 1] < 0:
b[i - 1] = b[i] + 1
r.append... |
You should process m queries over a set D of strings. Each query is one of three kinds:
1. Add a string s to the set D. It is guaranteed that the string s was not added before.
2. Delete a string s from the set D. It is guaranteed that the string s is in the set D.
3. For the given string s find the number of ... | #include <bits/stdc++.h>
using namespace std;
struct AC {
vector<string> keys;
vector<map<char, int>> trie;
vector<long long> endp;
vector<int> fail;
AC() {
trie.resize(1);
endp.resize(1);
}
void reset() {
keys.clear();
trie.clear();
endp.clear();
fail.clear();
trie.resize(1);
... |
Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.
There are n video cards in the shop, the power of the i-th video card is equal to in... | #include <bits/stdc++.h>
using namespace std;
long long a[400200], cnt[400200];
int vis[200100];
int main() {
long long n, sum = 0;
scanf("%I64d", &n);
for (int i = 0; i < n; i++) {
scanf("%I64d", &a[i]);
sum += a[i];
++cnt[a[i]];
}
sort(a, a + n);
for (int i = 1; i <= 400100; i++) cnt[i] += cnt... |
Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.
Pavel has a plan: a permutation p and a sequence b1, b2, ... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 50;
const int inf = 1e9 + 50;
const int mod = 1e9 + 7;
int read() {
int k = 0, sig = 1;
char c = getchar();
while (!isdigit(c)) {
if (c == '-') sig *= -1;
c = getchar();
}
while (isdigit(c)) {
k = (k << 3) + (k << 1) + c - '0';
... |
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their... | n = int(input())
s = list(map(int, list(input())))
m = map(int, list(input()))
ma = [0] * 10
for dig in m:
ma[dig] += 1
ma2 = list(ma)
min_f = 0
for nu in s:
for x in range(nu, 10):
if ma[x] > 0:
ma[x] -= 1
break
else:
min_f += 1
for z in range(len(ma)):
... |
You are given an integer m, and a list of n distinct integers between 0 and m - 1.
You would like to construct a sequence satisfying the properties:
* Each element is an integer between 0 and m - 1, inclusive.
* All prefix products of the sequence modulo m are distinct.
* No prefix product modulo m appears as... | #include <bits/stdc++.h>
using namespace std;
bool forbid[200017];
vector<int> d[200017];
unsigned int dp[200017], par[200017];
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
long long egcd(long long a, long long b, long long& x, long long& y) {
if (b == 0) {
x = 1;
y = 0;
retur... |
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple ta... | #include <bits/stdc++.h>
using namespace std;
int n, m, maxl, step, tmp;
string s, t;
int main() {
cin >> n >> m;
cin >> s >> t;
for (int i = 0; i <= m - n; i++) {
tmp = 0;
for (int j = 0; j < n; j++) {
if (s[j] == t[i + j]) {
tmp++;
}
}
if (tmp > maxl) {
maxl = tmp;
... |
There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.
The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.
Your task is to determine the mi... | //package neerc2017;
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 G {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
in... |
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes ... | a, b = map(int, raw_input().split())
if a == b:
print 1
elif b-a >= 5:
print 0
else :
t = 1
for i in xrange(a%10+1,a%10+(b-a)%5+1):
t = (t*i) % 10
print t
# 40 |
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide all piece... | n=int(input())
a=list(map(int,input().split()))
print(2*min(abs(180-sum(a[l:r])) for l in range(n) for r in range(l,n)))
|
Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:
Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As t... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k;
cin >> n >> k;
long long dim = 200000, sum = 0;
int bin[400000] = {0};
while (n > 0) {
bin[dim] = n % 2;
sum += bin[dim];
n = n / 2;
dim++;
}
dim--;
if (sum > k) {
cout << "No" << endl;
} else {
int q = ... |
In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, lo... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> vr(n);
vector<int> sum(n);
cin >> vr[0];
sum[0] = vr[0];
for (int i = 1; i < n; i++) {
cin >> vr[i];
vr[i] += vr[i - 1];
}
int s, f;
cin >> s >> f;
f--;
s--;
f--;
int ans;
int mx = -1;
for (in... |
A rectangle with sides A and B is cut into rectangles with cuts parallel to its sides. For example, if p horizontal and q vertical cuts were made, (p + 1) ⋅ (q + 1) rectangles were left after the cutting. After the cutting, rectangles were of n different types. Two rectangles are different if at least one side of one r... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
if (a % b == 0)
return b;
else
return gcd(b, a % b);
}
int main() {
int n;
scanf("%d", &n);
map<long long, map<long long, long long>> cnt;
long long g = 1;
bool first = true;
for (int i = 0; i < n; i += 1) {
... |
Vasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important — factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the ... | #include <bits/stdc++.h>
using namespace std;
map<long long, string> dict;
set<long long> record[10];
long long n;
long long ten[11];
string toString(long long x) {
ostringstream os;
os << x;
return os.str();
}
int getlen(long long x) {
int t = 0;
while (x) {
x /= 10;
t += 1;
}
return (max(1, t));... |
Subodh is celebrating its annual Techno-Cultural Fest. The IT student Kejal has agreed to supply candies for this festive season.
The Kejal has prepared N boxes of candies, numbered 1 to N (Each number occurring exactly once ). The Kejal is very particular about the arrangement of boxes. She wants boxes to be arranged... | for _ in range(input()):
try:n=input()
except:n=input()
if n==0:
print 0
continue
# print n
try:arr=raw_input().split()
except:arr=raw_input().split()
try:seq=raw_input().split()
except:seq=raw_input().split()
if n==1:
print 0
continue
#print n
count=0
flag=False
while len(arr)>0:
x=0
while arr[... |
In a game of chess, Check is a game position in which a player's King is under attack by any of the opponent's pieces.
Bob is playing with Chess pieces. He randomly arranges three pieces on 8x8 chessboard: a black's King , a white's King and any one of the white's Queen, Knight, Bishop or Rook. Positions of these piec... | #!/usr/bin/python
def getCoords(p):
if p[0] == 'a':
y = 1
elif p[0] == 'b':
y = 2
elif p[0] == 'c':
y = 3
elif p[0] == 'd':
y=4
elif p[0] == 'e':
y=5
elif p[0] == 'f':
y=6
elif p[0] == 'g':
y=7
elif p[0] == 'h':
y=8
x=... |
Russian version of the problem can be read here.
As you probably know, cats usually fight with dogs.
There are N doghouses in a backyard. For simplicity, we consider the backyard as a plane, and the doghouses as points on the plane. All doghouses are numbered from 1 to N. The i-th doghouse is located at point (i, Y[i... | def main():
n=int(raw_input())
Y=map(int,raw_input().split())
y={}
i=0
while(i<len(Y)):
if Y[i] in y:
y.update({Y[i]:[y[Y[i]][0],i,y[Y[i]][2]+1]})
else:
y.update({Y[i]:[i,i,1]})
i+=1
if n==1:
print "1"
else:
ans=0
flag=0
for key1 in y:
g=key1
for key2 in y:
if key2!=key1:
flag=... |
Little Arihant has always wanted to be the best Pokemon trainer in this world. And he thinks he has achieved his goal, so he wants to quickly go and meet Professor Oak and verify this fact. But like all Pokemon trainers, he has a weird habit, too. He catches Pokemons which can go through evolution to become a better on... | nosOfPokemon = input()
evolutionPeriod = sorted(map(int, raw_input().split()), reverse=True)
daysNeeded = 0
for i, v in enumerate(evolutionPeriod):
daysNeeded = max(daysNeeded, i+v)
print daysNeeded + 2 |
After minting loads of money from innocent people by using the psychic powers (As we saw in the previous question!) - little Jhool managed to woo his girlfriend big Jhool! And now, he's in love - madly, madly in love with his girlfriend.
But the road to love is not easy as they say, little Jhool and big Jhool live in... | import re
def main():
s1=raw_input()
if re.search("l.*o.*v.*e",s1):print 'I love you, too!'
else:print 'Let us breakup!'
if __name__=="__main__":
main() |
Mr. Smoothy is a restaurant that serves mostly smoothies at which Ben and his friends are regular customers. The titular mascot is a cup with face and legs that holds a smaller cup. It serves the strangest assortment of flavors in its smoothies, made to order.
The restaurant was about to open, and there was crowd gathe... | T = int(input())
for t in range(T):
L = map(int, raw_input().split())
N = L[0]
del L[0]
counter = 0
for i in range(N):
for j in range(i+1, N):
if L[i]>L[j]:
counter += 1
print counter |
Scientists, researchers, mathematicians and thinkers propose theories for a number of things.
For explaining a single thing, a number of theories are proposed. A number of theories are rendered
invalid after a new and more relevant theory surfaces, giving a better and a more valid explanation for the
subject of the ... | T = int(raw_input())
mod = 1000000007
for t in xrange(T):
startsorted = []
endsorted = []
events = []
n = int(raw_input())
for i in xrange(n):
x,y = map(int,raw_input().split())
startsorted.append((x,y-1))
endsorted.append((y-1,x))
events.append(x)
event... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.