input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
A message from humans to extraterrestrial intelligence was sent through the Arecibo radio telescope in Puerto Rico on the afternoon of Saturday November l6, l974. The message consisted of l679 bits and was meant to be translated to a rectangular picture with 23 × 73 pixels. Since both 23 and 73 are prime numbers, 23 × ... | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> make_prime(int N){
bool p[N+1];
memset(p, true, sizeof(p));
p[0] = p[1] = false;
for(int i = 0 ; i*i < N ; i++){
if(p[i]){
for(int j = 2*i ; j < N ; j += i){
p[j] = false;... |
Example
Input
4 6 5
-2 5
-2 -1
2 -1
2 5
-2 1
-2 0
0 0
0 -2
2 -2
2 1
Output
8 | #include<bits/stdc++.h>
#define inf 10010
#define linf 1e16
#define eps (1e-8)
#define mod 1000000007
#define pi acos(-1)
#define phi (1.0+sqrt(5))/2.0
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(),(a).end()
#define pd(a) printf("%.10f\n",(double)(a))
#define FOR(... |
Problem
There are N islands and M bridges. Numbers from 1 to N are assigned to each of the N islands. Numbers from 1 to M are also assigned to each of the M bridges.
Gaccho is currently on the first island (at time 0). Gaccho can move from the ai-th island to the bi-th island in one direction by using the i-th bridge... | #include <cstdio>
#include <climits>
#include <vector>
#include <queue>
constexpr int MAX_N = 100000;
constexpr int INF = INT_MAX;
template<class T>
using vec = std::vector<T>;
struct Edge {
int to, age;
Edge (int to, int age) : to{to}, age{age} {}
};
struct State {
int c, v;
State (int c, int v) : ... |
You are one of ICPC participants and in charge of developing a library for multiprecision numbers and radix conversion. You have just finished writing the code, so next you have to test if it works correctly. You decided to write a simple, well-known factorial function for this purpose:
<image>
Your task is to write ... | #include<iostream>
#include<string>
#include<cmath>
#include<algorithm>
using namespace std;
int N; string M;
int p[50]; long long power[20];
inline long long div(long long k, int m) {
long long sum = 0;
while (k >= 1) {
k /= m; sum += k;
}
return sum;
}
int main() {
while (true) {
cin >> N >> M; power[0] = 1;... |
Arthur is an innocent man who used to live on the Earth. He had lived a really commonplace life, until the day when the Earth was destroyed by aliens, who were not evil invaders but just contractors ordered to build a hyperspace bypass. In the moment when the demolition beams were shot at the Earth by them, Arthur was ... | #include<cstdio>
#include<complex>
#include<vector>
#include<cmath>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
typedef double Real;
typedef complex<Real> Point;
typedef complex<Real> Vector;
typedef pair<Point,Point> Segment;
typedef pair<Point,Point> Line;
typedef vector<Point> Pol... |
Equation
Identity
English text is not available in this practice contest.
In logical operations, only two types of values, T and F, are handled.
Let "-" be a unary operator (a symbol whose input represents one operation) and "*", "+", "->" be a binary operator (a symbol whose input represents two operations). "-" I... |
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class Main {
int INF = 1 << 28;
boolean val[];
String eq;
int p;
int MAX = 11;
void run() {
Scanner sc = new Scanner(System.in);
for(;;) {
eq = sc.next();
if( eq.equals("#") )break;
val = new boolean[MAX]... |
Problem Statement
You have just arrived in a small country. Unfortunately a huge hurricane swept across the country a few days ago.
The country is made up of $n$ islands, numbered $1$ through $n$. Many bridges connected the islands, but all the bridges were washed away by a flood. People in the islands need new bridg... | #include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef pair<int, int> P;
int main(){
int n;
while(cin >> n && n > 0){
if(n == 1){
cout << 0 << endl;
continue;
}
if(n == 2) {
int p1, t1, p2, t2;
... |
Example
Input
3
1 3 3
2
1 2
1 3
Output
5 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
class union_find {
public:
union_find(int n)
: par_(n, -1)
{}
void init(int n) {
par_.assign(n, -1);
}
int root(int x) {
return par_[x] < 0 ? x : par_[x] = root(par_[x]);
}
... |
You are playing a coin puzzle. The rule of this puzzle is as follows:
There are $N$ coins on a table. The $i$-th coin is a circle with $r_i$ radius, and its center is initially placed at ($sx_i, sy_i$). Each coin also has a target position: you should move the $i$-th coin so that its center is at ($tx_i, ty_i$). You c... | #include <bits/stdc++.h>
using namespace std;
using ld = long double;
constexpr ld eps = 1e-8;
using point = complex<ld>;
class segment {
public:
segment()
: a(point(0, 0)), b(point(0, 0))
{}
segment(point a_, point b_)
: a(a_), b(b_)
{}
point a, b;
};
class circle {
public:
... |
Problem
There are N sets of integers. Each of these sets is assigned a number from 1 to N. The number of elements in the i-th set is Ki, and the j-th smallest integer in the elements of the set is ai, j.
Taro decided to choose any number of sets from this. Taro, who thought it would be boring to just choose the right... | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define CIN_ONLY if(1)
struct cww{cww(){
CIN_ONLY{
ios::sync_with_stdio(false);cin.tie(0);
}
}}star;
#define fin "\n"
#define FOR(i,bg,ed) for(int i=(bg);i<(ed);i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
#defi... |
Find places where a R × C pattern is found within a H × W region. Print top-left coordinates (i, j) of sub-regions where the pattern found. The top-left and bottom-right coordinates of the region is (0, 0) and (H-1, W-1) respectively.
Constraints
* 1 ≤ H, W ≤ 1000
* 1 ≤ R, C ≤ 1000
* The input consists of alphabetica... | #include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cctype>
#include<cstdio>
#include<cassert>
using namespace std;
struct AhoCorasick {
static const int ALPHABET_SIZE = 62, root=0;
int index(char ch){
if(isupper(ch))return ch-'A';
if(islower(ch))return 26+ch-'a';
... |
Write a program which reads two integers x and y, and prints them in ascending order.
Constraints
* 0 ≤ x, y ≤ 10000
* the number of datasets ≤ 3000
Input
The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.
The input ends with two 0 (when both x and y... | while 1:
x, y = map(int, raw_input().split())
if (x == 0) and (y == 0):
break
elif x > y:
x, y = y, x
print x, y |
Problem Statement
A mountain hiker is descending from the mountain ranges. There are many mountains along his way each with it's own height. He will descend from
mountain only if the mountains' height ahead of him are Non Increasing.
You are given the height of the mountains ahead of you. Your task is to determine ... | import sys
T = int(raw_input())
while T > 0:
N = int(raw_input())
ans = 0
prev = None
#l = map(int, raw_input().split())
l = list(map(int,sys.stdin.readline().split()))
for i in range(N):
curr = l[i]
if i>0 and curr>prev:
ans += curr-prev
curr = prev ... |
Chef is on a vacation these days, so his friend Chefza is trying to solve Chef's everyday tasks.
Today's task is to make a sweet roll. Rolls are made by a newly invented cooking machine. The machine is pretty universal - it can make lots of dishes and Chefza is thrilled about this.
To make a roll, Chefza has to set all... | test_cases = int(raw_input())
for i in range(test_cases):
AB = raw_input().split()
A = int(AB[0])
B = int(AB[1])
counter = 0
while (A != B):
if (B%A == 0):
A=A*2
counter += 1
else:
A=A/2
counter += 1
print counter |
Chef has a rooted tree G, consisting of N vertices. Each edge of the tree has a color black or white.
Once Chef's friend Ksen offered Chef to play a game on the tree G. The game has very simple rule:
The players make moves in the game alternately.
On his move Chef deletes a single undeleted black edge. On her move Kse... | import random
class Ordinal(object):
def __init__(self, v, r = 0):
while (v&1)==0 and r > 0:
v >>= 1
r -= 1
self.v, self.r = v, r
def __repr__(self):
return '%d / 2^%d' % (self.v, self.r)
def __add__(self, o):
if isinstance(o, int):
o = O... |
Chef Ciel wants to put a fancy neon signboard over the entrance of her restaurant. She has not enough money to buy the new one so she bought some old neon signboard through the internet. Ciel was quite disappointed when she received her order - some of its letters were broken. But she realized that this is even better ... | for t in xrange(int(raw_input())):
line = list(raw_input())
length = len(line)
x = length-1
while x > 2:
tmp = [line[x], line[x-1], line[x-2], line[x-3]]
if (
(tmp[0] == '?' or tmp[0] == 'F') and
(tmp[1] == '?' or tmp[1] == 'E') and
(tmp[2] == '?' or t... |
There is a war going on between two countries and the enemy of your country depends heavily on the transportation of Weapons between two strategic points A and B. Point A and point B along with other points (C,D, etc... ) are connected by a network of roads. Disrupting all traffic between points A and B will give your ... | #!/usr/bin/env python
MAXN = 26
parent = [0] * MAXN
rank = [0] * MAXN
def UF_MakeSet():
for x in xrange(MAXN):
parent[x] = x
rank[x] = 0
def UF_Union(x, y):
xRoot = UF_Find(x)
yRoot = UF_Find(y)
if xRoot == yRoot:
return
if rank[xRoot] < rank[yRoot]:
pare... |
The game of billiards involves two players knocking 3 balls around
on a green baize table. Well, there is more to it, but for our
purposes this is sufficient.
The game consists of several rounds and in each round both players
obtain a score, based on how well they played. Once all the rounds
have been played, the tota... | t = int(raw_input())
scr1=0
scr2=0
ma = 0
flag = 0
for i in xrange(t):
s1,s2 = map(int,raw_input().split(' '))
scr1+=s1
scr2+=s2
if(scr1>scr2):
temp = scr1-scr2
if(temp > ma):
ma = temp
flag = 1
else:
temp = scr2-scr1
if(temp > ma):
ma = temp
flag = 2
print flag,ma |
Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction.
From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appea... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 5005;
const int INF = 0x3f3f3f3f;
int dp[maxn][3];
int high[maxn];
int cal1(int i) {
int ans = 0;
if (high[i] <= high[i - 1]) ans += (high[i - 1] - high[i] + 1);
if (high[i] <= high[i + 1]) ans += (high[i + 1] - high[i] + 1);
return ans;
}
int cal2(... |
Two players A and B have a list of n integers each. They both want to maximize the subtraction between their score and their opponent's score.
In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an elem... | import java.util.Collections;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Scanner;
/* Name of the class has to be "Main" only if the class is public. */
public class template {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Prio... |
There is a strip with an infinite number of cells. Cells are numbered starting with 0. Initially the cell i contains a ball with the number i.
There are n pockets located at cells a_1, …, a_n. Each cell contains at most one pocket.
Filtering is the following sequence of operations:
* All pockets at cells a_1, …, a... | #include <bits/stdc++.h>
using namespace std;
const int Maxn = 100000;
int m, n;
int a[Maxn + 5], p[Maxn + 5];
int x[Maxn + 5], k[Maxn + 5];
int e_pos[Maxn + 5], steps[Maxn + 5];
int Root[Maxn + 5];
struct Segment_Node {
int lson, rson;
int val;
} seg[Maxn * 25 + 5];
int id_tot;
void build(int &root, int left = 1, ... |
You are given array a of length n. You can choose one segment [l, r] (1 ≤ l ≤ r ≤ n) and integer value k (positive, negative or even zero) and change a_l, a_{l + 1}, ..., a_r by k each (i.e. a_i := a_i + k for each l ≤ i ≤ r).
What is the maximum possible number of elements with value c that can be obtained after one ... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void pr(vector<T> &v) {
for (int i = 0; i < (int)(v).size(); i++) cout << v[i] << " ";
cout << endl;
}
template <typename T>
void pr(vector<vector<T>> &v) {
for (int i = 0; i < (int)(v).size(); i++) {
pr(v[i]);
}
}
template <typename T>
voi... |
You are given an array a_1, a_2, ..., a_n of integer numbers.
Your task is to divide the array into the maximum number of segments in such a way that:
* each element is contained in exactly one segment;
* each segment contains at least one element;
* there doesn't exist a non-empty subset of segments such tha... | #include <bits/stdc++.h>
using namespace std;
using namespace std;
int n, x, everything = 0;
vector<int> basis;
int main() {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
cin >> n;
while (n--) {
cin >> x;
everything ^= x;
for (auto& i : basis) x = min(x, x ^ i);
if (x) basis.push_back(x);
... |
Little Petya loves training spiders. Petya has a board n × m in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to som... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int dp[45][64][64];
int ans;
bool get_bit(int a, int n) { return (a >> n) & 1; }
int set_bit(int a, int n) { return a | (1 << n); }
int reset_bit(int a, int n) { return a & ~(1 << n); }
int main() {
cin >> n >> m;
if (m > n) swap(n, m);
for (int i = 0; i <= ... |
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!
In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price o... | a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))
m=a[2]//(min(b))
p=m*max(c)+a[2]%min(b)
if(p>=a[2]):
print(p)
else:
print(a[2]) |
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points o... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int n;
vector<int> E[500005];
long long fac[500005], ans = 1;
void init() {
fac[0] = fac[1] = 1;
for (int i = 2; i <= 200000; ++i) {
fac[i] = fac[i - 1] * i % MOD;
}
}
void dfs(int u, int fa) {
int son = 0;
for (int &v : E[u]) {
... |
A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old d... | s=(raw_input()).split()
n=int(s[0])
k=int(s[1])
s=raw_input()
s=[ch for ch in s]
c=10*[0]
for i in range(len(s)):
j=int(s[i])
c[j]=c[j]+1
from string import join
def choosevalue(m):
global n,k,s,c
sol=[0,'']
if (c[m]>=k):
sol[1]=s
return sol
p=s[:]
remai... |
It is a holiday season, and Koala is decorating his house with cool lights! He owns n lights, all of which flash periodically.
After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters a_i and b_i. Light with parameters a_i and b_i will toggle (on to off, or off t... | #include <bits/stdc++.h>
using namespace std;
const int N = 105;
int n, a[N], b[N], st[N];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%1d", &st[i]);
for (int i = 1; i <= n; i++) scanf("%d%d", &a[i], &b[i]);
int ans = 0;
for (int i = 1; i <= 100000; i++) {
int sum = 0;
for (int j... |
You have two integers l and r. Find an integer x which satisfies the conditions below:
* l ≤ x ≤ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{5}).
Output
If an answer exists, print any of them. Oth... | l, r =map(int, input().split())
for i in range(l,r+1):
n = 0
a = str(i)
for j in a:
if a.count(j) == 1:
n = n+1
else:
pass
if n == len(a):
break
if n == len(a):
print(a)
else:
print('-1')
|
Two players decided to play one interesting card game.
There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
int x, y, k;
int num1 = -1, num2 = -1, num;
cin >> k >> x >> y;
for (int i = 0; i < x; i++) {
cin >> num;
num1 = max(num1, num);
}
for (int i = 0; i < y; i++) {
cin >> num;
num... |
[MisoilePunch♪ - 彩](https://www.youtube.com/watch?v=5VleIdkEeak)
This is an interactive problem!
On a normal day at the hidden office in A.R.C. Markland-N, Rin received an artifact, given to her by the exploration captain Sagar.
After much analysis, she now realizes that this artifact contains data about a strange f... | #include <bits/stdc++.h>
using namespace std;
int n, minID;
string res, key[3] = {"C", "H"};
void fill(int p, char F) {
res[p] = F;
minID = min(minID, p);
}
void query(char cmd, string trial) {
cout << cmd << " " << trial << '\n';
;
cout.flush();
if (cmd == '?') {
int T, p;
cin >> T;
for (int t ... |
The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces o... | #include <bits/stdc++.h>
#pragma GCC optimize("O3", "unroll-loops")
using namespace std;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
inline long long int gcd(long long int a, long long int b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
inline long long int lcm(long long int a,... |
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the s... | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
d = {}
maxd = 0
for x in a:
d[x] = d.get(x, 0) + 1
if d[x] > maxd:
maxd = d[x]
print(max(min(len(d)-1, maxd), min(len(d), maxd-1)))
|
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pill... | #!/usr/bin/env python3
import io
import os
from bisect import bisect
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_str():
return input().decode().strip()
def rint():
return map(int, input().split())
def oint():
return int(input())
def find_lu_value(th):
hi = bisect(h, th) - 1
... |
You're given an array of n integers between 0 and n inclusive.
In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).
For example, if the current array is [0, 2, 2, 1, 4], you can choose the second element and replace it... | #include <bits/stdc++.h>
using namespace std;
long long int smallestDivisor(long long int n) {
if (n % 2 == 0) return 2;
for (long long int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return i;
}
return n;
}
long long int max(long long int a, long long int b) { return a > b ? a : b; }
long long int min(lon... |
A running competition is going to be held soon. The stadium where the competition will be held can be represented by several segments on the coordinate plane:
* two horizontal segments: one connecting the points (0, 0) and (x, 0), the other connecting the points (0, y) and (x, y);
* n + 1 vertical segments, numbe... | #include <bits/stdc++.h>
using namespace std;
long long power(long long a, long long b) {
long long ans = 1;
while (b > 0) {
if (b & 1) {
ans = (ans * a) % 1000000007;
}
a = (a * a) % 1000000007;
b >>= 1;
}
return ans;
}
long long find(long long i, long long a[]) {
if (a[i] == i) return ... |
Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price n, Vova removes a non-empty substring of (cons... | //make sure to make new file!
import java.io.*;
import java.util.*;
public class C675{
public static long MOD = 1000000007L;
public static long[] fac;
public static long[] ifac;
public static long i2;
public static int MAX = 100005;
public static void main(String[] args)throws IOException{
... |
A median of an array of integers of length n is the number standing on the ⌈ {n/2} ⌉ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with 1. For example, a median of the array [2, 6, 4, 1, 3, 5] is equal to 3. There exist some other definitions of the median, but i... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int k;
cin >> k;
int ar[n * k];
for (int i = 0; i < n * k; i++) cin >> ar[i];
int step = n - ((n + 1) / 2);
long long int sum = 0;
n = n * k;
int i = n - step - 1;
... |
You are given three bags. Each bag contains a non-empty multiset of numbers. You can perform a number of operations on these bags. In one operation, you can choose any two non-empty bags, and choose one number from each of the bags. Let's say that you choose number a from the first bag and number b from the second bag.... |
// art by : Seoul_graffiti
// Last modified: 2021/01/08 22:44:15
#include <bits/stdc++.h>
using namespace std;
#define ERAGE(x) x.erase(unique(all(x)), x.end())
#define rall(x) x.rbegin(), x.rend()
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
#define show(x) cout << #x << " : " << x << "\n"
void no... |
This is an interactive problem.
Kochiya Sanae is playing with magnets. Realizing that some of those magnets are demagnetized, she is curious to find them out.
There are n magnets, which can be of the following 3 types:
* N
* S
* - — these magnets are demagnetized.
Note that you don't know the types of these... | #include <bits/stdc++.h>
using namespace std;
//.define
// #define FILE_IN_OUT
#define RET(_x) cout << (_x) << '\n'; return;
#define all(_obj) (_obj).begin(), (_obj).end()
#define loop(_n) for (int i = 0; i < (_n); ++i)
#define sz(_obj) static_cast<int>((_obj).size())
#ifdef SHJ_LOCAL
#define debug(_x) std::cerr << (#... |
Now you get Baby Ehab's first words: "Given an integer n, find the longest subsequence of [1,2, …, n-1] whose product is 1 modulo n." Please solve the problem.
A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly all) elements. The product of an empty subsequence is equal ... | import math
n=int(input())
ans=[]
prod=1
count=0
for i in range(1,n-1):
if math.gcd(n,i)==1:
ans.append(str(i))
prod=(prod*i)%n
count+=1
if n==2:
print(1)
print(1)
else:
if prod % n == 1:
print(count)
print(" ".join(ans))
else:
print(count+1)
print(" ".join(ans),n-1) |
Farmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is... | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.CollationElementIterator;
import java.util.*;
//changed
import javax.lang.model.type.IntersectionType;
import javax.print.attribute.standard.PrinterResolution;
... |
You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≤ j ≤ m) of sequence s means that you can choose an arbitrary position i (1 ≤ i ≤ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can par... | #include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
cin >> a;
int l = a.length(), i, j;
vector<string> s;
cin >> b;
int p = b.length();
s.push_back(b);
vector<int> visit(p, 0);
sort(s[0].rbegin(), s[0].rend());
j = 0;
for (i = 0; i < l; i++) {
if (((a[i] - 48) < (s[0][j] - ... |
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.
The park has n intersections numbered 1 through n. There are m bidir... | #include <bits/stdc++.h>
using namespace std;
long long mod_v(long long num) {
if (num >= 0)
return (num % 1000000007);
else
return (num % 1000000007 + 1000000007) % 1000000007;
}
long long bigmod(long long b, long long p, long long m) {
long long res = 1 % m, x = b % m;
while (p) {
if (p & 1) res =... |
Сity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right — the road network forms an undirected... | #include <bits/stdc++.h>
using namespace std;
struct fastIO {
inline fastIO operator>>(int& num) {
num = 0;
char c = getchar();
while (c != '-' && (c < '0' || c > '9')) c = getchar();
bool foo = 0;
if (c == '-') {
foo = 1;
c = getchar();
}
while (c >= '0' && c <= '9') {
n... |
Some days ago, WJMZBMR learned how to answer the query "how many times does a string x occur in a string s" quickly by preprocessing the string s. But now he wants to make it harder.
So he wants to ask "how many consecutive substrings of s are cyclical isomorphic to a given string x". You are given string s and n stri... | #include <bits/stdc++.h>
using namespace std;
const int N = (int)1e6 + 10, mod = (int)1e9 + 7;
int q, last, sz;
char s[N];
struct state {
int len, link, next[26], cnt;
};
vector<state> st;
vector<bool> vis;
vector<int> adj[2 * N];
void sa_init() {
st.resize(2 * N);
vis.resize(2 * N);
st[0].link = -1;
st[0].le... |
Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (m + 1) × (m + 1):
<image>
Maxim asks you to count, how many numbers m (1 ≤ m ≤ n) are there, such that the sum of values in the cells in the row number m + 1 of the resulting matrix equals t.
Expression (x xor y... | #include <bits/stdc++.h>
using namespace std;
long long dp[65][65][2];
int b[65];
int main() {
ios::sync_with_stdio(false);
cout.tie(0);
cin.tie(0);
long long n, t, cnt;
cin >> n >> t;
if (__builtin_popcountll(t) > 1) {
cout << 0;
return 0;
}
cnt = __builtin_ctzll(t) + 1;
cerr << cnt << endl;
... |
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.
You have a sequence of integers a1, a2, ..., an. In on... | def abs(x):
if x<0:
return 0-x
return x
n = input()
a = map(int,raw_input().split())
a.sort()
sum=0
for i in range(1,n+1):
sum+=abs(a[i-1]-i)
print sum |
One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him.
The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 20;
const long double inf = 1e18;
long double dp[maxn][2];
pair<pair<long long, long long>, pair<long long, long double> > a[maxn];
bool cmp(pair<pair<long long, long long>, pair<long long, long double> > a,
pair<pair<long long, long long>, p... |
Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of oth... | #include <bits/stdc++.h>
using namespace std;
void io_in_data() {
freopen("data.in", "r", stdin);
freopen("data1.out", "w", stdout);
}
template <class T>
void show(T *a, int n) {
for (int i = 0; i < n; i++) cout << a[i] << " ";
puts("");
}
int inLR(int a, int L, int R) { return a >= L && a <= R; }
int movR[] =... |
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tourname... | #include <bits/stdc++.h>
using namespace std;
int a[300005];
int main() {
int n, m, i, l, r, x;
set<int> s;
cin >> n >> m;
for (i = 1; i <= n; i++) s.insert(i);
for (i = 1; i <= m; i++) {
scanf("%d%d%d", &l, &r, &x);
for (set<int>::iterator it = s.lower_bound(l);
it != s.end() && (*it) <= r;)... |
Jack and Jill are tired of the New Year tree, now they've got a New Year cactus at home! A cactus is a connected undirected graph where any two simple cycles have at most one common vertex. In other words, this graph doesn't have any edges that lie on more than one simple cycle.
On the 31st of December they are going ... | #include <bits/stdc++.h>
using namespace std;
const int inf = 0xdddddddd, maxn = 2510;
int dp[maxn][maxn][3], pd[maxn][3], pd1[maxn][3][3], pd2[maxn][3][3], sz[maxn],
p[maxn], dfn[maxn], low[maxn], cnt, n, m, u, v;
vector<int> cyc, e[maxn];
void upd(int &a, int b) {
if (a <= b) a = b;
}
void cycle(int u, int v) {... |
Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the g... | first_row = input()
second_row = input()
third_row = input()
c = 0
o = 0
for i in range(0,3):
if first_row[i] == 'X':
c = c + 1
elif first_row[i] == '0':
o = o + 1
for i in range(0,3):
if second_row[i] == 'X':
c = c + 1
elif second_row[i] == '0':
o = o + 1
for i in range(... |
Sereja has two sequences a1, a2, ..., an and b1, b2, ..., bm, consisting of integers. One day Sereja got bored and he decided two play with them. The rules of the game was very simple. Sereja makes several moves, in one move he can perform one of the following actions:
1. Choose several (at least one) first elements... | #include <bits/stdc++.h>
using std::endl;
using std::make_pair;
using std::max;
using std::pair;
using std::set;
using std::upper_bound;
const int MAX_SEQ_SIZE = 100 * 1000;
const int MAX_NUM = 100 * 1000;
const int MAX_S = 300 * 1000;
const int MIN_E = 1000;
const int MAX_N = MAX_SEQ_SIZE;
const int MAX_M = MAX_SEQ_SI... |
Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy.
The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppos... | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class m6 {
static String s;
static int n;
static long DP[][][];
public static long call(int ind , int prev , int flag) {
if(ind==n && flag==0)
return 1;
if(ind==n)
return 0;
if(DP[in... |
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of di... | #include <bits/stdc++.h>
using namespace std;
int n, m, N, a[200500], b[200500], arr[200500 + 200500], z[200500 + 200500],
ans;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
if (n < m) {
cout << 0;
return 0;
}
if (m == 1) {
cout << n;
return 0;
}
for (int i = 1; i ... |
Malek is a rich man. He also is very generous. That's why he decided to split his money between poor people. A charity institute knows n poor people numbered from 1 to n. The institute gave Malek q recommendations. A recommendation is a segment of people like [l, r] which means the institute recommended that Malek give... | #include <bits/stdc++.h>
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1, T2> &left,
const std::pair<T1, T2> &right) {
Pred p;
return p(left.second, right.second);
}
};
using namespace std;
struct sol_t {
int start, ... |
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point — the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to l... | import java.io.*;
import java.util.*;
public class ProblemC {
InputReader in; PrintWriter out;
int n;
double[] ans = new double[5];
boolean ok(int[] a, double r) {
double from = a[0] - 1e-8;
double to = a[0] + 2 * r + 1e-8;
ans[0] = from + r;
int k = 0;
while (k ... |
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x > 1, such that n is divisible by x and replacing n with n / x. When n... | #include <bits/stdc++.h>
using namespace std;
int prime[5000001];
void SieveOfEratosthenes() {
int i, p;
for (i = 2; i < 5000001; i += 2) prime[i] = 2;
for (p = 3; p < 5000001; p += 2) {
if (!(prime[p])) {
prime[p] = p;
for (i = p * 3; i < 5000001; i += (2 * p)) prime[i] = p;
}
}
}
int aux[5... |
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.
Each player can double his bid any number of times and triple his bid any number of ... | import java.util.Scanner;
import java.util.Arrays;
public class Main{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int[] c = new int[n];
for(int i = 0 ; i < n ; i++){
... |
Today on a math lesson the teacher told Vovochka that the Euler function of a positive integer φ(n) is an arithmetic function that counts the positive integers less than or equal to n that are relatively prime to n. The number 1 is coprime to all the positive integers and φ(1) = 1.
Now the teacher gave Vovochka an arr... | #include <bits/stdc++.h>
using namespace std;
const int INF = 2 * int(1e9);
const long long INFll = 1ll * INF * INF;
const int MOD = 1000000007;
const int MAX_A = 1000001;
int lp[MAX_A];
vector<int> pr;
void findPrimes() {
for (int i = 2; i < MAX_A; ++i) {
if (!lp[i]) {
lp[i] = i;
pr.push_back(i);
... |
Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.
Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets a... | import math
n=raw_input().split()
t=[]
for i in range(int(n[0])):
a=raw_input().split()
mini=int(a[0])
for i in a:
if mini>int(i):
mini=int(i)
t.append(mini)
print max(t)
|
Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?
Input
The first line of the input contains two integers s and x (2 ≤ s ≤ 1012, 0 ≤ x ≤ 1012), the sum and bitwise xor of the pair of positive integers, respectively.
Output
Print a s... | #include <bits/stdc++.h>
using namespace std;
int main() {
unsigned long long s, x;
cin >> s >> x;
int delta = 2 * (s == x);
unsigned long long s1x1 = ((s & 1) << 1) | (x & 1);
unsigned long long c0 = (s1x1 == 0) + 2 * (s1x1 == 3);
unsigned long long c1 = s1x1 == 0;
for (int k = 0; k < 60; k++) {
x >>... |
You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.
Input
The only line of the input contains a re... | #include <bits/stdc++.h>
using namespace std;
vector<char> v;
int maxn = 200;
int main() {
int u[maxn];
string c = "?";
int x = 0, y = 1, n = 0, sum;
v.push_back('+');
while (c == "?" || c == "+" || c == "-" || c == "=") {
cin >> c;
if (c == "-") {
x++;
v.push_back('-');
}
if (c ==... |
Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.
Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Ar... | #include <bits/stdc++.h>
const long long mod = 1e9 + 7;
void fail() {
std::cout << "NO\n";
exit(0);
}
using namespace std;
const long long N = 502;
long long n, k, a[N];
bool dp[502][502][502];
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> k;
for (long long i = 1; i <= n; i++... |
You are given two arithmetic progressions: a1k + b1 and a2l + b2. Find the number of integers x such that L ≤ x ≤ R and x = a1k' + b1 = a2l' + b2, for some integers k', l' ≥ 0.
Input
The only line contains six integers a1, b1, a2, b2, L, R (0 < a1, a2 ≤ 2·109, - 2·109 ≤ b1, b2, L, R ≤ 2·109, L ≤ R).
Output
Print th... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:10240000,10240000")
using namespace std;
const double R = 0.5772156649015328606065120900;
const int N = 50 + 5;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = acos(-1.0);
long long gcd(long long a, long long b) { r... |
Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of n words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyp... | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 5e5 + 5;
const long long inf = 0x3f3f3f3f;
int a[2][maxn], num[maxn * 2];
int n, c;
void update(int l, int r) {
num[l]++;
num[r + 1]--;
}
int main(int argc, char const *argv[]) {
ios::sync_with_stdio(false);
int i, j, l, r, ans, tmpl, tmpr, tm... |
It's Christmas time! PolandBall and his friends will be giving themselves gifts. There are n Balls overall. Each Ball has someone for whom he should bring a present according to some permutation p, pi ≠ i for all i.
Unfortunately, Balls are quite clumsy. We know earlier that exactly k of them will forget to bring thei... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:32000000")
using namespace std;
inline bool read(int& val) { return scanf("%d", &val) != -1; }
inline bool read(long long& val) { return scanf("%I64d", &val) != -1; }
inline bool read(double& val) { return scanf("%lf", &val) != -1; }
inline bool read(char* val) {... |
Sherlock found a piece of encrypted data which he thinks will be useful to catch Moriarty. The encrypted data consists of two integer l and r. He noticed that these integers were in hexadecimal form.
He takes each of the integers from l to r, and performs the following operations:
1. He lists the distinct digits pr... | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int sum = 0;
char c = getchar();
bool f = 0;
while (c < '0' || c > '9') {
if (c == '-') f = 1;
c = getchar();
}
while (c >= '0' && c <= '9') {
sum = sum * 10 + c - '0';
c = getchar();
}
if (f) return -sum;
return sum;
}
... |
You have n devices that you want to use simultaneously.
The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.
You have a si... | #include <bits/stdc++.h>
using namespace std;
long double a[100005], b[100005], p;
int n;
bool chk(long double x) {
long double xa = p * x;
long double yb = 0;
for (int i = 0; i < n; i++) {
if ((a[i] * x) > b[i]) yb += ((a[i] * x) - b[i]);
}
if (xa >= yb)
return 1;
else
return 0;
}
long double t... |
Okabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points (x, y) such that x and y are non-negative. Okabe starts at the origin (point (0, 0)), and needs to re... | #include <bits/stdc++.h>
using namespace std;
const long long base = 1e9 + 7;
long long n, k;
struct line {
long long a, b, y;
} a[101];
struct matrix {
long long val[16][16];
matrix() { memset(val, 0, sizeof(val)); }
};
struct matran {
long long val[16];
matran() { memset(val, 0, sizeof(val)); }
};
matrix re... |
A game field is a strip of 1 × n square cells. In some cells there are Packmen, in some cells — asterisks, other cells are empty.
Packman can move to neighboring cell in 1 time unit. If there is an asterisk in the target cell then Packman eats it. Packman doesn't spend any time to eat an asterisk.
In the initial mome... | #include <bits/stdc++.h>
using namespace std;
string s;
vector<int> p;
bool check(int x) {
int ind = 0, i = 0;
while (1) {
while (ind < s.size() && s[ind] != '*') ind++;
if (ind >= s.size()) return true;
if (i >= p.size()) return false;
if (ind < p[i]) {
if (p[i] - ind > x) return false;
... |
The prehistoric caves of El Toll are located in Moià (Barcelona). You have heard that there is a treasure hidden in one of n possible spots in the caves. You assume that each of the spots has probability 1 / n to contain a treasure.
You cannot get into the caves yourself, so you have constructed a robot that can searc... | #include <bits/stdc++.h>
long long n, k, p, mo, gc, t, c, answ;
int ttt;
long long gcd(long long x, long long y) {
if (y == 0)
return (x);
else
return (gcd(y, x % y));
}
long long mi(long long aa, long long bb) {
long long s = 1;
while (bb != 0) {
if ((bb % 2) == 1) s = (s * aa) % mo;
aa = (aa *... |
Ralph is in the Binary Country. The Binary Country consists of n cities and (n - 1) bidirectional roads connecting the cities. The roads are numbered from 1 to (n - 1), the i-th road connects the city labeled <image> (here ⌊ x⌋ denotes the x rounded down to the nearest integer) and the city labeled (i + 1), and the len... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.Buffer... |
Let's call an array a of size n coprime iff gcd(a1, a2, ..., an) = 1, where gcd is the greatest common divisor of the arguments.
You are given two numbers n and k. For each i (1 ≤ i ≤ k) you have to determine the number of coprime arrays a of size n such that for every j (1 ≤ j ≤ n) 1 ≤ aj ≤ i. Since the answers can b... | #include <bits/stdc++.h>
using namespace std;
const long long mxDv = 7;
const long long mskDv = 1 << mxDv;
long long fpow(long long &a, long long b) {
if (b == 0) return 1;
if (b & 1) return (a * fpow(a, b ^ 1)) % 1000000007l;
long long d = fpow(a, b >> 1);
return (d * d) % 1000000007l;
}
void Solve() {
long ... |
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 ≤ fi ≤ n and fi ≠ i.
We call a love triangle a situation in which plane A likes plane... | n=int(input())
a=list(map(int,input().split()))
for i in range(n):
if a[a[a[i]-1]-1]==i+1:
print('YES')
exit(0)
print('NO')
|
You are given two integers a and b. Moreover, you are given a sequence s_0, s_1, ..., s_{n}. All values in s are integers 1 or -1. It's known that sequence is k-periodic and k divides n+1. In other words, for each k ≤ i ≤ n it's satisfied that s_{i} = s_{i - k}.
Find out the non-negative remainder of division of ∑ _{i... | import java.util.*;
import java.math.*;
import java.io.*;
public class CF964C implements Runnable {
final int MOD = (int) 1e9 + 9; // weird modulo
final double ERROR = 1e-9;
final double oo = 1e50;
long invA, c;
public void run() {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(Sys... |
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states:
XX XX .X X.
X. .X XX XX
Bishwocks don't attack any squares and can even occupy on the adjacent square... | def main():
a, b = [i for i in input()], [i for i in input()]
l = len(a)
c = 0
for i in range(l - 1):
if a[i] == '0':
if b[i] == '0':
if a[i + 1] == '0':
c += 1
a[i], b[i], a[i + 1] = 1, 1, 1
elif b[i + 1] == '0'... |
Arjit, Protector of The Realm, has an important task at hand. M new subjects are soon going to become a part of The Realm. The Realm, though, already has N subjects who are well skilled in the ways of The Realm. He wants the new subjects too to become perfect in the ways.
As any Protector would, Arjit also decides th... | T = int(raw_input())
for _ in xrange(T):
M, N = map(int,raw_input().split())
A = [0]*M
B = [0]*N
for i in xrange(M):
u,v = map(int,raw_input().split())
A[i] = (u,v)
for i in xrange(N):
w,x = map(int,raw_input().split())
B[i] = (w,x)
g,h = map(int,raw_input().split())
aa = a1 = dict()
bb = b1 = dict()
f... |
How many different ways can you make change for an amount, given a list of coins? In this problem, your code will need to efficiently compute the answer.
Task
Write a program that, given
An amount N and types of infinite available coins M.
A list of M coins - C={C1,C2,C3,..,CM}
Prints out how many different ways y... | sl = raw_input().split()
N,M = (int(sl[0]),int(sl[1]))
lis = map(int,raw_input().split())
arr = [[0]*M for _ in xrange(N+1)]
for i in xrange(M):
arr[0][i] = 1
for i in range(1,N+1):
for j in xrange(M):
x = arr[i-lis[j]][j] if i-lis[j] >=0 else 0
y = arr[i][j-1] if j>0 else 0
arr[i][j] = x+y
print arr[N][M-1] |
Nimbus, the techical festival of NIT Hanirpur is coming and thus Arun, the core-cordinator of departmental team of CSE, decided a conduct a game. In this game, the participant will be given a natural number N and will be asked T questions of form Type K.
Here Type denotes the type of question asked and K denotes a nat... | import math
N, noOfQueries = raw_input().split(" ")
N, noOfQueries = int(N), int(noOfQueries)
upperLimit = int(math.sqrt(N))
divisors = []
for i in range(1, upperLimit + 1):
if(N % i == 0):
divisors.append(N/i)
divisors.append(i)
for q in range(1, noOfQueries + 1):
t, k = raw_input().split(" ")
t, k = int(t... |
Ramesh and Suresh are best friends. But they are fighting over money now. Suresh has given some money to Ramesh but he has forgotten how much money he had given. So Ramesh made a plan that he will give Re. 1 to every rectangle Suresh makes in a N x M area. Since Suresh is poor in mathematics he needs your help to make ... | t=input()
while t:
n,m=map(int,raw_input().split())
print ((n*(n+1))/2)*(m*(m+1)/2)
t-=1 |
Little Syed loves brute force. He thinks that brute force can be the solution to any problem in the world. You give him any question, and he'll have a brute force answer ready for you, almost all the time. His good friend Little Jhool (Like, always!) decides to teach him a lesson, by giving him problems which cannot be... | tc = input()
sloane_list = [1729, 4104, 13832, 20683, 32832, 39312, 40033, 46683, 64232, 65728, 110656, 110808, 134379, 149389, 165464, 171288, 195841, 216027, 216125, 262656, 314496, 320264, 327763, 373464, 402597, 439101, 443889, 513000, 513856, 515375, 525824, 558441, 593047, 684019, 704977]
for i in range(0,tc):
n... |
Given two integers, L and R, find the maximal value of A xor B,
where A and B satisfy the following condition:
L ≤ A ≤ B ≤ R
Input Format:
First line contains T,number of test cases
following T lines containing 2 intergers L and R ; L is present in the first line and R in
the second line.
Output Format:
T lines ... | t=int(raw_input())
while t:
t-=1
m=0
l,r=map(int,raw_input().split())
for i in xrange(l,r+1):
for j in xrange(i,r+1):
m=max(m,i^j)
print m |
Pranav just learned about Modulus(%) and trying to solve a problem on Modulus but he always get TLE. Your task is to help him. Problem is simple, you have been given two numbers A and M and you have to find A%M and print it.
Input Format
Firstline: T, where T is the number of test cases. Now T line followed, Where e... | t=int(raw_input())
while t>0:
m,n=map(int,raw_input().split())
print(m%n)
t-=1 |
One day Samu went out for a walk in the park but there weren't any of her friends with her. So she decided to enjoy by her own. Samu noticed that she was walking in rectangular field of size N x M (units). So field can be divided into N horizontal rows, each containing M unit size squares. The squares have coordinates ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
print 'Hello World!'
'''
t = int(raw_input())
for i in range (t):
n,m=map(int,raw_input().split())
k=int(raw_input())
res=0
x,y=1,1
for j in range(k):
a,b=map(int,raw_input().split... |
Calculate the sum of the series :
INPUT:
First line contains the number of test cases t, for each test case a single line representing m and n with two space separated integers.
OUTPUT:
For each test case, a single line representing thee sum of the series in the form of p/q.
Constraints:
1 ≤ t ≤ 100
1 ≤ m, n ≤ 3... | def gcd(x, y):
while y != 0:
(x, y) = (y, x % y)
return x
t=(int)(raw_input())
for i in range(t):
m, n = [int(x) for x in raw_input().split()]
result=pow(2,m+n)
result1=(pow(2,n)-1)*(result);
result-=1
print str(result)+str('/')+str(result1) |
As the students are back in hostel after a long time, the gamers have decided to have a LAN gaming competition to find out who has utilized his time in gaming during vacations. They play "Counter ATOD". However, the scoring of this game is weird. There are N players and there are M rounds. Initially, each player has 0 ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
print 'Hello World!'
'''
n,m=raw_input().split()
n=int(n)
m=int(m)
x=[]
y=[]
M=0
for i in range(m):
name,pt=raw_input().split()
pt=int(pt)
if name not in x:
#print(name,pt)
x.append... |
You will be given a contest schedule for D days. For each d=1,2,\ldots,D, calculate the satisfaction at the end of day d.
Input
Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A.
D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,... | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;
int main() {
// const int C = 26;
int D;
cin >> D;
vector<int> C(26); // 0 to 25
rep(i, 26) {
cin >> C.at(i);
}
vector<vector<int>> S(D, vector<int>(26)); //... |
There are N stores called Store 1, Store 2, \cdots, Store N. Takahashi, who is at his house at time 0, is planning to visit some of these stores.
It takes Takahashi one unit of time to travel from his house to one of the stores, or between any two stores.
If Takahashi reaches Store i at time t, he can do shopping the... | #include<bits/stdc++.h>
#define sz(x) ((int)x.size())
#define pb push_back
#define ii pair<int,int>
#define ppb pop_back
#define orta ((bas+son)>>1)
#define st first
#define nd second
#define ll long long
#define N 200005
#define inf 1000000005
#define MOD 1000000007
#define LOG 29
#define EPS 0.000000001
#define M 305... |
The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)
We will close the window so as to minimize the total horizontal length of the uncovered part of the window. Fin... | A, B = map(int, raw_input().split())
print(max(0, A - 2 * B)) |
Snuke is playing with red and blue balls, placing them on a two-dimensional plane.
First, he performed N operations to place red balls. In the i-th of these operations, he placed RC_i red balls at coordinates (RX_i,RY_i). Then, he performed another N operations to place blue balls. In the i-th of these operations, he ... | #include<bits/stdc++.h>
using namespace std;
const int N=1e5+7,inf=1e9+7; bool fl[N];
int n,s,t,cnt,tot,ch[4],f[N],pre[N],que[N<<2];
long long sum,dis[N];
struct edge{int u,v,t,q,s;}ed[N<<1];
inline int read(){
int num=0; char g=getchar(); while(g<48||57<g) g=getchar();
while(47<g&&g<58) num=(num<<1)+(num<<3)+g-48,g=... |
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |... | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
vector<int> h(n),dp(n);
for(int i=0;i<n;i++) cin>>h[i];
dp[0]=0;
dp[1]=abs(h[1]-h[0]);
for(int i=2;i<n;i++){
dp[i]=min(dp[i-1]+abs(h[i]-h[i-1]),dp[i-2]+abs(h[i]-h[i-2]));
}
cout<<dp[n-1];
} |
You are given a string S consisting of lowercase English letters. We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom.
Constraints
* 1 \leq w \leq |S| \leq 1000
* S consists of lowercase E... | S = list(input())
w = int(input())
ans = S[::w]
for a in ans:
print(a, end="")
print()
|
A game is played on a strip consisting of N cells consecutively numbered from 1 to N.
Alice has her token on cell A. Borys has his token on a different cell B.
Players take turns, Alice moves first. The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or... | #include<iostream>
using namespace std;
int main(){
int n,a,b;
cin>>n>>a>>b;
cout<<(((a-b)%2==0)?"Alice":"Borys")<<endl;
} |
You are participating in a quiz with N + M questions and Yes/No answers.
It's known in advance that there are N questions with answer Yes and M questions with answer No, but the questions are given to you in random order.
You have no idea about correct answers to any of the questions. You answer questions one by one,... | #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cassert>
#define MOD 998244353
#define ll long long
using namespace std;
inline int read(){
int re=0,flag=1;char ch=getchar();
while(!isdigit(ch)){
if(ch=='-') flag=-1;
ch=getchar();
}
while(isdigit(ch)) re=(re<<1)+(re<<3)+ch-'0'... |
There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0. During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right. That is, if his coordinate at time i-1 is x, he can be a... | #include<iostream>
using namespace std;
int main() {
int x; cin >> x;
int now = 0, time = 0;
for (int i = 1; now < x; i++) {
now += i, time = i;
}
cout << time << endl;
return 0;
} |
Snuke is interested in strings that satisfy the following conditions:
* The length of the string is at least N.
* The first N characters equal to the string s.
* The last N characters equal to the string t.
Find the length of the shortest string that satisfies the conditions.
Constraints
* 1≤N≤100
* The lengths o... | import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws IOException {
Scan sc= new Scan();
int n =sc.scanInt();
String s = sc.scanString();
String t = sc.scanString();
String middle = "";
int i = 0;
for(; i < n; ++i){
... |
Using the given four integers from 1 to 9, we create an expression that gives an answer of 10. When you enter four integers a, b, c, d, write a program that outputs an expression that gives an answer of 10 according to the following conditions. Also, if there are multiple answers, only the first answer found will be ou... | #include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
bool calc(vector<char> op){
int st[4],sp=0;
rep(i,op.size()){
if('1'<=op[i]&&op[i]<='9'){
st[sp++] = op[i]-'0';
}
else{
if(sp<2)return false;
int a,b;
b=st[--sp];
... |
Aizu Gakuen High School holds a school festival every year. The most popular of these is the haunted house. The most popular reason is that 9 classes do haunted houses instead of 1 or 2 classes. Each one has its own unique haunted house. Therefore, many visitors come from the neighborhood these days.
Therefore, the sc... | #include <iostream>
#include <string>
using namespace std;
int main()
{
int i,j,k;
string n;
for(i=0;i<9;i++){
cin >> n >> j >> k;
cout << n << " " << j+k << " " << j*200+k*300 << endl;
}
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.