input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
We have a grid with N rows and N columns. The cell at the i-th row and j-th column is denoted (i, j).
Initially, M of the cells are painted black, and all other cells are white. Specifically, the cells (a_1, b_1), (a_2, b_2), ..., (a_M, b_M) are painted black.
Snuke will try to paint as many white cells black as poss... | #include<cstdio>
#define neko 100010
#define f(i,a,b) for(register int i=(a);i<=(b);i=-(~i))
#define travel(i,u,v) for(register int i=head[u],v=e[i].v;i;i=e[i].nex,v=e[i].v)
typedef long long ll;
int n,m,t,flag;
typedef int arr[neko];
arr head,col,book;
struct edge
{
int v,tp,nex;
}e[neko<<1];
ll ans,tot,cnt[5];
void ... |
There is data that records the altitude of mountains that have been climbed so far. Create a program that reads this data and outputs the elevation difference between the highest and lowest mountains.
Input
The input is given in the following format:
Mountain height
...
...
The height of the mountain is given o... | import sys
l = map(lambda i:float(i), sys.stdin)
print max(l) - min(l) |
Tetris is a game in which falling blocks are lined up on the board and erased. Here, let's consider a game that arranges it a little.
The size of the board of this game is 5 frames wide, and it is high enough to accommodate all the blocks that appear. The falling blocks are straight and come in two types, landscape an... | #include <iostream>
#include <vector>
using namespace std;
class TETORIS {
public:
int N;
vector<vector<int> > bd;
TETORIS() : N(0) {}
void put(int len, int pos) {
int k;
for (k=bd.size()-1; k>=0; --k) {
for (int i=0; i<len; ++i) {
if (bd[k][pos+i]) goto brk;... |
Computer graphics uses polygon models as a way to represent three-dimensional shapes. A polygon model is a model that creates a surface by giving the coordinates of vertices and how to connect those vertices.
A general polygon model can handle any polygon, but this time we will consider a polygon model consisting of t... | #include <bits/stdc++.h>
typedef long long ll;
#define ALL(a) a, a+sizeof(a)/sizeof(a[0])
#define all(a) a.begin(),a.end()
#define MOD 1000000007
using namespace std;
ll gcd(ll n, ll m) {
if (m == 0) return n;
return gcd(m, n % m);
}
ll lcm(ll n, ll m) {return m / gcd(n, m) * n;}
int main(void) {
ll n,ans=0;
stri... |
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, wh... | #include <set>
#include <iostream>
#include <cstdio>
#include <vector>
#include <climits>
#include <queue>
using namespace std;
int main(){
int n,k;
scanf("%d%d",&n,&k);
vector<int> c(n),r(n);
for(int i=0; i<n; i++) scanf("%d%d",&c[i],&r[i]);
vector<vector<int>> path(n,vector<int>());
for(int x,y,i=0; i<k; i++){
... |
As the proverb says,
> "Patience is bitter, but its fruit is sweet."
Writing programs within the limited time may impose some patience on you, but you enjoy it and win the contest, we hope.
The word "patience" has the meaning of perseverance, but it has another meaning in card games. Card games for one player are ca... | #include <iostream>
#include <algorithm>
#include <cassert>
#include <cctype>
#include <complex>
#include <cstdio>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
int N,c[20];
int f(int *c... |
You were lucky enough to get a map just before entering the legendary magical mystery world. The map shows the whole area of your planned exploration, including several countries with complicated borders. The map is clearly drawn, but in sepia ink only; it is hard to recognize at a glance which region belongs to which ... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
struct Pt {
T x, y;
Pt() : x(0), y(0) {}
Pt(const T x, const T y) : x(x), y(y) {}
template <class F> explicit operator Pt<F> () const {
return Pt<F>((F)x, (F)y); }
Pt operator+(const Pt b) const { return Pt(x + b.x, y + b.y); }
Pt o... |
Problem I Starting a Scenic Railroad Service
Jim, working for a railroad company, is responsible for planning a new tourist train service. He is sure that the train route along a scenic valley will arise a big boom, but not quite sure how big the boom will be.
A market survey was ordered and Jim has just received an ... | /* -*- coding: utf-8 -*-
*
* 1386.cc: Starting a Scenic Railroad Service
*/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#inclu... |
3D Printing
We are designing an installation art piece consisting of a number of cubes with 3D printing technology for submitting one to Installation art Contest with Printed Cubes (ICPC). At this time, we are trying to model a piece consisting of exactly k cubes of the same size facing the same direction.
First, usi... | #include <iostream>
#include <vector>
using namespace std;
int main()
{
while(true){
int n, k, s;
cin >> n >> k >> s;
if(n == 0 && k == 0 && s == 0) break;
int x[2001], y[2001], z[2001];
for(int i = 0; i < n; i++) cin >> x[i] >> y[i] >> z[i];
if(k == 1){
... |
In 20XX, many years of research have paid off, and wireless energy transmission and reception technology has been put into practical use. By using this technology, it has become possible to supply power to depopulated areas where it was not possible to draw power lines because the cost was not worth it. This technology... | #include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include... |
The customer telephone support center of the computer sales company called JAG is now in- credibly confused. There are too many customers who request the support, and they call the support center all the time. So, the company wants to figure out how many operators needed to handle this situation.
For simplicity, let u... | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <tuple>
#include <queue>
#include <list>
using namespace std;
// #define fprintf(...) void(0)
bool judge(int N, int T,
const vector< tuple<int, int, int> > &info, int O) {
priority_queue< int, vector... |
Mr. Morishita was in trouble ... I had Mr. Anehara write a program, but the program crashed.
Mr. Anehara wrote a program that reads the formula in Reverse Polish Notation and outputs the calculation result. According to the crash log, it seems that the cause was that it was divided by 0. This may be because Mr. Morish... | #include <iostream>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
using namespace std;
#define rep(i,n) for(int i = 0;i < n;i++)
#define each(i,n) for(auto i : n)
int main() {
int m;
cin >> m;
vector<string> c(m);
vector<int> l(m), r(m);
map<string, int> p;
p["+"] = -1;
p[... |
Problem Statement
Circles Island is known for its mysterious shape: it is a completely flat island with its shape being a union of circles whose centers are on the $x$-axis and their inside regions.
The King of Circles Island plans to build a large square on Circles Island in order to celebrate the fiftieth anniversa... | #include "bits/stdc++.h"
using namespace std;
using ld = long double;
const ld eps = 1e-9;
int N;
bool check(const vector<pair<ld, ld>>&cs, const ld amid) {
map<ld, int>mp;
for (auto c : cs) {
const ld r = c.second;
const ld x = c.first;
if (r > amid) {
ld dis = sqrt(r*r - amid*amid);
mp[x - dis]++;
... |
My futon
You bought N futons in preparation for your new life. The i-th futon has the warmth supply capacity of si. From the temperature forecast for the next M days, the warmth demand of dj is expected on the jth day. If the warmth is not enough or too much, the comfort will be impaired, so the absolute value of the ... | #include<algorithm>
#include<climits>
#include<cmath>
#include<cstring>
#include<deque>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<vector>
using namespace std;
using lint = long long;
using... |
Divide and rule
Taro, Hanako, and Jiro rule the JAG Kingdom together. There are N cities in the JAG Kingdom, some of which are connected by two-way roads. You can always reach all the other cities from any city via one or more roads.
One day, Taro and Hanako finally made a mistake and decided to share the city and go... | #include<bits/stdc++.h>
using namespace std;
#define lp(i,n) for(int i=0;i<n;i++)
int main(){
while(1){
int n,m;
cin>>n>>m;
if(n==0&&m==0) break;
vector<int> road[1000];
lp(i,n){
road[i].clear();
}
lp(i,m){
int a,b;
cin>>a>>b;
a--;
b--;
road[a].push_bac... |
Problem
There is a string $ S $ of length $ N $. All characters in $ S $ are numbers between 0 and 9.
When you make a sequence of $ \ frac {N \ times (N + 1)} {2} $, which is the number of terms created by enumerating all the numbers created from all the substrings of $ S $, Find the smallest value in $ H $.
Constrai... | //ランタイムエラーの原因が分からなかったので、もしやと思い、sortをstable_sortに書き換えたらAcceptedした。なぜsortではダメなのか、よくわからない…
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#define int long long
using namespace std;
typedef pair<int, int> P;
/*https://kimiyuki.net/blog/2016/04/09/arc-050-d/より引用*/
#define repeat(i,n) for (int ... |
Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.
Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] =... | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
class Main {
static int compare = 0;
static void merge(int[] A, int left, int mid, int right){
int l1 = mid-left;
int l2 = right-mid;
int[] L = new int[l1+1];
int[] R = new int[l2+1];
... |
Write a program which reads a word W and a text T, and prints the number of word W which appears in text T
T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive.
Constraints
* The length of W ≤ 10
* W consists of lower cas... | w=raw_input()
W=w.lower()
Text=[]
while True:
text=raw_input()
if text=='END_OF_TEXT':
break
Text.extend(text.split())
for i in range(len(Text)):
Text[i]=Text[i].lower()
print('%d'%Text.count(W)) |
In DDU's annual techno-cultural fest – Felicific, the Computer Engineering department is introducing a weird contest this time. In the contest, there are N registered participants, with heights h[1..N]. A coordinator speaks out a number K to all of them. The prize is awarded to any pair of participants whose heights ad... | from sets import Set;
def binsearch(arr,low,high,data) :
mid=(low+high)/2;
if low > high :
return -1;
if arr[mid] == data :
return mid;
elif arr[mid] < data :
return binsearch(arr,mid+1,high,data);
else :
retur... |
Suppose there is a X x Y x Z 3D matrix A of numbers having coordinates (i, j, k) where 0 ≤ i < X, 0 ≤ j < Y, 0 ≤ k < Z. Now another X x Y x Z matrix B is defined from A such that the (i, j, k) element of B is the sum of all the the numbers in A in the cuboid defined by the (0, 0, 0) and (i, j, k) elements as the diagon... | def removeTop(i,j,k):
return a[i-1][j][k] if i else 0
def removeBack(i,j,k):
return (a[i][j-1][k] - removeTop(i,j-1,k)) if j else 0
def removeSide(i,j,k):
return (a[i][j][k-1] - removeBack(i,j,k-1) - removeTop(i,j,k-1)) if k else 0
t = int(raw_input())
while t:
(i,j,k) = map(int, raw_input().split())
... |
Zucky has a frog Abby. Abby is very hungry and Zucky decides to feed it by playing a little game. Abby is a special frog which can jump as far as it wants but has a special pattern: He starts at the point 0.
In his first turn, he can make a jump of 1 unit. Now for all consequent turns, if the frog is currently at a dis... | t=input()
for i in range(t):
n=input()
s=0
a=[]
flag=0
a.append(1)
while(s<n):
for j in range(len(a)-1):
s+=a[j]
a.append(s)
for i in range(len(a)-1):
flag+=a[i]
if n==flag:
print True
else:
print False |
Little Egor is a huge movie fan. He likes watching different kinds of movies: from drama movies to comedy movies, from teen movies to horror movies. He is planning to visit cinema this weekend, but he's not sure which movie he should watch.
There are n movies to watch during this weekend. Each movie can be characterize... | for t in xrange(int(raw_input())):
n = int(raw_input())
l = map(int, raw_input().split())
r = map(int, raw_input().split())
ans = 0
m = 0
for i in range(n):
temp = l[i]*r[i]
if ((temp == m and r[i]>r[ans]) or temp>m):
m = temp
ans = i
print ans+1 |
Our Chef is catering for a big corporate office party and is busy preparing different mouth watering dishes. The host has insisted that he serves his delicious cupcakes for dessert.
On the day of the party, the Chef was over-seeing all the food arrangements as well, ensuring that every item was in its designated posi... | import sys
import math
t=int(input())
while t>0:
t=t-1
num=int(input())
mini=100000007
for i in range(1,int(math.sqrt(num))+1):
if num%i==0:
dif=abs(i-num/i)
if mini>dif :
mini=dif
dif=0
print(mini) |
Chef wants to implement wildcard pattern matching supporting only the wildcard '?'. The wildcard character '?' can be substituted by any single lower case English letter for matching. He has two strings X and Y of equal length, made up of lower case letters and the character '?'. He wants to know whether the strings X ... | t=int(raw_input())
while t>0:
rj=86
r=raw_input()
s=raw_input()
for i in xrange(len(r)):
if r[i]!=s[i]:
if r[i]!='?' and s[i]!='?':
rj=0
break
if rj==0:
print "No"
else:
print "Yes"
t=t-1 |
In "The Man in the High Castle" world, there are m different film endings.
Abendsen owns a storage and a shelf. At first, he has n ordered films on the shelf. In the i-th month he will do:
1. Empty the storage.
2. Put k_i ⋅ m films into the storage, k_i films for each ending.
3. He will think about a question:... | #include <bits/stdc++.h>
using namespace std;
int get() {
char ch;
while (ch = getchar(), (ch < '0' || ch > '9') && ch != '-')
;
if (ch == '-') {
int s = 0;
while (ch = getchar(), ch >= '0' && ch <= '9') s = s * 10 + ch - '0';
return -s;
}
int s = ch - '0';
while (ch = getchar(), ch >= '0' &... |
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is... | #include <bits/stdc++.h>
using namespace std;
int h[2011], e[2011], ne[2011], idx, d[2011];
bool st[2011];
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
void dfs(int x) {
st[x] = true;
for (int i = h[x]; ~i; i = ne[i]) {
int j = e[i];
if (!st[j]) {
cout << j << " " << x <<... |
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not o... | #include <bits/stdc++.h>
using namespace std;
int n, m, r, c, xx, yy;
char a[2005][2005];
deque<pair<pair<int, int>, pair<int, int>>> q;
int vis[2005][2005];
bool in(int x, int y) { return x <= n && x >= 1 && y <= m && y >= 1; }
int main() {
ios::sync_with_stdio(false);
cin >> n >> m >> r >> c >> xx >> yy;
for (i... |
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of... | import javafx.util.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class Prg1 {
PrintWriter pw = new PrintWriter(System.out);
Random rnd = new Random();
int a;
void run(){
a = ni()*2;
double s = ni();
HashMap<Integer, Integer> h = new HashMap<>();
... |
Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's".
The restaurant "Alice's" serves n kinds of food. The cost for the i-th kind is always c_i. Initially, the restaurant has enough ingredients for serving exactly a_i dishes of the i-th kind. In the New Year's Eve, m customers w... | import java.io.*;
import java.util.*;
public class B536
{
public static void main(String[] args) {
int n, m, t, d, i, pos;
long cost;
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
long[] a = new long[n];
long[] c = new long[n];
for(i=0; i<n; i++)
a[i]=sc.nextLong();
Map<Lon... |
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.
You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maxi... | n=int(input().strip())
numbers=list(map(int,input().strip().split(" ")))
numbers.sort()
start=0
current=0
l=[]
tot=0
while (current<len(numbers) and start<len(numbers)):
if(numbers[current]-numbers[start]>5):
start=start+1
l.append(tot)
tot-=1
else:
tot+=1
current+=1
if(l... |
Getting closer and closer to a mathematician, Serval becomes a university student on math major in Japari University. On the Calculus class, his teacher taught him how to calculate the expected length of a random subsegment of a given segment. Then he left a bonus problem as homework, with the award of a garage kit fro... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 4010, mod = (119 << 23) + 1;
int C[maxn], fac[maxn], ifac[maxn], inv[maxn];
inline int _C(int n, int k) {
if (k > n) return 0;
return 1ll * fac[n] * ifac[k] % mod * ifac[n - k] % mod;
}
int Pow(int a, int b) {
int ans = 1;
for (; b; b >>= 1, a = 1ll... |
You are given n intervals in form [l; r] on a number line.
You are also given m queries in form [x; y]. What is the minimal number of intervals you have to take so that every point (not necessarily integer) from x to y is covered by at least one of them?
If you can't choose intervals so that every point from x to y ... | #include <bits/stdc++.h>
using namespace std;
int n, m, fa[500005][21], l, r;
int main() {
scanf("%d%d", &n, &m);
while (n--) scanf("%d%d", &l, &r), fa[l][0] = max(fa[l][0], r);
for (int i = 1; i < 500005; i++) fa[i][0] = max(fa[i][0], fa[i - 1][0]);
for (int j = 1; j <= 20; j++)
for (int i = 0; i < 500005;... |
Alice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).
Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the ch... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n, k;
scanf("%d %d", &n, &k);
if (k % 3)
printf("%s\n", n % 3 ? "Alice" : "Bob");
else {
int r = n % (k + 1);
if (r < k && r % 3 == 0)
printf("Bob\n");
else
... |
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree — a connected undirected graph consisting of n vertices conne... | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> g;
vector<long long int> x;
long long int ans;
long long int gcd(long long int a, long long int b) {
return b ? gcd(b, a % b) : a;
}
void dfs(int u, map<long long int, int> vals, int p) {
map<long long int, int> nvals;
nvals[x[u]]++;
for (auto e ... |
You are given n integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the n numbers may not be chosen.
A rectangle (rectangular matrix)... | #include <bits/stdc++.h>
using namespace std;
ostream& operator<<(ostream& out, const pair<int, int>& p) {
out << '(' << p.first << ',' << p.second << ')';
return out;
}
template <typename T>
ostream& operator<<(ostream& out, const vector<T>& v) {
for (auto el : v) cout << el << ' ';
return out;
}
int max_divid... |
There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp.
You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it... | import java.util.*;
public class FightWithMonsters {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt(), a = s.nextInt(), b = s.nextInt(), k = s.nextInt();
List<Integer> list = new ArrayList<>();
int total = a + b;
int res = 0;
... |
A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to mo... | #include <bits/stdc++.h>
using namespace std;
int n;
vector<int> adj[3001];
int dis[3001];
bool visited[3001];
bool visited2[3001];
int par[3001];
bool dfs(int v, int p, queue<int>& q) {
par[v] = p;
for (int i = 0; i < adj[v].size(); i++) {
if (adj[v][i] == p) continue;
if (!visited[adj[v][i]]) {
visi... |
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes.
Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it.
2 coverings are different if some 2 triangles are covered by the same diamond shape in ... | import java.util.*;
import java.io.*;
public class Z_A {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t=in.nextInt();
for(int a=0;a<t;a++) {
int n=in.nextInt();
System.out.println(n);
}
}
}
|
Polygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0.
On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2... | def solve():
n = int(input())
polygon = [None for i in range(n)]
for i in range(n):
polygon[i] = list(map(int, input()))
for i in range(n - 2, -1, -1):
for j in range(i, -1, -1):
if polygon[i][j] == 1:
if polygon[i][j + 1] == 0 and polygon[i + 1][j] == 0:
... |
Let a and b be some non-negative integers. Let's define strange addition of a and b as following:
1. write down the numbers one under another and align them by their least significant digit;
2. add them up digit by digit and concatenate the respective sums together.
Assume that both numbers have an infinite n... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 998244353;
struct Two {
ll mat[2][2] = {};
ll &operator()(ll i, ll j) { return mat[i][j]; }
ll operator()(ll i, ll j) const { return mat[i][j]; }
Two operator*(const Two &rhs) {
Two res;
for (ll i = 0; i < 2; i++) {
... |
You are given an integer value x and a string s consisting of digits from 1 to 9 inclusive.
A substring of a string is a contiguous subsequence of that string.
Let f(l, r) be the sum of digits of a substring s[l..r].
Let's call substring s[l_1..r_1] x-prime if
* f(l_1, r_1) = x;
* there are no values l_2, r_2... | #include <bits/stdc++.h>
using ll = long long;
using P = std::pair<ll, ll>;
constexpr ll INF = 1ll << 60;
template <class T>
inline bool chmax(T& a, T b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <class T>
inline bool chmin(T& a, T b) {
if (a > b) {
a = b;
return 1;
}
return 0;
... |
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:
All of them take a sit at their round table, some of them with the golde... | #include <bits/stdc++.h>
signed main() {
long long n, m, c1 = 0, c2 = 0, t1, t2, i;
scanf("%lld%lld", &n, &m);
for (i = 1; i <= m; i++) {
scanf("%lld%lld", &t1, &t2);
c1 += t1 * t2;
c2 += t2;
}
if (c2 > n)
printf("-1\n");
else if (c2 == n) {
if (((1 + n) * n / 2) % n != c1 % n)
pri... |
There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.
A result of the elimination stage is the tota... | for k in range(int(input())):
a, b, c, d = input().split()
a, b, c, d = int(a), int(b), int(c), int(d)
if a+b >= c+d:
print(a+b)
else:
print(c + d)
|
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a mask of a positive integer n the number that is obtained after successive writing of... | #include <bits/stdc++.h>
using namespace std;
const int OO = INT_MAX;
const int MOD = 1e9 + 7;
const int N = 1e5 + 7;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int a;
string b;
cin >> a >> b;
reverse(b.begin(), b.end());
while (true) {
a++;
int x = a;
string s;
while (x > 0) {
... |
We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree.
Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are ... | import sys, os
from collections import defaultdict, deque
if os.environ['USERNAME']=='kissz':
inp=open('in2.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=sys.stdin.readline
def debug(*args):
pass
# SCRIPT STARTS HERE
def solve():
n,m=map(int,inp().... |
You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:
* has at least one red bean (or the number of red beans r_i ≥ 1);
* has at least one blue bean (or the number of blue beans b_i ≥ 1);
* the number of red and blue beans should diff... | from sys import stdin,stdout
I = lambda : map(int,stdin.readline().split())
import bisect
import math
from heapq import heappop, heappush
from collections import defaultdict, deque
# t = 1
def testcase():
a, b, d = I()
if a > b:
a,b = b,a
m = b/a
r = b%a
# print m, r, d
if b - a <= d * a... |
AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero):
* She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element ... | cases=int(input())
for idx in range(cases):
n=int(input())
a=list(map(int, input().split()))
b=list(map(int, input().split()))
if sum(a)!=sum(b): print(-1)
elif a==b: print(0)
else:
tuples=[]
count=0
for i in range(n):
if a[i]==b[i]: continue
if a[... |
"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anyb... | #include <bits/stdc++.h>
using namespace std;
bool vis[2009];
int d[2009];
char s[2009][2009];
struct Edge {
int v, next;
} edge[3000009];
int tot, n;
int head[2009];
inline void addedge(int u, int v) {
edge[tot].v = v;
edge[tot].next = head[u];
head[u] = tot++;
}
void bfs(int s) {
queue<int> q;
vis[s] = 1;... |
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have ... | import java.io.*;
import java.util.*;
public class C {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
boolean odd(int x) {
return (x & 1) == 1;
}
boolean test(int mask, int i) {
return ((mask >> i) & 1) == 1;
}
void solve() throws IOException {
int a1 = nextInt();
int a2 = ... |
The Bytelandian Institute for Biological Research (BIBR) is investigating the properties of two species of bacteria, named simply 0 and 1. Even under a microscope, bacteria of those two species are very difficult to distinguish. In fact, the only thing the scientists possess that is able to differentiate between them i... | #include <bits/stdc++.h>
using namespace std;
int calc(int x, int y, char c) {
if (c == '^') return x ^ y;
if (c == '&') return x & y;
if (c == '|') return x | y;
}
int get() {
char c = getchar();
if (c == '0') return 1;
if (c == '1') return 8;
if (c == '?') return 6;
int x = get(), y, z = 0;
c = getc... |
You have n friends and you want to take m pictures of them. Exactly two of your friends should appear in each picture and no two pictures should contain the same pair of your friends. So if you have n = 3 friends you can take 3 different pictures, each containing a pair of your friends.
Each of your friends has an att... | #include <bits/stdc++.h>
using namespace std;
struct Tire {
int b, size, son[2], num[31];
} t[51000 * 31];
int a[51000], n, tot = 1, ans, F;
long long m;
int Get(int i, int w) { return ((i & (1 << w))) ? true : false; }
void Insert(int a) {
int x = 1;
for (int i = 30; i >= 0; i--) {
t[x].size++;
for (int ... |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | n=int(input())
word=input()
count=0
for i in range(0,n-1):
if word[i]==word[i+1]:
count+=1
print(count)
|
Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate ... | #include <bits/stdc++.h>
using namespace std;
struct Node {
int x, y;
} A[510];
int B[510];
int F[510];
int L[510];
int n;
map<int, int> mm;
bool DFS(int i, int cnt) {
if (cnt == n) {
return true;
}
for (i = i; i < n; i++) {
if (F[i] != -1) continue;
int t = (i - 1 + n) % n;
if (F[t] == -1) {
... |
Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.
Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle ... | n=int(raw_input())
v=[0]*(101)
c=[]
for i in xrange(n):
a,b=map(int,raw_input().split(' '))
c.append((a,b))
v[i]=a
cnt=0
for i in xrange(n):
for j in xrange(n):
if i!=j and c[j][1]==v[i]:cnt+=1;break
print n-cnt |
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly,... | #include <bits/stdc++.h>
using namespace std;
long long bigmod(long long a, long long b) {
if (b == 0) {
return 1;
}
if (b % 2 == 0) {
long long r = bigmod(a, b / 2);
r = r * r;
r = r % 1000000009;
return r;
} else {
long long r = bigmod(a, b - 1);
r = r * a;
r = r % 1000000009;
... |
No Great Victory anniversary in Berland has ever passed without the war parade. This year is not an exception. That’s why the preparations are on in full strength. Tanks are building a line, artillery mounts are ready to fire, soldiers are marching on the main square... And the air forces general Mr. Generalov is in tr... | //package round35;
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Scanner;
public class E {
Scanner in;
PrintWriter out;
// String INPUT = "2 3 0 2 4 1 3";
String INPUT = "";
void solve()
{
int n = ni();
Building[] b = new Building[n];
... |
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1.
This tree has a special property: when a value val is added to a value of node i, the value -val is ... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 2e5 + 7;
vector<int> tree[MAX];
int idx[MAX];
int child[MAX];
int parity[MAX];
bool vst[MAX];
vector<int> euler;
void dfs(int node, int h = 0) {
vst[node] = true;
parity[node] = h & 1;
idx[node] = euler.size();
euler.push_back(node);
child[node] = ... |
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.
As the length of t... | [a,d] = [float(i) for i in raw_input().split()]
n = int(raw_input())
pos = [0,0]
for i in range(1,n+1):
fraction = i*d/(4*a)-int(i*d/(4*a))
#print fraction
if fraction >= 0 and fraction <= 0.25:
pos[1] = 0.0
pos[0] = fraction*4*a
elif fraction > 0.25 and fraction <= 0.5:
pos[0] ... |
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree.
A k-tree is an infinite rooted tree where:
* each vertex has exactly k children;
* each edge has some weight;
* if we look at the edges that goes ... |
import java.util.*;
public class DUFRESNE
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner Sc=new Scanner(System.in);
int s=Sc.nextInt();
int k=Sc.nextInt();
int d=Sc.nextInt();
int a[]=new int[s+1];
int b[]=new int[s+1];
for(int i=0;i<s+... |
Lord Tirek is a centaur and the main antagonist in the season four finale episodes in the series "My Little Pony: Friendship Is Magic". In "Twilight's Kingdom" (Part 1), Tirek escapes from Tartarus and drains magic from ponies to grow stronger.
<image>
The core skill of Tirek is called Absorb Mana. It takes all mana ... | #include <bits/stdc++.h>
using namespace std;
inline void read(int &x) {
int flg = 1;
char ch;
while (!isdigit(ch = getchar()))
if (ch == '-') flg = -flg;
for (x = ch - '0'; isdigit(ch = getchar()); x = x * 10 + ch - '0')
;
x *= flg;
}
const int MAXN = 100005;
const int MAXM = MAXN * 30;
const int inf... |
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a].
By <image> we denote the quotient of integer division of... | import java.util.*;
import java.io.*;
import java.lang.*;
public class Code73
{
private static long mod = 1000000007;
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputR... |
Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can... | import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
int n = nextInt();
char[] s = next().toCharArray();
int a = 0, b = 0;
for (int i = 0; i < n; i++) {
if (s[i] - '0' == i % 2)
++a;
else
++b;
}
out.print(Math.min(a, b));
}
... |
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarp... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 20020;
const int MAXT = 86400;
int n, m, t, a[MAXN], ans[MAXN], r, real_m, cnt[MAXN], last[MAXN];
queue<pair<int, int> > q;
set<pair<int, int> > cur_s;
int main() {
cin >> n >> m >> t;
for (int i = 0; i < n; ++i) {
int hh, mm, ss;
scanf("%d:%d:%... |
One of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names.
The friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name wil... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline T POW(T B, T P) {
if (P == 0) return 1;
if (P & 1)
return B * POW(B, P - 1);
else
return SQR(POW(B, P / 2));
}
template <class T>
inline T BMOD(T p, T e, T m) {
T ret = 1;
while (e) {
if (e & 1) ret = (ret * p) % m;
p =... |
Note the unusual memory limit for this problem.
You are given an undirected graph consisting of n vertices and m edges. The vertices are numbered with integers from 1 to n, the edges are numbered with integers from 1 to m. Each edge can be unpainted or be painted in one of the k colors, which are numbered with integer... | import java.io.*;
import java.util.*;
public class E_lowmem {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
DSU[] dsus;
int[] idxs;
int[] vals;
int ptr;
void set(DSU dsu, int idx, int val) {
if (dsu.p[idx] != val) {
dsus[ptr] = dsu;
idxs[ptr] = idx;
vals[ptr] = dsu.p[idx];... |
One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.
At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the heig... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, s = 1000000004, q = 0, c = 0, p = 0;
cin >> n;
bool o = true;
vector<int> v(n);
vector<int> v2(n + 1);
vector<int> v3(n);
for (int i = 0; i < n; ++i) {
cin >> v[i];
if (q < v[i]) {
q = v[i];
}
v3[i] = q;
}
for (int... |
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (<https://en.wikipedia.org/wiki/Seven-segment_display>).
<image>
Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find t... | #include <bits/stdc++.h>
int main() {
int a, b, i, j, count, n;
scanf("%d %d", &a, &b);
for (i = a, count = 0; i <= b; i++) {
for (n = i; n != 0;) {
j = n % 10;
if (j == 0 || j == 6 || j == 9) {
count = count + 6;
} else if (j == 1) {
count = count + 2;
} else if (j == ... |
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grassh... | #include <bits/stdc++.h>
using namespace std;
int n, now = 1, w[100005], dir[100005];
bool vis[100005];
char a[5];
string m;
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
if (m[i] == '<') {
dir[i + 1] = -1;
} else {
dir[i + 1] = 1;
}
}
for (int i = 1; i <= n; i++) {
cin >... |
Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.
More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a g... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, q;
scanf("%d %d", &n, &q);
pair<int, int> a;
a.first = 0;
a.second = 0;
for (int i = 0; i < q; i++) {
int t;
scanf("%d", &t);
if (t == 1) {
int x;
scanf("%d", &x);
if (x % 2 == 1 || x % 2 == -1) {
int v =... |
The Human-Cow Confederation (HC2), led by Heidi, has built a base where people and cows can hide, guarded from zombie attacks. The entrance to the base is protected by an automated gate which performs a kind of a Turing test: it shows the entering creature a photograph and asks them whether the top and bottom halves of... | #include <bits/stdc++.h>
using namespace std;
const int Maxn = int(1e6) + 256;
const int INF = int(1e9) + 7;
int main() {
ios_base ::sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
int dx, dy;
cin >> dx >> dy;
int px[600][600];
vector<int> px_sum(dx + 1, 0);
for (int i = 0; i < dx; i+... |
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.
When ZS the Coder is at level k, he can :
1. Pr... | import sys
from math import *
from fractions import gcd
readints=lambda:map(int, input().strip('\n').split())
n=int(input())
prev=2
for i in range(1,n+1):
nxt = (i*(i+1))**2
cur = (nxt-prev)//i
print(cur)
prev=int(sqrt(nxt))
|
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately.
Organizers are stil... | #include <bits/stdc++.h>
using namespace std;
long long n;
int main() {
scanf("%lld", &n);
long long f[3] = {1, 1, 2};
int idx = 1;
while (f[2] < n) {
f[0] = f[1];
f[1] = f[2];
f[2] = f[0] + f[1];
idx++;
}
if (f[2] > n) idx--;
printf("%d\n", idx);
}
|
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.
A common divisor for two positive numbers is a number which both numbers are divisible by.
But your teacher wants to give you a harder task, in this task... | #include <bits/stdc++.h>
using namespace std;
vector<int> cd;
int getRes(int lb, int rb) {
int low = 0, high = cd.size() - 1;
int res = -1;
while (low <= high) {
int mid = (low + high) >> 1;
int t = cd[mid];
if (t <= rb && t >= lb) {
low = mid + 1;
res = max(t, res);
} else if (t < lb)... |
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.
At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi ... | #include <bits/stdc++.h>
using namespace std;
const int N = 6e4 + 10;
int n;
double x[N], v[N];
double l = 0, r = 1e9;
int pd(double t) {
double l = 0, r = 1e9;
for (int i = 1; i <= n; i++) {
double ll = x[i] - v[i] * t, rr = x[i] + v[i] * t;
if (ll <= r)
l = max(l, ll);
else
return 0;
i... |
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.
Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.
Note th... | #include <bits/stdc++.h>
using namespace std;
const int mx = 100005;
bool flag[mx], sqr[mx];
vector<long long> divs[mx];
long long prmdivs[mx], ara[mx];
void sieve() {
long long i, j, k;
for (i = 2; i < mx; i++) {
if (sqr[i]) continue;
if (!flag[i]) {
for (j = i; j < mx; j += i) {
prmdivs[j]++... |
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be ... | 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... |
You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest.
The track's map is represented by a rectangle n × m in size divi... | #include <bits/stdc++.h>
using namespace std;
inline int GetBit(int mask, int num) { return (mask >> num) & 1; }
inline int GetAmountOfBits(int mask) {
int ans = 0;
while (mask > 0) {
ans += (mask & 1);
mask >>= 1;
}
return ans;
}
const int kAlphabetSize = 26;
const int kDx[4] = {-1, 0, 0, 1};
const int... |
You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length of the longest balanc... |
import java.util.*;
import java.io.*;
public class Solution {
static FastScanner scr=new FastScanner();
// static Scanner scr=new Scanner(System.in);
static PrintStream out=new PrintStream(System.out);
static StringBuilder sb=new StringBuilder();
static class pair{
int x;int y;
pair(int x,int y){
t... |
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, a, o = 0, t = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a;
if (a == 1) {
o++;
} else {
t++;
}
}
if (t == n) {
cout << 0 << "\n";
} else if (o == n) {
cout << n / 3 << "\n";
} else {
if (o > t)... |
There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.
The i-th walrus becomes displeased if there's a younger walrus stan... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class A {
public static void main(String[] args) throws IOException {
... |
We call an array almost increasing if we can erase not more than one element from it so that the array becomes strictly increasing (that is, every element is striclty greater than every element before it).
You are given an array a consisting of n elements. You are allowed to replace any element with any integer number... | #include <bits/stdc++.h>
using namespace std;
const int dx44[5] = {0, -1, -1, 1, 1};
const int dy44[5] = {0, -1, 1, -1, 1};
const int dx4[5] = {0, -1, 0, 1, 0};
const int dy4[5] = {0, 0, 1, 0, -1};
const int dx8[9] = {0, -1, 0, 1, 0, 1, 1, -1, -1};
const int dy8[9] = {0, 0, 1, 0, -1, 1, -1, 1, -1};
const int maxn = 2e5... |
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering.
Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and othe... | #include <bits/stdc++.h>
using namespace std;
using cd = complex<long double>;
int main() {
int n, q;
cin >> n >> q;
vector<cd> v(n);
for (auto& x : v) {
long double p, q;
cin >> p >> q;
x = cd{p, q};
}
cd delta = v[0];
for (auto& x : v) x -= delta;
cd cog = 0;
long double area = 0;
for ... |
Allen and Bessie are playing a simple number game. They both know a function f: \{0, 1\}^n → R, i. e. the function takes n binary arguments and returns a real value. At the start of the game, the variables x_1, x_2, ..., x_n are all set to -1. Each round, with equal probability, one of Allen or Bessie gets to make a mo... | #include <bits/stdc++.h>
using namespace std;
double a[1000010], x, ans;
int main() {
int N, R, W, i, j;
scanf("%d%d", &N, &R);
W = 1 << N;
for (i = 0; i < W; i++) scanf("%lf", &a[i]), ans += a[i];
printf("%.10lf\n", ans / W);
for (i = 1; i <= R; i++) {
scanf("%d%lf", &j, &x);
ans -= a[j];
a[j] ... |
Aklank is fond of numbers which are divisible by either P1 or P2. He termed those numbers as Bakku numbers. Recently his best friend gave him a range of numbers. Now he is wondering what is the probability of finding Bakku numbers from that range of numbers.
Input
First line of input contains two integers P1 and P2 (2... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
from sys import stdin
ar = map(int, stdin.readline().strip().split())
p1 = ar[0]
p2 = ar[1]
t = int(stdin.readline().strip())
#print p1, p2, t
for i in xrange(0, t, 1):
ar = map(int, s... |
Aniruddha and Andrew are playing a Game on Christmas Eve named "Christmas-Gamecon". In this they are given a list of numbers.
In each turn alternatively one will select any one number from the list and decrease it by 1,2,3 or 4.
The last person who is unable to decrease the number loses the game.
At last all the number... | def main():
test_cases = int(raw_input())
for _ in xrange(test_cases):
n = int(raw_input())
list1 = raw_input().split()
list2 = []
for i in xrange(n):
list2.append(int(list1[i])%5)
XOR = list2[0]
for i in xrange(1, n):
XOR = XOR ^ list2[i]
if XOR == 0:
print "Andrew"
else:
print "Aniru... |
View Russian Translation
In this problem the goal is to implement a program managing an elevator designed especially for mathematicians.
The elevator can go to any of N floors numbered from 1 to N and it can carry an arbitrary number of people at one time.
Initially the elevator is at floor 1, without any people in... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
import math
HUGE = 10**9 + 7
def _try_composite(a, d, n, s):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
re... |
You will be given a list of space separated integers, your task is to form a min-heap tree from the given set of inputs and display the root element of the Min-heap formed.
Input
A list of n Space separated integers.
Output
Root element of the Min-Heap formed.
Constrains
1 ≤ n ≤ 100
where n is the number of inte... | print sorted(map(int, raw_input().split()))[0] |
Golu wants to find out the sum of Lucky numbers.Lucky numbers are those numbers which contain exactly two set bits.This task is very diffcult for him.So Help Golu to find sum of those numbers which exactly contain two set bits upto a given number N.
3 5 10 are lucky numbers where 7 14 are not.
INPUT First line contai... | import math, bisect
temp , a , b , A , F = 1, [], [], [], {}
while temp < 10**20:
a.append(temp)
temp=temp*2
for i in range(len(a)):
for j in range(i+1,len(a)):
b.append(a[i] + a[j])
b = sorted(b)
for i in range(len(b)):
if(i==0): A.append(b[i])
else: A.append(A[i-1] + b[i])
# print A[i]
for _ in range(input()):... |
Nandu is stuck in a maze consisting of N rooms. Each room with room number x has a door leading into room number 2x (if 2x ≤ N) and another door leading into room number 2x+1 (if 2x+1 ≤ N). All these doors are 2-way doors ie. they can be opened from both the sides.
Some of these N rooms have monsters living in them.
... | N, Q = [int(_) for _ in raw_input().split()]
maze = raw_input()
for i in range(Q):
s, e = [int(_) for _ in raw_input().split()]
s, e = max(s, e), min(s, e)
if maze[s-1] == '1' or maze[e-1] == '1':
print 'No'
else:
ans = True
while s != e:
if s < e:
s, e = e, s
else:
s /= 2
if maze[s-1] == '1... |
The penultimate task involved the calculation of the typical Fibonacci sequence up to the nth term.
Input – single integer n
Output – Fibonacci sequence up to the nth term, all terms on a new line
SAMPLE INPUT
5
SAMPLE OUTPUT
1
1
2
3
5 | '''
# 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!'
#cout << fixed << setprecision(0) << fmod(((pow(1.6180339,i)-(pow(-0.6180339,i))) / 2.236067977) , pow(10,9)+7) << endl
n = int(raw_input())
i = 1
while (i <= n)... |
Shantam is very rich , even richer than Richie Rich. He is extremely talented in almost everything except one , mathematics. So one day, he pays a visit to a temple (to pray for his upcoming mathematics exams) and decides to donate some amount of money to the poor people ( everyone is poor on a relative scale to Shant... | for _ in range(int(raw_input())):
n,t=map(int,raw_input().split())
l,r,c,p,q,s=map(int,raw_input().split())
a=[0]*(n+5)
for i in range(t):
#l,r,c=map(int,raw_input().split())
if i:
temp=l
l= (l* p + r) % n + ... |
Cleartrip decided that they wanted to verify the username and password of its users while they were authenticating for a process. One of the code service forms a GET URL which contains the username and password as its parameters. While parsing the URL, the code needs to extract the key-value pairs of ALL the parameters... | inp=raw_input()
P=inp.split('?')
P1=P[0]
P2=P[1]
A=[]
V=['username','pwd','profile','role','key']
for i in xrange(len(V)):
if(i==len(V)-1):
A.append(P2[P2.index(V[i]):])
else:
A.append(P2[P2.index(V[i]):P2.index(V[i+1])-1])
for i in A:
extract=i.split('=')
print i.replace('=',': ',1) |
Xenny was a teacher and his class consisted of N boys and N girls. He took all his students to the playground and asked them to stand in a straight line. The boys and the girls formed a perfect line, but Xenny seemed unhappy. He wanted them to form an alternating sequence of boys and girls, i.e., he wanted that after a... | def func(typ,k,bg):
count=0
if typ==0:
for i in range(len(k)):
if k[i]!=bg[i]:
count+=1
return count/2
if typ==1 or typ==2:
b=[]
g=[]
for i in range(len(k)):
if k[i]!=bg[i]:
if k[i]=='B':
b.ap... |
Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.
Some of the squares have a lotus leaf on it and cannot be entered. The square (i,j) has a lotus leaf on i... | from collections import deque
dxdy = ((-1,0), (1,0), (0,-1), (0,1)) # タプルやリストで持っておくと便利
H, W, K = map(int,input().split())
x1, y1, x2, y2 = map(int,input().split())
mp = [input() for _ in range(H)]
INF = 10**10
dist = [[INF]*W for _ in range(H)]
dist[x1-1][y1-1] = 0
q = deque()
q.append((x1-1,y1-1)) # スタート地点をenqueue
wh... |
We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.
Print all strings that are written on the most number of votes, in lexicographical order.
Constraints
* 1 \leq N \leq 2 \times 10^5
* S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.
* The length of S... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.TreeMap;
public class Main {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integ... |
Snuke has permutations (P_0,P_1,\cdots,P_{N-1}) and (Q_0,Q_1,\cdots,Q_{N-1}) of (0,1,\cdots,N-1).
Now, he will make new permutations A and B of (0,1,\cdots,N-1), under the following conditions:
* For each i (0 \leq i \leq N-1), A_i should be i or P_i.
* For each i (0 \leq i \leq N-1), B_i should be i or Q_i.
Let u... | #include<bits/stdc++.h>
using namespace std;
const int N=2e5+9;
struct graph{
struct edge{int to,next,f;}e[N<<1];
int h[N],cur[N],xb;
inline void addedge(int x,int y,int z){
e[++xb]=(edge){y,h[x],z};h[x]=xb;
e[++xb]=(edge){x,h[y],0};h[y]=xb;
}
int S,T,d[N],n;
inline bool bfs(){
static int q[N];int t=0,w=1;q... |
Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:
1. Throw the die. The current score is the result of the die.
2. As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each t... | import sys
range = xrange
input = raw_input
N,K = [int(x) for x in input().split()]
prob = 0
for k in range(1,N+1):
p = 1.0/N
score = k
while score < K:
score *= 2
p /= 2
prob += p
print `prob`
|
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. Here, h_1 < h_2 < \cdots < h_N holds.
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 one of ... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 200005;
long long h[MAXN], dp[MAXN];
long double f(int i, int j)
{
return (dp[i] - dp[j] + h[i]*h[i] - h[j]*h[j]) / (2.0 * (h[i]-h[j]));
}
int main()
{
int n;
long long c;
scanf("%i%lli", &n, &c);
for (int x = 1; x <= n; x++)
... |
Takahashi has a tower which is divided into N layers. Initially, all the layers are uncolored. Takahashi is going to paint some of the layers in red, green or blue to make a beautiful tower. He defines the beauty of the tower as follows:
* The beauty of the tower is the sum of the scores of the N layers, where the sco... | #include <iostream>
#include <stdio.h>
#include <string.h>
#define MAX_N 300005
#define MOD 998244353
#define int long long
using namespace std;
int n,a,b,K,ans=0;
int f[MAX_N];
int inf[MAX_N];
void exgcd(int a,int b,int &x,int &y)
{
if(b==0)
{
x=1,y=0;
return;
}
exgcd(b,a%b,y,x);
y-=(a/b)*x;
}
int inv(int... |
For strings s and t, we will say that s and t are prefix-free when neither is a prefix of the other.
Let L be a positive integer. A set of strings S is a good string set when the following conditions hold true:
* Each string in S has a length between 1 and L (inclusive) and consists of the characters `0` and `1`.
* A... | #include <bits/stdc++.h>
#define LL long long
const int N = 200101;
int n, cnt = 1, ch[N][2], len[N];
LL L;
bool num[111];
char s[200001];
int lowbit(LL x)
{
int r = 0;
for(;!(x & 1); r++, x >>= 1);
return r;
}
void ins(int u, int id, int d, int leng) {
if (ch[u][s[len[id] + d - 1] - '0'] == 0) {
ch[u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.