input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
You are given a permutation P_1 ... P_N of the set {1, 2, ..., N}.
You can apply the following operation to this permutation, any number of times (possibly zero):
* Choose two indices i,j (1 โฆ i < j โฆ N), such that j - i โง K and |P_i - P_j| = 1. Then, swap the values of P_i and P_j.
Among all permutations that can... | #include <bits/stdc++.h>
using namespace std;
int n,k,cnt,a[1000005];
vector<int>v[1000005];
map<int,int>mp;
void dfs(int x)
{
for(int i=0;i<v[x].size();i++)
dfs(v[x][i]);
cnt++;
a[x]=cnt;
}
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<=n;i++)
{
if(i>k)
mp.erase(a[i-k]);
... |
Dr .: Peter. I did.
Peter: See you again? What kind of silly invention is this time?
Dr .: You invented the detector for that phantom elementary particle axion.
Peter: Speaking of Axion, researchers such as the European Organization for Nuclear Research (CERN) are chasing with a bloody eye, aren't they? Is that true... | #include <iostream>
#include <algorithm>
using namespace std;
const int H = 10;
const int W = 10;
int G[H][W];
int ans[H][W];
void put(int i, int j) {
const static int di[5] = {0,1,0,-1,0};
const static int dj[5] = {1,0,-1,0,0};
for(int k = 0; k < 5; ++k) {
int ni = i + di[k];
int nj = j + dj[k];
if... |
I decided to move and decided to leave this place. There is nothing wrong with this land itself, but there is only one thing to worry about. It's a plum tree planted in the garden. I was looking forward to this plum blooming every year. After leaving here, the fun of spring will be reduced by one. Wouldn't the scent of... | #include<iostream>
#include<vector>
#include<math.h>
#include<complex>
#define EPS 1e-4
#define PI 3.141592
#define EQ(a,b) (abs((a)-(b))<EPS)
using namespace std;
typedef complex<double> P;
vector<P> house;
vector<P> ume,sak,mo;
double cross(P v1,P v2){
return v1.real()*v2.imag()-v1.imag()*v2.real();
}
bool che... |
problem
Given two strings, find the longest of the strings contained in both strings and write a program that answers that length.
Here, the string s included in the string t means that s appears consecutively in t. An empty string, that is, a string of length 0, is included in any string. For example, the string ABR... | #include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#define int long long
#define mod 1000000007
using namespace std;
string s, t;
int dp[4005][4005], ans;
signed main() {
while (cin >> s >> t) {
for (int i = 0; i <= 4000; i++)for (int j = 0; j <= 4000; j++)dp[i][j] = 0;
ans = 0;
for (int i ... |
As usual, those who called wolves get together on 8 p.m. at the supermarket. The thing they want is only one, a box lunch that is labeled half price. Scrambling for a few discounted box lunch, they fiercely fight every day. And those who are blessed by hunger and appetite the best can acquire the box lunch, while other... | #include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#define rep(i,n) for(int i=0;i<n;i++)
#define rp(i,c) rep(i,(c).... |
Consider a data structure called BUT (Binary and/or Unary Tree). A BUT is defined inductively as follows:
* Let l be a letter of the English alphabet, either lowercase or uppercase (n the sequel, we say simply "a letter"). Then, the object that consists only of l, designating l as its label, is a BUT. In this case, it... | #include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<string>
using namespace std;
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define pb push_back
class Tree{
public:
Tree *l,*r;
char c;
int x,y;
int d;
Tree():l(NULL),r(NULL),d(0){;}
};
//parsig... |
Dragon's Cruller is a sliding puzzle on a torus. The torus surface is partitioned into nine squares as shown in its development in Figure E.1. Here, two squares with one of the sides on the development labeled with the same letter are adjacent to each other, actually sharing the side. Figure E.2 shows which squares are... | #include <bits/stdc++.h>
using namespace std;
constexpr int pDec[]={1,10,100,1000,10000,100000,1000000,10000000,100000000};
constexpr int fct[]={40320,5040,720,120,24,6,2,1};
constexpr int dif[]={-1,1,-3,3};
int makeHash(int num){
int ans=0;
int f=0;
for(int i=0;i<8;i++){
int tmp=num%10;
// ... |
Problem
In recent years, turf wars have frequently occurred among squids. It is a recent squid fighting style that multiple squids form a team and fight with their own squid ink as a weapon.
There is still a turf war, and the battlefield is represented by an R ร C grid. The squid Gesota, who is participating in the t... | #include <iostream>
#include <algorithm>
#define MAX_R 10000
#define MAX_C 30
#define INF 100000
using namespace std;
typedef pair<int, int> coordinate;
char field[MAX_R][MAX_C + 1];
bool used[MAX_R][MAX_C + 1];
int d[MAX_R][MAX_C + 1];
int dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 };
int R, C;
coordinate start, g... |
Peter P. Pepper is facing a difficulty.
After fierce battles with the Principality of Croode, the Aaronbarc Kingdom, for which he serves, had the last laugh in the end. Peter had done great service in the war, and the king decided to give him a big reward. But alas, the mean king gave him a hard question to try his in... | import static java.lang.Math.*;
import java.util.Scanner;
//Tetrahedra
public class Main{
double EPS = 1e-10;
double det(double[][] A){
int n = A.length;
double res = 1;
for(int i=0;i<n;i++){
int pivot = i;
for(int j=i+1;j<n;j++)if(abs(A[j][i])>abs(A[pivot][i]))pivot = j;
swap(A, pivot, i);
res *=... |
It was an era when magic still existed as a matter of course. A clan of magicians lived on a square-shaped island created by magic.
At one point, a crisis came to this island. The empire has developed an intercontinental ballistic missile and aimed it at this island. The magic of this world can be classified into eart... | #include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <ctime>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <deque>
#include <complex>
#include <string>
#include <iomanip>... |
Example
Input
2 10
Warsaw Petersburg
3
Kiev Moscow Petersburg
150 120
3
Moscow Minsk Warsaw
100 150
Output
380 1 | #include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
using namespace std;
#define FOR(i,k,n) for(int i=(k); i<(int)(n);... |
Problem Statement
There is a maze which can be described as a W \times H grid. The upper-left cell is denoted as (1, 1), and the lower-right cell is (W, H). You are now at the cell (1, 1) and have to go to the cell (W, H). However, you can only move to the right adjacent cell or to the lower adjacent cell. The followi... | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1e9;
const ll LINF = 1e18;
template<class S,class T> ostream& operator << (ostream& out,const pair<S,T>& o){ out << "(" << o.first << "," << o.second << ")"; return out; }
template<c... |
Example
Input
2 2
..
..
Output
Second | #include <bits/stdc++.h>
#define syosu(x) fixed<<setprecision(x)
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef pair<double,double> pdd;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double>... |
problem
There are $ V $ islands, numbered $ 0, 1, ..., V-1 $, respectively. There are $ E $ bridges, numbered $ 0, 1, ..., E-1 $, respectively. The $ i $ th bridge spans island $ s_i $ and island $ t_i $ and is $ c_i $ wide.
The AOR Ika-chan Corps (commonly known as the Squid Corps), which has a base on the island $ ... | #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
#define NUM 5000
//่พบใ่กจใๆง้ ไฝ(่กๅ
ใๅฎน้ใ้่พบใฎใคใณใใใฏใน)
struct Edge{
Edge(int arg_to,int arg_capacity,int arg_rev_index){
to = arg_to;
capacit... |
Problem Statement
Have you experienced $10$-by-$10$ grid calculation? It's a mathematical exercise common in Japan. In this problem, we consider the generalization of the exercise, $N$-by-$M$ grid calculation.
In this exercise, you are given an $N$-by-$M$ grid (i.e. a grid with $N$ rows and $M$ columns) with an addit... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef pair<int,P> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-7
#define INF 1000000000
//#define mod 998244353
#define fi first
#define sc second
#define rep(i,x) for(int... |
Problem statement
There is a positive integer sequence $ a_1, a_2, \ ldots, a_N $ of length $ N $.
Consider the following game, which uses this sequence and is played by $ 2 $ players on the play and the play.
* Alternately select one of the following operations for the first move and the second move.
* Select a pos... | #include<bits/stdc++.h>
using namespace std;
using ll=long long;
#define fr(i,n) for(int i=0;i<(n);++i)
#define Fr(i,n) for(int i=1;i<=(n);++i)
#define ifr(i,n) for(int i=(n)-1;i>=0;--i)
#define iFr(i,n) for(int i=(n);i>0;--i)
int main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
istream& in(cin);
... |
Find a cycle in a directed graph G(V, E).
Constraints
* 1 โค |V| โค 100
* 0 โค |E| โค 1,000
* si โ ti
Input
A directed graph G is given in the following format:
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1... | #include<iostream>
#include <list>
#include <limits.h>
using namespace std;
class Graph
{
int V;
list<int> *adj;
bool isCyclicUtil(int v, bool visited[], bool *rs);
public:
Graph(int V);
void addEdge(int v, int w);
bool isCyclic();
};
Graph::Graph(int V)
{
this->V = V;
adj = new lis... |
Problem description.
โMurphyโs Law doesnโt meant that something bad will happen. It means that whatever can happen, will happen.โ
โCooper
While traveling across space-time,the data sent by NASA to "The Endurance" spaceship is sent in the format of,
For... | def toBin(n):
binary = []
while n!=0:
bit = str(n%2)
binary.append(bit)
n = n/2
binary.reverse()
return binary
def main():
tc = int(raw_input())
while tc>0:
n = int(raw_input())
binary = toBin(n)
"""for x in xrange(0,32-len(binary)):
binary.append(0)"""
lenx=l... |
Chef had a hard day and want to play little bit. The game is called "Chain". Chef has the sequence of symbols. Each symbol is either '-' or '+'. The sequence is called Chain if each two neighboring symbols of sequence are either '-+' or '+-'.
For example sequence '-+-+-+' is a Chain but sequence '-+-+--+' is not.
H... | testCases = int(raw_input())
for testCase in range(testCases):
originalString = raw_input()
lenOfOriginalString = len(originalString)
# count variables to find the difference between the new string and original one
count1 = 0 # for "-+-+-+...."
count2 = 0 # for "+-+-+-...."
for pos in range(lenOfOriginalString):
... |
Chef recently printed directions from his home to a hot new restaurant across the town, but forgot to print the directions to get back home. Help Chef to transform the directions to get home from the restaurant.
A set of directions consists of several instructions. The first instruction is of the form "Begin on XXX", i... | t = int(raw_input())
while t:
n = int(raw_input())
directions = []
for i in range(n):
directions.append(raw_input().split())
if i:
directions[i-1][0]="Left" if directions[i][0]=="Right" else "Right"
directions[n-1][0]="Begin"
while n:
print ' '.join(directions.pop... |
Modern cryptosystems rely heavily on our inability to factor large integers quickly as the basis for their security. They need a quick and easy way to generate and test for primes. Very often, the primes generated are very large numbers. You need to implement ways to test the primality of very large numbers.
Input
Lin... | def primality(n):
for i in primes:
if (n % i == 0 and n != i):
return 0
return 1
primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229... |
Buffalo Marketing
Gopal wants to make some money from buffalos, but in a quite a different way. He decided that his future lay in speculating on buffalos. In the market in his village, buffalos were bought and sold everyday. The price fluctuated over the year, but on any single day the price was always the same.
... | t=int(input())
while(t>0):
n=int(input())
a=map(int,raw_input().split(" "))
i=n-1
m=a[i]
ans=0
i=n-2
while(i>=0):
if(m>a[i]):
ans+=m-a[i]
elif(m<a[i]):
m=a[i]
i-=1
print ans
t-=1 |
Mrityunjay is a high-school teacher, currently coaching students for JEE (Joint Entrance Exam). Mrityunjay every year gives prizes to the toppers of JEE in India. A lot of students give this exam in India and it is difficult for him to manually go through results and select two top students from them. So he asked for y... | N = int(raw_input())
arr = map(int,raw_input().strip().split(' '))
c = []
for i in range(2):
m = max(arr)
c.append(m)
arr.remove(m)
print ' '.join(str(t) for t in c) |
You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.
Your task is the following: for every k โ [1..n], calculate the number of points with integer ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e6 + 5;
long long l[maxn], r[maxn], ans[maxn];
int tl[maxn], tr[maxn], s[maxn];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<long long> ds;
for (int i = 0; i < n; ++i) {
cin >> l[i] >> r[i];
ds.push... |
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees!
Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and s... | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
import javafx.util.*;
public class Solution {
static class com implements Comparator<Pair<Integer,Integer>>{
public int compare(Pair<Integer,Integer... |
Ani and Borna are playing a short game on a two-variable polynomial. It's a special kind of a polynomial: the monomials are fixed, but all of its coefficients are fill-in-the-blanks dashes, e.g. $$$ \\_ xy + \\_ x^4 y^7 + \\_ x^8 y^3 + โฆ $$$
Borna will fill in the blanks with positive integers. He wants the polynomial... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
struct Node {
int x, y, id;
Node operator+(Node A) { return (Node){x + A.x, y + A.y, id}; }
Node operator-(Node A) { return (Node){x - A.x, y - A.y, id}; }
long long operator*(Node A) const { return 1ll * x * A.y - 1ll * y * A.x; }
long lon... |
Ivan places knights on infinite chessboard. Initially there are n knights. If there is free cell which is under attack of at least 4 knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the en... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int y = 0, k = 0;
while (y != n) {
if (k % 2 == 0) {
cout << k << " 0" << endl;
y++;
} else {
if (n - y == 1) {
cout << k << " 0" << endl;
y++;
} else if (k % 2 == 1) {
cout << k... |
Misha didn't do his math homework for today's lesson once again. As a punishment, his teacher Dr. Andrew decided to give him a hard, but very useless task.
Dr. Andrew has written two strings s and t of lowercase English letters at the blackboard. He reminded Misha that prefix of a string is a string formed by removing... | #include <bits/stdc++.h>
const int N = 200005;
std::string s, t;
int lcp, next[N], occur[N];
void kmp(const std::string &s) {
for (int i = 1, j = next[0] = -1; i <= s.size(); next[i++] = ++j)
for (; j >= 0 && s[j] != s[i - 1];) j = next[j];
}
int size[N], idx = 1, lst = 1;
int nxt[N][26], fail[N], max[N];
void ap... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i... | n=int(raw_input())
s="abcd" * n
print s[:n] |
There are n students and m clubs in a college. The clubs are numbered from 1 to m. Each student has a potential p_i and is a member of the club with index c_i. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next d days. There is a coding competit... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
std::pair<int, int> DR[] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1},
{-1, 1}, {-1, -1}, {1, 1}, {1, -1}};
using namespace std;
int gcd(int a, int b) {
if (b) return gcd(b, a % b);
return a;
}
mt19937 rng(chrono::steady_clock::now().time_sinc... |
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% ... | #!/usr/bin/env python
from __future__ import division, print_function
import operator as op
import os
import sys
from bisect import bisect_left, bisect_right, insort
from io import BytesIO, IOBase
from itertools import chain, repeat, starmap
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
... |
In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representi... | #include <bits/stdc++.h>
using namespace std;
int const MAX = 1000 * 1000 * 1000;
int main() {
long long a, b, m, i;
cin >> a >> b >> m;
if (m <= b + 1 || MAX % m == 0) {
cout << 2;
return 0;
}
for (i = 1; i <= min(m - 1, a); ++i) {
int k = MAX * i % m;
if (0 < k && k < m - b) {
printf("... |
You are given a graph with 3 โ
n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices.
A set of edges is called a matching if no two edges share an endpoint.
A set of vertices is called an independent set if no two vertices are connected with an edge.
Input
The first line... | #include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
int n, m;
bool vis[300010];
vector<int> ans;
int main() {
int t;
cin >> t;
while (t--) {
scanf("%d %d", &n, &m);
for (int i = 1; i < 3 * n + 1; i++) {
vis[i] = false;
}
ans.clear();
bool findans = false;
for ... |
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i โ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l โค r) such that a_l โ
a_{l + 1} ... a_{r - 1} โ
a_r is negative;
2. the number of pairs of indices (l, r) (l โค r) such that a_l โ
a... | input()
a=list(map(int,input().split()))
q,w,e,t,y=0,0,1,0,0
for i in a:
if e>0:
q+=1
if i>0:
e=1
else:
e=-1
else:
w+=1
if i>0:
e=-1
else:
e=1
if e>0:
t+=q
y+=w
else:
t+=w
y+=q... |
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examp... | #include <bits/stdc++.h>
using namespace std;
int n;
string s;
bool f = false;
bool l = false;
long long res = 0;
int main() {
scanf("%d", &n);
cin >> s;
res = (long long)n * (n - 1) / 2;
for (int i = 0; i < n; i++) {
char c = s[i];
int j = i + 1;
int br = 0;
while (j < n && s[j] != c) {
b... |
There are n students at your university. The programming skill of the i-th student is a_i. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has 2 โ
10^5 students ready for the finals!
Each team should consist of at least three s... | import java.util.*;
import java.io.*;
public class E1256
{
public static void main(String [] args)
{
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
Student [] skills = new Student [n];
for (int i = 0; i < n; i++)
... |
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-read... | import java.io.* ;
import java.util.*;
import static java.lang.Math.* ;
import static java.util.Arrays.* ;
public class C {
public static void main(String[] args) throws IOException {
new C().solveProblem();
out.close();
}
//static Scanner in = new Scanner(new InputStreamReader(System.in));
static Bu... |
N ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can ju... |
/*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CF12D {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final long MOD = 1000L * 1000L * 1000L + 7;
class Lady {
int b;
int i;
int r;
int idx;
public La... |
A popular reality show is recruiting a new cast for the third season! n candidates numbered from 1 to n have been interviewed. The candidate i has aggressiveness level l_i, and recruiting this candidate will cost the show s_i roubles.
The show host reviewes applications of all candidates from i=1 to i=n by increasing ... | #include <bits/stdc++.h>
void rd(int &x) {
x = 0;
int f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar();
x *= f;
}
void lrd(long long &x) {
x = 0;
int f = 1;
char ch = getch... |
Calculate the number of ways to place n rooks on n ร n chessboard so that both following conditions are met:
* each empty cell is under attack;
* exactly k pairs of rooks attack each other.
An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two... | import io,os
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
def solve(n,k):
mod=998244353
if k==0:
ans=1
for i in range(1,n+1):
ans*=i
ans%=mod
return ans
if k>=n:
return 0
inv=lambda x: pow(x,mod-2,mod)
Fact=[1] #้ไน
... |
This is an interactive problem!
Ehab has a hidden permutation p of length n consisting of the elements from 0 to n-1. You, for some reason, want to figure out the permutation. To do that, you can give Ehab 2 different indices i and j, and he'll reply with (p_i|p_j) where | is the [bitwise-or](https://en.wikipedia.org/... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.StringTokenizer;
public class EBrute {
static FastScanner fs;
//TODO: don't fix seed before submitting!
static Random random=new Random();
// static Random random=new Random(5);
... |
Koa the Koala has a matrix A of n rows and m columns. Elements of this matrix are distinct integers from 1 to n โ
m (each number from 1 to n โ
m appears exactly once in the matrix).
For any matrix M of n rows and m columns let's define the following:
* The i-th row of M is defined as R_i(M) = [ M_{i1}, M_{i2}, โฆ, M... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<vector<int>> mat(n, vector<int>(m));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) cin >> mat[i][j];
vector<int> h(n * m + 1);
vector<int> v(n * m + 1);
fo... |
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.
A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the sma... | // package CodeForces;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.LinkedList;
public class Round670C {
public static LinkedList<Integer>[] adj;
public... |
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 โค k โค n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the f... | from sys import stdin, stdout
n = int(stdin.readline())
c = [int(x) for x in stdin.readline().split()]
ops = []
turn = True
for x in range(n-1):
newC = []
newC2 = []
op = []
ind = c.index(x+1)
if turn:
if ind != 0:
op.append(ind)
op.append(n-x-ind)
op += [1]*x... |
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of ... | #include <bits/stdc++.h>
#include <random>
#include <chrono>
using namespace std;
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef ... |
Positive integer x is called divisor of positive integer y, if y is divisible by x without remainder. For example, 1 is a divisor of 7 and 3 is not divisor of 8.
We gave you an integer d and asked you to find the smallest positive integer a, such that
* a has at least 4 divisors;
* difference between any two di... | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define mod 1000000007
vector<int> v2;
bool prime[1000000];
void fun(int n)
{
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int p = 2; p <= n; p++)
{
... |
Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.
You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a ... | #include <bits/stdc++.h>
char s[800];
long long dp[800][800][3][3];
int match[800];
void find_match(int n) {
int stac[800], top = 0, i;
for (i = 0; i <= n; i++) {
if (s[i] == '(')
stac[++top] = i;
else {
match[i] = stac[top];
match[stac[top]] = i;
top--;
}
}
return;
}
void df... |
<image>
William is hosting a party for n of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.
For each William's friend i it is known whether he likes currency j. There are... | #include <stdio.h>
#include <algorithm>
#include <vector>
#include <memory.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <string.h>
#include <string>
#include <math.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
typedef long long ll;
const int INF = 1e9;
const int MOD = 1e9 ... |
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about ... | import java.util.*;
public class c
{
static boolean[][] graph;
static int[] w;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
char[] word = in.next().toCharArray();
w = new int[word.length];
for(int i = 0; i < w.length; i++)
w[i] = (int)(word[i]-'a');
graph = new boolean[... |
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.
A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers... | #include <bits/stdc++.h>
using namespace std;
int a[100005], b[100005], ans[100005];
int main() {
int mod, n, m, i, j, sum = 0;
scanf("%d %d %d", &n, &m, &mod);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
for (i = 0; i < m; i++) scanf("%d", &b[i]);
for (i = 0; i < n; i++) {
if (i < m) sum += b[i];
if ... |
You've got an n ร n ร n cube, split into unit cubes. Your task is to number all unit cubes in this cube with positive integers from 1 to n3 so that:
* each number was used as a cube's number exactly once;
* for each 1 โค i < n3, unit cubes with numbers i and i + 1 were neighbouring (that is, shared a side);
* ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 105;
inline int gi() {
char c = getchar();
while (c < '0' || c > '9') c = getchar();
int sum = 0;
while ('0' <= c && c <= '9') sum = sum * 10 + c - 48, c = getchar();
return sum;
}
int n, A[maxn][maxn][maxn];
int main() {
n = gi();
if (n == 1)... |
The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1 โค i โค n) element of the permutation a as ai, the j-th (1 โค j โค n) element of the permutation b โ as bj.
The distance between permutations a and b is the minimum absolute value of the dif... | #include <bits/stdc++.h>
using namespace std;
const int Maxn = 100 * 1000 + 10;
int n, inda[Maxn], indb[Maxn];
set<pair<int, int> > a, b, b1;
int main() {
scanf("%d", &n);
int aa;
for (int i = 0; i < n; i++) {
scanf("%d", &aa);
aa--;
inda[aa] = i;
}
for (int i = 0; i < n; i++) {
scanf("%d", &a... |
You've got a list of program warning logs. Each record of a log stream is a string in this format:
"2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes).
String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the ... | #include <bits/stdc++.h>
using namespace std;
int que[10000000];
char ss[10000000];
int day[13] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
int main() {
int n, m;
int head = 0, tail = 0;
int now;
int ye, mo, da, h, mi, s;
cin >> n >> m;
while (scanf("%d-%d-%d %d:%d:%d:", &ye, &mo, &da, &... |
Emuskald is an avid horticulturist and owns the world's longest greenhouse โ it is effectively infinite in length.
Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant o... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual soluti... |
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int i, m, n, y, x, a[106];
cin >> n;
for (i = 1; i <= n; ++i) cin >> a[i];
cin >> m;
for (i = 1; i <= m; ++i) {
cin >> x >> y;
a[x - 1] += y - 1;
a[x + 1] += a[x] - y;
a[x] = 0;
}
for (i = 1; i <= n; ++i) cout << a[i] << endl;
re... |
Vasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact).
Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive in... | #include <bits/stdc++.h>
using namespace std;
const int sq = 40 * 1000;
bool used[sq + 1];
const int G[30] = {0, 1, 2, 1, 4, 3, 2, 1, 5, 6, 2, 1, 8, 7, 5,
9, 8, 7, 3, 4, 7, 4, 2, 1, 10, 9, 3, 6, 11, 12};
int main() {
int n;
cin >> n;
int res = 0;
int after_sq = 0;
for (int i = 1; i <= sq;... |
Iahub does not like background stories, so he'll tell you exactly what this problem asks you for.
You are given a matrix a with n rows and n columns. Initially, all values of the matrix are zeros. Both rows and columns are 1-based, that is rows are numbered 1, 2, ..., n and columns are numbered 1, 2, ..., n. Let's den... | #include <bits/stdc++.h>
using namespace std;
const int N = 1002;
const int M = 123;
const double Pi = acos(-1);
const long long Inf = 1e18;
const int inf = 1e9;
const int mod = 1e9 + 7;
void add(int &a, int b) {
a += b;
if (a >= mod) a -= mod;
}
int mult(int a, int b) { return 1ll * a * b % mod; }
int n, m, t[2][2... |
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).
Input
The first line contains integers n and k (1 โค n โค 100, 0 โค k โค 9). The i-th ... | /**
* @author : Kshitij
*/
import java.io.*;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Set;
public class Main {
public static void main(String[] xps){
InputReader in = new InputReader(System.in);
Ou... |
There is a meteor shower on the sky and there are n meteors. The sky can be viewed as a 2D Euclid Plane and the meteor is point on this plane.
Fox Ciel looks at the sky. She finds out that the orbit of each meteor is a straight line, and each meteor has a constant velocity. Now Ciel wants to know: what is the maximum... | #include <bits/stdc++.h>
using namespace std;
int n, ans, an, cnt;
long double ti[1010];
struct Xn {
long double x, y, vx, vy;
} xn[1010], tmp;
struct Dn {
long double x, y;
} jd[1010];
inline long double cj(Dn u, Dn v) { return u.x * v.y - u.y * v.x; }
inline bool cmp(const Dn &u, const Dn &v) {
if (fabs(cj(u, v... |
Salve, mi amice.
Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus.
Rp:
I Aqua Fortis
I Aqua Regia
II Amalgama
VII Minium
IV Vitriol
Misce in vitro et รฆstus, et nil admirari. Festina lente, et nulla tenaci invia est via.
Fac... | import java.io.IOException;
import java.util.Scanner;
import static java.lang.Math.min;
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int a = nextInt();
int b = nextInt();
int c = nextInt();
int ... |
Have you ever played Pudding Monsters? In this task, a simplified one-dimensional model of this game is used.
<image>
Imagine an infinite checkered stripe, the cells of which are numbered sequentially with integers. Some cells of the strip have monsters, other cells of the strip are empty. All monsters are made of pu... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
const int MAXM = 2005;
int N, M;
int mon[MAXN];
int cell[MAXM];
int start[MAXN];
int use[MAXN];
int dp[MAXN];
int main() {
ios::sync_with_stdio(false);
cin >> N >> M;
for (int i = 0; i < N; i++) cin >> mon[i];
for (int i = 0; i < M; i++) cin... |
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.
You are given a weighted directed graph with n vertices and m edges. You need to find a path (perh... | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new Main().run(in, out);
out.close();
}
int N, M;
List<Edg... |
Jaroslav owns a small courier service. He has recently got and introduced a new system of processing parcels. Each parcel is a box, the box has its weight and strength. The system works as follows. It originally has an empty platform where you can put boxes by the following rules:
* If the platform is empty, then t... | #include <bits/stdc++.h>
using namespace std;
const int md = 1000000007;
const int maxn = 1100;
const long long inf = 2020202020202020202LL;
struct box {
int in, out, w, s, v;
};
int dp[1100][1100], n, s, subdp[1100];
vector<box> nice;
bool cmp(const box& a, const box& b) {
return a.in < b.in || a.in == b.in && a.o... |
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, tha... | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt(), m = s.nextInt();
int[] f = new int[n], count = new int[n], min = new int[n];
Vertex[] vs = new Vertex[n];
for (int i = 0; i < n; i++) {
... |
Polycarpus has a chessboard of size n ร m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of โโthe bo... | #include <bits/stdc++.h>
using namespace std;
int n, m, K, Q, pv[101000], IT[131072 + 131072 + 1];
vector<int> E[101000];
bool chk[201000];
struct point {
int x, y;
bool operator<(const point &p) const { return y < p.y; }
} w[201000];
struct Query {
int x1, x2, y1, y2, num;
bool operator<(const Query &p) const ... |
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (the... | #include <bits/stdc++.h>
using namespace std;
const long long M = 1e9 + 7;
int n, m, v, u, t, cnt, dis[100100];
long long ans = 1;
bool mark[100100];
vector<pair<int, int> > g[100100];
void dfs(int a) {
mark[a] = true;
for (int i = 0; i < g[a].size(); i++)
if (!mark[g[a][i].first]) {
dis[g[a][i].first] = ... |
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible.
Kefa knows that the i-th dish gives him ai units of satisfact... | #include <bits/stdc++.h>
using namespace std;
long long dp[262149][20];
long long kt[20];
long long s[20][20];
long long solve(long long mask, long long pr, long long n, long long t,
long long u) {
if (t == n) {
return ((long long)0);
}
if (dp[mask][pr] != -1) {
return dp[mask][pr];
}
... |
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network โ for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one r... | def bfs(l,st,en, dis):
vis, que = set(),[st]
t = 0
while que:
v = que.pop(0)
if v not in vis:
vis.add(v)
for ne in l[v]:
if ne not in vis:
que.append(ne)
if dis[ne] == 0:
dis[ne] = dis[v]+1
... |
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.
Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plas... | n=(int)(input());
a=(int)(input());
b=(int)(input());
c=(int)(input());
cnt=a;
cnt=0;
cnt1=a;
cnt1=(int)(n//a);
if (n<b):
while (n//b>0):
cnt+=n//b;
n-=(n//b)*b-n//b*c;
#print (n," ",cnt);
#print(n//a," ",cnt," ",cnt+n//a);
cnt+=n//a;
print((int)(max(cnt,cnt1)));
else:
n-=b;
... |
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.
For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the bigges... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import... |
Bearland is a dangerous place. Limak canโt travel on foot. Instead, he has k magic teleportation stones. Each stone can be used at most once. The i-th stone allows to teleport to a point (axi, ayi). Limak can use stones in any order.
There are n monsters in Bearland. The i-th of them stands at (mxi, myi).
The given k... | #include <bits/stdc++.h>
using namespace std;
template <typename tp>
inline void read(tp& x) {
x = 0;
char tmp;
bool key = 0;
for (tmp = getchar(); !isdigit(tmp); tmp = getchar()) key = (tmp == '-');
for (; isdigit(tmp); tmp = getchar()) x = (x << 3) + (x << 1) + (tmp ^ '0');
if (key) x = -x;
}
template <ty... |
Sasha has an array of integers a1, a2, ..., an. You have to perform m queries. There might be queries of two types:
1. 1 l r x โ increase all integers on the segment from l to r by values x;
2. 2 l r โ find <image>, where f(x) is the x-th Fibonacci number. As this number may be large, you only have to find it mod... | import java.util.*;
import java.io.*;
public class SashaandArray
{
/************************ SOLUTION STARTS HERE ***********************/
static final Matrix unit = new Matrix(1, 0, 0, 1);
static final Matrix fib = new Matrix(1, 1, 1, 0);
static final int mod = (int) (1e9) + 7; // Default
static Matrix DP0[] ... |
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.
Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose severa... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
int n, m;
cin >> n >> m;
vector<int> val(n);
for (auto &i : val) cin >> i;
int a, b;
long long res = 0;
for (int i = 0; i < m; ++i) {
cin >> a >> b;
long long t = 0;
for (int j = a - 1; j < b; ++j) t += ... |
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day cons... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m, z, c = 0;
;
vector<int> v;
cin >> n >> m >> z;
for (int i = 1; (i * n) <= z; i++) v.push_back(i * n);
for (int i = 1; (i * m) <= z; i++) {
if (binary_search(v.begin(), v.end(), i * m... |
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.
In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the oth... | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
int n, k1, k2;
int cnt[14005], edges[2], res[14005];
int a[7005], b[7005];
vector<int> rev[2];
bool visited[14005];
queue<int> q;
int main() {
ios_base::sync_with_stdio(0);
while (cin >> n) {
cin >> k1;
for (i... |
Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.
Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.
H... | #include <bits/stdc++.h>
using namespace std;
void solve() {
string s, t;
cin >> s >> t;
s = "#" + s;
t = "#" + t;
int n = s.length() - 1;
int m = t.length() - 1;
vector<vector<int>> go(m + 2, vector<int>(26));
vector<int> pi(m + 2);
vector<vector<int>> dp(n + 2, vector<int>(m + 2));
if (t.length() ... |
<image>
Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner.
Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabr... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 19;
char L[MAXN + 5], R[MAXN + 5];
int x[MAXN + 5], y[MAXN + 5];
int c[10], cc[10];
bool check_less(int i, int nz) {
if (i == MAXN) {
if (nz > 0)
return false;
else
return true;
}
for (int j = 0; j < y[i]; j++) {
if (cc[j] > 0)... |
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction <image> is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive comm... | import math
n=int(input())
d=n//2
c=n-d
while math.gcd(c,d)!=1:
c+=1
d-=1
print(d,c)
|
Nikita and Sasha play a computer game where you have to breed some magical creatures. Initially, they have k creatures numbered from 1 to k. Creatures have n different characteristics.
Sasha has a spell that allows to create a new creature from two given creatures. Each of its characteristics will be equal to the maxi... | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int s = 0, t = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') t = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
s = (s << 3) + (s << 1) + (ch ^ 48), ch = getchar();
return s * t;
}
const int N = 2e5 +... |
Pig is visiting a friend.
Pig's house is located at point 0, and his friend's house is located at point m on an axis.
Pig can use teleports to move along the axis.
To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost ... | n, m = list( map( int, input().split() ) )
A = []
B = []
CanReach = []
start_idx = 0
end_idx = 0
for i in range( n ):
a, b = list( map( int, input().split() ) )
A.append( a )
B.append( b )
memo = {}
def best( i ):
if A[i] <= m <= B[i]:
return ( True )
if i in memo:
return memo... |
Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.
Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water d... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 10 + 1e5;
const int MOD = 1e9 + 7;
int n, m;
int a[MAXN], c[MAXN];
void Inout() {
freopen(
"ABC"
".inp",
"r", stdin);
freopen(
"ABC"
".out",
"w", stdout);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
... |
Not to be confused with [chessboard](https://en.wikipedia.org/wiki/Chessboard).
<image>
Input
The first line of input contains a single integer N (1 โค N โค 100) โ the number of cheeses you have.
The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and... | import java.util.*;
public class cfCheeseboard {
static int f1(int n){
if(n==1){
return 1;
}
int x= (n%2==0) ? (n-1) : n;
return f1(n-1)+x;
}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
... |
A set of points on a plane is called good, if for any two points at least one of the three conditions is true:
* those two points lie on same horizontal line;
* those two points lie on same vertical line;
* the rectangle, with corners in these two points, contains inside or on its borders at least one point of... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int INF = INT_MAX;
const long long LINF = LLONG_MAX;
const int N = 1e4 + 20;
pair<int, int> a[N];
set<pair<int, int> > s;
int n;
void solve(int l, int r) {
if (r - l < 2) return;
int mid = (l + r) / 2;
solve(l, mid);
solve(mid, r);
i... |
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup... | import java.io.*;
import java.math.*;
import java.util.*;
public class B {
private void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
int[] r = a.clone();
int res = 0;
... |
One fine day, Benny decided to calculate the number of kilometers that she traveled by her bicycle. Therefore, she bought an odometer and installed it onto her bicycle. But the odometer was broken. It was not able to display the digit 3. This would precisely mean, that the odometer won't be able to display the numbers ... | import math
def distance_removal(n):
if n < 3:
return 0
digits = int(math.log10(n))
# print 'digits =', digits
num_count = int(10**digits) - int(9**digits)
p = int(10**digits)
msd = int(n/p)
# print 'n/p =', n//p
# print 'msd = ', msd
if msd > 3:
return (msd-1)*n... |
We all know that every positive integer can be represented as the sum of one or more odd integers.
For eg: 4 = 1 + 1 + 1 + 1. Now, your task in this question is to find out the value of G(n), which equals to the number of all possible representations, as described above, of the given integer, n. Since the answer coul... | fib_matrix = [[1,1],
[1,0]]
def matrix_square(A, mod):
return mat_mult(A,A,mod)
def mat_mult(A,B, mod):
if mod is not None:
return [[(A[0][0]*B[0][0] + A[0][1]*B[1][0])%mod, (A[0][0]*B[0][1] + A[0][1]*B[1][1])%mod],
[(A[1][0]*B[0][0] + A[1][1]*B[1][0])%mod, (A[1][0]*B[0][1] + A[1]... |
Vipul has N empty boxes, numbered from 1 to N, with infinite capacity. He performs M operations. Each operation is described by 3 integers, a, b, and k. Here, a and b are indices of the boxes, and k is the number of marbles to be added inside each box whose index lies between a and b (both inclusive). Can you tell the ... | s = raw_input().split(" ")
n = int(s[0])
m = int(s[1])
items = [0]*n;
for i in range(0,m):
s = raw_input().split(" ")
a = int(s[0])
b = int(s[1])
k = int(s[2])
for j in range(a-1,b):
items[j]=items[j]+k
sum=0
for j in range(0,n):
sum=sum+items[j]
print sum/n |
Ikshu and his prime matrix
Ikshu is in love with prime numbers. He has a matrix of size N X N and wants atleast 5 prime numbers in that matrix arranged like a cross as shown in figure. Let us call this matrix "new year matrix"
X ย X ย ย X Xย X
If matrix is not a "new year matrix" he can alter it with the operation a... | import math
def getPrime(Max):
used = [0] * Max
used[1] = 1
for i in xrange( 4, Max, 2 ):
used[i] = 1
for i in xrange( 3, int(math.sqrt(Max) + 1), 2 ):
if used[i] == 1:
continue
for j in xrange( i * i, Max, i ):
used[j] = 1
return used
... |
Marut is now a well settled person. Impressed by the coding skills of Marut, N girls wish to marry him. Marut will consider marriage proposals of only those girls who have some special qualities. Qualities are represented by positive non-zero integers.
Marut has a list of M qualities which he wants in a girl. He can a... | m = int(raw_input())
dict = {}
for i in raw_input().split(" "):
dict[int(i)] = 0
girls = 0
for j in range(input()):
count = 0
for e in raw_input().split(" "):
if int(e) in dict:
count+=1
if (count >= m):
girls+=1
print girls |
Quan_Lank is a great team with some uncommon interests in programming. Sometimes the team loves to solve strings puzzles, sometimes game puzzles and sometimes metrix type puzzles . Yesterday they have added a new interest to their list that is 'number theory' as they have solved some amazing puzzles related to number t... | t = int(raw_input())
def check(k,dict):
kk = str(k)
for char in kk:
if (dict.has_key(char) == True):
return True;
return False;
while (t>0):
i = int(raw_input())
j = str(i)
dict = {}
for char in j:
dict[char] = 1
k = 1;
count = 0;
while (k*k <= i):
if (i % k == 0):
if (check(k,dict) == True):
... |
Raghu and Sayan both like to eat (a lot) but since they are also looking after their health, they can only eat a limited amount of calories per day. So when Kuldeep invites them to a party, both Raghu and Sayan decide to play a game. The game is simple, both Raghu and Sayan will eat the dishes served at the party till ... | if __name__ == '__main__':
T = int(raw_input())
while T > 0:
[R, S, N] = [int(x) for x in raw... |
Shil is now finally in a relationship with Uttu. Both of them like to exchange love letters. However, to avoid exposing their relationship, they use "encryption" to send their messages. They use the famous Caesar cipher to encrypt their messages, which mathematically explained is as follows:
Encryption of a letter x b... | def find(s):
n=26-(ord(s[0])-ord('a'))
z="z"
out=""
for i in s:
if ord(i)+n <= ord(z):
out+=chr(ord(i)+n)
else:
x=ord(z)-ord(i)
y=n-x-1
out+=chr(ord('a')+y)
print out
if __name__ == '__main__':
t=int(raw_input())
while t>0:
s=raw_input()
find(s)
t-=1 |
HackerMan has a message that he has coded in form of digits, which means that the message contains only numbers and nothing else. He is fearful that the enemy may get their hands on the secret message and may decode it. HackerMan already knows the message by heart and he can simply destroy it.
But he wants to keep it ... | import string
t=int(raw_input())
while t:
s=[]
a,b=raw_input().split()
c=int(a[::-1])+int(b[::-1])
print string.lstrip(str(c)[::-1],'0')
t=t-1 |
There are 2N people numbered 1 through 2N. The height of Person i is h_i.
How many ways are there to make N pairs of people such that the following conditions are satisfied? Compute the answer modulo 998,244,353.
* Each person is contained in exactly one pair.
* For each pair, the heights of the two people in the pai... | #include <bits/stdc++.h>
#define MOD (int)(998244353)
using namespace std;
template <int mod = (int)(998244353)>
struct NTT {
int base, maxb, root;
vector<int> rv, roots, invr;
NTT() : base(1), rv({0, 1}), roots({0, 1}), invr({0, 1}) {
assert(mod >= 3 && mod & 1);
int tmp = mod - 1;
maxb = 0;
whi... |
Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to rig... | import sys
input = sys.stdin.readline
n = int(input())
l = list(map(int,input().split()))
l = [((i-1)//n, (i-1) % n) for i in l]
check = [[1]*n for i in range(n)]
d = [[min(i, n-i-1, j, n-j-1) for j in range(n)] for i in range(n)]
ans = 0
for x,y in l:
check[x][y] = 0
ans += d[x][y]
q = [(x,y,d[x][y])]
... |
We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N.
Determine whether the conditions below can be satisfied by assigning a color - white or black - to each v... | """
ๆใใใซ็ก็โๆๅฐใ2ใค็กใ or ๆๅฐๅๅฃซใใใขใซใชใฃใฆใชใ
(ๆๅฐใใๆฅ็ถใใ้ ็นใซๆๅฐใใชใ)
ๆบใใใฆใโๆๅฐใฎ่พบใ็ฝฎใใกใใใ
ๅฐใใๅฅดใใGreedyใซ็ฝฎใใฆใ๏ผ
่ชๅใฎๅจใใซendใใฆใใใค or ๅคงใใใๅใใใคใใใฃใใ็นใใกใใ
ใใฎใจใ็ฝ้ปใฏใฉใใงใ่ฏใใใ๏ผ
"""
import sys
N,M = map(int,input().split())
D = list(map(int,input().split()))
dic2 = [[] for i in range(N)]
for i in range(M):
U,V = map(int,input().split())
... |
You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.
When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where... | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
float a[n];
for(int i=0;i<n;i++) cin>>a[i];
sort(a,a+n);
if(n==1){
cout<<a[0]<<endl;
return 0;
}
double c=(a[0]+a[1])/2;
for(int i=2;i<n;i++){
c=(c+a[i])/2;
}
cout<<c<<endl;
} |
There are N mountains ranging from east to west, and an ocean to the west.
At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.
The height of the i-th mountain from the west is H_i.
You can certainly see the ocean from the inn at the top of the westmost mountain.
F... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] h = new int[N];
for (int i = 0; i < N; i++) {
h[i] = sc.nextInt();
}
int count = 1, max = h[0];
for (int i = 1; i < N; i++) {
if (h[i] >= max) {
ma... |
Niwango-kun is an employee of Dwango Co., Ltd.
One day, he is asked to generate a thumbnail from a video a user submitted.
To generate a thumbnail, he needs to select a frame of the video according to the following procedure:
* Get an integer N and N integers a_0, a_1, ..., a_{N-1} as inputs. N denotes the number of t... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
input = raw_input()
N = int(input)
aVec = raw_input().split(" ")
a = []
for i in aVec:
a.append(float(i))
#ๅนณๅใ็ฎๅบ
mean = sum(a) / N
#ๅนณๅใซๆใ่ฟใๅคใ็ฎๅบ(ๅนณๅใๅผใใใจใใฎๆๅฐๅคใๅบใ)
near_mean = []
for i in a:
near_mean.append(abs(i - mean))
#ๅนณๅๅคใซๆใ่ฟใๅคใฎใใฌใผใ ็ชๅท(0ๅงใพใ)ใๅบๅ
... |
We have an integer sequence A, whose length is N.
Find the number of the non-empty contiguous subsequences of A whose sums are 0. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from differ... | from collections import Counter
N = int(input())
A = list(map(int, input().split()))
B = [0]
for i in A:
B.append(B[-1] + i)
B_C = Counter(B)
ans = 0
for key, value in B_C.items():
ans += value * (value-1) // 2
print(ans)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.