input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.
Print the answer in degrees, but do not print units.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print an integer representing the sum of th... | a = int(input())
print(int(a * 180 - 360)) |
There are N items, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.
Taro has decided to choose some of the N items and carry them home in a knapsack. The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.
Find ... |
#include <bits/stdc++.h>
using namespace std;
#define fo(i,ini,n) for(int i=ini;i<n;i++)
#define rfo(i,ini,n) for(int i=ini;i>=n;i--)
int const inf=1e9+7;
typedef long long ll;
int main(){
int t=1;
while(t--){
ll n,W,v,w;
cin>>n>>W;
vector<ll>dp(100001,inf);
dp[0]=0;
fo(i,0,n){
cin>>w>>v;
rfo(j,1000... |
Kenkoooo found a simple connected graph. The vertices are numbered 1 through n. The i-th edge connects Vertex u_i and v_i, and has a fixed integer s_i.
Kenkoooo is trying to write a positive integer in each vertex so that the following condition is satisfied:
* For every edge i, the sum of the positive integers writt... | import sys
from sys import setrecursionlimit
from collections import deque
from heapq import heappop, heappush
setrecursionlimit(10**9)
#input = sys.stdin.readline
def inpl(): return map(int, input().split())
INF = 2**31
N, M = inpl()
D = [[] for _ in range(N+1)]
for _ in range(M):
u, v, s = inpl()
D[u].app... |
Let f(A, B), where A and B are positive integers, be the string satisfying the following conditions:
* f(A, B) has length A + B;
* f(A, B) contains exactly A letters `A` and exactly B letters `B`;
* The length of the longest substring of f(A, B) consisting of equal letters (ex., `AAAAA` or `BBBB`) is as small as possi... | #include<bits/stdc++.h>
using namespace std;
int T,a,b,c,d,k,l,r,ca,cb,mid,o,n;
int main()
{
scanf("%d",&T);
while (T--)
{
scanf("%d %d %d %d",&a,&b,&c,&d);
n=a+b;
k=max(a,b)/(min(a,b)+1)+(max(a,b)%(min(a,b)+1)==0?0:1);
l=0,r=n+1;
while (r>l)
{
mid=l+r>>1;
ca=a-mid/(k+1)*k-mid%(k+1);
cb=b-mid/(k... |
We have a board with a 2 \times N grid. Snuke covered the board with N dominoes without overlaps. Here, a domino can cover a 1 \times 2 or 2 \times 1 square.
Then, Snuke decided to paint these dominoes using three colors: red, cyan and green. Two dominoes that are adjacent by side should be painted by different colors... | #include<bits/stdc++.h>
#define MOD 1000000007
using namespace std;
int i,n,a[52];
long long x;
string s,t;
int main(){
cin>>n>>s>>t;
if(s[0]==s[1])i=2,x=6;
else i=1,x=3;
for(;i<s.size();){
if(s[i]==s[i+1]){
if(s[i-2]==s[i-1])x=x*3%MOD;
else x=x*2%MOD;
i+=2;
}
else if(s[i-1]==t[i-1... |
Snuke found N strange creatures. Each creature has a fixed color and size. The color and size of the i-th creature are represented by i and A_i, respectively.
Every creature can absorb another creature whose size is at most twice the size of itself. When a creature of size A and color B absorbs another creature of siz... | #include <cstdio>
#include <algorithm>
int main(){
int N,i;
scanf("%d",&N);
long long A[100000]={0},large=0;
for(i=0;i<N;i++){
scanf("%lld",&A[i]);
}
std::sort(A,A+N);
int color_num=N;
large=A[0];
for(i=1;i<N;i++){
if(large*2<A[i]){
color_num=N-i;
}
large+=A[i];
}
printf("%d",color_num);
} |
We have a pyramid with N steps, built with blocks. The steps are numbered 1 through N from top to bottom. For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally. The pyramid is built so that the blocks at the centers of the steps are aligned vertically.
<image>
A pyramid with N=4 steps
Snuke wrote a per... | #include<bits/stdc++.h>
#define N 200005
using namespace std;
int n,m,a[N],b[N];
int check(int x)
{
for (int i=1;i<=m;i++)
b[i]=a[i]>=x;
if (b[n]==b[n-1]||b[n]==b[n+1]) return b[n];
int l=n,r=n;
while(l>1&&b[l-1]!=b[l])l--;
while(r<m&&b[r+1]!=b[r])r++;
if (l==1&&r==n) return b[1];
if ((r^l)&1) return (l+r>>1)>... |
A prime number is an integer that is greater than 1 and can only be divided by itself or 1. For example, 2 is a prime number because it is divisible only by 2 and 1, but 12 is not a prime number because it is divisible by 2, 3, 4, 6 in addition to 12 and 1.
When you enter the integer n, write a program that outputs th... | from math import sqrt, ceil
N = 53000
temp = [True]*(N+1)
temp[0] = temp[1] = False
for i in range(2, ceil(sqrt(N+1))):
if temp[i]:
temp[i+i::i] = [False]*(len(temp[i+i::i]))
while True:
try:
n = int(input())
print(n-1-temp[n-1:0:-1].index(True), n+1+temp[n+1:].index(True))
except ... |
Taro, who aims to become a web designer, is currently training. My senior at the office tells me that the background color of this page is # ffe085, which is a color number peculiar to web design, but I can't think of what kind of color it is.
This color number represents the intensity of each of the three primary col... | import java.util.Scanner;
import java.util.HashMap;
import java.util.Arrays;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in).useDelimiter("[\n#]+");
while (true)
{
String str = sc.next();
if (str.equals("0")) break;
int rk = Integer.parseInt(str.substring(0, 2)... |
The "Western calendar" is a concept imported from the West, but in Japan there is a concept called the Japanese calendar, which identifies the "era name" by adding a year as a method of expressing the year on the calendar. For example, this year is 2016 in the Christian era, but 2016 in the Japanese calendar. Both are ... | #include <bits/stdc++.h>
using namespace std;
int main(){
int E,Y;
cin>>E>>Y;
if(E == 0)
{
if(1868 <= Y && Y <= 1911) cout<<"M"<<Y - 1867<<endl;
else if(1912 <= Y && Y <= 1925) cout<<"T"<<Y - 1911<<endl;
else if(1926 <= Y && Y <= 1988) cout<<"S"<<Y - 1925<<endl;
else if(1989 <= Y && Y <= 2016) cout<<"H"<<Y - 1988<<end... |
IOI Real Estate rents condominiums. The apartment room handled by this company is 1LDK, and the area is 2xy + x + y as shown in the figure below. However, x and y are positive integers.
Figure_Madori
In the IOI real estate catalog, the areas of condominiums are listed in ascending order (in ascending order), but it... | #include <iostream>
using namespace std;
int main() {
int Z, N;
int enable = 0;
cin >> N;
for(int i = 0; i < N; i++) {
cin >> Z;
for(int y = 1; y * y < Z; y++) {
if(((Z - y) % (2 * y + 1)) == 0) {
enable++;
break;
}
}
}
cout << (N - enable) << endl;
return 0;
}
|
Travelling by train is fun and exciting. But more than that indeed. Young challenging boys often tried to purchase the longest single tickets and to single ride the longest routes of various railway systems. Route planning was like solving puzzles. However, once assisted by computers, and supplied with machine readable... | #include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
vector<int> con;
vector<int> cost;
vector<int> e_id;
};
typedef vector<node> Graph;
struct State{
int now;
int dist;
int used;
State(int n, int d, int u):now(n),dist(d),used(u){}
bool visited(in... |
Meikyokan University is very famous for its research and education in the area of computer science. This university has a computer center that has advanced and secure computing facilities including supercomputers and many personal computers connected to the Internet.
One of the policies of the computer center is to le... | #include <bits/stdc++.h>
using namespace std;
#define MAX 201
typedef pair<string,string> P;
int N,D,idx;
string s[MAX];
map<int,set<string> > mp;
vector<P> vec;
void dfs(string now,int step){
if(step == 1){
mp[idx].insert(now);
return;
}
int len = now.size();
// delete
for(int i = 0 ; i < le... |
Problem F Pizza Delivery
Alyssa is a college student, living in New Tsukuba City. All the streets in the city are one-way. A new social experiment starting tomorrow is on alternative traffic regulation reversing the one-way directions of street sections. Reversals will be on one single street section between two adjac... | #include <map>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
const int mod = 1000000021;
const long long inf = 1LL << 61;
struct edge { int to, cost, id; };
struct edge2 { int to, id; };
struct state { int pos; long long cost; };
bool operator<(const state& s1, const s... |
Bamboo Blossoms
The bamboos live for decades, and at the end of their lives, they flower to make their seeds. Dr. ACM, a biologist, was fascinated by the bamboos in blossom in his travel to Tsukuba. He liked the flower so much that he was tempted to make a garden where the bamboos bloom annually. Dr. ACM started resea... | #include<cstdio>
#include<cstring>
typedef long long int lli;
char prime[8000000];
int main(void) {
while(1) {
lli m,n;
scanf("%lld%lld",&m,&n);
if(!m) break;
memset(prime, 1, sizeof(prime));
prime[0] = prime[1] = 0;
lli cnt=0;
lli i;
for(i=m; cnt<=... |
Aaron is a vicious criminal. He has repeatedly committed crimes (2 shoplifting, 16 peeping, 256 underwear thieves, 65,536 escapes), but has continued to escape from the police with his extraordinary physical abilities. Bruce is a police officer. Although he does not have outstanding athletic ability, he enjoys photogra... | #include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
using namespace std;
const int IINF = INT_MAX;
const int MAX_V = 60;
int V,initial_Aaron,initial_Bruce,memo[MAX_V][MAX_V][2];
vector<int> G[MAX_V];
#define REPEAT -1
void compute(){
rep(i,V) rep(j,V) rep(k,2) memo[i][j][... |
"ACM48" is one of the most popular dance vocal units in Japan. In this winter, ACM48 is planning a world concert tour. You joined the tour as a camera engineer.
Your role is to develop software which controls the camera on a stage. For simplicity you can regard the stage as 2-dimensional space. You can rotate the came... | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
#include <complex>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-7;
... |
In a country that has been frequently invaded by unidentified creatures, it has decided to protect important facilities with new defense weapons.
This weapon can damage unidentified creatures by filling a polygonal area with a special gas. If the concentration of gas changes during the invasion of an unidentified creat... | #include<bits/stdc++.h>
#define MAX 1000
#define inf 1<<29
#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)... |
Problem Statement
Infinite Chronicle -Princess Castle- is a simple role-playing game. There are $n + 1$ checkpoints, numbered $0$ through $n$, and for each $i = 1, 2, \ldots, n$, there is a unique one-way road running from checkpoint $i - 1$ to $i$. The game starts at checkpoint $0$ and ends at checkpoint $n$. Evil mo... | //
// main.cpp
//
// Under GPLv3 license
//
// #pragma GCC diagnostic error "-std=c++14"
// #pragma GCC optimize("O3")
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <string.h>
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <complex>
#include <cstdio>
#inclu... |
curtain
Summer is coming soon. You decide to redecorate your room for the summer. It is expected that the sun will be very strong this summer, and it will be a difficult season for you who are not good at dazzling. So you thought about installing a curtain on the window of the room to adjust the brightness of the room... | #include "bits/stdc++.h"
using namespace std;
#ifdef _DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif
//#define int long long
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f... |
Proof of knowledge
The entrance door of the apartment you live in has a password-type lock. This password consists of exactly four digits, ranging from 0 to 9, and you always use the password P given to you by the apartment manager to unlock this door.
One day, you wondered if all the residents of the apartment were ... | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
while (true) {
string s;
cin >> s;
if (s == ".") return 0;
reverse(s.begin(), s.end());
int p;
cin >> p;
int hash;
map<int, int> mp;
for (int num = 0; num < 10... |
Problem
There are $ N $ Amidakuji with 3 vertical lines.
No matter which line you start from, the Amidakuji that ends at the starting line is considered a good Amidakuji.
You can select one or more Amidakuji and connect them vertically in any order.
Output "yes" if you can make a good Amidakuji, otherwise output "no".... | #include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for... |
You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the s... | from sys import stdin
def binSearch(k, p_min, p_max):
global w
while p_max-p_min > 1:
mid = p_min + (p_max-p_min)//2
if k >= countTrack(w, mid):
p_max = mid
else:
p_min = mid
return p_max
def countTrack(w, p):
rest = []
for wi in w:
if len(r... |
Write a program which counts and reports the number of each alphabetical letter. Ignore the case of characters.
Constraints
* The number of characters in the sentence < 1200
Input
A sentence in English is given in several lines.
Output
Prints the number of alphabetical letters in the following format:
a : The n... | import time
import sys
import io
import re
import math
#start = time.clock()
i = [0]*127
#n = raw_input()
for x in sys.stdin.read().lower():
i[ord(x)]+=1
for y in range(ord('a'), ord('z')+1):
print chr(y)+ ' : ' + str(i[y]) |
Chef is playing a game on a sequence of N positive integers, say A1, A2, ... AN. The game is played as follows.
If all the numbers are equal, the game ends.
Otherwise
Select two numbers which are unequal
Subtract the smaller number from the larger number
Replace the larger number with the result from above (see the e... | from fractions import gcd
t=int(raw_input())
while(t>0):
t-=1
n=input()
a=[int(i) for i in raw_input().split()]
ans=gcd(a[0],a[1])
for i in range(2,n):
ans=gcd(ans,a[i])
print ans |
Gru has not been in the limelight for a long time and is, therefore, planning something particularly nefarious. Frustrated by his minions' incapability which has kept him away from the limelight, he has built a transmogrifier — a machine which mutates minions.
Each minion has an intrinsic characteristic value (simila... | import sys
t=int(raw_input(""))
while t:
m,n=map(int,sys.stdin.readline().split())
l=list(map(int,sys.stdin.readline().split()))
count=0
for i in range(len(l)):
if (l[i]+n)%7==0:
count+=1
print count
t-=1 |
The faculty of application management and consulting services (FAMCS) of the Berland State University (BSU) has always been popular among Berland's enrollees. This year, N students attended the entrance exams, but no more than K will enter the university. In order to decide who are these students, there are series of e... | def entExam(N,K,E,M, D):
scoreSet = []
for i in range(N-1):
scoreSet.append(sum(D[i]))
scoreSet = sorted(scoreSet)
myScore = sum(D[-1])
if(scoreSet[N-K-1]+1 > myScore+M):
print "Impossible"
else:
anw = scoreSet[N-K-1]-myScore+1
if(anw < 0):
print 0
... |
Sum and Color
Chef is a mathematics student. His professor has given him a difficult task. Professor initially provides Chef with a list of numbers. For every number in the list, Chef has to calculate the sum 'S' of digits such that 0<=S<=9. Even if the sum of digits is coming as a 'n' digit number, Chef has to bring i... | def con(a):
summ=0
while True:
summ+=a%10
a/=10
if(a==0):
break
if((summ/10)>=1):
return con(summ)
else:
return summ
for _ in xrange(input()):
s_li=[]
input()
li=map(int,raw_input().split())
for j in xrange(len(li)):
s_li.ap... |
In Byteland it is always the military officer's main worry to order his soldiers on parade correctly. Luckily, ordering soldiers is not really such a problem. If a platoon consists of n men, all of them have different rank (from 1 - lowest to n - highest) and on parade they should be lined up from left to right in incr... | #!/bin/python
import sys
for z in range(int(raw_input())):
l = int(raw_input())
data = map(int,raw_input().split())
out = range(1,l+1)
for i in range(l-1,-1,-1):
sol = out.pop(i-data[i])
out.insert(i,sol)
print ' '.join(map(str,out)) |
Lo and Behold! For you may be surprised by what our chief chef Noodle has in mind for this season! Today, Noodle announced one of his most extra-ordinary ideas ever - Project Spoon.
Noodle plans to deploy large spoons in the atmosphere so that people all around the world can download food directly from his kitchen th... | #!/usr/bin/python
def factorial(a):
res = 1
for i in range(1, a+1):
res *= i
return res
# end of factorial
def perestanovki(a,b):
return factorial(a)/(factorial(b)*factorial(a-b))
# end of perestanovki
def getIndex(start, end, a):
ind = (start + end) / 2
if mins[ind] == a:
ret... |
Polycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, ..., a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip ... | # Accepted:
isVerbose = False
def v(msg):
if isVerbose:
print(msg)
n, k = map(int, input().split())
nums = list(enumerate(map(int, input().split())))
#print(n, k)
#print(nums)
nums.sort(key=lambda tup:tup[1])
#print(nums)
nums_top = nums[-min(k, n):]
#print(nums_top)
nums_top.sort(key=lambda tup:tup[0])... |
A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.
Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has i... | #include <bits/stdc++.h>
using namespace std;
int n, m = 3000001, i, j, k, ans, l, y, x, z, c, t;
int a[101][101] = {0}, b[101];
bool can = false;
int main() {
std::ios_base::sync_with_stdio(false);
cin >> n >> m;
if (m < 3) {
cout << -1;
return 0;
}
for (i = 1; i <= n; i++) cin >> b[i];
for (i = 0;... |
Vasya came up with a password to register for EatForces — a string s. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.
But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin l... |
def check( s, L, R ):
for i in s:
if i>=L and i<=R:
return False
return True
def ok(s):
low = True;
for i in s:
if i>='a' and i<='z':
low = False;
break
if low :
return False
low = True;
for i in s:
if i>='A' and i<='Z':
low = False;
break
if low :
return False
low = True;
f... |
Vasya has got n books, numbered from 1 to n, arranged in a stack. The topmost book has number a_1, the next one — a_2, and so on. The book at the bottom of the stack has number a_n. All numbers are distinct.
Vasya wants to move all the books to his backpack in n steps. During i-th step he wants to move the book number... | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from functools import *
from heapq import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout ... |
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible... | #include <bits/stdc++.h>
using namespace std;
int main() {
string s, ans;
int n, maxx = -1, minn = -1;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
sort(v.begin(), v.end());
if (v[1] - v[0] > v[n - 1] - v[n - 2]) {
cout << v[n - 1] - v[1];
} else {
cout << v[n -... |
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a n... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
long long qpow(long long n, long long k) {
long long ans = 1;
assert(k >= 0);
n %= mod;
while (k > 0) {
if (k & 1) ans = (ans * n) % mod;
n = (n * n) % mod;
k >>= 1;
}
return ans % mod;
}
long long n, b;
vector<pair<long l... |
Traveling around the world you noticed that many shop owners raise prices to inadequate values if the see you are a foreigner.
You define inadequate numbers as follows:
* all integers from 1 to 9 are inadequate;
* for an integer x ≥ 10 to be inadequate, it is required that the integer ⌊ x / 10 ⌋ is inadequate, ... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool chkmin(T &a, const T &b) {
return a > b ? a = b, 1 : 0;
}
template <typename T>
inline bool chkmax(T &a, const T &b) {
return a < b ? a = b, 1 : 0;
}
template <typename T>
inline bool smin(T &a, const T &b) {
return a > b ? a = b : a;... |
You are given a string s consisting of characters "1", "0", and "?". The first character of s is guaranteed to be "1". Let m be the number of characters in s.
Count the number of ways we can choose a pair of integers a, b that satisfies the following:
* 1 ≤ a < b < 2^m
* When written without leading zeros, the ... | #include <bits/stdc++.h>
using namespace std;
int readInt() {
int x;
if (scanf(" %d", &x) != EOF) return x;
return -1;
}
long long int readLint() {
long long int x;
if (cin >> x) return x;
return -1;
}
string readString() {
string s;
if (cin >> s) return s;
return "";
}
struct Graph {
int n;
vecto... |
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between th... | R = lambda: map(int, input().split())
n,k = R()
s = input()
p = [s]
ans = 0
d= set()
while p:
q = p.pop(0)
if q not in d:
k -= 1
ans += (n-len(q))
if k == 0:
print(ans)
quit()
d.add(q)
for i in range(len(q)):
t = q[:i]+q[i+1:]
... |
Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can h... | #include <bits/stdc++.h>
using namespace std;
const int M = 1e3 + 10, N = 2520;
int n, k[M], ans[M][N + 5], tim[M], dep;
vector<int> vt[M];
int dfs(int x, int y) {
if (ans[x][y] > 0) return ans[x][y];
if (ans[x][y] < 0) {
int siz = 0;
for (int i = 1; i <= n; i++)
if (tim[i] <= ans[x][y]) siz++;
re... |
We are definitely not going to bother you with another generic story when Alice finds about an array or when Alice and Bob play some stupid game. This time you'll get a simple, plain text.
First, let us define several things. We define function F on the array A such that F(i, 1) = A[i] and F(i, m) = A[F(i, m - 1)] for... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 234;
vector<pair<int, int> > arpa[N], pasha[N];
int mark[N], cmp[N], plCycl[N], Next[N];
int st[N], en[N], hei[N], now;
vector<int> Prev[N], cycles[N], height[N];
int goPrev(int x, long long n) {
int cLen = ((int)cycles[cmp[x]].size());
n = cLen - (n... |
Ujan has finally cleaned up his house and now wants to decorate the interior. He decided to place a beautiful carpet that would really tie the guest room together.
He is interested in carpets that are made up of polygonal patches such that each side of a patch is either a side of another (different) patch, or is an ex... | #include <bits/stdc++.h>
int pp[300000], n, cnt;
void connect(int *qq, int a, int b) {
int h, j, k;
k = 0;
for (h = cnt - 1; h >= cnt - b; h--) qq[k++] = pp[h];
j = pp[cnt - 1];
cnt -= b - 1;
for (h = 0; h < a - b; h++) qq[k++] = pp[cnt++] = n++;
pp[cnt++] = j;
}
int main() {
static int aa[300000], hh[3... |
Your program fails again. This time it gets "Wrong answer on test 233"
.
This is the harder version of the problem. In this version, 1 ≤ n ≤ 2⋅10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
The problem is to finish n one-choice-questions. Eac... | #include <bits/stdc++.h>
using namespace std;
const int N = 200000;
const int MOD = 998244353;
const int INV2 = (MOD + 1) / 2;
int n, k;
int h[N], fac[N + 1], ifac[N + 1], two[N + 1];
inline int add(int x, int y) {
int res = (x + y);
if (res >= MOD) {
res -= MOD;
}
if (res < 0) {
res += MOD;
}
retur... |
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ... | from sys import stdin, stdout
def main():
(n1, n2) = tuple([int(x) for x in stdin.readline().split()])
arr1 = [x for x in stdin.readline().split()]
arr2 = [x for x in stdin.readline().split()]
q = int(stdin.readline())
res = []
for i in range(0, q):
year = int(stdin.readline())
... |
Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all 26 lowercase Latin letters will be arranged in some order.
Polycarp uses the same password s on all websites where he is registered (it is bad, but he doesn't care)... | #include <bits/stdc++.h>
using namespace std;
set<pair<char, char> > t;
set<char> p;
int main() {
int k;
cin >> k;
while (k--) {
t.clear();
p.clear();
string s;
cin >> s;
if (s.size() == 1) {
cout << "YES" << endl << "abcdefghijklmnopqrstuvwxyz" << endl;
continue;
}
bool fl... |
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a a... | #include <bits/stdc++.h>
using namespace std;
long long solve(void) {
int n;
cin >> n;
vector<int> p(n), c(n);
for (auto &v : p) {
cin >> v;
v--;
}
for (int i(0); i < n; ++i) cin >> c[i];
vector<bool> visited(n, false);
vector<vector<int>> cycles;
for (int i(0); i < n; ++i) {
if (visited[i... |
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then a... | from sys import stdin
input = stdin.readline
n = int(input())
a = [*map(lambda x: bin(int(x))[:1:-1], input().split())]
c1 = len(max(a, key=len))
a = [x + '0' * (c1 - len(x)) for x in a]
b = [sum(c[i] == '1' for c in a) for i in range(c1)]
c2 = max(b)
ans = 0
for i in range(c2):
num = ''
for i in range(c1):
if b[i]... |
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i ≠ t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there ex... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using PII = pair<int, int>;
const int mod = 998244353;
const int inf = 1 << 30;
const int maxn = 400000 + 5;
struct Seg {
int l, r, t;
bool operator<(const Seg& rhs) const {
if (r != rhs.r) {
return r < rhs.r;
}
return l < rhs.l;
... |
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any thr... | import java.io.*;
import java.util.*;
import java.math.*;
public class Main implements Runnable {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private Random rnd;
final String filename = "codeforces";
class Pair implements Comparable<Pair> {
int val, howMuch;
Pair(in... |
You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i.
Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} -... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 10;
const long long INF = 1e15;
int n, m;
int cnt = 1;
int s, t;
struct Edge {
int to, nx;
long long cap;
} edge[MAXN << 1];
int head[MAXN];
void _add(int from, int to, long long cap) {
cnt++;
edge[cnt].to = to;
edge[cnt].cap = cap;
edge[c... |
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any ... | for _ in range(int(input())):
n = int(input())
x = list(map(int, input().split()))
o = {x[0]: [0]}
for i in range(1, n):
if x[i] in o:
o[x[i]].append(i)
else:
o[x[i]] = [i]
m = n
if len(o) == 1:
print(0)
else:
for k, l in o.items():
... |
Nezzar has n balls, numbered with integers 1, 2, …, n. Numbers a_1, a_2, …, a_n are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that a_i ≤ a_{i+1} for all 1 ≤ i < n.
Nezzar wants to color the balls using the minimum number of colors, such that the following holds.
... | import java.util.*;
import java.io.*;
public class Main {
static FastReader sc;
static PrintWriter out;
static int mod = 1000000007;
public static void main(String[] args) throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
File f1 = new File("input.txt");
... |
Input
The input contains two integers N, M (1 ≤ N ≤ 1024, 2 ≤ M ≤ 16), separated by a single space.
Output
Output "YES" or "NO".
Examples
Input
2 3
Output
YES
Input
3 2
Output
NO
Input
33 16
Output
YES
Input
26 5
Output
NO | import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.... |
There are n cities in Shaazzzland, numbered from 0 to n-1. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.
As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.
AaParsa has planted m transport canno... | #include "bits/stdc++.h"
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
template<typename T>
int sz(const T &a){return int(a.size());}
const int MN=601;
int dist[MN];
bool used[MN];
int arr[MN][MN];
int main(){
cin.tie(NULL);
ios_base::sync_with_stdio(false);
... |
There are n stone quarries in Petrograd.
Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it.
Two oligarchs p... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll get(ll n) {
if (n % 4 == 0)
return n;
else if (n % 4 == 1)
return 1;
else if (n % 4 == 2)
return n + 1;
else
return 0;
}
ll get(ll l, ll r) { return (get(r) ^ get(l - 1)); }
int32_t main() {
ios_base::sync_with_stdio(false)... |
The Smart Beaver from ABBYY has a long history of cooperating with the "Institute of Cytology and Genetics". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows.
There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercas... | import java.io.*;
import java.util.*;
public class A {
static long INF = (long) 1e18;
static long[][][] dp;
static int[] lcp;
static void solve(int l, int r) {
if (l == r) {
dp[l][r] = new long[2];
return;
}
int min = l;
for (int i = l; i < r; i++)
if (lcp[i] < lcp[min])
min = i;
solve(l, ... |
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ≤ ... | #include <bits/stdc++.h>
using namespace std;
string str;
void solve() {
int count;
char c = 'a' - 1;
for (int i = 0; i < (int)str.size(); i++)
if (str[i] > c) {
count = 1;
c = str[i];
} else if (str[i] == c)
count++;
for (int i = 1; i <= count; i++) cout << c;
}
int main() {
cin.syn... |
In Berland each feudal owns exactly one castle and each castle belongs to exactly one feudal.
Each feudal, except one (the King) is subordinate to another feudal. A feudal can have any number of vassals (subordinates).
Some castles are connected by roads, it is allowed to move along the roads in both ways. Two castle... | #include <bits/stdc++.h>
using namespace std;
struct apple {
int v, nxt;
} edge[100011 * 4];
struct node {
int l, r, lson, rson, sum, len;
} tree[100011 * 30];
int indexx[100011], tt[100011], root[100011], f[100011], max_son[100011],
wgt[100011], fa[100011], top[100011], tot, siz, Root, deep[100011];
int sumx, ... |
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.
On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival progra... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
int n, k;
cin >> n >> k;
int a[n];
for (int i = 0; i < n; ++i) cin >> a[i];
int m = unique(a, a + n) - a;
int cont[k + 1];
memset(cont, 0, sizeof cont);
for (int i = 0; i < m; ++i) ++cont[a[i]];
for (int i = 1; i + 1... |
A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tr... | import java.util.*;
import static java.lang.System.*;
public class D275 {
Scanner sc = new Scanner(in);
public static class Node{
public int id;
public int val;
public List<Node> link=new LinkedList<Node>();
public Node(int id){
this.id=id;
}
}
cl... |
Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.
Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!
Input
The first line contains integer n (1 ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 5;
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int main() {
int n, a, b;
vector<int> v;
cin >> n;
cin >> a;
v.push_back(a);
for (int i = 1; i < n; i++) {
cin >> b;
v.push_back(b);
if (a < b) swap(a, b);
a ... |
Fox Ciel has a board with n rows and n columns, there is one integer in each cell.
It's known that n is an odd number, so let's introduce <image>. Fox Ciel can do the following operation many times: she choose a sub-board with size x rows and x columns, then all numbers in it will be multiplied by -1.
Return the maxi... | #include <bits/stdc++.h>
using namespace std;
long long fpm(long long b, long long e, long long m) {
long long t = 1;
for (; e; e >>= 1, b = b * b % m) e & 1 ? t = t * b % m : 0;
return t;
}
template <class T>
inline bool chkmin(T &a, T b) {
return a > b ? a = b, true : false;
}
template <class T>
inline bool c... |
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substri... | #include <bits/stdc++.h>
using namespace std;
string s, t, pp;
int b[105], len1, len2, len3, dp[105][105][105], pizza;
bool done[105][105][105];
inline void preprocess() {
int i = 0, j = -1;
b[i] = j;
while (i < len3) {
while (j >= 0 && pp.at(i) != pp.at(j)) j = b[j];
j++, i++;
b[i] = j;
}
}
int f(i... |
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he ... | import java.io.*;
import java.util.*;
public final class code
// public class Main
// class code
// public class Solution
{
static void solve()throws IOException
{
int n=nextInt();
String s=nextLine();
int i=0;
while(i<n && s.charAt(i)!='1')
i++;
int diff=-1,t... |
This problem consists of two subproblems: for solving subproblem D1 you will receive 3 points, and for solving subproblem D2 you will receive 16 points.
Manao is the chief architect involved in planning a new supercollider. He has to identify a plot of land where the largest possible supercollider can be built. The su... | #include <bits/stdc++.h>
using namespace std;
const int Maxn = 50005;
const int Maxm = 3 * Maxn;
const int lim = 50000000;
struct event {
int typ, x, y, y2;
event(int typ = 0, int x = 0, int y = 0, int y2 = 0)
: typ(typ), x(x), y(y), y2(y2) {}
bool operator<(const event &e) const {
if (x != e.x) return ... |
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he rem... | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class A {
public static void main(String... args) {
final Scanner sc = new Scanner(System.in);
final int n = sc.nextInt();
final int k = sc.nextInt();
if (n / 2 > k) {
System.out.println(-1)... |
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Ou... | #include <bits/stdc++.h>
using namespace std;
long long n, a[16];
long long solve(long long n, int step) {
long long ans = (step + 1LL) * (n / a[step]);
n %= a[step];
if (n == 0) return ans;
return ans + min(solve(n, step - 1), step + 1 + solve(a[step] - n, step - 1));
}
int main() {
a[0] = 1;
for (int i = ... |
Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types:
1. Fold the sheet of paper at position pi. After this query the leftmost... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 101000;
int a[maxn], n, q;
inline int lowbit(int x) { return x & (-x); }
void add(int p, int v) {
for (int i = p; i <= n; i += lowbit(i)) a[i] += v;
}
int sum(int p) {
int sum = 0;
for (int i = p; i; i -= lowbit(i)) sum += a[i];
return sum;
}
int ma... |
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In ... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
i... |
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows a... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class cbr47c {
public static void main(String[] args) throws IOExceptio... |
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are n bus stops located along the street, the i-th of them is located at the distance ai from the central square, all distances are distinct, the stops are numbered in the orde... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 444444;
int n, m, a[MAXN], b[MAXN], c[MAXN], tc[MAXN];
void read() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
scanf("%d", &m);
for (int i = 1; i <= m; i++) scanf("%d", &b[i]);
}
long long go(int start, int dir) {
for (int ... |
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path ... | #include <bits/stdc++.h>
using namespace std;
int N, Ans, F[105][105][2];
struct Nod {
int x, l;
} A[105];
bool Cmp(Nod a, Nod b) { return a.x < b.x; }
int main() {
scanf("%d", &N);
for (int i = 1; i <= N; i++) scanf("%d%d", &A[i].x, &A[i].l);
sort(A + 1, A + N + 1, Cmp);
A[0].x = -(1 << 30);
for (int i = 0... |
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a let... | import fractions
def solve(x, y):
if fractions.gcd(x, y) > 1: return 'Impossible'
turn = x > y
if not turn: x, y = y, x
ans = []
while x != 0 and y != 0:
ans.append((x//y, 'A' if turn else 'B'))
x, y = y, x%y
turn = not turn
ans[-1] = (ans[-1][0]-1, ans[-1][1])
return... |
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2... | #include <bits/stdc++.h>
using namespace std;
const int inft = 1000000009;
const int mod = 1000000007;
const int MAXN = 1000006;
int n;
bool kmp(string P) {
P = "#" + P;
int pi[P.size()], m = P.size() - 1, q = 0;
pi[0] = pi[1] = 0;
for (int i = 2; i <= m; ++i) {
while (q && P[i] != P[q + 1]) q = pi[q];
... |
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far A... | #include <bits/stdc++.h>
int n, a, b, m, f, male[400], female[400], ans;
char gender;
int main() {
scanf(" %d", &n);
for (int i = 0; i < n; i++) {
scanf(" %c %d %d", &gender, &a, &b);
if (gender == 'M') {
male[a]++;
male[b + 1]--;
} else {
female[a]++;
female[b + 1]--;
}
}
... |
The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:
* ti < ti + 1 for each odd i < n;
* ti > ti + 1 for each even i < n.
For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, ... | #include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
inline long long read() {
long long t = 0, dp = 1;
char c = getchar();
while (!isdigit(c)) {
if (c == '-') dp = -1;
c = getchar();
}
while... |
This is an interactive problem. In the output section below you will see the information about flushing the output.
Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.
Integer x > 1 is called prime if it has exactly two distinct ... | import java.io.*;
import java.util.*;
public class Solution {
private BufferedReader in;
private StringTokenizer line;
private PrintWriter out;
private boolean isDebug;
public Solution(boolean isDebug) {
this.isDebug = isDebug;
}
private static final int mm = 1000000007;
pub... |
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a roo... | import java.io.*;
import java.util.*;
/**
* @author Alexander Tsupko (alexander.tsupko@outlook.com)
* (c) Codeforces Round 364. All rights reserved. July 22, 2016.
*/
public class B {
private static class Solve {
// instance variables
private void solve(InputReader in, OutputWriter out) {
... |
Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1, a2, ..., an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others.
We define as bj the number of songs the g... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.StringBuilder;
import java.util.*;
import java.lang.Math;
public class CF375C {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(... |
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that th... | a, b = [int(x) for x in raw_input().split(" ")]
lineas = []
for i in xrange(a):
lineas.append(raw_input())
while lineas[0] == "."*b:
lineas.pop(0)
while lineas[-1] == "."*b:
lineas.pop(-1)
salir = False
while not salir:
for i in xrange(len(lineas)):
if lineas[i][0] == "X":
salir = ... |
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2005;
double dp[10005][maxn];
int ans[maxn];
const double eps = 1e-7;
int main() {
int q, k;
scanf("%d %d", &k, &q);
dp[0][0] = 1;
for (int i = 1; i < 10005; i++) {
for (int j = 1; j <= k; j++) {
dp[i][j] += dp[i - 1][j] * double(j) / k;
... |
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zer... | // Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUD... |
Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd ... | #include <bits/stdc++.h>
using namespace std;
long long int n, x, sum = 0, cnt = 0, a[100005], an;
vector<long long int> vt[100005];
map<long long int, long long int> use, mp;
map<long long int, long long int>::iterator it;
long long int dfs(long long int node, long long int par) {
long long int tmp, siz = vt[node].s... |
You are given an strictly convex polygon with n vertices. It is guaranteed that no three points are collinear. You would like to take a maximum non intersecting path on the polygon vertices that visits each point at most once.
More specifically your path can be represented as some sequence of distinct polygon vertices... | #include <bits/stdc++.h>
using namespace std;
int n;
double f[2][2600], g[2][2600], ans;
struct q {
double x, y;
} a[2600];
double dis(q a, q b) {
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%lf%lf", &a[i].x, &a[i].... |
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy... | import java.util.*;
import java.io.*;
public class LazySecurityGuard {
/************************ SOLUTION STARTS HERE ************************/
private static void solve() {
int N = nextInt();
int block = (int) Math.sqrt(N);
long peri =... |
Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend... | import java.util.Scanner;
public class BookReading {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s[]=in.nextLine().split(" ");
int t=Integer.parseInt(s[0]);
int n=Integer.parseInt(s[1]);
int a[]=new int[t];
String ss[]=in.nextLine().split(" ");
int count=0,count11... |
Carol is currently curling.
She has n disks each with radius r on the 2D plane.
Initially she has all these disks above the line y = 10100.
She then will slide the disks towards the line y = 0 one by one in order from 1 to n.
When she slides the i-th disk, she will place its center at the point (xi, 10100). She w... | #include <bits/stdc++.h>
using namespace std;
int n, r, x[1005];
double ans[1005];
int main() {
cin >> n >> r;
for (int i = 1; i <= n; i++) cin >> x[i];
for (int i = 1; i <= n; i++) {
ans[i] = r;
for (int j = 1; j < i; j++) {
if (abs(x[i] - x[j]) > 2 * r) continue;
ans[i] = max(ans[i], ans[j] ... |
Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.
Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by... | #include <bits/stdc++.h>
using namespace std;
int main() {
string str;
cin >> str;
int z = 0, on = 0, fl = 0;
for (int i = str.size() - 1; i >= 0; i--) {
if (str[i] == '0' && fl == 1) {
z++;
} else if (str[i] == '1') {
on++;
fl = 1;
}
}
if (on > 1) {
cout << str.size() + 1 ... |
The stardate is 2015, and Death Stars are bigger than ever! This time, two rebel spies have yet again given Heidi two maps with the possible locations of the Death Stars.
Heidi has now received two maps with possible locations of N Death Stars. She knows that each of the maps is possibly corrupted, and may contain som... | #include <bits/stdc++.h>
using namespace std;
const int oo = 0x3f3f3f3f;
const long long ooo = 9223372036854775807ll;
const int _cnt = 1000 * 1000 + 7;
const int _p = 1000 * 1000 * 1000 + 7;
const int N = 100005;
const double PI = acos(-1.0);
const double eps = 0.5;
int o(int x) { return x % _p; }
int gcd(int a, int b)... |
For an array b of length m we define the function f as
f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] ⊕ b[2],b[2] ⊕ b[3],...,b[m-1] ⊕ b[m]) & otherwise, \end{cases}
where ⊕ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, f(1,2,4,8)=f(1⊕2,2⊕4,4⊕8)=f(3,6,12)=f(3⊕6... | import java.util.*;
import java.io.*;
public class _0983_B_XORPyramid {
public static void main(String[] args) throws IOException {
int N = readInt(); int arr[] = new int[N+1]; for(int i = 1; i<=N; i++) arr[i] = readInt();
int val[][] = new int[N+1][N+1], max[][] = new int[N+1][N+1];
for(int i =1; i<=N; i++) m... |
Consider a new order of english alphabets (a to z), that we are not aware of.
What we have though, dictionary of words, ordered according to the new order.
Our task is to give each alphabet a rank, ordered list of words.
The rank of an alphabet is the minimum integer R that can be given to it, such that:
if alphabet ... | Adj = {}
root = {}
def add(a, b):
if a in Adj:
Adj[a]["child"].add(b)
else:
Adj[a] = {"rank":0, "child":set([b])}
if b in Adj:
if b in root:
del root[b]
return
else:
if b in root:
del root[b]
Adj[b] = {"rank":0, "child":set()}
def addv(a):
if a in Adj:
return
else:
Adj[a] = {"rank":0, "... |
You are a member of a bomb-disposal squad. Each bomb is identified by a unique serial id X, which is a positive integer. To disarm the bomb, a positive integral key Y needs to be entered such that X + Y = X ⊕ Y (here "⊕" denotes the bit-wise XOR operator and "+" denotes the arithmetic sum operator).
However, there ar... | z=input()
for i in range(z):
x,y=map(int,raw_input().split())
c=0
j=1
while True:
if x+j==x^j:
c+=1
if y==c:
break
j+=1
print "Case #"+str(i+1)+": "+str(j) |
Golu is crazy about numbers. He loves those numbers such that the difference between the adjacent digits of that number is exactly one. He calls these numbers crazy numbers and wants to find out how many such numbers exist for N number of digits. This task is very difficult for him so he wants your help.
Now your task... | def crazy(n):
if n==0:
return 0
table = [[0]*n for _ in range(10)]
for j in range(n):
for i in range(10):
if j==0:
table[i][j] = 1
else:
if 0<i and i<9:
if i==1 and j==1:
table[i][j] = table[i+1][j-1]
else:
table[i][j] = table[i-1][j-1] + table[i+1][j-1]
elif i==0:
ta... |
Flip the world is a game. In this game a matrix of size N*M is given, which consists of numbers. Each number can be 1 or 0 only.
The rows are numbered from 1 to N, and the columns are numbered from 1 to M.
Following steps can be called as a single move.
Select two integers x,y (1 ≤ x ≤ N\; and\; 1 ≤ y ≤ M) i.e. one s... | T = input()
board = []
def flipSquare(n, m):
if board[n][m]: return 0
else:
for i in xrange(n + 1):
for j in xrange(m + 1):
board[i][j] = not board[i][j]
return 1
def flipRow(n):
moves = 0
for m in reversed(xrange(len(board[n]))):
moves += flipSquare(n, m)
return moves
for _ in xrange(T):
N, M = ... |
JholiBaba is a student of vnit and he has a craze for rotation. A Roller contest is organized in vnit which JholiBaba wants to win. In the contest, there is one roller which is represented similar to a strip of 1xN blocks. Each block has a number written on it. The roller keeps rotating and you will figure out that aft... | n = int(raw_input())
a = map(int, raw_input().split())
s = sum(a)
p = sum((i+1) * a[i] for i in xrange(n))
ans = p
for i in xrange(n-1):
p += a[i] * n - s
ans = max(ans, p)
print ans |
Mike has a huge guitar collection which the whole band is jealous of. Brad, the lead guitarist of the band, gave Mike a challenge so that he can't use all his guitars. The band is on a world tour and Brad told Mike to assign numbers to all his guitars. After that, he told Mike that he can use the guitars in such a mann... | from itertools import combinations
for _ in range(input()):
arr=[]
n=input()
a=map(int,raw_input().split())
for i in range(n+1):
comb = combinations(a,i)
arr.append(comb)
count=0
sumset=set()
# Print the obtained combinations
for it in arr:
for i in list(it):
#print i
sumset.add(sum(... |
Raj's lucky number is 101. His girl friend Rani wants to give him a string S as a birthday present to him. She went to a shop and there are variety of strings which contains only 1 and 0 ( Binary string ) in that shop. Now in order to impress Raj , she wants to buy a string with highest number of subsequence’s of 101'... | def num(seq, sub):
m, n = len(seq), len(sub)
table = [0] * n
for i in xrange(m):
previous = 1
for j in xrange(n):
current = table[j]
if seq[i] == sub[j]:
table[j] += previous
previous = current
return table[n-1] if n else 1
x=raw_input... |
After getting her PhD, Christie has become a celebrity at her university, and her facebook profile is full of friend requests. Being the nice girl she is, Christie has accepted all the requests.
Now Kuldeep is jealous of all the attention she is getting from other guys, so he asks her to delete some of the guys from h... | for i in range(input()):
N, K = [int(i) for i in raw_input().split()]
P = [int(i) for i in raw_input().split()]
stack = []
count = 0
for p in P:
while len(stack) > 0 and count < K and stack[-1] < p:
stack.pop()
count += 1
stack.append(p)
if count < K:
stack = stack[0:K... |
Sona is busy in organizing Port '16. Sona has to formulate two number sequence as two list. As she loves numbers she wrote the two number sequence in two different papers. Both the list have N numbers. She also named the number sequence as A and B where A = {a0,a1,...aN-1} and B = {b0,b1,..,bN-1} where as
b0 = a0... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n=input()
b=map(int,raw_input().split())
a=[b[0]]
for i in xrange(1,n):
e=b[i]*(i+1)
e=e-sum(a)
a.append(e)
for i in a:
print i, |
Problem Statement:
Tom is collecting money for his birthday party, he is having 'a' coins today and his father gives him 'k' coins each day.
Since his birthday is on 'nth' day, he wants to know the amount of money he will have on his birthday.
Tom is weak at maths, help him calculate the number of coins he will hav... | t = int(raw_input())
for cases in range(t):
a, k, n = raw_input().split()
coins = int(a) + int(k) * (int(n) - 1)
print coins |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.