input
stringlengths 29
13k
| output
stringlengths 9
73.4k
|
---|---|
Chef has bought N robots to transport cakes for a large community wedding. He has assigned unique indices, from 1 to N, to each of them. How it will happen?
Chef arranges the N robots in a row, in the (increasing) order of their indices. Then, he chooses the first M robots and moves them to the end of the queue. Now, Chef goes to the robot at the first position in the row and hands it one cake. He then notes this robot's index (say k) in his notebook, and goes to the k^th position in the row. If the robot at this position does not have a cake, he give him one cake, notes his index in his notebook, and continues the same process. If a robot visited by Chef already has a cake with it, then he stops moving and the cake assignment process is stopped.
Chef will be satisfied if all robots have a cake in the end. In order to prepare the kitchen staff for Chef's wrath (or happiness :) ), you must find out if he will be satisfied or not? If not, you have to find out how much robots have a cake, so that the kitchen staff can prepare themselves accordingly.
Input
The first line of input contains a single integer T denoting the number of test cases.
The single line of each test cases contains two space separated integers N and M.
Output
For each of the T test cases, output a single line:
If all N robots have a cake, output "Yes" (without quotes).
Otherwise, output "No" (without quotes) followed by a space and the number of robots which have a cake.
Constraints and Example
Input:
3
2 0
2 1
4 2
Output:
No 1
Yes
No 2
Explanation
In test case 1, we have two robots indexed 1 and 2. They are arranged as (1 2). Chef goes to the first robot, gives him a cake, and moves to position 1. In the next step, he sees that robot at this position already has a has cake. So Chef stops moving, and our answer is "No 1".
In test case 2, we again have two robots indexed 1 and 2. Initially, they are arranged as (1 2). Then, Chef moves robot#1 to the end of the row, and thus the arrangement becomes (2 1). Chef goes to the robot at the first position, which is robot#2. Chef hands him a cake, and moves to position 2. Then, he hands a cake to robot#1 at position 2, and moves back to the first position. Since, robot#2 at the first position already ahs a cake, Chef stops moving. All N robots have cakes, so Chef is satisfied, and our answer is "Yes".
In the 3^rd test case, we have the following arrangement of robots: (3 4 1 2). Only robots with indices 3 and 1 will get cakes. So our answer is "No 2".
|
def GI(): return int(raw_input())
def GIS(): return map(int, raw_input().split())
def main():
# Trying for better than O(N)
gcd = lambda a, b: gcd(b, a%b) if a%b else b
for i in xrange(GI()):
N, M = GIS()
if M == 0:
cakes_distributed = 1
else:
g = gcd(N, M)
cakes_distributed = N/g
if cakes_distributed == N:
print 'Yes'
else:
print 'No', cakes_distributed
main()
|
Chef is the new king of the country Chefland. As first and most important responsibility he wants to reconstruct the road system of Chefland. There are N (1 to N) cities in the country and each city i has a population Pi. Chef wants to build some bi-directional roads connecting different cities such that each city is connected to every other city (by a direct road or through some other intermediate city) and starting from any city one can visit every other city in the country through these roads. Cost of building a road between two cities u and v is Pu x Pv. Cost to build the road system is the sum of cost of every individual road that would be built.
Help king Chef to find the minimum cost to build the new road system in Chefland such that every city is connected to each other.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line contains an integer N denoting the number of cities in the country. Second line contains N space separated integers Pi, the population of i-th city.
Output
For each test case, print a single integer, the minimum cost to build the new road system on separate line.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 10^5
1 ≤ Pi ≤ 10^6
Example
Input:
2
2
5 10
4
15 10 7 13
Output:
50
266
|
for _ in xrange(input()):
n = input()
p = map(int, raw_input().strip().split())
p.sort()
min = p[0]
print sum([min*p[i] for i in range(1,n)])
|
3:33
It's possible for all the digits displayed on a digital clock in the hours:minutes format to be identical. The time shown above (3:33) is an example of such a situation. Other examples are 2:2 and 1:11. Note that the digits of 33:33 are identical, but it is not a valid time on a usual digital clock.
The above example was for a usual 24-hour format digital clock. Let's consider a more general clock, where an hour lasts M minutes and a day lasts H hours (therefore, the clock can show any number of hours between 0 and H-1, inclusive, and any number of minutes between 0 and M-1, inclusive). Both the hours and the minutes are shown without leading zeroes in decimal notation and their separator (e.g., ':') doesn't matter.
Can you tell how many minutes during a day will the digital clock have identical digits displayed on it?
Input
The first line of the input contains an integer T - the number of test cases.
Each of the next T lines contains two space-separated integers H and M for one test case.
Output
For each test case, output a single line corresponding to the answer of the problem.
Constraints
1 ≤ T ≤ 50
1 ≤ H, M ≤ 100
Example
Input:
6
24 60
34 50
10 11
10 12
11 11
1 1
Output:
19
20
10
11
10
1
Explanation
Example case 1. A clock shows two identical digits at times 0:0, 1:1, .., 9:9, three identical digits at times 11:1, 22:2, 1:11, 2:22, 3:33, 4:44, 5:55, and four identical digits at times 11:11 and 22:22. So, there are 19 minutes during which the time displayed by the clock will have identical digits.
Example case 2. Compared to the previous case, the clock doesn't show 5:55, but can show 33:3 and 33:33.
Example case 6. In this example, our day consists of one hour and one hour consists of one minute. Hence, the entire day is just 1 minute - the only time the digital clock will display is 0:0 during the entire day, (i.e. the entire hour, i.e. entire minute). And 0:0 has all digits identical, so the answer is 1.
|
for _ in xrange(input()):
H, M = map(int, raw_input().split())
count = 0
for i in range(1, H):
if i < 10 or i % 11 == 0:
start = str(i)[0]
while int(start) in range(M):
count += 1
start += str(i)[0]
print count + 1
|
On Internet sites usually the registration form automatically checks and validate the passowrd's crypt resistance. If the user's password isn't complex enough a message is displayed. You have already implemented password validation in Web Programming class. Today your task is to implement password validation program.
It should meet the following conditions:
Length is atleast 5 characters.
At least one Large English letter.
At least one small English letter.
It should contain at least one digit.
You are given a password. Check whether password satisfies all the conditions.
Input
First line contains sequence of characters (Not more than 100) . Character can be either a small letter, or a large letter, or a digit or one of the characters : "_" , "." , "?" , "," , "!" .
Output
If the password satisfies all the conditions print "YES", otherwise print "NO".
Example
Input:
abcdefgh
Output:
NO
Input:
SPIT_Coders_Club_2.0
Output:
YES
Explanation
Case 1. It contains only lowercase letters.
Case 2. It satisfies all the conditions.
|
import re
t=raw_input()
flag=1
if len(t)<5:
flag=0
regex=re.compile('[a-z]')
if len(regex.findall(t))==0:
flag=0
regex2=re.compile('[A-Z]')
if len(regex2.findall(t))==0:
flag=0
regex3=re.compile('[0-9]')
if len(regex3.findall(t))==0:
flag=0
if flag==1:
print "YES"
else:
print "NO"
|
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 100;
int n, m, k;
struct Edge {
int u, v;
Edge(int _u = 0, int _v = 0) : u(_u), v(_v) {}
} road[maxn];
bool vis[maxn];
int dis[maxn];
int f[maxn];
vector<int> edge[maxn];
vector<int> p[maxn];
vector<string> path;
void bfs() {
queue<int> Q;
Q.push(1);
vis[1] = 1;
while (!Q.empty()) {
int from = Q.front();
Q.pop();
for (int i = 0; i < edge[from].size(); i++) {
int to = edge[from][i];
if (vis[to]) continue;
dis[to] = dis[from] + 1;
vis[to] = true;
Q.push(to);
}
}
}
void getPath() {
memset(f, 0, sizeof(f));
path.clear();
int i, j;
for (i = 0; i < k; i++) {
string s(m, '0');
for (j = 2; j <= n; j++) s[p[j][f[j]]] = '1';
path.push_back(s);
bool flag = false;
for (j = 2; j <= n; j++) {
if (f[j] + 1 < p[j].size()) {
flag = true;
f[j]++;
break;
} else {
f[j] = 0;
}
}
if (!flag) return;
}
}
int main() {
int i, j, x, y;
while (scanf("%d%d%d", &n, &m, &k) != EOF) {
for (i = 0; i <= n; i++) {
vis[i] = dis[i] = 0;
p[i].clear();
edge[i].clear();
}
for (i = 0; i < m; i++) {
scanf("%d%d", &x, &y);
edge[x].push_back(y);
edge[y].push_back(x);
road[i].u = x;
road[i].v = y;
}
bfs();
for (i = 0; i < m; i++) {
int u = road[i].u;
int v = road[i].v;
if (dis[u] == dis[v] + 1) p[u].push_back(i);
if (dis[v] == dis[u] + 1) p[v].push_back(i);
}
getPath();
cout << path.size() << endl;
for (i = 0; i < path.size(); i++) cout << path[i] << endl;
}
return 0;
}
|
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
|
#include <bits/stdc++.h>
using namespace std;
int n, ans, d[200010], p[200010];
vector<vector<int> > gr;
void dfs(int x, int par) {
p[x] = par;
if (par != -1) {
d[x] = d[par] + 1;
}
for (auto j : gr[x]) {
if (j == par) {
continue;
}
dfs(j, x);
}
}
set<pair<int, int> > pajestegreedy;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
vector<int> vi;
gr.resize(n, vi);
for (int i = 0; i < n - 1; ++i) {
int u, v;
cin >> u >> v;
--u, --v;
gr[u].push_back(v);
gr[v].push_back(u);
}
dfs(0, -1);
for (int i = 0; i < n; ++i) {
if (d[i] > 2) pajestegreedy.insert({-d[i], i});
}
while (!pajestegreedy.empty()) {
int x = pajestegreedy.begin()->second;
x = p[x];
if (pajestegreedy.find({-d[x], x}) != pajestegreedy.end())
pajestegreedy.erase({-d[x], x});
for (auto i : gr[x]) {
if (pajestegreedy.find({-d[i], i}) != pajestegreedy.end()) {
pajestegreedy.erase({-d[i], i});
}
}
++ans;
}
cout << ans;
}
|
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all.
Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner.
Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one.
More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots).
Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.
Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?
Input
The first line contains three integers n, k and p (1 ≤ n ≤ 1018, 0 ≤ k ≤ n, 1 ≤ p ≤ 1000) — the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1 ≤ xi ≤ n) the number of slot to describe.
Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
For each query print "." if the slot should be empty and "X" if the slot should be charged.
Examples
Input
3 1 3
1
2
3
Output
..X
Input
6 3 6
1
2
3
4
5
6
Output
.X.X.X
Input
5 2 5
1
2
3
4
5
Output
...XX
Note
The lexicographical comparison of is performed by the < operator in modern programming languages. The a string is lexicographically less that the b string, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.
|
import java.util.Scanner;
public class D
{
public static void main(String[] args)
{
Scanner inp = new Scanner(System.in);
long n=inp.nextLong(),k=inp.nextLong();
int p = inp.nextInt();
if(n%2 == 1){n--;k--;}
for(int i = 0 ; i < p ; i++)
{
long a = inp.nextLong();
if(a>n)
{
if(k>-1)System.out.print("X");
else System.out.print(".");
}
else
{
long b = n-a;
b = (b%2)*(n/2)+(b)/2+1;
if(b<=k)System.out.print("X");
else System.out.print(".");
}
}
System.out.println();
}
}
|
A lot of people dream of convertibles (also often called cabriolets). Some of convertibles, however, don't have roof at all, and are vulnerable to rain. This is why Melon Ask, the famous inventor, decided to create a rain protection mechanism for convertibles.
The workplace of the mechanism is a part of plane just above the driver. Its functional part consists of two rails with sliding endpoints of a piece of stretching rope. For the sake of simplicity we can consider this as a pair of parallel segments in a plane with the rope segment, whose endpoints we are free to choose as any points on these rails segments.
<image>
The algorithmic part of the mechanism detects each particular raindrop and predicts when and where it reaches the plane. At this exact moment the rope segment must contain the raindrop point (so the rope adsorbs the raindrop).
You are given the initial position of the rope endpoints and all information about raindrops. You are to choose the minimal possible speed v of the endpoints sliding (both endpoints can slide in any direction along their segments independently of each other) in such a way that it is possible to catch all raindrops moving both endpoints with speed not greater than v, or find out that it's impossible no matter how high the speed is.
Input
The first line contains three integers n, w and h (1 ≤ n ≤ 10^5, 1≤ w, h ≤ 10^3), meaning that there are n raindrops, and two rails are represented as segments connecting (0, 0) and (w, 0) and connecting (0, h) and (w, h).
The second line contains two integers e_1 and e_2, meaning that the initial (that is, at the moment t = 0) positions of the endpoints are (e_1, 0) and (e_2, h) (0≤ e_1, e_2≤ w).
The i-th of the following n lines contains three integers t_i, x_i and y_i (1≤ t_i≤ 10^5, 0≤ x_i ≤ w, 0 < y_i < h) meaning that the i-th raindrop touches the plane at the point (x_i, y_i) at the time moment t_i. It is guaranteed that t_i ≤ t_{i+1} for all valid i.
Output
If it is impossible to catch all raindrops, print -1.
Otherwise, print the least possible maximum speed of the rope endpoints for which it is possible to catch them all. Your answer is considered correct if the absolute or relative error doesn't exceed 10^{-4}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-4}.
Examples
Input
3 5 5
0 0
1 1 4
2 2 4
3 3 4
Output
1.0000000019
Input
2 5 5
0 0
2 4 1
3 1 4
Output
2.1428571437
Input
3 5 5
0 0
1 2 1
1 3 3
1 4 2
Output
-1
Note
That is how one can act in the first sample test:
<image>
Here is the same for the second:
<image>
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const long double eps1 = 1e-4;
const long double eps2 = 1e-10;
int gi() {
int x = 0, o = 1;
char ch = getchar();
while (!isdigit(ch) && ch != '-') ch = getchar();
if (ch == '-') o = -1, ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
return x * o;
}
struct point {
long double x, y;
point() {}
point(long double x, long double y) : x(x), y(y) {}
point operator+(const point &A) const { return point(x + A.x, y + A.y); }
point operator-(const point &A) const { return point(x - A.x, y - A.y); }
point operator*(long double v) const { return point(x * v, y * v); }
bool operator<(const point &A) const {
return x < A.x - eps1 || (fabsl(x - A.x) < eps1 && y < A.y - eps1);
}
bool operator==(const point &A) const {
return fabsl(x - A.x) < eps1 && fabsl(y - A.y) < eps1;
}
long double operator%(const point &A) const { return x * A.y - y * A.x; }
void print() { cerr << x << ' ' << y << '\n'; }
};
struct line {
point p, v;
line() {}
line(point p, point q) : p(p), v(q - p) {}
void setkb(long double k, long double b) {
*this = line(point(0, b), point(1, k + b));
}
} l[N];
vector<point> sec(line a, line b) {
vector<point> ret;
if (fabsl(b.v % a.v) < eps2) {
if (fabsl(b.v % (a.p - b.p)) < eps2)
ret.push_back(b.p), ret.push_back(b.p + b.v);
return ret;
}
long double tmp = ((a.p - b.p) % a.v) / (b.v % a.v);
if (-eps2 <= tmp && tmp <= 1 + eps2) ret.push_back(b.p + b.v * tmp);
return ret;
}
int n, w, h, e1, e2, t[N];
bool sec(line l, vector<point> vec, point &p, point &q) {
set<point> all;
for (int j = 0; j < int(vec.size()); j++) {
vector<point> tmp = sec(l, line(vec[j], vec[(j + 1) % int(vec.size())]));
for (auto p : tmp) all.insert(p);
}
assert(int(all.size()) <= 2);
if (int(all.size()) == 0) return 0;
if (int(all.size()) == 1)
p = q = *all.begin();
else
p = *all.begin(), q = *all.rbegin();
return 1;
}
bool check(long double mid) {
point p = point(e1, e2), q = p;
for (int i = 1; i <= n; i++) {
vector<point> vec;
long double d = (t[i] - t[i - 1]) * mid;
vec.push_back(p + point(-d, d));
vec.push_back(p + point(d, d));
vec.push_back(q + point(d, d));
vec.push_back(q + point(d, -d));
vec.push_back(q + point(-d, -d));
vec.push_back(p + point(-d, -d));
vec.erase(unique(vec.begin(), vec.end()), vec.end());
while (int(vec.size()) > 1 && vec.back() == vec[0]) vec.pop_back();
if (int(vec.size()) == 1) {
auto r = vec[0], p = l[i].p, q = l[i].p + l[i].v;
if (!(fabsl((r - p) % (r - q)) < eps2)) return 0;
continue;
}
if (!sec(l[i], vec, p, q)) return 0;
if (p == q) {
if (!(-eps2 <= p.x && p.x <= w + eps2 && -eps2 <= p.y && p.y <= w + eps2))
return 0;
} else {
vec.clear();
vec.push_back(point(0, 0));
vec.push_back(point(w, 0));
vec.push_back(point(w, w));
vec.push_back(point(0, w));
point r, s;
if (!sec(line(p, q), vec, r, s)) return 0;
if (p.x < r.x) p = r;
if (q.x > s.x) q = s;
if (p.x > q.x) return 0;
}
}
return 1;
}
int main() {
cin >> n >> w >> h >> e1 >> e2;
cout << setprecision(15) << fixed;
cerr << setprecision(15) << fixed;
for (int i = 1, a, b; i <= n; i++) {
t[i] = gi();
a = gi();
b = gi();
l[i].setkb(1.0 * (b - h) / b, 1.0 * a * h / b);
}
long double l = 0, r = w + 1;
for (int T = 1; T <= 50; T++) {
long double mid = (l + r) / 2;
if (check(mid))
r = mid;
else
l = mid;
}
if (l > w + 0.5)
cout << -1;
else
cout << l;
return 0;
}
|
You are given an array a of n points in k-dimensional space. Let the distance between two points a_x and a_y be ∑ _{i = 1}^{k} |a_{x, i} - a_{y, i}| (it is also known as Manhattan distance).
You have to process q queries of the following two types:
* 1 i b_1 b_2 ... b_k — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
Input
The first line contains two numbers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 5) — the number of elements in a and the number of dimensions of the space, respectively.
Then n lines follow, each containing k integers a_{i, 1}, a_{i, 2}, ..., a_{i, k} (-10^6 ≤ a_{i, j} ≤ 10^6) — the coordinates of i-th point.
The next line contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries.
Then q lines follow, each denoting a query. There are two types of queries:
* 1 i b_1 b_2 ... b_k (1 ≤ i ≤ n, -10^6 ≤ b_j ≤ 10^6) — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r (1 ≤ l ≤ r ≤ n) — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
There is at least one query of the second type.
Output
Print the answer for each query of the second type.
Example
Input
5 2
1 2
2 3
3 4
4 5
5 6
7
2 1 5
2 1 3
2 3 5
1 5 -1 -2
2 1 5
1 4 -1 -2
2 1 5
Output
8
4
4
12
10
|
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.FileReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
GMultidimensionalQueries solver = new GMultidimensionalQueries();
solver.solve(1, in, out);
out.close();
}
static class GMultidimensionalQueries {
private int get(int[] p, int mask) {
int toRet = 0;
for (int i = 0; i < p.length; i++) {
toRet += p[i] * ((mask & 1 << i) != 0 ? -1 : 1);
}
return toRet;
}
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int n = sc.nextInt();
int k = sc.nextInt();
int[][] arr = new int[n][k];
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++)
arr[i][j] = sc.nextInt();
}
int N = 1;
while (N < n)
N <<= 1;
SegmentTree[] trees = new SegmentTree[1 << k];
for (int i = 0; i < 1 << k; i++) {
int[] temp = new int[N + 1];
for (int j = 0; j < n; j++)
temp[j + 1] = get(arr[j], i);
trees[i] = new SegmentTree(temp);
}
int q = sc.nextInt();
while (q-- > 0) {
int type = sc.nextInt();
if (type == 2) {
long max = 0;
int l = sc.nextInt(), r = sc.nextInt();
for (int i = 0; i < (1 << k); i++) {
int temp = trees[i].query(l, r);
int temp2 = trees[((1 << k) - 1) ^ i].query(l, r);
max = Math.max(max, temp + temp2);
}
pw.println(max);
} else {
int idx = sc.nextInt();
int[] temp = new int[k];
for (int i = 0; i < k; i++)
temp[i] = sc.nextInt();
for (int i = 0; i < 1 << k; i++) {
trees[i].update_point(idx, get(temp, i));
}
}
}
}
public class SegmentTree {
int N;
int[] array;
int[] max;
SegmentTree(int[] in) {
array = in;
N = in.length - 1;
max = new int[N << 1]; //no. of nodes = 2*N - 1, we add one to cross out index zero
build(1, 1, N);
}
void build(int node, int b, int e) {
if (b == e) {
max[node] = array[e];
} else {
int mid = b + e >> 1;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
max[node] = Math.max(max[node << 1], max[node << 1 | 1]);
}
}
void update_point(int index, int val) {
array[index] = val;
index += N - 1;
max[index] = val;
while (index > 1) {
index >>= 1;
max[index] = Math.max(max[index << 1], max[index << 1 | 1]);
}
}
int query(int i, int j) {
return query(1, 1, N, i, j);
}
int query(int node, int b, int e, int i, int j) {
if (i > e || j < b)
return (int) -1e9;
if (b >= i && e <= j)
return max[node];
int mid = b + e >> 1;
int q1 = query(node << 1, b, mid, i, j);
int q2 = query(node << 1 | 1, mid + 1, e, i, j);
return Math.max(q1, q2);
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 15:00:31 2019
@author: avina
"""
x,y,z = map(int, input().strip().split())
a,b,c = map(int,input().strip().split())
k=0
if a+b+c >= x+y+z:
if a+b >= x+y:
if a>=x:
k+=1
if k != 0:
print("YES")
else:
print("NO")
|
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1 << 18;
int a[N], pre[N], p[N], pos[N];
int fa[N][20], dp[N][20];
int rmq(int l, int r) {
int k = 31 - __builtin_clz(r - l + 1);
return max(dp[l][k], dp[r - (1 << k) + 1][k]);
}
int main() {
int n, m, q;
scanf("%d%d%d", &n, &m, &q);
for (int i = 1; i <= n; i++) scanf("%d", &p[i]), pre[p[i]] = p[i - 1];
pre[p[1]] = p[n];
for (int i = 1, x; i <= m; i++) {
scanf("%d", &x);
fa[i][0] = pos[pre[x]];
for (int j = 1; j < 20; j++) fa[i][j] = fa[fa[i][j - 1]][j - 1];
pos[x] = i;
}
for (int i = 1; i <= m; i++) {
int x = i, k = n - 1;
for (int j = 19; j >= 0; j--)
if (k >> j & 1) x = fa[x][j];
dp[i][0] = x;
}
for (int j = 1; (1 << j) <= m; j++)
for (int i = 1; i + (1 << j) - 1 <= m; i++)
dp[i][j] = max(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
for (int i = 0, l, r; i < q; i++) {
scanf("%d%d", &l, &r);
putchar(rmq(l, r) >= l ? '1' : '0');
}
}
|
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
|
#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
using vi = vector<int>;
using ll = long long;
int n, m;
vector<pii> a;
unordered_set<ll> s;
bool f(int r) {
for (int i = int(0); i < int(m); i++) {
ll x = a[i].first + r, y = a[i].second + r;
if (x >= n) x -= n;
if (y >= n) y -= n;
if (x > y) swap(x, y);
if (!s.count(x * n + y)) return 0;
}
return 1;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
a.resize(m);
s.reserve(1 << 17);
s.max_load_factor(0.25);
for (int i = int(0); i < int(m); i++) {
int x, y;
cin >> x >> y;
if (x == n) x = 0;
if (y == n) y = 0;
if (x > y) swap(x, y);
a[i] = {x, y};
s.emplace(ll(x) * n + y);
}
for (int i = 1; i * i <= n; i++) {
if (n % i == 0 && (f(i) || (i > 1 && f(n / i)))) return cout << "Yes\n", 0;
}
return cout << "No\n", 0;
}
|
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a;
* if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b;
* if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries. Each query is presented by a single line.
The only line of the query contains four integers k, n, a and b (1 ≤ k, n ≤ 10^9, 1 ≤ b < a ≤ 10^9) — the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.
Output
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
Example
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
Note
In the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
|
n=int(input())
for i in range(0,n):
p=input().rstrip().split(' ')
k=int(p[0])
K=k;
n=int(p[1])
CC=n;
a=int(p[2])
b=int(p[3])
T=min(a,b);
if (k%T==0):
H=(k//T)-1;
else:
H=(k//T)
if n>H:
print(-1)
else:
if k%a==0:
A=(k//a)-1;
else:
A=(k//a)
B=k-(A*a)
k=B;
n=n-A;
if n<=0:
if A>=CC:
print(CC)
else:
print(A)
else:
G=(b*n);
if k>G:
if A>=CC:
print(CC)
else:
print(A)
else:
V=-99999;
GG=1;
MM=G-k;
LL=a-b;
XX=(MM//LL)+1;
A=A-XX;
if A>=CC:
print(CC)
else:
print(A)
|
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint — black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 ≤ k ≤ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 ≤ i, j ≤ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i ≤ i' ≤ i + k - 1 and j ≤ j' ≤ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2000) — the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines — the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
|
import java.io.*;
import java.math.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.util.Comparator.*;
public class Main {
FastScanner in;
PrintWriter out;
ArrayList<Integer>[] graph;
ArrayList<GraphPair>[] weightedGraph;
long mod = (long) 1e9 + 7; // 998_244_353L || (long) 1e9 + 9
boolean multitests = false;
private void solve() throws IOException {
// solveA();
// solveB();
// solveC();
solveD();
// solveE();
// solveF();
}
private void solveA() throws IOException {
in.next();
boolean[] used = new boolean[10];
for (char c : in.next().toCharArray())
if (c == 'L') {
for (int i = 0; i < 10; i++) {
if (!used[i]) {
used[i] = true;
break;
}
}
} else if (c == 'R') {
for (int i = 9; i >= 0; i--) {
if (!used[i]) {
used[i] = true;
break;
}
}
} else
used[c - '0'] = false;
for (int i = 0; i < 10; i++)
out.print(used[i] ? 1 : 0);
}
private void solveB() throws IOException {
int n = in.nextInt();
long m = in.nextLong(), k = in.nextLong();
long[] h = in.nextLongArray(n);
for (int i = 0; i < n - 1; i++) {
if (h[i] > max(0, h[i + 1] - k)) {
m += h[i] - max(0, h[i + 1] - k);
} else if (h[i] < h[i + 1] - k) {
m -= h[i + 1] - k - h[i];
if (m < 0) {
out.println("NO");
return;
}
}
}
out.println("YES");
}
private void solveC() throws IOException {
long n = in.nextLong(), m = in.nextLong();
long gcd = gcd(n, m);
int q = in.nextInt();
while (q-- > 0) {
long sx = in.nextLong(), sy = in.nextLong() - 1;
long ex = in.nextLong(), ey = in.nextLong() - 1;
if ((sx == 1 ? sy / (n / gcd) : sy / (m / gcd)) == (ex == 1 ? ey / (n / gcd) : ey / (m / gcd)))
out.println("YES");
else
out.println("NO");
}
}
private void solveD() throws IOException {
int n = in.nextInt(), k = in.nextInt();
int[] maxI = new int[n], minI = new int[n];
int[] maxJ = new int[n], minJ = new int[n];
fill(maxI, -1);
fill(minI, n + 1);
fill(maxJ, -1);
fill(minJ, n + 1);
for (int i = 0; i < n; i++) {
char[] s = in.next().toCharArray();
for (int j = 0; j < n; j++) {
if (s[j] == 'B') {
minI[i] = min(minI[i], j);
maxI[i] = max(maxI[i], j);
minJ[j] = min(minJ[j], i);
maxJ[j] = max(maxJ[j], i);
}
}
}
int answer = 0;
int[][] ansI = new int[n][n];
for (int i = 0; i < n; i++) {
if (minI[i] > maxI[i])
answer++;
else if (maxI[i] - minI[i] + 1 > k)
continue;
else {
int add = k - (maxI[i] - minI[i] + 1);
for (int j = 0; j < k && i - j >= 0; j++) {
ansI[i - j][max(0, minI[i] - add)]++;
if (minI[i] + 1 < n)
ansI[i - j][minI[i] + 1]--;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 1; j < n; j++) {
ansI[i][j] += ansI[i][j - 1];
}
}
int[][] ansJ = new int[n][n];
for (int j = 0; j < n; j++) {
if (minJ[j] > maxJ[j])
answer++;
else if (maxJ[j] - minJ[j] + 1 > k)
continue;
else {
int add = k - (maxJ[j] - minJ[j] + 1);
for (int i = 0; i < k && j - i >= 0; i++) {
ansJ[max(0, minJ[j] - add)][j - i]++;
if (minJ[j] + 1 < n)
ansJ[minJ[j] + 1][j - i]--;
}
}
}
for (int j = 0; j < n; j++) {
for (int i = 1; i < n; i++) {
ansJ[i][j] += ansJ[i - 1][j];
}
}
int max = 0;
for (int i = 0; i < n - k + 1; i++) {
for (int j = 0; j < n - k + 1; j++) {
max = max(max, ansI[i][j] + ansJ[i][j]);
}
}
out.println(answer+max);
}
private void solveE() throws IOException {
}
private void solveF() throws IOException {
}
void shuffleInt(int[] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
int swap = a[j];
a[j] = a[i];
a[i] = swap;
}
}
void shuffleLong(long[] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
long swap = a[j];
a[j] = a[i];
a[i] = swap;
}
}
void reverseInt(int[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
void reverseLong(long[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
long swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
int maxInt(int[] a) {
int max = a[0];
for (int i = 1; i < a.length; i++)
if (max < a[i])
max = a[i];
return max;
}
long maxLong(long[] a) {
long max = a[0];
for (int i = 1; i < a.length; i++)
if (max < a[i])
max = a[i];
return max;
}
int minInt(int[] a) {
int min = a[0];
for (int i = 1; i < a.length; i++)
if (min > a[i])
min = a[i];
return min;
}
long minLong(long[] a) {
long min = a[0];
for (int i = 1; i < a.length; i++)
if (min > a[i])
min = a[i];
return min;
}
long sumInt(int[] a) {
long s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];
return s;
}
long sumLong(long[] a) {
long s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];
return s;
}
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long binpowmod(long a, long n) {
long res = 1;
a %= mod;
n %= mod - 1;
while (n > 0) {
if (n % 2 == 1)
res = (res * a) % mod;
a = (a * a) % mod;
n /= 2;
}
return res;
}
class GraphPair implements Comparable<GraphPair> {
int v;
long w;
GraphPair(int v, long w) {
this.v = v;
this.w = w;
}
public int compareTo(GraphPair o) {
return w != o.w ? Long.compare(w, o.w) : Integer.compare(v, o.v);
}
}
ArrayList<Integer>[] createGraph(int n) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
ArrayList<GraphPair>[] createWeightedGraph(int n) throws IOException {
ArrayList<GraphPair>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s), 32768);
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
return a;
}
int[][] nextIntTable(int n, int m) throws IOException {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextInt();
return a;
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = in.nextLong();
return a;
}
long[][] nextLongTable(int n, int m) throws IOException {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextLong();
return a;
}
ArrayList<Integer>[] nextGraph(int n, int m, boolean directed) throws IOException {
ArrayList<Integer>[] graph = createGraph(n);
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1, u = in.nextInt() - 1;
graph[v].add(u);
if (!directed)
graph[u].add(v);
}
return graph;
}
ArrayList<GraphPair>[] nextWeightedGraph(int n, int m, boolean directed) throws IOException {
ArrayList<GraphPair>[] graph = createWeightedGraph(n);
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1, u = in.nextInt() - 1;
long w = in.nextLong();
graph[v].add(new GraphPair(u, w));
if (!directed)
graph[u].add(new GraphPair(v, w));
}
return graph;
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
for (int t = multitests ? in.nextInt() : 1; t-- > 0; )
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
}
|
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 ≤ N ≤ 10^5) and K (1 ≤ K ≤ 10^5) – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 ≤ X[i] ≤ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 ≤ A ≤ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 ≤ C[i] ≤ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.
|
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify
def main():
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
for _ in range(1):
n,k=ria()
x=ria()
a=ri()
c=ria()
mcum=[]
heapmcum=heapify(mcum)
m=9999999999999999999999
spent=0
for i in range(n):
cost=0
heappush(mcum,c[i])
if k<x[i]:
while k<x[i]:
if len(mcum)==0:
spent=-1
break
cost+=heappop(mcum)
k+=a
if spent==-1:
break
spent+=cost
print(spent)
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
|
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 ≤ k ≤ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 ≤ n_i ≤ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, …, a_{i,n_i} (|a_{i,j}| ≤ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 15 * 5000 + 5;
int k, v[20], vis[maxn];
long long a[20][5050], ss[20], tot, sum;
struct node {
int val, bel;
} x[maxn];
map<long long, int> mp;
vector<int> g[maxn], rec[1 << 15 + 5], tmp;
int pre[1 << 15 + 5], dp[1 << 15 + 5], ok[1 << 15 + 5], l[20], r[20];
void getans(int y) {
int sz = rec[y].size();
for (int i = 0; i < sz; i++) {
int now = rec[y][i];
int nxt;
if (i == sz - 1)
nxt = rec[y][0];
else
nxt = rec[y][i + 1];
l[x[now].bel + 1] = x[now].val;
r[x[now].bel + 1] = x[nxt].bel + 1;
}
}
void dfs(int u, int st) {
if (vis[u]) {
int num = tmp.size();
int now = 0;
for (int i = num - 1; i >= 0; i--) {
now = now | (1 << x[tmp[i]].bel);
if (tmp[i] == u) break;
}
if (!ok[now]) {
ok[now] = 1;
for (int i = num - 1; i >= 0; i--) {
rec[now].push_back(tmp[i]);
if (tmp[i] == u) break;
}
}
return;
}
if (st & (1 << x[u].bel)) {
return;
}
vis[u] = 1;
tmp.push_back(u);
for (int i = 0; i < g[u].size(); i++) {
dfs(g[u][i], (st | (1 << x[u].bel)));
}
vis[u] = 0;
tmp.pop_back();
}
int main() {
scanf("%d", &k);
sum = tot = 0;
for (int i = 1; i <= k; i++) {
scanf("%d", &v[i]);
for (int j = 1; j <= v[i]; j++) {
scanf("%lld", &a[i][j]);
ss[i] += a[i][j];
sum += a[i][j];
mp[a[i][j]] = ++tot;
x[tot].val = a[i][j];
x[tot].bel = i - 1;
}
}
if (sum % k) {
printf("No\n");
return 0;
}
sum /= k;
for (int i = 1; i <= k; i++) {
for (int j = 1; j <= v[i]; j++) {
if (mp.count(a[i][j] - ss[i] + sum)) {
g[mp[a[i][j]]].push_back(mp[a[i][j] - ss[i] + sum]);
}
}
}
int mx = (1 << k) - 1;
for (int i = 0; i <= mx; i++) dp[i] = 0, ok[i] = 0;
dp[0] = 1;
for (int i = 1; i <= tot; i++) {
tmp.clear();
dfs(i, 0);
}
for (int i = 0; i <= mx; i++) {
if (dp[i]) {
int S = mx ^ i;
for (int j = S; j; j = ((j - 1) & S)) {
if (ok[j]) {
dp[i | j] = 1;
pre[i | j] = i;
}
}
}
}
if (!dp[mx]) {
printf("No\n");
return 0;
}
int now = mx;
while (now) {
int y = now ^ pre[now];
getans(y);
now = pre[now];
}
printf("Yes\n");
for (int i = 1; i <= k; i++) {
printf("%d %d\n", l[i], r[i]);
}
}
|
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.
A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a n × m rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.
The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as 0) some trees were set on fire. At the beginning of minute 0, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of 8 neighboring trees. At the beginning of minute T, the fire was extinguished.
The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of T (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of T (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.
Note that you'd like to maximize value T but the set of trees can be arbitrary.
Input
The first line contains two integer n and m (1 ≤ n, m ≤ 10^6, 1 ≤ n ⋅ m ≤ 10^6) — the sizes of the map.
Next n lines contain the map. The i-th line corresponds to the i-th row of the map and contains m-character string. The j-th character of the i-th string is "X" if the corresponding tree is burnt and "." otherwise.
It's guaranteed that the map contains at least one "X".
Output
In the first line print the single integer T — the maximum time the Forest was on fire. In the next n lines print the certificate: the map (n × m rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".
Examples
Input
3 6
XXXXXX
XXXXXX
XXXXXX
Output
1
......
.X.XX.
......
Input
10 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........
Output
2
..........
..........
...XX.....
..........
..........
..........
.....XX...
..........
..........
..........
Input
4 5
X....
..XXX
..XXX
..XXX
Output
0
X....
..XXX
..XXX
..XXX
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* https://codeforces.com/contest/1261/problem/C
*/
public class TaskC {
public static void main(String[] arg) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
final int m = in.nextInt();
char[][] forest = new char[n][];
for(int i=0;i<n;i++){
forest [i] = in.next().toCharArray();
}
Solution sol = new Solution(forest);
sol.bfs();
sol.checkSolution(out);
out.close();
in.close();
}
public static class Solution {
private final char [][] forest;
private final Map<Integer,List<int[]>> pA = new HashMap<>();
private final int[][] mem;
public Solution(char [][] forest){
this.forest=forest;
mem = new int[forest.length][forest[0].length];
}
public void bfs() {
for(int i=0;i<mem.length;i++){
for(int j=0;j<mem[i].length;j++){
if(forest[i][j]=='.') {
mem[i][j] = -1;
}
}
}
Queue<int[]> toVisit = new LinkedList<>();
for (int i = 0; i < forest.length; i++) {
for (int j = 0; j < forest[i].length; j++) {
if (forest[i][j]=='X' && border(i, j)) {
toVisit.add(new int[]{i, j});
mem[i][j]=1;
addToMap(1,new int[]{i,j});
}
}
}
while(!toVisit.isEmpty()){
int [] point = toVisit.poll();
List<int[]> notVisited = notVisited(point[0],point[1],mem);
for(int[]p:notVisited){
mem[p[0]][p[1]]=mem[point[0]][point[1]]+1;
toVisit.add(p);
addToMap(mem[p[0]][p[1]], p);
}
}
}
public void checkSolution(PrintWriter out){
int[] keys = pA.keySet().stream().sorted().mapToInt(i->i).toArray();
int h = 0;
int l = 0;
h = keys.length - 1;
int m = (l + h + 1) / 2;
while (l != h) {
int key = keys[m];
if (runFireBFS(key)) {
l = m;
} else {
h = m - 1;
}
m = (l + h + 1) / 2;
}
printAnsw(keys[h], out);
return;
}
public void printAnsw(int key, PrintWriter out){
char[][] iF = new char[forest.length][forest[0].length];
for(int x=0;x<iF.length;x++){
for(int y=0;y<iF[x].length;y++){
iF[x][y]='.';
if(mem[x][y]>=key){
iF[x][y]='X';
}
}
}
out.printf("%d%n",key-1);
for(int x=0;x<iF.length;x++){
out.println(String.valueOf(iF[x]));
}
}
public boolean runFireBFS(int key){
Queue<int[]> q = new LinkedList<>();
//init
int step = 1;
int [][] m = new int[forest.length][forest[0].length];
for(int i=0;i<mem.length;i++){
for(int j=0;j<mem[i].length;j++) {
if(mem[i][j]>=key) {
int x = i;
int y = j;
q.add(new int[]{step, x, y});
m[i][j] = 1;
}
}
}
while(!q.isEmpty()&&step<=key){
int [] fire = q.poll();
step=fire[0];
m[fire[1]][fire[2]]=step;
List<int[]> spred = spredFire(fire[1],fire[2],m);
for(int[] nF:spred){
int x = nF[0];
int y = nF[1];
int nS=step+1;
if(nS<=key) {
if (forest[x][y] == '.') {
return false;
}
m[x][y]=nS;
q.add(new int[]{nS, x, y});
}
}
}
for(int i=0;i<forest.length;i++){
for(int j=0;j<forest[i].length;j++){
if(m[i][j]==0 &&forest[i][j]=='X'){
return false;
}
if(m[i][j]!=0&&forest[i][j]=='.'){
return false;
}
}
}
return true;
}
private List<int[]> spredFire(int x, int y, int[][] mem) {
List<int[]> result = new ArrayList<>();
for(int i=x-1;i<=x+1;i++){
if(i<0){continue;}
if(i>=mem.length){continue;}
for(int j=y-1;j<=y+1;j++){
if(j<0){continue;}
if(j>=mem[i].length){continue;}
if(mem[i][j]!=0){
continue;
}
result.add(new int[]{i,j});
}
}
return result;
}
public void addToMap(int key, int[] point) {
List<int[]> points = pA.get(key);
if(points==null){
points = new ArrayList<>();
pA.put(key,points);
}
points.add(point);
}
private List<int[]> notVisited(final int x, final int y, int [][] mem){
List<int[]> result = new LinkedList<>();
for(int i=x-1;i<=x+1;i++){
if(i<0){continue;}
if(i>=mem.length){
continue;
}
for(int j=y-1;j<=y+1;j++){
if(j<0){continue;}
if(j>=mem[i].length){continue;}
if(mem[i][j]==0){
result.add(new int[]{i,j});
}
}
}
return result;
}
private boolean border(final int x, final int y){
for(int i=x-1;i<=x+1;i++){
if(i<0) {return true;}
if(i>=forest.length){return true;}
for(int j=y-1;j<=y+1;j++){
if(j<0){return true;}
if(j>=forest[i].length){return true;}
if(forest[i][j]=='.'){
return true;
}
}
}
return false;
}
}
private static void printMatrix(int [][] forest){
for(int i=0;i<forest.length;i++){
for(int j=0;j<forest[i].length;j++){
System.out.printf("%3d",forest[i][j]);
}
System.out.printf("%n");
}
}
private static void printMatrix(char [][] forest){
for(int i=0;i<forest.length;i++){
for(int j=0;j<forest[i].length;j++){
System.out.printf("%c",forest[i][j]);
}
System.out.printf("%n");
}
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.
For all friends 1 ≤ x_i ≤ n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).
For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.
So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of friends.
The second line contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ n) — the coordinates of the houses of the friends.
Output
Print two integers — the minimum and the maximum possible number of occupied houses after all moves are performed.
Examples
Input
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
Note
In the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.
For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example.
|
#include <bits/stdc++.h>
using namespace std;
const long long MOD = 998244353;
long long mpow(long long a, long long b, long long p = MOD) {
a = a % p;
long long res = 1;
while (b > 0) {
if (b & 1) res = (res * a) % p;
a = (a * a) % p;
b = b >> 1;
}
return res % p;
}
const long long N = 2e5 + 100;
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long n;
cin >> n;
long long a[n];
for (long long i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
map<long long, long long> ma;
ma[a[0] + 1]++;
for (long long i = 1; i < n; i++) {
long long poss1 = ma[a[i] - 1];
long long poss2 = ma[a[i] + 1];
long long poss3 = ma[a[i]];
if (poss1 == 1 || poss2 == 1 || poss3 == 1) {
} else {
ma[a[i] + 1]++;
}
}
long long mn = 0;
for (auto x : ma) mn += x.second;
ma.clear();
ma[a[0] - 1]++;
for (long long i = 1; i < n; i++) {
long long poss1 = ma[a[i] - 1];
long long poss2 = ma[a[i] + 1];
long long poss3 = ma[a[i]];
if (poss1 == 0 || poss2 == 0 || poss3 == 0) {
if (poss1 == 0) {
ma[a[i] - 1]++;
} else if (poss3 == 0) {
ma[a[i]]++;
} else {
ma[a[i] + 1]++;
}
} else {
}
}
long long mx = 0;
for (auto x : ma) mx += x.second;
cout << mn << " " << mx << "\n";
}
|
You are given a string s. Each character is either 0 or 1.
You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.
You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases.
Then t lines follow, each representing a test case. Each line contains one string s (1 ≤ |s| ≤ 100); each character of s is either 0 or 1.
Output
Print t integers, where the i-th integer is the answer to the i-th testcase (the minimum number of 0's that you have to erase from s).
Example
Input
3
010011
0
1111000
Output
2
0
0
Note
In the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
|
n=int(input())
for i in range(n):
x=input()
if '1' in x:
a=x.index('1')
c=0
for j in range(a+1,len(x)):
if x[j]=='1':
c+=x.count('0',a,j)
a=j
print(c)
else:
print(0)
|
The King of Berland Polycarp LXXXIV has n daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are n other kingdoms as well.
So Polycarp LXXXIV has enumerated his daughters from 1 to n and the kingdoms from 1 to n. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.
Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.
For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the n-th daughter.
For example, let there be 4 daughters and kingdoms, the lists daughters have are [2, 3], [1, 2], [3, 4], [3], respectively.
<image>
In that case daughter 1 marries the prince of kingdom 2, daughter 2 marries the prince of kingdom 1, daughter 3 marries the prince of kingdom 3, leaving daughter 4 nobody to marry to.
Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.
Polycarp LXXXIV wants to increase the number of married couples.
Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.
If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.
For your and our convenience you are asked to answer t independent test cases.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases.
Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^5) — the number of daughters and the number of kingdoms.
Each of the next n lines contains the description of each daughter's list. The first integer k (0 ≤ k ≤ n) is the number of entries in the i-th daughter's list. After that k distinct integers follow g_i[1], g_i[2], ..., g_i[k] (1 ≤ g_i[j] ≤ n) — the indices of the kingdoms in the list in the increasing order (g_i[1] < g_i[2] < ... < g_i[k]).
It's guaranteed that the total number of daughters over all test cases does not exceed 10^5.
It's also guaranteed that the total number of kingdoms in lists over all test cases does not exceed 10^5.
Output
For each test case print the answer to it.
Print "IMPROVE" in the first line if Polycarp LXXXIV can add some kingdom to some of his daughter's list so that the total number of married couples increases. The second line then should contain two integers — the index of the daughter and the index of the kingdom Polycarp LXXXIV should add to that daughter's list.
If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.
Otherwise the only line should contain one word "OPTIMAL".
Example
Input
5
4
2 2 3
2 1 2
2 3 4
1 3
2
0
0
3
3 1 2 3
3 1 2 3
3 1 2 3
1
1 1
4
1 1
1 2
1 3
1 4
Output
IMPROVE
4 4
IMPROVE
1 1
OPTIMAL
OPTIMAL
OPTIMAL
Note
The first test case is depicted in the statement. Adding the fourth kingdom to the list of the fourth daughter makes her marry the prince of the fourth kingdom.
In the second test case any new entry will increase the number of marriages from 0 to 1.
In the third and the fourth test cases there is no way to add an entry.
In the fifth test case there is no way to change the marriages by adding any entry.
|
t = int(input())
setups = []
for _ in range(t):
n = int(input())
setup = []
for _ in range(n):
count_and_list = input().split(" ")
if len(count_and_list) == 1:
husbands = tuple()
else:
husbands = tuple(int(x) for x in count_and_list[1:])
setup.append(husbands)
setups.append(setup)
def process(setup):
available_husbands = set(range(1, len(setup)+1))
for daughter_index, daughter_prefs in enumerate(setup, 1):
took_someone = False
for husband in daughter_prefs:
if husband in available_husbands:
took_someone = True
available_husbands.remove(husband)
break
if not took_someone:
bad_daughter = daughter_index
if len(available_husbands) > 0:
print("IMPROVE")
print(f"{bad_daughter} {available_husbands.pop()}")
else:
print("OPTIMAL")
for setup in setups:
process(setup)
|
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.
Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from left to right. For example, codeforces contains codeforces a single time, while codeforcesisawesome contains codeforces four times: codeforcesisawesome, codeforcesisawesome, codeforcesisawesome, codeforcesisawesome.
Help Karl find any shortest string that contains at least k codeforces subsequences.
Input
The only line contains a single integer k (1 ≤ k ≤ 10^{16}).
Output
Print a shortest string of lowercase English letters that contains at least k codeforces subsequences. If there are several such strings, print any of them.
Examples
Input
1
Output
codeforces
Input
3
Output
codeforcesss
|
k = int(input())
cur = 10**18
best = []
for p in range(1, 41):
for q in range(1, 41):
for i in range(1, 10):
res = (p**i)*(q**(10-i))
if res >= k:
temp = p*i+q*(10-i)-10
if temp <= cur:
cur = temp
best = (p, q, i)
#print(cur)
#print(best)
p, q, i = best
t = 'codeforces'
t1 = t[0:i]
t2 = t[i:]
s = ''
for j in range(len(t1)):
s += p*t1[j]
for j in range(len(t2)):
s += q*t2[j]
print(s)
|
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
|
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa=ifa[::-1]
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def linc(f,t,l,r):
while l<r:
mid=(l+r)//2
if t>f(mid):
l=mid+1
else:
r=mid
return l
def rinc(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t<f(mid):
r=mid-1
else:
l=mid
return l
def ldec(f,t,l,r):
while l<r:
mid=(l+r)//2
if t<f(mid):
l=mid+1
else:
r=mid
return l
def rdec(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t>f(mid):
r=mid-1
else:
l=mid
return l
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def binfun(x):
c=0
for w in arr:
c+=ceil(w/x)
return c
def lowbit(n):
return n&-n
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
'''
class SMT:
def __init__(self,arr):
self.n=len(arr)-1
self.arr=[0]*(self.n<<2)
self.lazy=[0]*(self.n<<2)
def Build(l,r,rt):
if l==r:
self.arr[rt]=arr[l]
return
m=(l+r)>>1
Build(l,m,rt<<1)
Build(m+1,r,rt<<1|1)
self.pushup(rt)
Build(1,self.n,1)
def pushup(self,rt):
self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1]
def pushdown(self,rt,ln,rn):#lr,rn表区间数字数
if self.lazy[rt]:
self.lazy[rt<<1]+=self.lazy[rt]
self.lazy[rt<<1|1]=self.lazy[rt]
self.arr[rt<<1]+=self.lazy[rt]*ln
self.arr[rt<<1|1]+=self.lazy[rt]*rn
self.lazy[rt]=0
def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间
if r==None: r=self.n
if L<=l and r<=R:
self.arr[rt]+=c*(r-l+1)
self.lazy[rt]+=c
return
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
if L<=m: self.update(L,R,c,l,m,rt<<1)
if R>m: self.update(L,R,c,m+1,r,rt<<1|1)
self.pushup(rt)
def query(self,L,R,l=1,r=None,rt=1):
if r==None: r=self.n
#print(L,R,l,r,rt)
if L<=l and R>=r:
return self.arr[rt]
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
ans=0
if L<=m: ans+=self.query(L,R,l,m,rt<<1)
if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1)
return ans
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]<self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
for v in graph[u]:
if v not in d or d[v]>d[u]+graph[u][v]:
d[v]=d[u]+graph[u][v]
heappush(heap,(d[v],v))
return d
def GP(it): return [(ch,len(list(g))) for ch,g in groupby(it)]
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
t=N()
for i in range(t):
n,k=RL()
l1,r1=RL()
l2,r2=RL()
if l1>l2:
l1,r1,l2,r2=l2,r2,l1,r1
if r1<l2:
if k<=r2-l1:
ans=l2-r1+k
else:
#print(r2,l1,k)
k-=r2-l1
#print(k)
n-=1
ans=l2-l1+r2-r1
d,m=divmod(k,r2-l1)
#print(k,n,ans,d,m)
if d>=n:
ans+=n*(r2-r1+l2-l1)+(k-n*(r2-l1))*2
else:
ans+=d*(r2-r1+l2-l1)+min(m*2,l2-r1+m)
else:
a=min(r1,r2)-l2
p=max(r1,r2)-l1
if n*a>=k:
ans=0
elif n*p>=k:
ans=k-n*a
else:
ans=n*(p-a)+(k-n*p)*2
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
|
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image>
|
//package round100;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), R = ni(), r = ni();
if(r > R){
out.println("NO");
}else if(R < 2*r){
out.println(n == 1 ? "YES" : "NO");
}else{
double th = Math.asin((double)r/(R-r))*2;
if(n >= 2*Math.PI/th+(1E-10)){
out.println("NO");
}else{
out.println("YES");
}
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception
{
new A().run();
}
public int ni()
{
try {
int num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public long nl()
{
try {
long num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public String ns()
{
try{
int b = 0;
StringBuilder sb = new StringBuilder();
while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
if(b == -1)return "";
sb.append((char)b);
while(true){
b = is.read();
if(b == -1)return sb.toString();
if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
sb.append((char)b);
}
} catch (IOException e) {
}
return "";
}
public char[] ns(int n)
{
char[] buf = new char[n];
try{
int b = 0, p = 0;
while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
if(b == -1)return null;
buf[p++] = (char)b;
while(p < n){
b = is.read();
if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
buf[p++] = (char)b;
}
return Arrays.copyOf(buf, p);
} catch (IOException e) {
}
return null;
}
double nd() { return Double.parseDouble(ns()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
You are given a string s. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the string "aeddba". To accomplish your goal, you can swap the neighboring elements of the string.
Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.
Input
The first line contains one integer n (2 ≤ n ≤ 200 000) — the length of s.
The second line contains s — a string consisting of n lowercase Latin letters.
Output
Print one integer — the minimum number of swaps of neighboring elements you have to perform to reverse the string.
Examples
Input
5
aaaza
Output
2
Input
6
cbaabc
Output
0
Input
9
icpcsguru
Output
30
Note
In the first example, you have to swap the third and the fourth elements, so the string becomes "aazaa". Then you have to swap the second and the third elements, so the string becomes "azaaa". So, it is possible to reverse the string in two swaps.
Since the string in the second example is a palindrome, you don't have to do anything to reverse it.
|
#include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long sum = 0, ff = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') ff = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') sum = sum * 10 + ch - '0', ch = getchar();
return sum * ff;
}
const long long N = 2e5 + 7;
long long n, a[28][N], b[N], cnt[27], tr[N], ans;
char s[N], t[N];
inline long long lowbit(long long x) { return x & (-x); }
void modify(long long x) {
for (; x <= n; x += lowbit(x)) tr[x]++;
}
long long ask(long long x) {
long long sum = 0;
for (; x; x -= lowbit(x)) sum += tr[x];
return sum;
}
signed main() {
n = read();
for (long long i = 1; i <= n; i++) cin >> s[i], t[n - i + 1] = s[i];
for (long long i = 1; i <= n; i++)
a[t[i] - 'a' + 1][++cnt[t[i] - 'a' + 1]] = i;
memset(cnt, 0, sizeof(cnt));
for (long long i = 1; i <= n; i++)
b[i] = a[s[i] - 'a' + 1][++cnt[s[i] - 'a' + 1]];
for (long long i = n; i >= 1; i--) modify(b[i]), ans += ask(b[i] - 1);
cout << ans;
return 0;
}
|
You are given one integer n (n > 1).
Recall that a permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation of length 5, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n = 3 but there is 4 in the array).
Your task is to find a permutation p of length n that there is no index i (1 ≤ i ≤ n) such that p_i = i (so, for all i from 1 to n the condition p_i ≠ i should be satisfied).
You have to answer t independent test cases.
If there are several answers, you can print any. It can be proven that the answer exists for each n > 1.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The only line of the test case contains one integer n (2 ≤ n ≤ 100) — the length of the permutation you have to find.
Output
For each test case, print n distinct integers p_1, p_2, …, p_n — a permutation that there is no index i (1 ≤ i ≤ n) such that p_i = i (so, for all i from 1 to n the condition p_i ≠ i should be satisfied).
If there are several answers, you can print any. It can be proven that the answer exists for each n > 1.
Example
Input
2
2
5
Output
2 1
2 1 5 3 4
|
def lip(): return list(map(int,input().split()))
def splip(): return map(int,input().split())
def intip(): return int(input())
for _ in range(intip()):
n = intip()
l = [i for i in range(1,n+1)]
l = l[::-1]
mid = n//2
if n==2:
print(*l)
elif n%2!=0:
l[mid] , l[mid-1] = l[mid-1],l[mid]
print(*l)
else:
l[mid+1] , l[mid] = l[mid],l[mid+1]
print(*l)
|
In the famous Oh-Suit-United tournament, two teams are playing against each other for the grand prize of precious pepper points.
The first team consists of n players, and the second team consists of m players. Each player has a potential: the potential of the i-th player in the first team is a_i, and the potential of the i-th player in the second team is b_i.
In the tournament, all players will be on the stage in some order. There will be a scoring device, initially assigned to an integer k, which will be used to value the performance of all players.
The scores for all players will be assigned in the order they appear on the stage. Let the potential of the current player be x, and the potential of the previous player be y (y equals x for the first player). Then, x-y is added to the value in the scoring device, Afterwards, if the value in the scoring device becomes negative, the value will be reset to 0. Lastly, the player's score is assigned to the current value on the scoring device. The score of a team is the sum of the scores of all its members.
As an insane fan of the first team, Nezzar desperately wants the biggest win for the first team. He now wonders what is the maximum difference between scores of the first team and the second team.
Formally, let the score of the first team be score_f and the score of the second team be score_s. Nezzar wants to find the maximum value of score_f - score_s over all possible orders of players on the stage.
However, situation often changes and there are q events that will happen. There are three types of events:
* 1 pos x — change a_{pos} to x;
* 2 pos x — change b_{pos} to x;
* 3 x — tournament is held with k = x and Nezzar wants you to compute the maximum value of score_f - score_s.
Can you help Nezzar to answer the queries of the third type?
Input
The first line contains three integers n, m, and q (1 ≤ n,m ≤ 2 ⋅ 10^5, 1 ≤ q ≤ 5 ⋅ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^6).
The third line contains m integers b_1, b_2, …, b_m (0 ≤ b_i ≤ 10^6).
The following q lines contain descriptions of events, described in the statement, each in one of the three possible formats:
* 1 pos x (1 ≤ pos ≤ n, 0 ≤ x ≤ 10^6);
* 2 pos x (1 ≤ pos ≤ m, 0 ≤ x ≤ 10^6);
* 3 x (0 ≤ x ≤ 10^6).
Output
For each query of the third type print the answer to this query.
Examples
Input
3 4 3
1 2 7
3 4 5 6
3 5
1 1 10
3 5
Output
-4
9
Input
7 8 12
958125 14018 215153 35195 90380 30535 204125
591020 930598 252577 333333 999942 1236 9456 82390
3 123458
2 4 444444
3 123456
1 2 355555
3 123478
3 1111
2 6 340324
3 1111
2 8 999999
2 7 595959
3 222222
3 100
Output
1361307
1361311
1702804
1879305
1821765
1078115
1675180
Note
In the first query of the first test, the tournament is held with k = 5. It would be optimal to arrange players in such way (here their potentials are written):
\underline{7}, 3, 5, 4, 6, \underline{1}, \underline{2} (underlined numbers are potentials of players that are from the first team).
The individual scores of players, numbered in the order of their appearance, are:
* max(5 + (7 - 7), 0) = 5 for the \underline{1}-st player;
* max(5 + (3 - 7), 0) = 1 for the 2-nd player;
* max(1 + (5 - 3), 0) = 3 for the 3-rd player;
* max(3 + (4 - 5), 0) = 2 for the 4-th player;
* max(2 + (6 - 4), 0) = 4 for the 5-th player;
* max(4 + (1 - 6), 0) = 0 for the \underline{6}-th player;
* max(0 + (2 - 1), 0) = 1 for the \underline{7}-th player.
So, score_f = 5 + 0 + 1 = 6 and score_s = 1 + 3 + 2 + 4 = 10. The score difference is 6 - 10 = -4. It can be proven, that it is the maximum possible score difference.
|
//zxggtxdy!
#include<bits/stdc++.h>
using namespace std;
#define LL long long
const int N=1e6,Q=1e6+7;
int n,m,k,q,a[Q],b[Q],pos[Q];
multiset<int>f1,f2;
struct Seg{
LL f1[Q<<2],f2[Q<<2];
inline void covex(int u,LL A,LL B){
u=pos[u],f1[u]+=A,f2[u]+=B,u=u>>1;
while(u>0) f1[u]=f1[u<<1]+f1[u<<1|1],f2[u]=f2[u<<1]+f2[u<<1|1],u=u>>1;
}
inline pair<LL,LL> getsum(int l,int r,int t,int ql,int qr){
if(l==ql&&r==qr) return make_pair(f1[t],f2[t]); int d=(l+r)>>1; LL A=0,B=0;
if(ql<=d){
pair<LL,LL>T=getsum(l,d,t<<1,ql,min(d,qr)); A+=T.first,B+=T.second;
}
if(d+1<=qr){
pair<LL,LL>T=getsum(d+1,r,t<<1|1,max(d+1,ql),qr); A+=T.first,B+=T.second;
}
return make_pair(A,B);
}
}T1,T2;
inline void build(int l,int r,int t){
if(l==r) {pos[l]=t; return;} int d=(l+r)>>1; build(l,d,t<<1),build(d+1,r,t<<1|1);
}
inline int read(){
int num=0; char g=getchar(); while(g<48||57<g) g=getchar();
while(47<g&&g<58) num=(num<<1)+(num<<3)+g-48,g=getchar(); return num;
}
inline long long getans1(int u){
long long ans=0; int D=u-k; T1.covex(u,-1,-u);
if(D<=N){
pair<LL,LL>T=T2.getsum(0,N,1,max(D,0),N);
ans=ans-T.second+T.first*D;
}
D=min(min((*f1.begin()),(*f2.begin())),D);
if(D<=N){
pair<LL,LL>T=T1.getsum(0,N,1,max(D,0),N);
ans=ans+T.second-T.first*D;
}
T1.covex(u,1,u); return ans+k;
}
inline long long getans2(int u){
long long ans=0; int D=u-k; T2.covex(u,-1,-u);
if(D<=N){
pair<LL,LL>T=T2.getsum(0,N,1,max(D,0),N);
ans=ans-T.second+T.first*D;
}
D=min(min((*f1.begin()),(*f2.begin())),D);
if(D<=N){
pair<LL,LL>T=T1.getsum(0,N,1,max(D,0),N);
ans=ans+T.second-T.first*D;
}
T2.covex(u,1,u); return ans-k;
}
int main(){
n=read(),m=read(),q=read(); build(0,N,1);
for(int i=1;i<=n;i++) a[i]=read(),T1.covex(a[i],1,a[i]),f1.insert(a[i]);
for(int i=1;i<=m;i++) b[i]=read(),T2.covex(b[i],1,b[i]),f2.insert(b[i]);
while(q--){
int op=read();
if(op==1){
int u=read(),v=read(); T1.covex(a[u],-1,-a[u]),f1.erase(f1.find(a[u]));
a[u]=v,T1.covex(a[u],1,a[u]),f1.insert(a[u]);
}
if(op==2){
int u=read(),v=read(); T2.covex(b[u],-1,-b[u]),f2.erase(f2.find(b[u]));
b[u]=v,T2.covex(b[u],1,b[u]),f2.insert(b[u]);
}
multiset<int>::iterator zxak;
if(op==3){
long long ans=-1e18; k=read();
ans=max(ans,getans1((*f1.begin())));
ans=max(ans,getans2((*f2.begin())));
ans=max(ans,getans1((*f1.rbegin())));
ans=max(ans,getans2((*f2.rbegin())));
zxak=f1.lower_bound(k-min(*f1.begin(),*f2.begin()));
if(zxak!=f1.end()) ans=max(ans,getans1(*zxak));
if(zxak!=f1.begin()) ans=max(ans,getans1(*(--zxak)));
zxak=f1.lower_bound(*f2.rbegin()+k);
if(zxak!=f1.end()) ans=max(ans,getans1(*zxak));
if(zxak!=f1.begin()) ans=max(ans,getans1(*(--zxak)));
zxak=f2.lower_bound(k-min(*f1.begin(),*f2.begin()));
if(zxak!=f2.end()) ans=max(ans,getans2(*zxak));
if(zxak!=f2.begin()) ans=max(ans,getans2(*(--zxak)));
zxak=f2.lower_bound(*f1.rbegin()+k);
if(zxak!=f2.end()) ans=max(ans,getans2(*zxak));
if(zxak!=f2.begin()) ans=max(ans,getans2(*(--zxak)));
printf("%lld\n",ans);
}
}
return 0;
}
|
Interaction
This is an interactive problem. You need to read participants' queries from standard input and print your responses to standard output. You don't know the number of queries upfront, so you'll need to process them as you get them; you'll know you're done once you reach the end of the file.
In each query, you will be asked the question, written in one line. You have to answer it correctly, patiently and without any display of emotions. Your response is case-insensitive.
Please make sure to use the stream flushing operation after each response in order not to leave part of your output in some buffer.
Example
Input
Is it rated?
Is it rated?
Is it rated?
Output
NO
NO
NO
|
#include<bits/stdc++.h>
using namespace std;
#define MOD 1000000007
using ll = long long;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string d;
while ( getline(cin, d) ) {
cout << "NO" << endl;
cout.flush();
}
return 0;
}
|
Kavi has 2n points lying on the OX axis, i-th of which is located at x = i.
Kavi considers all ways to split these 2n points into n pairs. Among those, he is interested in good pairings, which are defined as follows:
Consider n segments with ends at the points in correspondent pairs. The pairing is called good, if for every 2 different segments A and B among those, at least one of the following holds:
* One of the segments A and B lies completely inside the other.
* A and B have the same length.
Consider the following example:
<image>
A is a good pairing since the red segment lies completely inside the blue segment.
B is a good pairing since the red and the blue segment have the same length.
C is not a good pairing since none of the red or blue segments lies inside the other, neither do they have the same size.
Kavi is interested in the number of good pairings, so he wants you to find it for him. As the result can be large, find this number modulo 998244353.
Two pairings are called different, if some two points are in one pair in some pairing and in different pairs in another.
Input
The single line of the input contains a single integer n (1≤ n ≤ 10^6).
Output
Print the number of good pairings modulo 998244353.
Examples
Input
1
Output
1
Input
2
Output
3
Input
3
Output
6
Input
100
Output
688750769
Note
The good pairings for the second example are:
<image>
In the third example, the good pairings are:
<image>
|
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
#from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.buffer.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = 998244353
n = int(data())
l=[1]*(n+1)
for i in range(1,n+1):
for j in range(i*2,n+1,i):
l[j]+=1
dp = [1]
s = 1
for i in range(1,n+1):
a = s
a+=l[i]-1
dp.append(a%mod)
s+=dp[i]
print(dp[-1])
|
A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.
The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.
Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?
Input
The first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).
Output
Output the amount of possible positions of the new house.
Examples
Input
2 2
0 4
6 2
Output
4
Input
2 2
0 4
5 2
Output
3
Input
2 3
0 4
5 2
Output
2
Note
It is possible for the x-coordinate of the new house to have non-integer value.
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, t;
cin >> n >> t;
map<double, int> m;
for (int i = 0; i < n; i++) {
double xi, ai;
cin >> xi >> ai;
m[xi - ai / 2.0]++;
m[xi + ai / 2.0]--;
}
vector<pair<double, int> > v;
int res = 2;
for (__typeof(m.begin()) it = m.begin(); it != m.end(); ++it) {
v.push_back(make_pair(it->first, it->second));
}
int ct = 0;
for (int i = 0; i < (int)v.size() - 1; i++) {
ct += v[i].second;
if (!ct) {
if (v[i + 1].first - v[i].first - 1e-10 > t)
res += 2;
else if (abs(v[i + 1].first - v[i].first - t) <= 1e-10)
res += 1;
}
}
cout << res << endl;
return 0;
}
|
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 lowercase Latin letters. The problem that the scientists offered to the Beaver is to select a subcollection of size k from the initial collection of proteins so that the representativity of the selected subset of proteins is maximum possible.
The Smart Beaver from ABBYY did some research and came to the conclusion that the representativity of a collection of proteins can be evaluated by a single number, which is simply calculated. Let's suppose we have a collection {a1, ..., ak} consisting of k strings describing proteins. The representativity of this collection is the following value:
<image>
where f(x, y) is the length of the longest common prefix of strings x and y; for example, f("abc", "abd") = 2, and f("ab", "bcd") = 0.
Thus, the representativity of collection of proteins {"abc", "abd", "abe"} equals 6, and the representativity of collection {"aaa", "ba", "ba"} equals 2.
Having discovered that, the Smart Beaver from ABBYY asked the Cup contestants to write a program that selects, from the given collection of proteins, a subcollection of size k which has the largest possible value of representativity. Help him to solve this problem!
Input
The first input line contains two integers n and k (1 ≤ k ≤ n), separated by a single space. The following n lines contain the descriptions of proteins, one per line. Each protein is a non-empty string of no more than 500 characters consisting of only lowercase Latin letters (a...z). Some of the strings may be equal.
The input limitations for getting 20 points are:
* 1 ≤ n ≤ 20
The input limitations for getting 50 points are:
* 1 ≤ n ≤ 100
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 2000
Output
Print a single number denoting the largest possible value of representativity that a subcollection of size k of the given collection of proteins can have.
Examples
Input
3 2
aba
bzd
abq
Output
2
Input
4 3
eee
rrr
ttt
qqq
Output
0
Input
4 3
aaa
abba
abbc
abbd
Output
9
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2000 + 10;
const int MAX_K = 500 + 10;
string Arr[MAX_N];
pair<long long, long long> T[2 * MAX_N][12];
long long Dist(const string &a, const string &b) {
long long sz = (int)min(a.size(), b.size());
int i;
for (i = 0; i < sz; i++)
if (a[i] != b[i]) return i;
return i;
}
vector<long long> Solve(int x, int y) {
if (x == y) return vector<long long>(2, 0);
long long len = y - x;
long long t = 0;
long long p = 1;
while ((p *= 2) <= len) t++;
pair<long long, long long> MN = min(T[x][t], T[y - (1 << t)][t]);
vector<long long> A = Solve(x, MN.second);
vector<long long> B = Solve(MN.second + 1, y);
vector<long long> Ret(y - x + 2, 0);
for (long long i = 0; i <= y - x + 1; i++)
for (long long j = 0; j <= min((MN.second - x + 1), i); j++) {
long long k = i - j;
if (k > y - MN.second) continue;
Ret[i] = max(Ret[i], A[j] + B[k] + (j * k * MN.first));
}
return Ret;
}
int main() {
ios::sync_with_stdio(false);
int N, K;
cin >> N >> K;
for (int i = 0; i < N; i++) cin >> Arr[i];
sort(Arr, Arr + N);
for (int i = 0; i < 2 * MAX_N; i++)
for (int j = 0; j < 12; j++) T[i][j] = make_pair(1LL << 60, 0);
for (int j = 0; j < 12; j++) {
for (int i = 0; i < N - 1; i++) {
if (j == 0) {
T[i][0] = make_pair(Dist(Arr[i], Arr[i + 1]), i);
continue;
}
T[i][j] = min(T[i][j - 1], T[i + (1 << (j - 1))][j - 1]);
}
}
cout << Solve(0, N - 1)[K] << endl;
return 0;
}
|
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.
You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.
You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.
The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as <image>, where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.
The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.
Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.
Input
The first line contains a single integer n (1 ≤ n ≤ 15) — the number of words in Lesha's problem. The second line contains n space-separated words — the short description of the problem.
The third line contains a single integer m (1 ≤ m ≤ 10) — the number of problems in the Torcoder.com archive. Next m lines contain the descriptions of the problems as "k s1 s2 ... sk", where k (1 ≤ k ≤ 500000) is the number of words in the problem and si is a word of the problem description.
All words from all problem descriptions contain no more than 10 lowercase English letters. It is guaranteed that the total length of words in all problem descriptions does not exceed 500015.
Output
If Lesha's problem is brand new, print string "Brand new problem!" (without quotes).
Otherwise, on the first line print the index of the archive problem which resembles Lesha's problem most. If there are multiple such problems, print the one with the smallest index. On the second line print a string consisting of characters [:, character | repeated p times, and characters :], where p is the "similarity" between this problem and Lesha's one. The archive problems are numbered starting from one in the order in which they are given in the input.
Examples
Input
4
find the next palindrome
1
10 find the previous palindrome or print better luck next time
Output
1
[:||||||:]
Input
3
add two numbers
3
1 add
2 two two
3 numbers numbers numbers
Output
Brand new problem!
Input
4
these papers are formulas
3
6 what are these formulas and papers
5 papers are driving me crazy
4 crazy into the night
Output
1
[:||||:]
Input
3
add two decimals
5
4 please two decimals add
5 decimals want to be added
4 two add decimals add
4 add one two three
7 one plus two plus three equals six
Output
3
[:|||:]
Note
Let us remind you that the number of inversions is the number of pairs of words that follow in the permutation not in their original order. Thus, for example, if the original problem is "add two numbers", then permutation "numbers add two" contains two inversions — pairs of words "numbers" and "add", "numbers" and "two".
Sequence b1, b2, ..., bk is a subsequence of sequence a1, a2, ..., an if there exists such a set of indices 1 ≤ i1 < i2 < ... < ik ≤ n that aij = bj (in other words, if sequence b can be obtained from a by deleting some of its elements).
In the first test case the first problem contains the "find the palindrome next" permutation as a subsequence, in which the number of inversions equals 1 (words "palindrome" and "next").
In the second test case there is no problem that contains a permutation of words from Lesha's problem as a subsequence.
|
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int N = r.nextInt();
char[][] a = new char[N][];
for(int i = 0; i < N; i++)
a[i] = r.next().toCharArray();
M = r.nextInt();
b = new char[M][][];
for(int i = 0; i < M; i++){
int k = r.nextInt();
b[i] = new char[k][];
for(int j = 0; j < k; j++)
b[i][j] = r.next().toCharArray();
}
pp = new int[M];
Arrays.fill(pp, -inf);
dfs(0, a, new char[N][], new boolean[N]);
int max = -1;
int maxi = 0;
for(int i = 0; i < M; i++)
if(pp[i] != -inf && max < pp[i]){
max = pp[i];
maxi = i;
}
// System.out.println(Arrays.toString(pp));
if(max == -1)System.out.println("Brand new problem!");
else{
System.out.println(maxi + 1);
System.out.print("[:");
for(int i = 0; i < max; i++)
System.out.print("|");
System.out.println(":]");
}
}
static int inf = 1 << 28;
static int M;
static char[][][] b;
static int[] pp;
private static void dfs(int i, char[][] a, char[][] p, boolean[] v) {
if(i == a.length){
for(int j = 0; j < M; j++){
int ptr = 0;
boolean can = false;
for(int x = 0; x < b[j].length; x++){
if(Arrays.equals(b[j][x], p[ptr])){
ptr++;
if(ptr == a.length){
can = true;
break;
}
}else continue;
}
if(!can)continue;
// System.out.print(j + ", ");
// for(int x = 0; x < p.length; x++)
// System.out.print(new String(p[x]) + ", ");
// System.out.println();
pp[j] = Math.max(pp[j], a.length * (a.length - 1) / 2 - calc(a, p) + 1);
}
}else{
for(int j = 0; j < a.length; j++)if(!v[j]){
v[j] = true;
p[i] = a[j];
dfs(i + 1, a, p, v);
v[j] = false;
}
}
}
private static int calc(char[][] a, char[][] p) {
HashMap<String, Integer> mp = new HashMap<String, Integer>();
for(int i = 0; i < a.length; i++)
mp.put(new String(a[i]), i);
int ret = 0;
for(int i = 0; i < p.length; i++)
for(int j = i + 1; j < p.length; j++)
if(mp.get(new String(p[i])) > mp.get(new String(p[j])))ret++;
return ret;
}
}
|
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.
Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers l, l + 1, l + 2, ..., r; let's consider all its k-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.
Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where F1 = 1, F2 = 1, Fn = Fn - 1 + Fn - 2 for n ≥ 3.
Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by m.
Input
The first line contains four space-separated integers m, l, r and k (1 ≤ m ≤ 109; 1 ≤ l < r ≤ 1012; 2 ≤ k ≤ r - l + 1).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Output
Print a single integer — the residue from dividing the sought greatest common divisor by m.
Examples
Input
10 1 8 2
Output
3
Input
10 1 8 3
Output
1
|
#include <bits/stdc++.h>
using namespace std;
long long MOD, L, R, d, k, ans;
map<long long, long long> F;
long long fib(long long x) {
if (x < 2) return 1 % MOD;
if (F.count(x)) return F[x];
long long k = x / 2;
if (x % 2)
return F[x] = (fib(k) * fib(k + 1) % MOD + fib(k) * fib(k - 1) % MOD) % MOD;
return F[x] = (fib(k) * fib(k) % MOD + fib(k - 1) * fib(k - 1) % MOD) % MOD;
}
void cmon(long long x) {
if (x && R / x - (L - 1) / x >= k) ans = max(ans, x);
}
void check(long long x) {
long long l, r;
for (l = 1; l <= x; l = r + 1) {
r = x / (x / l);
cmon(l - 1);
cmon(l);
cmon(l + 1);
cmon(r - 1);
cmon(r);
cmon(r + 1);
}
}
int main() {
scanf("%lld %lld %lld %lld", &MOD, &L, &R, &k);
d = R - L + 1;
ans = d / k;
check(R);
check(L - 1);
printf("%lld\n", fib(ans - 1));
return 0;
}
|
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.
Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.
It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (ai < 0), he loses his temper and his wrath is terrible.
Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.
Write a program that, given sequence ai, will print the minimum number of folders.
Input
The first line contains integer n (1 ≤ n ≤ 100), n is the number of days. The second line contains a sequence of integers a1, a2, ..., an (|ai| ≤ 100), where ai means the company profit on the i-th day. It is possible that the company has no days with the negative ai.
Output
Print an integer k — the required minimum number of folders. In the second line print a sequence of integers b1, b2, ..., bk, where bj is the number of day reports in the j-th folder.
If there are multiple ways to sort the reports into k days, print any of them.
Examples
Input
11
1 2 3 -4 -5 -6 5 -5 -6 -7 6
Output
3
5 3 3
Input
5
0 -1 100 -1 0
Output
1
5
Note
Here goes a way to sort the reports from the first sample into three folders:
1 2 3 -4 -5 | -6 5 -5 | -6 -7 6
In the second sample you can put all five reports in one folder.
|
import java.io.*;
import java.util.*;
public class minFolder
{
public static void main(String[] args) throws IOException
{
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine().trim());
int cnt = 0, res = 0;
ArrayList<Integer> folder = new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(reader.readLine());
for(int i = 0; i < n; i++)
{
res++;
int num = Integer.parseInt(st.nextToken());
if(num < 0)
cnt++;
if(cnt == 3)
{
folder.add(res-1);
res = cnt = 1;
}
}
if(res != 0)
folder.add(res);
writer.println(folder.size() == 0 ? 1 : folder.size());
for(int i = 0; i < folder.size(); i++)
writer.print(folder.get(i) + (i != folder.size()-1 ? " ": "\n"));
writer.flush();
writer.close();
}
}
|
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES
|
#include <bits/stdc++.h>
using namespace std;
const int INF_MAX = 0x7FFFFFFF;
const int INF_MIN = -(1 << 30);
const double eps = 1e-10;
const double pi = acos(-1.0);
int toInt(string s) {
istringstream sin(s);
int t;
sin >> t;
return t;
}
template <class T>
string toString(T x) {
ostringstream sout;
sout << x;
return sout.str();
}
template <class T>
inline T gcd(T a, T b) {
if (a < 0) return gcd(-a, b);
if (b < 0) return gcd(a, -b);
return (b == 0) ? a : gcd(b, a % b);
}
template <class T>
inline T lcm(T a, T b) {
if (a < 0) return lcm(-a, b);
if (b < 0) return lcm(a, -b);
return a * (b / gcd(a, b));
}
template <class T>
inline void CLR(priority_queue<T, vector<T>, greater<T> > &Q) {
while (!Q.empty()) Q.pop();
}
inline int random(int l, int r) { return rand() % (r - l + 1) + l; }
int dir_4[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
int dir_8[8][2] = {{0, 1}, {-1, 1}, {-1, 0}, {-1, -1},
{0, -1}, {1, -1}, {1, 0}, {1, 1}};
char mat[55][55];
int n, m;
bool solve() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
char ch1 = mat[i][j];
if (ch1 != 'B') continue;
for (int ii = 0; ii < n; ii++) {
for (int jj = 0; jj < m; jj++) {
bool flag1 = true, flag2 = true;
bool flag3 = true, flag4 = true;
char ch2 = mat[ii][jj];
if (ch2 != 'B') continue;
int minx = min(i, ii);
int maxx = max(i, ii);
int miny = min(j, jj);
int maxy = max(j, jj);
for (int k = miny; k <= maxy; k++) {
if (mat[i][k] != 'B') flag1 = false;
if (mat[ii][k] != 'B') flag3 = false;
}
for (int k = minx; k <= maxx; k++) {
if (mat[k][jj] != 'B') flag2 = false;
if (mat[k][j] != 'B') flag4 = false;
}
if ((flag1 && flag2) || (flag3 && flag4))
continue;
else
return false;
}
}
}
}
return true;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> mat[i];
if (solve())
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
|
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds.
Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?
Input
The first line contains three integers n, m, k (1 ≤ n, m ≤ 105, 1 ≤ k ≤ 109) — the number of fish caught by Alice and Bob respectively, and the number of fish species.
The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob.
Note that one may have caught more than one fish for a same species.
Output
Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise.
Examples
Input
3 3 3
2 2 2
1 1 3
Output
YES
Input
4 7 9
5 2 7 3
3 5 2 7 3 8 7
Output
NO
Note
In the first sample, if w1 = 1, w2 = 2, w3 = 2.5, then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5.
In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish.
|
//package com.congli.codeforces;
import java.io.*;
import java.util.*;
public class C180Div2D_FishWeight {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
C180Div2D_FishWeight test = new C180Div2D_FishWeight();
test.start();
}
public void solve() throws IOException
{
int n = readInt();
int m = readInt();
int k = readInt();
Hash[] hash = new Hash[m+n+10];
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int hash_ind = 0;
int weight = 0;
for(int i = 0; i < n; ++i)
{
weight = readInt();
if(map.containsKey(weight))
hash[map.get(weight)].count++;
else
{
map.put(weight, hash_ind);
hash[hash_ind++] = new Hash(weight, 1);
}
}
for(int i = 0; i < m; ++i)
{
weight = readInt();
if(map.containsKey(weight))
hash[map.get(weight)].count--;
else
{
map.put(weight, hash_ind);
hash[hash_ind++] = new Hash(weight, -1);
}
}
while(hash_ind < hash.length)
hash[hash_ind++] = new Hash(0, 0);
Arrays.sort(hash);
calculate(hash);
}
public void calculate(Hash[] hash)
{
int i = 0;
if(hash[0].count > 0)
{
out.println("YES");
return;
}
int count_plus = 0, count_minus = 0;
while(i < hash.length && hash[i].key > 0)
{
while(i < hash.length && hash[i].count <= 0)
count_minus -= hash[i++].count;
//count_minus = -count_minus;
while(i < hash.length && hash[i].count >= 0)
count_plus += hash[i++].count;
if(count_plus > count_minus)
{
out.println("YES");
return;
}
/*else if(count_plus < count_minus)
{
out.println("NO");
return;
}*/
}
out.println("NO");
}
class Hash implements Comparable<Hash>
{
int key;
int count;
public Hash(int key, int count)
{
this.key = key;
this.count = count;
}
@Override
public int compareTo(Hash o) {
// TODO Auto-generated method stub
return o.key - this.key;
}
}
public void start()
{
try {
long t1 = System.currentTimeMillis();
if (System.getProperty("ONLINE_JUDGE") != null) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("..\\Codeforces\\src\\com\\congli\\codeforces\\input.txt"));
out = new PrintWriter(System.out);
}
Locale.setDefault(Locale.US);
solve();
in.close();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Throwable t) {
t.printStackTrace(System.err);
System.exit(-1);
}
}
public String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int readInt() throws IOException {
return Integer.parseInt(readString());
}
public long readLong() throws IOException {
return Long.parseLong(readString());
}
public double readDouble() throws IOException {
return Double.parseDouble(readString());
}
}
|
Fox Ciel is playing a card game with her friend Jiro.
Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.
Now is Ciel's battle phase, Ciel can do the following operation many times:
1. Choose one of her cards X. This card mustn't be chosen before.
2. If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then:
* If Y's position is Attack, then (X's strength) ≥ (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength).
* If Y's position is Defense, then (X's strength) > (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage.
Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of cards Jiro and Ciel have.
Each of the next n lines contains a string position and an integer strength (0 ≤ strength ≤ 8000) — the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense.
Each of the next m lines contains an integer strength (0 ≤ strength ≤ 8000) — the strength of Ciel's current card.
Output
Output an integer: the maximal damage Jiro can get.
Examples
Input
2 3
ATK 2000
DEF 1700
2500
2500
2500
Output
3000
Input
3 4
ATK 10
ATK 100
ATK 1000
1
11
101
1001
Output
992
Input
2 4
DEF 0
ATK 0
0
0
1
1
Output
1
Note
In the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.
In the second test case, she should use the "1001" card to attack the "ATK 100" card, then use the "101" card to attack the "ATK 10" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.
In the third test case note that she can destroy the "ATK 0" card by a card with strength equal to 0, but she can't destroy a "DEF 0" card with that card.
|
#include <bits/stdc++.h>
using namespace std;
int adj[222][222], deg[222], flow[222][222], cost[222][222], dis[222], pre[222];
int N, M, fl;
void add_edge(int u, int v, int w, int c = 0) {
adj[u][deg[u]++] = v;
adj[v][deg[v]++] = u;
flow[u][v] = w;
flow[v][u] = 0;
cost[u][v] = c;
cost[v][u] = -c;
}
queue<int> q;
int max_flow(int s, int t) {
int ans = 0, u, v, bot;
while (1) {
q = queue<int>();
q.push(s);
memset(pre, -1, sizeof(pre));
memset(dis, 0x3f, sizeof(dis));
dis[s] = 0;
while (!q.empty()) {
u = q.front();
q.pop();
for (int i = 0; i < deg[u]; i++) {
v = adj[u][i];
if (flow[u][v] == 0) continue;
if (dis[v] > dis[u] + cost[u][v]) {
dis[v] = dis[u] + cost[u][v];
q.push(v);
pre[v] = u;
}
}
}
if (dis[t] == 0x3f3f3f3f) return ans;
bot = 0x3f3f3f3f;
for (u = t; u != s; u = pre[u]) bot = min(bot, flow[pre[u]][u]);
for (u = t; u != s; u = pre[u]) {
flow[pre[u]][u] -= bot;
flow[u][pre[u]] += bot;
}
fl += bot;
ans += dis[t] * bot;
}
}
char s[11];
int a[222], b[222], tp[222];
int main() {
scanf("%d %d", &N, &M);
int src = 0, tar = N + M + 1;
for (int i = 1; i <= N; i++) {
scanf("%s %d", s, b + i);
tp[i] = (strcmp(s, "ATK") == 0);
}
for (int i = 1; i <= M; i++) {
scanf("%d", a + i);
}
int mx = 0, MM = 100000;
int S = N + M + 2, tmp = S + 1;
for (int k = 1; k <= M; k++) {
memset(deg, 0, sizeof(deg));
add_edge(S, src, k);
for (int i = 1; i <= N; i++) add_edge(M + i, tar, 1);
for (int i = 1; i <= M; i++) {
add_edge(src, i, 1);
add_edge(i, tmp, 1, -a[i]);
for (int j = 1; j <= N; j++) {
if (tp[j] && a[i] >= b[j]) add_edge(i, M + j, 1, b[j] - a[i]);
if (!tp[j] && a[i] > b[j]) add_edge(i, M + j, 1);
}
}
add_edge(tmp, tar, M, MM);
int ans = -max_flow(S, tar);
if (M - flow[tmp][tar] > max(0, k - N)) continue;
mx = max(mx, ans + MM * (M - flow[tmp][tar]));
}
printf("%d\n", mx);
return 0;
}
|
One fine morning, n fools lined up in a row. After that, they numbered each other with numbers from 1 to n, inclusive. Each fool got a unique number. The fools decided not to change their numbers before the end of the fun.
Every fool has exactly k bullets and a pistol. In addition, the fool number i has probability of pi (in percent) that he kills the fool he shoots at.
The fools decided to have several rounds of the fun. Each round of the fun looks like this: each currently living fool shoots at another living fool with the smallest number (a fool is not stupid enough to shoot at himself). All shots of the round are perfomed at one time (simultaneously). If there is exactly one living fool, he does not shoot.
Let's define a situation as the set of numbers of all the living fools at the some time. We say that a situation is possible if for some integer number j (0 ≤ j ≤ k) there is a nonzero probability that after j rounds of the fun this situation will occur.
Valera knows numbers p1, p2, ..., pn and k. Help Valera determine the number of distinct possible situations.
Input
The first line contains two integers n, k (1 ≤ n, k ≤ 3000) — the initial number of fools and the number of bullets for each fool.
The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 100) — the given probabilities (in percent).
Output
Print a single number — the answer to the problem.
Examples
Input
3 3
50 50 50
Output
7
Input
1 1
100
Output
1
Input
2 1
100 100
Output
2
Input
3 3
0 0 0
Output
1
Note
In the first sample, any situation is possible, except for situation {1, 2}.
In the second sample there is exactly one fool, so he does not make shots.
In the third sample the possible situations are {1, 2} (after zero rounds) and the "empty" situation {} (after one round).
In the fourth sample, the only possible situation is {1, 2, 3}.
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vvi = vector<vector<int>>;
using vi = vector<int>;
using vvll = vector<vector<long long>>;
using vll = vector<long long>;
using vd = vector<double>;
using vvd = vector<vector<double>>;
using pii = pair<int, int>;
using vpii = vector<pair<int, int>>;
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V> &x) {
cerr << '{';
__print(x.first);
cerr << ',';
__print(x.second);
cerr << '}';
}
template <typename T>
void __print(const T &x) {
int f = 0;
cerr << '{';
for (auto &i : x) cerr << (f++ ? "," : ""), __print(i);
cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
__print(t);
if (sizeof...(v)) cerr << ", ";
_print(v...);
}
enum prob { ALWAYS, NEVER, SOMETIMES };
int INF = 1e9 + 7;
void solve() {
int n, k;
cin >> n >> k;
if (n == 1) {
cout << 1 << endl;
return;
}
vector<prob> v(n);
for (int i = 0; i < n; i++) {
int x;
cin >> x;
switch (x) {
case 0:
v[i] = NEVER;
break;
case 100:
v[i] = ALWAYS;
break;
default:
v[i] = SOMETIMES;
break;
}
}
vi suf_has_never(n + 1);
vi suf_has_always(n + 1);
vi suf_has_killable(n + 1);
for (int i = n - 1; i >= 0; i--) {
suf_has_never[i] = suf_has_never[i + 1] || v[i] == NEVER;
suf_has_always[i] = suf_has_always[i + 1] || v[i] == ALWAYS;
suf_has_killable[i] = suf_has_killable[i + 1] || v[i] != NEVER;
};
vvi dp(n, vi(n, INF));
dp[0][1] = 0;
int ans = 1;
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
if (b <= a || (a == 0 && b == 1)) continue;
if (a + 1 == b) {
for (int c = 0; c < a; c++) {
if (v[c] != ALWAYS && suf_has_killable[a]) {
dp[a][b] = min(dp[a][b], dp[c][a] + 1);
}
}
for (int c = 0; c < a - 1; c++) {
if (v[c] != NEVER && suf_has_killable[a - 1]) {
dp[a][b] = min(dp[a][b], dp[c][a - 1] + 1);
}
}
} else {
if (v[a] != NEVER && !suf_has_always[b - 1]) {
dp[a][b] = min(dp[a][b], dp[a][b - 1] + 1);
}
}
if (dp[a][b] <= k) ans++;
}
};
for (int a = 0; a < n - 1; a++) {
if (dp[a][n - 1] < k && v[a] != NEVER && v[n - 1] != ALWAYS) {
ans++;
}
}
bool good = false;
for (int a = 0; a < n - 2; a++) {
if (dp[a][n - 2] < k && v[a] != NEVER && v[n - 2] != NEVER) {
good = true;
}
}
for (int a = 0; a < n - 1; a++) {
if (dp[a][n - 1] < k && v[a] != ALWAYS && v[n - 1] != NEVER) {
good = true;
}
}
if (good) ans++;
for (int a = 0; a < n - 1; a++) {
if (dp[a][n - 1] < k && v[a] != NEVER && v[n - 1] != NEVER) {
ans++;
break;
}
}
cout << ans << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
}
|
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.
Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had pi points.
Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort ei he needs to invest to win against the i-th contestant. Losing a fight costs no effort.
After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here.
Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible.
Input
The first line contains a pair of integers n and k (1 ≤ k ≤ n + 1). The i-th of the following n lines contains two integers separated by a single space — pi and ei (0 ≤ pi, ei ≤ 200000).
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem C1 (4 points), the constraint 1 ≤ n ≤ 15 will hold.
* In subproblem C2 (4 points), the constraint 1 ≤ n ≤ 100 will hold.
* In subproblem C3 (8 points), the constraint 1 ≤ n ≤ 200000 will hold.
Output
Print a single number in a single line — the minimum amount of effort Manao needs to use to rank in the top k. If no amount of effort can earn Manao such a rank, output number -1.
Examples
Input
3 2
1 1
1 4
2 2
Output
3
Input
2 1
3 2
4 0
Output
-1
Input
5 2
2 10
2 10
1 1
3 1
3 1
Output
12
Note
Consider the first test case. At the time when Manao joins the tournament, there are three fighters. The first of them has 1 tournament point and the victory against him requires 1 unit of effort. The second contestant also has 1 tournament point, but Manao needs 4 units of effort to defeat him. The third contestant has 2 points and victory against him costs Manao 2 units of effort. Manao's goal is top be in top 2. The optimal decision is to win against fighters 1 and 3, after which Manao, fighter 2, and fighter 3 will all have 2 points. Manao will rank better than fighter 3 and worse than fighter 2, thus finishing in second place.
Consider the second test case. Even if Manao wins against both opponents, he will still rank third.
|
#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
pair<int, int> a[N];
int n, k;
vector<int> w;
long long calc(int v) {
int l = lower_bound(a + 1, a + n + 1, pair<int, int>(v - 1, 0)) - a;
int r = lower_bound(a + 1, a + n + 1, pair<int, int>(v + 1, 0)) - a - 1;
int must = k - l + 1;
if (must > r - l + 1 || v > n || v < must) return (1ll << 60);
long long ans = 0;
w.clear();
for (int i = (int)(l); i <= (int)(r); i++) w.push_back(a[i].second);
sort(w.begin(), w.end(), greater<int>());
for (int i = (int)(1); i <= (int)(must); i++) {
ans += w.back();
w.pop_back();
--v;
}
for (int i = (int)(1); i <= (int)(l - 1); i++) w.push_back(a[i].second);
for (int i = (int)(r + 1); i <= (int)(n); i++) w.push_back(a[i].second);
sort(w.begin(), w.end(), greater<int>());
for (int i = (int)(1); i <= (int)(v); i++) {
ans += w.back();
w.pop_back();
}
return ans;
}
int main() {
scanf("%d%d", &n, &k);
k = n - k + 1;
for (int i = (int)(1); i <= (int)(n); i++)
scanf("%d%d", &a[i].first, &a[i].second);
sort(a + 1, a + n + 1);
if (!k) return puts("0"), 0;
int s = a[k].first;
long long ans = (1ll << 60);
for (int i = (int)(s - 1); i <= (int)(s + 3); i++) ans = min(ans, calc(i));
printf("%lld\n", ans == (1ll << 60) ? -1 : ans);
}
|
The programmers from the R2 company love playing 2048. One day, they decided to invent their own simplified version of this game — 2k on a stripe.
Imagine an infinite in one direction stripe, consisting of unit squares (the side of each square is equal to the height of the stripe). Each square can either be empty or contain some number.
Initially, all squares are empty. Then at infinity one of the unit squares number 2 or 4 appears. Then the player presses a button once, and the appeared number begins to move towards the beginning of the stripe. Let's assume that some number x moves to the beginning of the stripe, then it will stop if:
1. it either gets in the first square of the stripe;
2. or it is in the square that is preceded by a square with number y (y ≠ x). But if number x at some point of time gets to the square with the same number then both numbers add to each other and result in 2x. The new number 2x continues moving to the beginning of the stripe by the same rules.
After the final stop of the number moving process, the infinity gets a new number 2 or 4 and the process repeats. Read the notes to the test samples to better understand the moving strategy.
I guess you've understood that the game progress fully depends on the order in which numbers 2 and 4 appear. Let's look at some sequence of numbers 2 and 4 in the game. We assume that the sequence is winning if it results in at least one square getting the number greater or equal than 2k.
The goal of the game is to make up a winning sequence of n numbers. But not everything is so simple, some numbers in the sequence are identified beforehand. You are given a sequence consisting of numbers 0, 2, 4. Count how many ways there are to replace each 0 of the sequence with 2 or 4 to get a winning sequence.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2000; 3 ≤ k ≤ 11). The next line contains sequence of n integers, each of them is either 0, or 2, or 4.
Output
Print a single integer — the number of ways to replace zeroes by numbers 2 or 4 to get a winning sequence. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
7 4
2 2 4 2 2 2 2
Output
1
Input
1 3
0
Output
0
Input
2 3
0 4
Output
1
Input
5 4
2 0 0 4 4
Output
2
Note
Consider the first example. The beginning of the strip will look as follows:
2 → 4 → 8 → 8 2 → 8 4 → 8 4 2 → 16.
To better understand the game, you can see the original game on http://gabrielecirulli.github.io/2048/. Please note that the game that is described on the strip is slightly different from the original game (when the two numbers add up in the original game, they do not keep moving). Be careful, the game is addictive, there isn't much time for the contest!
|
#include <bits/stdc++.h>
using namespace std;
template <class T, class L>
bool smax(T &x, L y) {
return x < y ? (x = y, 1) : 0;
}
template <class T, class L>
bool smin(T &x, L y) {
return y < x ? (x = y, 1) : 0;
}
const int maxn = 2e3 + 17, mod = 1e9 + 7;
int n, dp[maxn][2048], ans, s[maxn], a[maxn], k;
void go(int i, int mask, int ad) {
if ((mask & -mask) < ad)
(dp[i + 1][ad] += dp[i][mask]) %= mod;
else if (mask + ad == 1 << k)
(ans += (long long)dp[i][mask] * s[i + 1] % mod) %= mod;
else
(dp[i + 1][mask + ad] += dp[i][mask]) %= mod;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> k, k--;
for (int i = 0; i < n; i++) cin >> a[i], a[i] /= 2;
s[n] = 1;
for (int i = n - 1; ~i; i--) s[i] = s[i + 1] * (a[i] ? 1 : 2) % mod;
dp[0][0] = 1;
for (int i = 0; i < n; i++)
for (int mask = 0; mask < 1 << k; mask++) {
if (a[i] != 1) go(i, mask, 2);
if (a[i] != 2) go(i, mask, 1);
}
cout << ans << '\n';
return 0;
}
|
Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n.
Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?
Input
The first line of the input contains integer n (2 ≤ n ≤ 100000) — the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n.
The second line contains n - 1 integer a1, a2, ..., an (1 ≤ ai ≤ n) — the numbers of episodes that Polycarpus has watched. All values of ai are distinct.
Output
Print the number of the episode that Polycarpus hasn't watched.
Examples
Input
10
3 8 10 1 7 9 6 5 2
Output
4
|
import sys
input=sys.stdin.buffer.readline
n=int(input())
arr=list(map(int,input().split()))
arr.sort()
z=0
for i in range(0,n-1):
if arr[i]==i+1:
continue
else:
print(i+1)
z=1
break
if z==0:
print(n)
|
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:
* Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.
* Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
Input
The first line contains a single integer n (1 ≤ n ≤ 3·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial group that is given to Toastman.
Output
Print a single integer — the largest possible score.
Examples
Input
3
3 1 5
Output
26
Input
1
10
Output
10
Note
Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.
|
import java.io.*;
import java.util.*;
public class Toastman
{
public static void main(String[]args)throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String s[]=br.readLine().split(" ");
long a[]=new long[n];
int i;
long sum=0;
for(i=0;i<n;i++)
{
a[i]=Long.parseLong(s[i]);
}
Arrays.sort(a);
for(i=0;i<n-1;i++)
{
sum+=((i+2)*(a[i]));
}
sum+=(a[n-1]*n);
System.out.println(sum);
}
}
|
Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner:
<image> where <image> is equal to 1 if some ai = 1, otherwise it is equal to 0.
Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1 ≤ i ≤ m) and column j (1 ≤ j ≤ n) is denoted as Aij. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:
<image>.
(Bij is OR of all elements in row i and column j of matrix A)
Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.
Input
The first line contains two integer m and n (1 ≤ m, n ≤ 100), number of rows and number of columns of matrices respectively.
The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).
Output
In the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.
Examples
Input
2 2
1 0
0 0
Output
NO
Input
2 3
1 1 1
1 1 1
Output
YES
1 1 1
1 1 1
Input
2 3
0 1 0
1 1 1
Output
YES
0 0 0
0 1 0
|
#B problem
X = raw_input()
X = X.split()
#print X
m = int(X[0])
n = int(X[1])
A = [[0]*n for i in range(m)]
#print A
B = [[0]*n for i in range(m)]
for i in range(m):
temp = raw_input()
for j in range(n):
B[i][j] = int(temp[2*j])
temp1 = []
temp2 = []
for i in range(m):
if (sum(B[i]) == n):
temp1.append(i)
for j in range(n):
if (sum([row[j] for row in B]) == m):
temp2.append(j)
if((len(temp1) != 0) & (len(temp2) != 0)):
for i in range(len(temp1)):
for j in range(len(temp2)):
A[temp1[i]][temp2[j]] = 1
count1 = 0
count2 = 0
for i in range(m):
for j in range(n):
if (B[i][j] == 1):
count1 += 1
for i in range(m):
for j in range(n):
if (B[i][j] == 0):
count2 += 1
#print temp1, temp2, len(temp1), len(temp2), m, n
if(count2 == (m*n)):
print "YES"
C = [[0]*n for i in range(m)]
for i in range(m):
for j in range(n):
print C[i][j],
print "\n",
elif((count1 == (len(temp1)*n + len(temp2)*m - len(temp1)*len(temp2))) & ((len(temp1) != 0) & (len(temp2) != 0))):
print "YES"
for i in range(m):
for j in range(n):
print A[i][j],
print "\n",
else:
print "NO"
|
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
Input
In a single line you are given two integers M and N — board sizes in squares (1 ≤ M ≤ N ≤ 16).
Output
Output one number — the maximal number of dominoes, which can be placed.
Examples
Input
2 4
Output
4
Input
3 3
Output
4
|
#domino piling
M,N=map(int,input().split())
d=(M*N)//2
print(d)
|
Polycarp has n dice d1, d2, ..., dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1, d2, ..., dn. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).
For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.
Input
The first line contains two integers n, A (1 ≤ n ≤ 2·105, n ≤ A ≤ s) — the number of dice and the sum of shown values where s = d1 + d2 + ... + dn.
The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 106), where di is the maximum value that the i-th dice can show.
Output
Print n integers b1, b2, ..., bn, where bi is the number of values for which it is guaranteed that the i-th dice couldn't show them.
Examples
Input
2 8
4 4
Output
3 3
Input
1 3
5
Output
4
Input
2 3
2 3
Output
0 1
Note
In the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.
In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.
In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.
|
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] xa) throws IOException {
InputReader sc = new InputReader(new BufferedInputStream(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
int n = sc.nextInt() , i = 0 ;
long A = sc.nextLong();
String b;
int a[] = new int[n];
while (i < n && (b = sc.next()) != null) {
a[i++] = Integer.parseInt(b);
}
ArrayList<Integer> temp = PolyarpusDice.findCouldnts(n, A, a);
for (int j = 0; j < temp.size(); j++) {
out.print(temp.get(j) + " ");
}
out.flush();
out.close();
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
class PolyarpusDice {
public static ArrayList<Integer> findCouldnts(int n, long A, int[] d) {
ArrayList<Integer> couldnts = new ArrayList<>();
long sum = 0;
for (int i = 0; i < d.length; i++) {
sum += d[i];
}
for (int i = 0; i < d.length; i++) {
int couldnt = 0;
if (d[i] > A - (n - 1)) {
couldnt += d[i] - (A - n + 1);
}
long k = sum - d[i];
if (k < A - 1) {
couldnt += A - 1 - k;
}
couldnts.add(couldnt);
}
return couldnts;
}
}
|
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279
|
#include <bits/stdc++.h>
using namespace std;
const int maxN = 2000 + 10;
const int maxM = 1000 * 100 * 4;
const int mod = 1e9 + 7;
inline int bpow(int a, int b) {
int res = 1;
for (; b; b /= 2) {
if (b & 1) res = res * 1ll * a % mod;
a = a * 1ll * a % mod;
}
return res;
}
int fact[maxM];
inline int ch(int r, int n) {
return fact[n] * 1ll * bpow(fact[r] * 1ll * fact[n - r] % mod, mod - 2) % mod;
}
int dp[maxN];
pair<int, int> a[maxN];
int main() {
ios::sync_with_stdio(false);
fact[0] = 1;
for (int i = 1; i < maxM; i++) fact[i] = fact[i - 1] * 1ll * i % mod;
int h, w, n;
cin >> h >> w >> n;
for (int i = 0; i < n; i++) cin >> a[i].first >> a[i].second;
a[n++] = {h, w};
sort(a, a + n, [](pair<int, int> a, pair<int, int> b) {
return a.first + a.second < b.first + b.second;
});
for (int i = 0; i < n; i++) {
dp[i] = ch(a[i].first - 1, a[i].first + a[i].second - 2);
for (int j = 0; j < i; j++)
if (a[j].first <= a[i].first && a[j].second <= a[i].second)
dp[i] = (dp[i] + mod -
dp[j] * 1ll *
ch(a[i].first - a[j].first,
a[i].first - a[j].first + a[i].second - a[j].second) %
mod) %
mod;
}
cout << dp[n - 1] << endl;
}
|
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.
While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one — by value vi - 1, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged.
If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj.
All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.
Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.
Input
The first line of the input contains a positive integer n (1 ≤ n ≤ 4000) — the number of kids in the line.
Next n lines contain three integers each vi, di, pi (1 ≤ vi, di, pi ≤ 106) — the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.
Output
In the first line print number k — the number of children whose teeth Gennady will cure.
In the second line print k integers — the numbers of the children who will make it to the end of the line in the increasing order.
Examples
Input
5
4 2 2
4 1 2
5 2 4
3 3 5
5 1 2
Output
2
1 3
Input
5
4 5 1
5 3 9
4 1 2
2 1 8
4 1 9
Output
4
1 2 4 5
Note
In the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.
In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5, - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last.
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Tarek
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
AGennadyTheDentist solver = new AGennadyTheDentist();
solver.solve(1, in, out);
out.close();
}
static class AGennadyTheDentist {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int[] v = new int[n];
int[] d = new int[n];
int[] p = new int[n];
for (int i = 0; i < n; i++) {
v[i] = in.readInt();
d[i] = in.readInt();
p[i] = in.readInt();
}
boolean[] inQueue = new boolean[n];
IntList answer = new IntArrayList();
Arrays.fill(inQueue, true);
for (int i = 0; i < n; i++) {
if (inQueue[i]) {
answer.add(i + 1);
IntList runAway = new IntArrayList();
inQueue[i] = false;
int current = v[i];
for (int j = i + 1; j < n && current > 0; j++) {
if (inQueue[j]) {
p[j] -= current--;
if (p[j] < 0) {
inQueue[j] = false;
runAway.add(j);
}
}
}
for (int l = 0; l < runAway.size(); l++) {
int j = runAway.get(l);
for (int k = j + 1; k < n; k++) {
if (inQueue[k]) {
p[k] -= d[j];
if (p[k] < 0) {
inQueue[k] = false;
runAway.add(k);
}
}
}
}
}
}
out.printLine(answer.size());
out.printLine(answer);
}
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void addAt(int index, int value);
public abstract void removeAt(int index);
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void add(int value) {
addAt(size(), value);
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static interface IntCollection extends IntStream {
public int size();
default public void add(int value) {
throw new UnsupportedOperationException();
}
default public IntCollection addAll(IntStream values) {
for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
add(it.value());
}
return this;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static interface IntReversableCollection extends IntCollection {
}
static class IntArrayList extends IntAbstractStream implements IntList {
private int size;
private int[] data;
public IntArrayList() {
this(3);
}
public IntArrayList(int capacity) {
data = new int[capacity];
}
public IntArrayList(IntCollection c) {
this(c.size());
addAll(c);
}
public IntArrayList(IntStream c) {
this();
if (c instanceof IntCollection) {
ensureCapacity(((IntCollection) c).size());
}
addAll(c);
}
public IntArrayList(IntArrayList c) {
size = c.size();
data = c.data.clone();
}
public IntArrayList(int[] arr) {
size = arr.length;
data = arr.clone();
}
public int size() {
return size;
}
public int get(int at) {
if (at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size);
}
return data[at];
}
private void ensureCapacity(int capacity) {
if (data.length >= capacity) {
return;
}
capacity = Math.max(2 * data.length, capacity);
data = Arrays.copyOf(data, capacity);
}
public void addAt(int index, int value) {
ensureCapacity(size + 1);
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size) {
System.arraycopy(data, index, data, index + 1, size - index);
}
data[index] = value;
size++;
}
public void removeAt(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size - 1) {
System.arraycopy(data, index + 1, data, index, size - index - 1);
}
size--;
}
}
}
|
There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.
Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons.
The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j.
Output
Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added.
Examples
Input
4
1 9
3 1
6 1
7 4
Output
1
Input
7
1 1
2 1
3 1
4 1
5 1
6 1
7 1
Output
3
Note
For the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.
For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.
|
import sys
input = sys.stdin.readline
from bisect import *
n = int(input())
ab = [tuple(map(int, input().split())) for _ in range(n)]
ab.sort(key=lambda k: k[0])
a = [-10**18]+[ai for ai, _ in ab]
dp = [0]*(n+1)
for i in range(1, n+1):
j = bisect_left(a, ab[i-1][0]-ab[i-1][1])-1
dp[i] = dp[j]+i-j-1
ans = 10**18
for i in range(n+1):
ans = min(ans, dp[i]+n-i)
print(ans)
|
Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve.
It's a well-known fact that Limak, as every bear, owns a set of numbers. You know some information about the set:
* The elements of the set are distinct positive integers.
* The number of elements in the set is n. The number n is divisible by 5.
* All elements are between 1 and b, inclusive: bears don't know numbers greater than b.
* For each r in {0, 1, 2, 3, 4}, the set contains exactly <image> elements that give remainder r when divided by 5. (That is, there are <image> elements divisible by 5, <image> elements of the form 5k + 1, <image> elements of the form 5k + 2, and so on.)
Limak smiles mysteriously and gives you q hints about his set. The i-th hint is the following sentence: "If you only look at elements that are between 1 and upToi, inclusive, you will find exactly quantityi such elements in my set."
In a moment Limak will tell you the actual puzzle, but something doesn't seem right... That smile was very strange. You start to think about a possible reason. Maybe Limak cheated you? Or is he a fair grizzly bear?
Given n, b, q and hints, check whether Limak can be fair, i.e. there exists at least one set satisfying the given conditions. If it's possible then print ''fair". Otherwise, print ''unfair".
Input
The first line contains three integers n, b and q (5 ≤ n ≤ b ≤ 104, 1 ≤ q ≤ 104, n divisible by 5) — the size of the set, the upper limit for numbers in the set and the number of hints.
The next q lines describe the hints. The i-th of them contains two integers upToi and quantityi (1 ≤ upToi ≤ b, 0 ≤ quantityi ≤ n).
Output
Print ''fair" if there exists at least one set that has all the required properties and matches all the given hints. Otherwise, print ''unfair".
Examples
Input
10 20 1
10 10
Output
fair
Input
10 20 3
15 10
5 0
10 5
Output
fair
Input
10 20 2
15 3
20 10
Output
unfair
Note
In the first example there is only one set satisfying all conditions: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.
In the second example also there is only one set satisfying all conditions: {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}.
Easy to see that there is no set satisfying all conditions from the third example. So Limak lied to you :-(
|
#include <bits/stdc++.h>
int read() {
int ans = 0, c, f = 1;
while (!isdigit(c = getchar()))
if (c == '-') f *= -1;
do ans = ans * 10 + c - '0';
while (isdigit(c = getchar()));
return ans * f;
}
const int N = 10050;
const int K = 5;
inline int query(int l, int r, int t) {
return (r + K - t) / K - (l - 1 + K - t) / K;
}
std::pair<int, int> Q[N];
int main() {
int n = read(), b = read(), q = read();
for (int i = 0; i < q; ++i) {
Q[i].first = read();
Q[i].second = read();
}
Q[q++] = std::make_pair(0, 0);
Q[q++] = std::make_pair(b, n);
std::sort(Q, Q + q);
for (int i = 1; i < q; ++i)
if (Q[i].second < Q[i - 1].second ||
Q[i].second - Q[i - 1].second > Q[i].first - Q[i - 1].first) {
puts("unfair");
return 0;
}
for (int S = 1; S < (1 << K); ++S) {
int t = n;
for (int i = 1; i < q; ++i) {
int l = Q[i - 1].first + 1, r = Q[i].first,
s = Q[i].second - Q[i - 1].second;
int b = 0;
for (int j = 0; j < K; ++j)
if ((S >> j) & 1) b += query(l, r, j);
if (b - s < 0) t += b - s;
}
int sx = 0;
for (int j = 0; j < K; ++j)
if ((S >> j) & 1) ++sx;
sx *= n / 5;
if (sx > t) {
puts("unfair");
return 0;
}
}
puts("fair");
return 0;
}
|
Limak is a little polar bear. He has n balls, the i-th ball has size ti.
Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy:
* No two friends can get balls of the same size.
* No two friends can get balls of sizes that differ by more than 2.
For example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 (two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2).
Your task is to check whether Limak can choose three balls that satisfy conditions above.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 50) — the number of balls Limak has.
The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 1000) where ti denotes the size of the i-th ball.
Output
Print "YES" (without quotes) if Limak can choose three balls of distinct sizes, such that any two of them differ by no more than 2. Otherwise, print "NO" (without quotes).
Examples
Input
4
18 55 16 17
Output
YES
Input
6
40 41 43 44 44 44
Output
NO
Input
8
5 972 3 4 1 4 970 971
Output
YES
Note
In the first sample, there are 4 balls and Limak is able to choose three of them to satisfy the rules. He must must choose balls with sizes 18, 16 and 17.
In the second sample, there is no way to give gifts to three friends without breaking the rules.
In the third sample, there is even more than one way to choose balls:
1. Choose balls with sizes 3, 4 and 5.
2. Choose balls with sizes 972, 970, 971.
|
n = int(input())
s = map(int, input().split())
l = []
a = 'NO'
for i in s:
if i not in l:
l += [i]
l = sorted(l)
if len(l) >= 3:
for i in range(len(l) - 2):
if l[i] + 2 == l[i + 1] + 1 == l[i + 2]:
a = 'YES'
print(a)
|
The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.
Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.
Input
The first line contains a single integer n (1 ≤ n ≤ 18) — the number of participants of the Sith Tournament.
Each of the next n lines contains n real numbers, which form a matrix pij (0 ≤ pij ≤ 1). Each its element pij is the probability that the i-th participant defeats the j-th in a duel.
The elements on the main diagonal pii are equal to zero. For all different i, j the equality pij + pji = 1 holds. All probabilities are given with no more than six decimal places.
Jedi Ivan is the number 1 in the list of the participants.
Output
Output a real number — the probability that Jedi Ivan will stay alive after the Tournament. Absolute or relative error of the answer must not exceed 10 - 6.
Examples
Input
3
0.0 0.5 0.8
0.5 0.0 0.4
0.2 0.6 0.0
Output
0.680000000000000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j, k, h, t1, t2, index, t = 2;
scanf("%d", &n);
double a[n][n], p1 = 0, ans = 0, ans2 = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%lf", &a[i][j]);
if (i == 0 && a[i][j] > p1) {
p1 = a[i][j];
index = j;
}
}
}
if (n == 1) {
printf("1");
} else if (n == 2) {
printf("%.10lf", a[0][1]);
} else {
int b[n - 1];
double p[n - 1];
bool f[n];
for (t1 = 0; t1 < n; t1++) {
f[t1] = true;
}
b[1] = index;
stack<int> s;
s.push(index);
f[index] = false;
while (t != n) {
ans2 = 0;
index = 1;
for (t1 = 1; t1 < n; t1++) {
if (f[t1]) {
s.push(t1);
k = 0;
while (!s.empty()) {
b[k++] = s.top();
s.pop();
}
k--;
while (k >= 0) {
s.push(b[k--]);
}
for (i = 0; i < t; i++) {
p[i] = 0;
}
p[0] = 1;
p[1] = a[b[1]][b[0]];
for (i = 2; i < t; i++) {
for (j = i - 1; j >= 0; j--) {
p1 = 1;
for (k = j + 1; k < i; k++) {
p1 *= a[b[j]][b[k]];
}
p[i] += p[j] * p1 * a[b[i]][b[j]];
}
}
ans = 0;
for (i = 0; i < t; i++) {
p1 = 1;
for (j = i + 1; j < t; j++) {
p1 *= a[b[i]][b[j]];
}
ans += p1 * p[i] * a[0][b[i]];
}
if (ans > ans2) {
ans2 = ans;
index = t1;
}
s.pop();
}
}
s.push(index);
f[index] = false;
t++;
}
printf("%.10lf", ans2);
return 0;
}
}
|
Bomboslav set up a branding agency and now helps companies to create new logos and advertising slogans. In term of this problems, slogan of the company should be a non-empty substring of its name. For example, if the company name is "hornsandhoofs", then substrings "sand" and "hor" could be its slogans, while strings "e" and "hornss" can not.
Sometimes the company performs rebranding and changes its slogan. Slogan A is considered to be cooler than slogan B if B appears in A as a substring at least twice (this occurrences are allowed to overlap). For example, slogan A = "abacaba" is cooler than slogan B = "ba", slogan A = "abcbcbe" is cooler than slogan B = "bcb", but slogan A = "aaaaaa" is not cooler than slogan B = "aba".
You are given the company name w and your task is to help Bomboslav determine the length of the longest sequence of slogans s1, s2, ..., sk, such that any slogan in the sequence is cooler than the previous one.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the company name that asks Bomboslav to help. The second line contains the string w of length n, that consists of lowercase English letters.
Output
Print a single integer — the maximum possible length of the sequence of slogans of the company named w, such that any slogan in the sequence (except the first one) is cooler than the previous
Examples
Input
3
abc
Output
1
Input
5
ddddd
Output
5
Input
11
abracadabra
Output
3
|
#include <bits/stdc++.h>
const int MAX_N = 2e5 + 10, SIGMA = 26;
int N, ans;
char S[MAX_N];
struct SegTree {
int l, r, m;
SegTree *cl, *cr;
SegTree(int l, int r)
: l(l), r(r), m((l + r) / 2), cl(nullptr), cr(nullptr) {}
};
SegTree *touch(int l, int r, int x) {
SegTree *res = new SegTree(l, r);
if (l != r) {
if (x <= res->m)
res->cl = touch(l, res->m, x);
else
res->cr = touch(res->m + 1, r, x);
}
return res;
}
SegTree *merge(SegTree *a, SegTree *b) {
if (!a) return b;
if (!b) return a;
SegTree *res = new SegTree(a->l, a->r);
res->cl = merge(a->cl, b->cl);
res->cr = merge(a->cr, b->cr);
return res;
}
int last_before(SegTree *t, int x) {
if (!t || t->l > x) return -1;
if (t->l == t->r) return t->l;
int res = last_before(t->cr, x);
return res == -1 ? last_before(t->cl, x) : res;
}
int first_after(SegTree *t, int x) {
if (!t || t->r < x) return -1;
if (t->l == t->r) return t->l;
int res = first_after(t->cl, x);
return res == -1 ? first_after(t->cr, x) : res;
}
struct SAM {
struct Node {
int len, right, f, flen;
Node *trans[SIGMA], *fail;
SegTree *seg, *fseg;
Node(SAM *sam, int len, int right)
: len(len),
right(right),
f(0),
flen(0),
fail(nullptr),
seg(nullptr),
fseg(nullptr) {
sam->nodes.push_back(this);
std::fill_n(trans, SIGMA, nullptr);
}
} * empty, *last;
std::vector<Node *> nodes;
SAM() { last = empty = new Node(this, 0, 0); }
void extend(int ch) {
Node *u = new Node(this, last->len + 1, last->len + 1), *v = last;
for (; v && !v->trans[ch]; v = v->fail) v->trans[ch] = u;
if (!v)
u->fail = empty;
else {
Node *q = v->trans[ch];
if (q->len == v->len + 1)
u->fail = q;
else {
Node *p = new Node(this, v->len + 1, 0);
p->fail = q->fail;
q->fail = u->fail = p;
std::copy_n(q->trans, SIGMA, p->trans);
for (; v && v->trans[ch] == q; v = v->fail) v->trans[ch] = p;
}
}
last = u;
}
void solve() {
sort(nodes.begin(), nodes.end(),
[](Node *a, Node *b) { return a->len < b->len; });
for (auto i = nodes.rbegin(); i != nodes.rend(); i++) {
Node *node = *i;
if (node->right) node->seg = merge(node->seg, touch(1, N, node->right));
if (node->fail) node->fail->seg = merge(node->seg, node->fail->seg);
}
for (Node *node : nodes) {
if (node == empty) continue;
if (node->fail == empty) {
node->f = 1;
node->fseg = node->seg;
node->flen = node->len;
} else {
int p = first_after(node->seg, 1);
int pf = last_before(node->fail->fseg, p - 1);
if (pf - node->fail->flen + 1 >= p - node->len + 1) {
node->f = node->fail->f + 1;
node->fseg = node->seg;
node->flen = node->len;
} else {
node->f = node->fail->f;
node->fseg = node->fail->fseg;
node->flen = node->fail->flen;
}
}
ans = std::max(ans, node->f);
}
}
} sam;
int main() {
std::scanf("%d", &N);
std::scanf("%s", S + 1);
for (int i = 1; i <= N; i++) sam.extend(S[i] - 'a');
sam.solve();
std::printf("%d\n", ans);
}
|
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer.
Input
The first line of the input contains three distinct integers x1, x2 and x3 (1 ≤ x1, x2, x3 ≤ 100) — the coordinates of the houses of the first, the second and the third friends respectively.
Output
Print one integer — the minimum total distance the friends need to travel in order to meet together.
Examples
Input
7 1 4
Output
6
Input
30 20 10
Output
20
Note
In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4.
|
def GetDistance(x1,x2,x3,z):
return abs(z-x1) + abs(z-x2) + abs(z-x3)
friends= raw_input().split()
x1=int(friends[0])
x2=int(friends[1])
x3=int(friends[2])
frnds=[x1,x2,x3]
dist=[]
for i in range(min(frnds),max(frnds)+1):
dist.append(GetDistance(x1,x2,x3,i))
print min(dist)
|
Hongcow's teacher heard that Hongcow had learned about the cyclic shift, and decided to set the following problem for him.
You are given a list of n strings s1, s2, ..., sn contained in the list A.
A list X of strings is called stable if the following condition holds.
First, a message is defined as a concatenation of some elements of the list X. You can use an arbitrary element as many times as you want, and you may concatenate these elements in any arbitrary order. Let SX denote the set of of all messages you can construct from the list. Of course, this set has infinite size if your list is nonempty.
Call a single message good if the following conditions hold:
* Suppose the message is the concatenation of k strings w1, w2, ..., wk, where each wi is an element of X.
* Consider the |w1| + |w2| + ... + |wk| cyclic shifts of the string. Let m be the number of these cyclic shifts of the string that are elements of SX.
* A message is good if and only if m is exactly equal to k.
The list X is called stable if and only if every element of SX is good.
Let f(L) be 1 if L is a stable list, and 0 otherwise.
Find the sum of f(L) where L is a nonempty contiguous sublist of A (there are <image> contiguous sublists in total).
Input
The first line of input will contain a single integer n (1 ≤ n ≤ 30), denoting the number of strings in the list.
The next n lines will each contain a string si (<image>).
Output
Print a single integer, the number of nonempty contiguous sublists that are stable.
Examples
Input
4
a
ab
b
bba
Output
7
Input
5
hh
ee
ll
ll
oo
Output
0
Input
6
aab
ab
bba
b
ab
c
Output
13
Note
For the first sample, there are 10 sublists to consider. Sublists ["a", "ab", "b"], ["ab", "b", "bba"], and ["a", "ab", "b", "bba"] are not stable. The other seven sublists are stable.
For example, X = ["a", "ab", "b"] is not stable, since the message "ab" + "ab" = "abab" has four cyclic shifts ["abab", "baba", "abab", "baba"], which are all elements of SX.
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 35;
const int MAXS = 100005;
long long n, b1 = 31337, b2 = 1299721, p1 = 1000000007, p2 = 1000000011, sol;
string s[MAXN];
int len[MAXN], bio[MAXS];
long long h1[MAXN][MAXS], h2[MAXN][MAXS];
long long pot1[MAXS], pot2[MAXS];
vector<int> c[MAXN], v[MAXS];
long long sub(long long a, long long b, long long mod) {
if (a - b < 0) return a - b + mod;
return a - b;
}
long long get_hash1(int ind, int a, int b) {
if (a == 0) return h1[ind][b];
return sub(h1[ind][b], pot1[b - a + 1] * h1[ind][a - 1] % p1, p1);
}
long long get_hash2(int ind, int a, int b) {
if (a == 0) return h2[ind][b];
return sub(h2[ind][b], pot2[b - a + 1] * h2[ind][a - 1] % p2, p2);
}
int isti(int ind1, int a1, int b1, int ind2, int a2, int b2) {
return get_hash1(ind1, a1, b1) == get_hash1(ind2, a2, b2) &&
get_hash2(ind1, a1, b1) == get_hash2(ind2, a2, b2);
}
void precompute() {
int cnt = 0;
for (int i = 0; i < n; i++) {
len[i] = s[i].size();
for (int j = 0; j < len[i]; j++) {
cnt++;
c[i].push_back(cnt);
h1[i][j] = (s[i][j] + b1 * (j == 0 ? 0 : h1[i][j - 1])) % p1;
h2[i][j] = (s[i][j] + b2 * (j == 0 ? 0 : h2[i][j - 1])) % p2;
pot1[j] = (j == 0 ? 1 : b1 * pot1[j - 1]) % p1;
pot2[j] = (j == 0 ? 1 : b2 * pot2[j - 1]) % p2;
}
}
}
void gen(int a, int b) {
for (int i = 0; i < MAXS; i++) {
v[i].clear();
}
for (int i = a; i <= b; i++) {
v[0].push_back(c[i][0]);
for (int j = 0; j < len[i]; j++) {
for (int k = a; k <= b; k++) {
if (len[i] - j > len[k]) {
if (isti(i, j, j + len[k] - 1, k, 0, len[k] - 1)) {
v[c[i][j]].push_back(c[i][j + len[k]]);
}
} else if (len[i] - j < len[k]) {
if (isti(i, j, len[i] - 1, k, 0, len[i] - 1 - j)) {
v[c[i][j]].push_back(c[k][len[i] - j]);
}
} else {
if (j != 0 && isti(i, j, len[i] - 1, k, 0, len[k] - 1)) {
v[c[i][j]].push_back(0);
}
}
}
}
}
return;
for (int i = 0; i < MAXS; i++) {
if (v[i].empty()) continue;
cout << i << " ";
for (int j = 0; j < v[i].size(); j++) {
cout << v[i][j] << " ";
}
cout << endl;
}
}
int dfs(int cvor) {
bio[cvor] = 1;
for (int i = 0; i < v[cvor].size(); i++) {
int sus = v[cvor][i];
if (bio[sus] == 1) return 1;
if (bio[sus] == 0 && dfs(sus)) return 1;
}
bio[cvor] = 2;
return 0;
}
int ciklus() {
memset(bio, 0, sizeof bio);
for (int i = 0; i < MAXS; i++) {
if (bio[i] == 0 && dfs(i)) return 1;
}
return 0;
}
string rev(string bla) {
string res = "";
int lim = bla.size();
for (int i = 0; i < lim; i++) {
if (bla[i] == 'a')
res += 'b';
else
res += 'a';
}
return res;
}
string fair(int br) {
string res = "a";
for (int i = 0; i < br; i++) {
res = res + rev(res);
}
return res;
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s[i];
}
precompute();
int lef = 0;
for (int i = 0; i < n; i++) {
if (lef < i) lef = i;
while (lef < n) {
gen(i, lef);
if (ciklus()) break;
lef++;
}
if (i == lef) continue;
sol += lef - i;
}
cout << sol;
return 0;
}
|
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility.
Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1.
Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?
Input
The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r.
It is guaranteed that r is not greater than the length of the final list.
Output
Output the total number of 1s in the range l to r in the final sequence.
Examples
Input
7 2 5
Output
4
Input
10 3 10
Output
5
Note
Consider first example:
<image>
Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4.
For the second example:
<image>
Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5.
|
'''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
Date:08/06/2020
'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def func(a,x):
ans=0
n=len(a)
for i in range(n,0,-1):
x1=(1<<i)-1
if(x>=x1):
ans+=a[i-1]
x-=x1
if(x>0):
ans+=a[i]%(2*a[i-1])
x-=1
return ans
def solve():
# for _ in range(ii()):
n,l,r=mi()
a=[n]
while(n>1):
a.append(n//2)
n//=2
a.reverse()
cnt1=[a[0]]
for i in range(1,len(a)):
cnt1.append(2*cnt1[i-1]+a[i]%2)
tot=(1<<len(cnt1))-1
if(r>tot):
r-=tot
if(l>tot):
l-=tot
x=func(cnt1,r)
y=func(cnt1,l-1)
print(x-y)
if __name__ =="__main__":
solve()
|
There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.
It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.
It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs.
Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.
Input
The first line contains one integer number n (2 ≤ n ≤ 2·105).
The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct.
Output
Print two integer numbers — the minimal distance and the quantity of pairs with this distance.
Examples
Input
4
6 -3 0 4
Output
2 1
Input
3
-2 0 2
Output
2 2
Note
In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance.
|
n = int(input())
array = list(map(int, input().split()))
array = sorted(array)
mink = array[-1] - array[0]
count = 0
for i in range(1, len(array)):
if mink > array[i] - array[i-1]:
mink = array[i] - array[i-1]
count = 1
elif mink == array[i] - array[i-1]:
count += 1
print(mink, count)
|
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.
Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?
Input
The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs.
Output
On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.
Examples
Input
3 11
2 3 5
Output
2 11
Input
4 100
1 2 5 6
Output
4 54
Input
1 7
7
Output
0 0
Note
In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items.
In the second example, he can buy all items as they will cost him [5, 10, 17, 22].
In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it.
|
n,m1=map(int,input().split())
lp=list(map(int,input().split()))
l=0
r=n
while l<r :
m=(l+r+1)//2
l1=lp[::]
for i in range(n) :
l1[i]=lp[i]+((i+1)*m)
l1=sorted(l1)
s=sum(l1[:m])
if s>m1 :
r=m-1
else :
l=m
l1=lp[::]
for i in range(n) :
l1[i]=lp[i]+((i+1)*l)
l1=sorted(l1)
s=sum(l1[:l])
print(l,s)
|
Alice and Bob are playing a game with a string of characters, with Alice going first. The string consists n characters, each of which is one of the first k letters of the alphabet. On a player’s turn, they can either arbitrarily permute the characters in the words, or delete exactly one character in the word (if there is at least one character). In addition, their resulting word cannot have appeared before throughout the entire game. The player unable to make a valid move loses the game.
Given n, k, p, find the number of words with exactly n characters consisting of the first k letters of the alphabet such that Alice will win if both Alice and Bob play optimally. Return this number modulo the prime number p.
Input
The first line of input will contain three integers n, k, p (1 ≤ n ≤ 250 000, 1 ≤ k ≤ 26, 108 ≤ p ≤ 109 + 100, p will be prime).
Output
Print a single integer, the number of winning words for Alice, modulo p.
Example
Input
4 2 100000007
Output
14
Note
There are 14 strings that that Alice can win with. For example, some strings are "bbaa" and "baaa". Alice will lose on strings like "aaaa" or "bbbb".
|
#include <bits/stdc++.h>
using namespace std;
const int logMax = 20;
const int NMax = 250005;
int DP[logMax][NMax];
int MOD, N, K;
int supra[NMax], cnt;
int Inv[NMax], Fact[NMax];
int power(int n, int p) {
int sol = 1;
while (p) {
if (p & 1) sol = (1LL * sol * n) % MOD;
p /= 2;
n = (1LL * n * n) % MOD;
}
return sol;
}
void precalcFact() {
Fact[0] = Inv[0] = 1;
for (int i = 1; i <= N; i++) {
Fact[i] = (1LL * Fact[i - 1] * i) % MOD;
Inv[i] = power(Fact[i], MOD - 2);
}
}
void Add(int& x, int y) {
x += y;
if (x >= MOD) x -= MOD;
}
int Comb(int n, int k) {
return (((1LL * Fact[n] * Inv[n - k]) % MOD) * Inv[k]) % MOD;
}
void Solve() {
if (N % 2 == 1) {
cout << power(K, N) << "\n";
return;
}
DP[0][0] = 1;
for (int i = 0; i <= N; i++) {
if ((N & i) != i) continue;
cnt = 0;
for (int j = i | (i + 1); j <= N; j = i | (j + 1)) {
if ((N & j) == j) supra[++cnt] = j;
if (j == N) break;
}
for (int j = 0; j < min(K, 16); j++) {
if (DP[j][i] == 0) continue;
for (int k = 1; k <= cnt; k++) {
Add(DP[j + 1][supra[k]], (1LL * DP[j][i] * Inv[supra[k] - i]) % MOD);
}
}
}
int ans = 0;
for (int i = 1; i <= min(K, 16); i++) {
Add(ans, (1LL * DP[i][N] * Comb(K, i)) % MOD);
}
ans = (1LL * ans * Fact[N]) % MOD;
ans = (power(K, N) - ans + MOD) % MOD;
cout << ans << "\n";
}
int main() {
cin >> N >> K >> MOD;
precalcFact();
Solve();
return 0;
}
|
All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland!
It is well-known that there are n cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that the road network is connected, i.e. it is possible that you can't reach some city from some other.
The tour will contain several episodes. In each of the episodes:
* the wizard will disembark at some city x from the Helicopter;
* he will give a performance and show a movie for free at the city x;
* he will drive to some neighboring city y using a road;
* he will give a performance and show a movie for free at the city y;
* he will drive to some neighboring to y city z;
* he will give a performance and show a movie for free at the city z;
* he will embark the Helicopter and fly away from the city z.
It is known that the wizard doesn't like to use roads, so he agrees to use each road at most once (regardless of direction). In other words, for road between a and b he only can drive once from a to b, or drive once from b to a, or do not use this road at all.
The wizards wants to plan as many episodes as possible without violation the above rules. Help the wizard!
Please note that the wizard can visit the same city multiple times, the restriction is on roads only.
Input
The first line contains two integers n, m (1 ≤ n ≤ 2·105, 0 ≤ m ≤ 2·105) — the number of cities and the number of roads in Berland, respectively.
The roads description follow, one in each line. Each description is a pair of two integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the ids of the cities connected by the i-th road. It is guaranteed that there are no two roads connecting the same pair of cities. Every road is bidirectional. The cities are numbered from 1 to n.
It is possible that the road network in Berland is not connected.
Output
In the first line print w — the maximum possible number of episodes. The next w lines should contain the episodes in format x, y, z — the three integers denoting the ids of the cities in the order of the wizard's visits.
Examples
Input
4 5
1 2
3 2
2 4
3 4
4 1
Output
2
1 4 2
4 3 2
Input
5 8
5 3
1 2
4 5
5 1
2 5
4 3
1 4
3 2
Output
4
1 4 5
2 3 4
1 5 3
5 2 1
|
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 2e5 + 7;
long long n, m, a[maxn], par[maxn], delp[maxn], cnt;
long long num[maxn], delpar[maxn];
vector<long long> cac[maxn];
vector<long long> vt[maxn];
long long ans1[maxn], ans2[maxn], ans3[maxn], cnt2;
void DFS(long long u, long long p) {
par[u] = p;
num[u] = ++cnt2;
for (auto v : vt[u]) {
if (v == p) continue;
if (num[v] == 0) {
DFS(v, u);
if (!delpar[v]) {
cac[u].push_back(v);
}
} else if (num[v] < num[u]) {
cac[v].push_back(u);
}
}
for (long long i = 0; i + 1 < cac[u].size(); i += 2) {
ans1[++cnt] = cac[u][i];
ans2[cnt] = u;
ans3[cnt] = cac[u][i + 1];
}
if (cac[u].size() & 1) {
if (par[u] != u) {
ans1[++cnt] = cac[u].back();
ans2[cnt] = u;
ans3[cnt] = par[u];
delpar[u] = 1;
}
}
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (long long i = 1; i <= m; i++) {
long long u, v;
cin >> u >> v;
vt[u].push_back(v);
vt[v].push_back(u);
}
for (long long i = 1; i <= n; i++) {
if (par[i] == 0) {
par[i] = i;
DFS(i, i);
}
}
cout << cnt << '\n';
for (long long i = 1; i <= cnt; i++) {
cout << ans1[i] << ' ' << ans2[i] << ' ' << ans3[i] << "\n";
}
}
|
Berland.Taxi is a new taxi company with k cars which started operating in the capital of Berland just recently. The capital has n houses on a straight line numbered from 1 (leftmost) to n (rightmost), and the distance between any two neighboring houses is the same.
You have to help the company schedule all the taxi rides which come throughout the day according to the following rules:
* All cars are available for picking up passengers. Initially the j-th car is located next to the house with the number xj at time 0.
* All cars have the same speed. It takes exactly 1 minute for any car to travel between neighboring houses i and i + 1.
* The i-th request for taxi ride comes at the time ti, asking for a passenger to be picked up at the house ai and dropped off at the house bi. All requests for taxi rides are given in the increasing order of ti. All ti are distinct.
When a request for taxi ride is received at time ti, Berland.Taxi operator assigns a car to it as follows:
* Out of cars which are currently available, operator assigns the car which is the closest to the pick up spot ai. Needless to say, if a car is already on a ride with a passenger, it won't be available for any rides until that passenger is dropped off at the corresponding destination.
* If there are several such cars, operator will pick one of them which has been waiting the most since it became available.
* If there are several such cars, operator will pick one of them which has the lowest number.
After a car gets assigned to the taxi ride request:
* The driver immediately starts driving from current position to the house ai.
* Once the car reaches house ai, the passenger is immediately picked up and the driver starts driving to house bi.
* Once house bi is reached, the passenger gets dropped off and the car becomes available for new rides staying next to the house bi.
* It is allowed for multiple cars to be located next to the same house at the same point in time, while waiting for ride requests or just passing by.
If there are no available cars at time ti when a request for taxi ride comes, then:
* The i-th passenger will have to wait for a car to become available.
* When a car becomes available, operator will immediately assign it to this taxi ride request.
* If multiple cars become available at once while the passenger is waiting, operator will pick a car out of them according to the rules described above.
Operator processes taxi ride requests one by one. So if multiple passengers are waiting for the cars to become available, operator will not move on to processing the (i + 1)-th ride request until the car gets assigned to the i-th ride request.
Your task is to write a program that will process the given list of m taxi ride requests. For each request you have to find out which car will get assigned to it, and how long the passenger will have to wait for a car to arrive. Note, if there is already car located at the house ai, then the corresponding wait time will be 0.
Input
The first line of input contains integers n, k and m (2 ≤ n ≤ 2·105, 1 ≤ k, m ≤ 2·105) — number of houses, number of cars, and number of taxi ride requests. The second line contains integers x1, x2, ..., xk (1 ≤ xi ≤ n) — initial positions of cars. xi is a house number at which the i-th car is located initially. It's allowed for more than one car to be located next to the same house.
The following m lines contain information about ride requests. Each ride request is represented by integers tj, aj and bj (1 ≤ tj ≤ 1012, 1 ≤ aj, bj ≤ n, aj ≠ bj), where tj is time in minutes when a request is made, aj is a house where passenger needs to be picked up, and bj is a house where passenger needs to be dropped off. All taxi ride requests are given in the increasing order of tj. All tj are distinct.
Output
Print m lines: the j-th line should contain two integer numbers, the answer for the j-th ride request — car number assigned by the operator and passenger wait time.
Examples
Input
10 1 2
3
5 2 8
9 10 3
Output
1 1
1 5
Input
5 2 1
1 5
10 3 5
Output
1 2
Input
5 2 2
1 5
10 3 5
20 4 1
Output
1 2
2 1
Note
In the first sample test, a request comes in at time 5 and the car needs to get from house 3 to house 2 to pick up the passenger. Therefore wait time will be 1 and the ride will be completed at time 5 + 1 + 6 = 12. The second request comes in at time 9, so the passenger will have to wait for the car to become available at time 12, and then the car needs another 2 minutes to get from house 8 to house 10. So the total wait time is 3 + 2 = 5.
In the second sample test, cars 1 and 2 are located at the same distance from the first passenger and have the same "wait time since it became available". Car 1 wins a tiebreaker according to the rules because it has the lowest number. It will come to house 3 at time 3, so the wait time will be 2.
|
#include <bits/stdc++.h>
using namespace std;
multiset<int> W;
set<pair<long long, long long> > S[200020];
struct str {
str() {}
str(long long tm, int c, int b) : tm(tm), c(c), b(b) {}
long long tm;
int c, b;
bool operator>(const str &rhs) const { return tm > rhs.tm; }
};
priority_queue<str, vector<str>, greater<str> > pq;
void solve() {
int n, k, m;
scanf("%d%d%d", &n, &k, &m);
for (int i = 1; i <= k; i++) {
int x;
scanf("%d", &x);
S[x].insert(pair<long long, long long>(0, i));
W.insert(x);
}
long long fm = 0;
for (int i = 1; i <= m; i++) {
long long t;
int a, b;
scanf("%lld%d%d", &t, &a, &b);
fm = max(fm, t);
while (!pq.empty() && pq.top().tm <= fm) {
auto e = pq.top();
pq.pop();
W.insert(e.b);
S[e.b].insert(pair<long long, long long>(e.tm, e.c));
}
if (((int)(W).size()) == 0) {
fm = pq.top().tm;
while (!pq.empty() && pq.top().tm == fm) {
auto e = pq.top();
pq.pop();
W.insert(e.b);
S[e.b].insert(pair<long long, long long>(e.tm, e.c));
}
}
auto it = W.lower_bound(a);
int idis = 1e9, jdis = 1e9;
if (it != W.end()) idis = *it - a;
auto jt = it;
if (it != W.begin()) jt = prev(it), jdis = a - *jt;
pair<long long, long long> tex = pair<long long, long long>(-1, -1);
if (idis < jdis || (idis == jdis && *S[*it].begin() < *S[*jt].begin())) {
tex = *S[*it].begin();
S[*it].erase(S[*it].begin());
W.erase(it);
long long det = fm + idis + abs(a - b);
pq.push(str(det, (int)tex.second, b));
printf("%d %lld\n", (int)tex.second, fm + idis - t);
} else {
tex = *S[*jt].begin();
S[*jt].erase(S[*jt].begin());
W.erase(jt);
long long det = fm + jdis + abs(a - b);
pq.push(str(det, (int)tex.second, b));
printf("%d %lld\n", (int)tex.second, fm + jdis - t);
}
}
}
int main() {
int Tc = 1;
for (int tc = 1; tc <= Tc; tc++) {
solve();
}
return 0;
}
|
Your friend has n cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.
For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.
To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.
Input
The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit.
Output
Print a single integer, the minimum number of cards you must turn over to verify your claim.
Examples
Input
ee
Output
2
Input
z
Output
0
Input
0ay1
Output
2
Note
In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side.
In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them.
In the third sample, we need to flip the second and fourth cards.
|
s = list(input())
d = {'a', 'u', 'o', 'e', 'i', '1', '3', '5', '7', '9'}
ans = 0
for i in s:
if i in d:
ans += 1
print(ans)
|
Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor.
Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces».
With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols?
A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.».
Input
The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty.
Output
Print a single integer — the minimum number of clicks.
Examples
Input
snow affects sports such as skiing, snowboarding, and snowmachine travel.
snowboarding is a recreational activity and olympic and paralympic sport.
Output
141
Input
'co-co-co, codeforces?!'
Output
25
Input
thun-thun-thunder, thunder, thunder
thunder, thun-, thunder
thun-thun-thunder, thunder
thunder, feel the thunder
lightning then the thunder
thunder, feel the thunder
lightning then the thunder
thunder, thunder
Output
183
Note
In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks.
In sample case two it doesn't matter whether to use autocompletion or not.
|
import java.io.*;
public class D {
static PrintStream out = System.out;
static BufferedReader br;
static Node root = new Node(null);
static Node current = root;
static int counter;
static boolean pressEnter = false;
static int skipped = 0;
static {
root.trans = new Node[26];
root.unique = false;
br = new BufferedReader(new InputStreamReader(System.in));
}
static class Node {
int children = 0;
boolean unique = true;
boolean terminal = false;
Node parent;
Node[] trans;
Node(Node x) {
parent = x;
}
void transit(char ch) {
if(trans == null) {
trans = new Node[26];
}
int at = ch - 'a';
if (trans[at] == null) {
trans[at] = new Node(this);
children++;
counter++;
pressEnter = false;
// System.out.print("+");
if (children > 1 || terminal) {
propogate();
}
if (skipped != 0 && !terminal) {
counter += skipped;
skipped = 0;
} else if (skipped != 0 && terminal) {
skipped = 0;
}
} else if (!unique && trans[at].unique) {
pressEnter = true;
// System.out.print("+");
counter++;
} else if (pressEnter) {
counter++;
// System.out.print("+");
// System.out.print("<enter>");
pressEnter = false;
} else if (!unique && !trans[at].unique) {
counter++;
// System.out.print("+");
} else {
skipped++;
}
current = trans[at];
}
void propogate() {
Node cur = this;
while (cur.unique) {
cur.unique = false;
cur = cur.parent;
}
}
}
public static void main(String... args) {
String s;
try {
StringBuilder builder = new StringBuilder();
while ((s = br.readLine()) != null) {
for (int t = 0; t < s.length(); ++t) {
char ch = s.charAt(t);
if (ch == '*') break;
if (ch < 'a' || ch > 'z') {
// System.out.print("+");
counter++;
if (skipped != 0 && !current.terminal) {
counter += skipped;
skipped = 0;
} else if (skipped != 0 && current.terminal) {
skipped = 0;
}
current.terminal = true;
if (current.children > 0) {
current.propogate();
}
current = root;
root.terminal = false;
pressEnter = false;
} else current.transit(ch);
// System.out.print(ch);
}
counter++;
if (skipped != 0 && !current.terminal) {
counter += skipped;
skipped = 0;
} else if (skipped != 0 && current.terminal) {
skipped = 0;
}
current.terminal = true;
if (current.children > 0) {
current.propogate();
}
current = root;
root.terminal = false;
pressEnter = false;
// System.out.print(System.lineSeparator());
}
System.out.println(counter);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
|
The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct.
Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information.
Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out.
Input
The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format.
Output
The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations.
Examples
Input
4
XOOO
XXOO
OOOO
XXXX
XOOO
XOOO
XOXO
XOXX
Output
Yes
Input
2
XX
OO
XO
OX
Output
No
Note
In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise.
|
n=int(input())
a=[]
b=[]
for i in range(n):
a.append(input())
for i in range(n):
b.append(input())
def h(d):
c=[]
for i in range(n):
c.append(d[n-i-1])
return c
def r(d):
c=[]
for i in range(n):
temp=""
for j in range(n):
temp+=d[j][n-i-1]
c.append(temp)
return c
yes=0
for i in range(4):
if a==b:
print('YES')
yes=1
break
a=r(a)
if yes==0:
a=h(a)
for i in range(4):
if a==b:
print('YES')
yes=1
break
a=r(a)
if yes==0:
print('NO')
|
Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping.
Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two intersections. Petr wants to select one intersection such that if the robbers continue to drive the roads indefinitely, they will sooner or later come to that intersection. The initial position of the robbers is unknown. Find such an intersection that fits the requirements.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 10^5, 2 ≤ m ≤ 5 ⋅ 10^5) — the number of intersections and the number of directed roads in Braginsk, respectively.
Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — the start and finish of the i-th directed road. It is guaranteed that the robbers can move along the roads indefinitely.
Output
Print a single integer k — the intersection Petr needs to choose. If there are multiple answers, print any. If there are no such intersections, print -1.
Examples
Input
5 6
1 2
2 3
3 1
3 4
4 5
5 3
Output
3
Input
3 3
1 2
2 3
3 1
Output
1
Note
In the first example the robbers can move, for example, along the following routes: (1-2-3-1), (3-4-5-3), (1-2-3-4-5-3-1). We can show that if Petr chooses the 3-rd intersection, he will eventually meet the robbers independently of their route.
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 111111;
const int INF = 0x3f3f3f3f;
int vis[maxn];
bool selected[maxn];
int n, m;
vector<int> adj[maxn];
bool test[maxn];
double elapsed() { return clock() / (double)CLOCKS_PER_SEC; }
bool dfs(int v) {
if (selected[v] == true) return false;
vis[v] = -1;
for (auto w : adj[v]) {
if (vis[w] == 0) {
if (dfs(w)) return true;
} else if (vis[w] == -1) {
for (int i = 1; i <= n; i++) {
if (vis[i] != -1) test[i] = true;
}
return true;
}
}
vis[v] = 1;
return false;
}
bool check() {
memset(vis, 0, sizeof vis);
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
bool state = dfs(i);
if (state) return false;
}
}
return true;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
adj[x].push_back(y);
}
vector<int> emp;
for (int i = 0; i < n; ++i) emp.push_back(i + 1);
random_shuffle(emp.begin(), emp.end());
for (int i = 0; elapsed() <= 0.95 and i < emp.size(); i++) {
selected[emp[i]] = true;
if (!test[emp[i]] && check()) {
cout << emp[i] << "\n";
return 0;
}
selected[emp[i]] = false;
}
cout << -1 << endl;
}
|
Our hacker, Little Stuart lately has been fascinated by ancient puzzles. One day going through some really old books he finds something scribbled on the corner of a page. Now Little Stuart believes that the scribbled text is more mysterious than it originally looks, so he decides to find every occurrence of all the permutations of the scribbled text in the entire book. Since this is a huge task, Little Stuart needs your help, he needs you to only figure out if any permutation of the scribbled text exists in the given text string, so he can save time and analyze only those text strings where a valid permutation is present.
Input:
First line contains number of test cases T.Each test case contains two lines ,first line contains pattern and next line contains a text string. All characters in both the strings are in lowercase only [a-z].
Output:
For each test case print "YES" or "NO" (quotes for clarity) depending on whether any permutation of the pattern exists in the text string.
Constraints:
1 ≤ T ≤ 100
1 ≤ |Pattern| ≤ 1000
1 ≤ |Text String| ≤ 100000
SAMPLE INPUT
3
hack
indiahacks
code
eddy
coder
iamredoc
SAMPLE OUTPUT
YES
NO
YES
|
t=int(raw_input())
while(t>0):
s=raw_input()
str=raw_input()
s2=s[::-1]
if s in str or s2 in str:
print "YES"
else:
print "NO"
t-=1
|
My flatmate, Sayan, once invited all his relatives and friends from all over the city to join him on his birthday party.
He is also famous for boasting that all his friends and relatives belong to "proper" families.
Now, he appointed a gaurd to allow only his relatives and friends into the party.
It is gauranteed that all the relatives and friends come with their families all at once ,i.e, all members belonging to the same family reach all at once.
Now gaurd's task is to count the number of "proper" families who came in the party.
All families have a unique "special number" assigned to them ,i.e., all members of the same family share the same "special number".
A family is said to be proper only if the number of members in the familiy is a number which can be made by adding numbers from a given set of "valid" numbers N. Further constraint is that each valid number can be used only once.
Take an example:-
if N={1,2,8}
then all the families with 1,2,3,8,9,10 , or 11 members are allowed in the party , where as families with 4,5,6,7, etc members are not allowed.
The gaurd being a lazy fellow came to you for help.You need to write a program that computes the number of "proper families" in who turned up.
INPUT.
First line of input contains a number T denoting the number of test cases.T test cases follow.
In each test case, the first line contains the number(P) of total number of people coming for the party and the number (M) denoting the number of "valid" numbers.
The 2nd line contains M numbers, the set N ,containing all distinct "valid" numbers separated with spaces.
The 3rd line contains P numbers, the "special" number of the members separated with spaces.
OUTPUT.
Output a single line for each of the test cases that denotes the number of "proper families" who turned up for the party.
CONSTRAINTS:
1 ≤ T ≤ 5
1 ≤ P,N,M ≤ 1000
SAMPLE INPUT
2
8 3
1 2 8
2 2 2 3 4 4 4 4
10 3
2 4 6
2 9 9 9 19 19 19 19 19 20
SAMPLE OUTPUT
2
0
Explanation
In the first case:
Clearly, The families with 1,2,3,8,9,10 and 11 members are allowed in the party.
The family with "Special" number 2 has 3 members in it which is allowed.Same for the family with "special" number 3.
But for the family with "special" number 4 has 4 members, which is not allowed.
So the total number of "proper" families = 2.
|
from collections import Counter as C
t=int(raw_input())
def positiveSubsetSum( A, x ):
# preliminary
if x < 0 or x > sum( A ): # T = sum(A)
return 0
# algorithm
sub_sum = [0] * ( x + 1 )
sub_sum[0] = 1
p = 0
while not sub_sum[x] and p < len( A ):
a = A[p]
q = x
while not sub_sum[x] and q >= a:
if not sub_sum[q] and sub_sum[q - a]:
sub_sum[q] = 1
q -= 1
p += 1
return sub_sum[x]
for x in xrange(t):
p,m = map(int,raw_input().split())
n = map(int,raw_input().split())
m = C(map(int,raw_input().split()))
count = 0
for k in m:
count += positiveSubsetSum(n,m[k])
print count
|
Little Jhool is a world renowned kangaroo trainer. He's now living in Australia, and is training kangaroos for his research project on mobile soccer. (We don't know the connection, too.) Anyway, for the project to be completed he observes kangaroos for a lot of time - because he wants to figure out the hop count for various kangaroos he's training.
Now, he makes a kangaroo stand at the starting point, and lets him jump to the finishing point - given the hop count
of that particular kangaroo, figure out the number of jumps he would take between the starting point to the ending point. Both the starting point and the ending points are inclusive.
Note: He will jump only to those positions which are multiples of M or hop count.
Input:
First line contains number of test cases T. Next T lines contains three integers A, B and M separated by single space. A denoted the starting point, B the finishing point - and M, the hop count - the distance covered by that kangaroo in one jump.
Output:
For each test case print the number of jumps the kangaroo had to make in the range [A, B] inclusive.
Constraints:
1 ≤ T ≤ 100000
1 ≤ A ≤ B ≤ 10^12
1 ≤ M ≤ 10^12
SAMPLE INPUT
3
1 10 2
5 10 3
7 9 5SAMPLE OUTPUT
5
2
0
Explanation
Test Case #1:
There are 5 multiples of 2 that are {2,4,6,8,10} in range [1,10] .
Test Case#2:
There are 2 multiples of 3 that are {6,9} in range [5,10] .
Test Case#3:
There are no any multiple of 5 is there in range [7,9].
|
'''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
count = int(raw_input())
for i in range(count):
val = map(int, raw_input().split(" "))
B = val[1]
A = val[0]
M = val[2]
print (B/M)-(A-1)/M
|
Deepak like strings which are in flip flop in nature. For example, he likes XYXYX, while he doesn't like XXYX. Now he want to convert every string into a string which he likes. for this, he only delete the character in the string.
Now find the minimum number of delete operation which is required to covert a string that deepak likes.
Input Format :
The first line contains an integer N i.e the number of test cases.
Next N lines contain a string each.
Output Format :
For each test case, print the minimum delete operation required.
Constraints :
1 ≤ N ≤ 10
1 ≤ length of String ≤ 10^5
SAMPLE INPUT
5
XXXX
YYYYY
XYXYXYXY
YXYXYX
XXXYYY
SAMPLE OUTPUT
3
4
0
0
4
Explanation
XXXX => X, 3 deletions
YYYYY => Y, 4 deletions
XYXYXYXY => XYXYXYXY, 0 deletions
YXYXYXYX => YXYXYXYX, 0 deletions
XXXYYY => XY, 4 deletions
|
n=input()
for nn in range(n):
s=raw_input()
last=s[0]
cnt=0
for c in s[1:]:
if c==last: cnt+=1
last=c
print cnt
|
Jal Mahal Lake is famous tourist place in Jaipur. The lake has floating planks in a straight line. The planks are currently not attached to each other, and there may be gaps between some of them. You have to push them all together and connect them into a single long plank.
You are given the positions and lengths. For each valid i, there is a plank that is lengths[i] meters long and starts positions[i] meters from the beginning of the Tourist site of lake. (In other words, the coordinates currently occupied by this plank are in the interval from positions[i] to positions[i]+lengths[i].)
Moving a single plank one meter in either direction costs one unit of energy. Compute the smallest total amount of energy sufficient to push all planks together. In the final configuration the planks must be located one after another with no gaps between them.
(Note that there is no restriction on the movement of planks or on the final position of the single long plank. You may push the cars in any order, and he may even push some planks by a non-integer number of meters if he wants to.)
Input :
First line of input contains number of test cases T
Each test case contains three lines of input containing space separated integers.
First line of each test case, contains an integer N, denoting number of planks.
Next line contains N space separated integers, which is the position of N planks on x co-ordinate.
Next line contains again N separated integers denoting the lengths of the N planks.
Output :
Print the minimum energy required on a line for each test case.
Constraints :
1 ≤ T ≤ 10
2 ≤ Total Number of Planks ≤ 50
1 ≤ Length[i], Position[i] ≤ 10^9
Planks cannot overlap each other
SAMPLE INPUT
2
4
1 3 10 20
2 2 5 3
3
100 50 1
10 2 1
SAMPLE OUTPUT
15
96
Explanation
Test Case #1:
There are four planks. The intervals currently occupied by the planks are (1,3), (3,5), (10,15), and (20,23). In one optimal solution you would move each of the first two planks three meters to the right, the third plank two meters to the left, and the fourth plank seven meters to the left. At the end, the planks occupy the intervals (4,6), (6,8), (8,13), and (13,16). Total energy spent: 3+3+2+7 = 15.
Test Case #2;
There are three planks. The gaps between consecutive planks have 48 meters each. The best solution is to keep the middle plank in place and to push the other two towards it. This requires 48+48 = 96 units of energy.
|
for _ in xrange(input()):
n=input()
pos=map(int,raw_input().split())
sz=map(int,raw_input().split())
a=[]
for i in xrange(n):
a.append([pos[i],sz[i]])
a.sort()
tmp=a[0][0]+a[0][1]
ans=0
for i in xrange(1,n):
ans+=a[i][0]-tmp
tmp+=a[i][1]
for z in xrange(1,n):
t=0
tmp=a[z][0]+a[z][1]
for i in xrange(z+1,n):
t+=a[i][0]-tmp
tmp+=a[i][1]
tmp=a[z][0]
for i in xrange(z-1,-1,-1):
t+=tmp-(a[i][0]+a[i][1])
tmp-=a[i][1]
ans=min(ans,t)
print ans
|
Micro is a big fan of the famous competitive programmer Gennady Korotkevich, known by his handle tourist. He wants to be like him. He has been practising hard but is not reaching anywhere. So he has left his fate to one game he has, called MinMax. The game consists of an array A of N integers. If the difference between the maximum and minimum values of the array A is odd, then it prints a slip with string "Yes" written on it, otherwise it prints a slip with string "No" written on it. Now Micro decided if the output is "Yes", then one day he will surely be as good as tourist and will keep practicing otherwise he will quit. Now help Micro find the output of the game.
Input:
First line of input consists of a single integer, T denoting the number of test cases.
First line of each test case consists of a single integer denoting N.
Second line of each test case consists of N space separated integers denoting the elements of the array.
Output:
For each test case print "Yes" (without quotes), if the game's output is going to be "Yes", otherwise print "No" (without quotes). Print a new line after each test case.
Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 2 \times 10^5
1 ≤ A[i] ≤ 2 \times 10^7
SAMPLE INPUT
1
5
1 2 3 4 5
SAMPLE OUTPUT
No
|
t=input()
while t>0:
t=t-1
o=input()
n=map(int ,raw_input().split())
if (max(n)-min(n))%2==0:
print 'No'
else:
print 'Yes'
|
A:It is a natural number greater than 1 that has no positive divisors other than 1 and itself.
B: It is a number that remains the same when its digits are reversed. It is "symmetrical".
Patrik lives in Palestine. He loves everything starting with P and so numbers also. His friend gave him a number X and asked him to find smallest integer say Y where, Y ≥ X such that Y is a A and B type number. You task is to Help Patrik to find required number Y every time.
Input format:
First line of input contains an integer t, which is the number of test cases. t lines follow, with each test containing an integer X.
Output format:
For each test case output a single line number Y which is of type A and B both.
Constraints:
1 ≤ X ≤ 1000000
1 ≤ t ≤ 100
NOTE:
A and B are a type of number. Read definition statement properly if you are not getting.
SAMPLE INPUT
3
42
108
250
SAMPLE OUTPUT
101
131
313
Explanation
101 is the smallest number prime number which is palindrome also after 42.
Similarly all the cases have respective output on provided input.
|
p=[1 , 1 , 2 , 3 , 5 , 7 , 11 , 101 , 131 , 151 , 181 , 191 , 313 , 353 , 373 , 383 , 727 , 757 , 787 , 797 , 919 , 929 , 10301 , 10501 , 10601 , 11311 , 11411 , 12421 , 12721 , 12821 , 13331 , 13831 , 13931 , 14341 , 14741 , 15451 , 15551 , 16061 , 16361 , 16561 , 16661 , 17471 , 17971 , 18181 , 18481 , 19391 , 19891 , 19991 , 30103 , 30203 , 30403 , 30703 , 30803 , 31013 , 31513 , 32323 , 32423 , 33533 , 34543 , 34843 , 35053 , 35153 , 35353 , 35753 , 36263 , 36563 , 37273 , 37573 , 38083 , 38183 , 38783 , 39293 , 70207 , 70507 , 70607 , 71317 , 71917 , 72227 , 72727 , 73037 , 73237 , 73637 , 74047 , 74747 , 75557 , 76367 , 76667 , 77377 , 77477 , 77977 , 78487 , 78787 , 78887 , 79397 , 79697 , 79997 , 90709 , 91019 , 93139 , 93239 , 93739 , 94049 , 94349 , 94649 , 94849 , 94949 , 95959 , 96269 , 96469 , 96769 , 97379 , 97579 , 97879 , 98389 , 98689 , 1003001]
for _ in xrange(input()):
n=input()
for i in p:
if i>=n:
break
print i
|
Little Bear has received a home assignment to find the sum of all digits in a number N. Following his affinity towards single digit number, he intends to repeatedly compute the sum of all digits until the sum itself becomes a single digit number.
Can you write a program to compute the final single-digit sum?
As the number N is very big, it is given in the following run length encoded format - N is represented as a sequence of M blocks, where each block i (0 ≤ i < M) is represented by two integers - (len[i], d[i]). This implies that the digit d[i] occurs len[i] number of times.
For example, {(2,1), (1,2), (2,9)} represents the number 11299.
Input:
The first line contains a single integer T, denoting the number of test cases.
Each test case starts with a single integer M, which is the number of following run-length encoded blocks.
Each of the next M lines contains two space separated integers: len[i] and d[i].
Output:
Print the single-digit sum for each of the T test cases in a new line.
Constraints:
0 ≤ d[i] ≤ 9
1 ≤ len[i] ≤ 10^15
1 ≤ M ≤ 10^4
1 ≤ T ≤ 10
SAMPLE INPUT
3
3
2 1
1 2
2 9
1
8 1
3
2 5
1 4
1 5
SAMPLE OUTPUT
4
8
1
Explanation
Case 1:
The number is 11299.
We shall calculate the desired sum as: 1+1+2+9+9=2+2=4
Case 2:
The number is 11111111.
We shall calculate the desired sum as: 1+1+1+1+1+1+1+1=8
Case 3:
The number is 5545.
We shall calculate the desired sum as: 5+5+4+5=1+9=1+0=1
|
__author__ = 'pjha'
def main():
N=input()
for i in range(0,N):
M=input()
sum=0
for j in range(0,M):
a=map(int,raw_input().split())
sum=sum+a[1]*a[0]
while(sum>9):
fsum=0
while(sum>0):
fsum=fsum+sum%10
sum=sum/10
sum=fsum
print sum
if __name__ == '__main__':
main()
|
DM of Bareilly wants to make Bareilly a smart city. So, one point amongst his management points is to arrange shops. He starts by arranging the bakery shops linearly, each at a unit distance apart and assigns them a number depending on its owner.
Momu loves pastries of shops with same number so he wants to find the minimum distance between the shops with the same number.
Given n bakery shops, you have to find the minimum distance between two shops such that the number of shop is same.
NOTE : The shop numbers should not be more than one digit, i.e. <10
See below testcase for more understanding.
Input:
First line contains t test cases
Each test case contains an integer n denoting no of shops
Next line contains n shops, each assigned a number
Output:
Minimum distance between them. If no two shops exists with the same number print -1.
TEST CASE :
Input :
3
5
12345
5
12321
7
1234514
Output :
-1
2
3
Explaination :
Input 1) -1 as no two of same number.
Input 2) two such pair 1 1 and 2 2 and distance between them is 5 and 2 respectively so 2 is the output
Input 3) two such pair 1 1 and 4 4 and distance between them is 6 and 3 respectively so 3 is the output
SAMPLE INPUT
10
1
1
2
11
3
121
4
1231
5
12321
6
123421
7
1234321
8
12345321
9
123454321
10
1234565321
SAMPLE OUTPUT
-1
1
2
3
2
3
2
3
2
2
|
noOfTestCases = int(raw_input())
def minDistance(n):
structureCount = {}
curIndex = 0
for digit in n:
if(structureCount.has_key(digit) == False):
structureCount[digit] = [curIndex,-1]
else:
newDistance = curIndex - structureCount[digit][0]
if(structureCount[digit][1] == -1 or newDistance < structureCount[digit][1]):
structureCount[digit] = [curIndex,newDistance]
else:
structureCount[digit][0] = curIndex
curIndex += 1
distances = []
for key,value in structureCount.items():
if(value[1] != -1):
distances.append(value[1])
if(len(distances) == 0):
return -1
else:
return min(distances)
for caseNo in range(1, noOfTestCases + 1):
count = int(raw_input())
print minDistance(raw_input())
|
Singh is getting bored at work. He has a lot of ideas (N) to work on (as side projects) but is unable to choose one.
He chooses a random number (R) and lines up his ideas in a circle. He starts counting from first and removes the R^th idea in the circle until only one remains. Help him choose an idea to work on.
Input Format:
no_of_ideas random_number
Output Format:
idea_number
Constraints:
1 ≤ N ≤ 20
1 ≤ R ≤ 10000000
SAMPLE INPUT
5 3
SAMPLE OUTPUT
4
Explanation
List: {1,2,3,4,5}. Start counting from 1,
1 2 3 -> 3 removed
4 5 1 -> 1 removed
2 4 5 -> 5 removed
2 4 2 -> 2 removed
Remaining number: 4
|
n, k = list(map(int, raw_input().strip().split()))
l = [i for i in range(n)]
ind = 0
while len(l) != 1:
ind = ( ind + k - 1 ) % len(l)
l = l[0:ind] + l[ind+1:]
print(l[0]+1)
|
You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353.
Constraints
* 1 \leq N, M \leq 524288
* 0 \leq a_i, b_i < 998244353
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N M
a_0 a_1 ... a_{N-1}
b_0 b_1 ... b_{M-1}
Output
Print the answer in the following format:
c_0 c_1 ... c_{(N - 1) + (M - 1)}
Output
Print the answer in the following format:
c_0 c_1 ... c_{(N - 1) + (M - 1)}
Examples
Input
4 5
1 2 3 4
5 6 7 8 9
Output
5 16 34 60 70 70 59 36
Input
1 1
10000000
10000000
Output
871938225
|
#Convolution_998244353
MOD = 998244353
ROOT = 3
sum_e = (911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601, 842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 0, 0, 0, 0, 0, 0, 0, 0, 0)
sum_ie = (86583718, 372528824, 373294451, 645684063, 112220581, 692852209, 155456985, 797128860, 90816748, 860285882, 927414960, 354738543, 109331171, 293255632, 535113200, 308540755, 121186627, 608385704, 438932459, 359477183, 824071951, 0, 0, 0, 0, 0, 0, 0, 0, 0)
def butterfly(arr):
n = len(arr)
h = (n - 1).bit_length()
for ph in range(1, h + 1):
w = 1 << (ph - 1)
p = 1 << (h - ph)
now = 1
for s in range(w):
offset = s << (h - ph + 1)
for i in range(p):
l = arr[i + offset]
r = arr[i + offset + p] * now
arr[i + offset] = (l + r) % MOD
arr[i + offset + p] = (l - r) % MOD
now *= sum_e[(~s & -~s).bit_length() - 1]
now %= MOD
def butterfly_inv(arr):
n = len(arr)
h = (n - 1).bit_length()
for ph in range(1, h + 1)[::-1]:
w = 1 << (ph - 1)
p = 1 << (h - ph)
inow = 1
for s in range(w):
offset = s << (h - ph + 1)
for i in range(p):
l = arr[i + offset]
r = arr[i + offset + p]
arr[i + offset] = (l + r) % MOD
arr[i + offset + p] = (MOD + l - r) * inow % MOD
inow *= sum_ie[(~s & -~s).bit_length() - 1]
inow %= MOD
def convolution(a, b):
n = len(a)
m = len(b)
if not n or not m: return []
if min(n, m) <= 50:
if n < m:
n, m = m, n
a, b = b, a
res = [0] * (n + m - 1)
for i in range(n):
for j in range(m):
res[i + j] += a[i] * b[j]
res[i + j] %= MOD
return res
z = 1 << (n + m - 2).bit_length()
a += [0] * (z - n)
b += [0] * (z - m)
butterfly(a)
butterfly(b)
for i in range(z):
a[i] *= b[i]
a[i] %= MOD
butterfly_inv(a)
a = a[:n + m - 1]
iz = pow(z, MOD - 2, MOD)
for i in range(n + m - 1):
a[i] *= iz
a[i] %= MOD
return a
def autocorrelation(a):
n = len(a)
if not n: return []
if n <= 50:
res = [0] * (2 * n - 1)
for i in range(n):
for j in range(n):
res[i + j] += a[i] * a[j]
res[i + j] %= MOD
return res
z = 1 << (2 * n - 2).bit_length()
a += [0] * (z - n)
butterfly(a)
for i in range(a):
a[i] *= a[i]
a[i] %= MOD
butterfly_inv(a)
a = a[:2 * n - 1]
iz = pow(z, MOD - 2, MOD)
for i in range(2 * n - 1):
a[i] *= iz
a[i] %= MOD
return a
N, M = map(int, input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
print(*convolution(A, B))
|
Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.
The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)
Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?
Constraints
* 101 \le X \le 10^{18}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X
Output
Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.
Examples
Input
103
Output
3
Input
1000000000000000000
Output
3760
Input
1333333333
Output
1706
|
#include <iostream>
int main()
{
unsigned long long N=100, X;
std::cin >> X;
int i=0;
while (N < X) {
N *= 1.01;
i++;
}
std::cout << i;
}
|
2N players are running a competitive table tennis training on N tables numbered from 1 to N.
The training consists of rounds. In each round, the players form N pairs, one pair per table. In each pair, competitors play a match against each other. As a result, one of them wins and the other one loses.
The winner of the match on table X plays on table X-1 in the next round, except for the winner of the match on table 1 who stays at table 1.
Similarly, the loser of the match on table X plays on table X+1 in the next round, except for the loser of the match on table N who stays at table N.
Two friends are playing their first round matches on distinct tables A and B. Let's assume that the friends are strong enough to win or lose any match at will. What is the smallest number of rounds after which the friends can get to play a match against each other?
Constraints
* 2 \leq N \leq 10^{18}
* 1 \leq A < B \leq N
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print the smallest number of rounds after which the friends can get to play a match against each other.
Examples
Input
5 2 4
Output
1
Input
5 2 3
Output
2
|
N,A,B=map(int,input().split())
if (A+B)%2==0:
ans=(B-A)//2
else:
ans=min(A-1,N-B)+1+(B-A-1)//2
print(ans)
|
There are N+1 towns. The i-th town is being attacked by A_i monsters.
We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.
What is the maximum total number of monsters the heroes can cooperate to defeat?
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* 1 \leq B_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N
Output
Print the maximum total number of monsters the heroes can defeat.
Examples
Input
2
3 5 2
4 5
Output
9
Input
3
5 6 3 8
5 100 8
Output
22
Input
2
100 1 1
1 100
Output
3
|
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
const int INF = pow(10, 7);
int main(){
int n;cin>>n;
ll ans=0;
vector<int> a(n+1);
for(int i=0;i<=n;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
int b, d;cin>>b;
d=min(a[i], b);
ans+=d;a[i]-= d;b -= d;
d=min(a[i+1], b);
ans+=d;a[i+1]-=d;
}
cout<<ans<<endl;
}
|
You are given a string S of length N. Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.
Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.
Constraints
* 1 \leq N \leq 100000
* S consists of lowercase English letters.
* |S|=N
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the number of the subsequences such that all characters are different, modulo 10^9+7.
Examples
Input
4
abcd
Output
15
Input
3
baa
Output
5
Input
5
abcab
Output
17
|
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const ll mod = 1e9 + 7;
int main()
{
int n; string s; cin >> n >> s;
map<char, int> mp; for(auto i : s)mp[i]++;
ll res = 1;
for(auto i : mp) {
res *= (1 + i.second);
res %= mod;
}
cout << ((res - 1) + mod ) % mod<< endl;
}
|
You are given integers N and M.
Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* N \leq M \leq 10^9
Input
Input is given from Standard Input in the following format:
N M
Output
Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.
Examples
Input
3 14
Output
2
Input
10 123
Output
3
Input
100000 1000000000
Output
10000
|
import itertools
import math
import copy
N,M=map(int, raw_input().split())
M2=copy.deepcopy(M)
A={}
a=int( math.sqrt(M) )+2
for i in range(2,a):
while M%i==0:
if i not in A:
A[i]=1
else:
A[i]+=1
M/=i
else:
A[M]=1
B=[]
for x in A.values():
B.append( range(x+1) )
L=list(itertools.product(*B))
Y=[] #Yakusu
for x in L:
t=1
for i,j in zip(A,x):
t*=i**j
Y.append(t)
ans=0
for cd in Y: #cd: Common Divivor(yakusu)
if M2/cd>=N:
ans=max(ans,cd)
print ans
|
Nagase is a top student in high school. One day, she's analyzing some properties of special sets of positive integers.
She thinks that a set S = \\{a_{1}, a_{2}, ..., a_{N}\\} of distinct positive integers is called special if for all 1 \leq i \leq N, the gcd (greatest common divisor) of a_{i} and the sum of the remaining elements of S is not 1.
Nagase wants to find a special set of size N. However, this task is too easy, so she decided to ramp up the difficulty. Nagase challenges you to find a special set of size N such that the gcd of all elements are 1 and the elements of the set does not exceed 30000.
Constraints
* 3 \leq N \leq 20000
Input
Input is given from Standard Input in the following format:
N
Output
Output N space-separated integers, denoting the elements of the set S. S must satisfy the following conditions :
* The elements must be distinct positive integers not exceeding 30000.
* The gcd of all elements of S is 1, i.e. there does not exist an integer d > 1 that divides all elements of S.
* S is a special set.
If there are multiple solutions, you may output any of them. The elements of S may be printed in any order. It is guaranteed that at least one solution exist under the given contraints.
Examples
Input
3
Output
2 5 63
Input
4
Output
2 5 20 63
|
N=input()
if N==3:
print "2 5 63"
quit()
elif N==4:
print "2 5 20 63"
quit()
#N>=5
#For 2 and 3
S=[2,3,4]
N-=3
x=N/4 # N=4x+b
b=N%4
for i in range(1,x+1):
S.append(6*i)
S.append(6*i+2)
S.append(6*i+3)
S.append(6*i+4)
if x%2==0:
if b==0:
S.remove(6*x+3)
S.append(6*x+6)
elif b==1:
S.append(6*(x+1)+3)
elif b==2:
S.append(6*(x+1))
S.append(6*(x+1)+3)
elif b==3:
S.append(6*(x+1))
S.append(6*(x+1)+3)
S.append(6*(x+1)+6)
else:
if b==0:
pass
elif b==1:
S.append(6*(x+1))
elif b==2:
S.append(6*(x+1)+2)
S.append(6*(x+1)+4)
elif b==3:
S.append(6*(x+1))
S.append(6*(x+1)+2)
S.append(6*(x+1)+4)
for i in S:
print i,
|
Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.
Constraints
* 2 \leq K \leq 10^5
* K is an integer.
Input
Input is given from Standard Input in the following format:
K
Output
Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.
Examples
Input
6
Output
3
Input
41
Output
5
Input
79992
Output
36
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int K = in.nextInt();
MinHeap minHeap = new MinHeap(K);
int[] td = new int[K];
ArrayUtils.fill(td, 99999999);
for (int i = 9; i >= 1; --i) {
minHeap.add(i % K, i);
td[i % K] = i;
}
while (minHeap.size() > 0) {
int cur = minHeap.argmin();
minHeap.remove(cur);
for (int k = 0; k < 10; ++k) {
int next = (cur * 10 + k) % K;
int nd = td[cur] + k;
if (nd < td[next]) {
td[next] = nd;
minHeap.update(next, nd);
}
}
}
out.println(td[0]);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class MinHeap {
public int[] a;
public int[] map;
public int[] imap;
public int n;
public int pos;
public static int INF = Integer.MAX_VALUE;
public MinHeap(int m) {
n = m + 2;
a = new int[n];
map = new int[n];
imap = new int[n];
Arrays.fill(a, INF);
Arrays.fill(map, -1);
Arrays.fill(imap, -1);
pos = 1;
}
public int add(int ind, int x) {
int ret = imap[ind];
if (imap[ind] < 0) {
a[pos] = x;
map[pos] = ind;
imap[ind] = pos;
pos++;
up(pos - 1);
}
return ret != -1 ? a[ret] : x;
}
public int update(int ind, int x) {
int ret = imap[ind];
if (imap[ind] < 0) {
a[pos] = x;
map[pos] = ind;
imap[ind] = pos;
pos++;
up(pos - 1);
} else {
int o = a[ret];
a[ret] = x;
up(ret);
down(ret);
// if(a[ret] > o){
// up(ret);
// }else{
// down(ret);
// }
}
return x;
}
public int remove(int ind) {
if (pos == 1) return INF;
if (imap[ind] == -1) return INF;
pos--;
int rem = imap[ind];
int ret = a[rem];
map[rem] = map[pos];
imap[map[pos]] = rem;
imap[ind] = -1;
a[rem] = a[pos];
a[pos] = INF;
map[pos] = -1;
up(rem);
down(rem);
return ret;
}
public int argmin() {
return map[1];
}
public int size() {
return pos - 1;
}
private void up(int cur) {
for (int c = cur, p = c >>> 1; p >= 1 && a[p] > a[c]; c >>>= 1, p >>>= 1) {
int d = a[p];
a[p] = a[c];
a[c] = d;
int e = imap[map[p]];
imap[map[p]] = imap[map[c]];
imap[map[c]] = e;
e = map[p];
map[p] = map[c];
map[c] = e;
}
}
private void down(int cur) {
for (int c = cur; 2 * c < pos; ) {
int b = a[2 * c] < a[2 * c + 1] ? 2 * c : 2 * c + 1;
if (a[b] < a[c]) {
int d = a[c];
a[c] = a[b];
a[b] = d;
int e = imap[map[c]];
imap[map[c]] = imap[map[b]];
imap[map[b]] = e;
e = map[c];
map[c] = map[b];
map[b] = e;
c = b;
} else {
break;
}
}
}
}
static class ArrayUtils {
public static void fill(int[] array, int value) {
Arrays.fill(array, value);
}
}
}
|
You are given a image with a height of H pixels and a width of W pixels. Each pixel is represented by a lowercase English letter. The pixel at the i-th row from the top and j-th column from the left is a_{ij}.
Put a box around this image and output the result. The box should consist of `#` and have a thickness of 1.
Constraints
* 1 ≤ H, W ≤ 100
* a_{ij} is a lowercase English letter.
Input
Input is given from Standard Input in the following format:
H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}
Output
Print the image surrounded by a box that consists of `#` and has a thickness of 1.
Examples
Input
2 3
abc
arc
Output
#####
#abc#
#arc#
#####
Input
1 1
z
Output
z#
|
#include <stdio.h>
int main(void) {
int i, j, h, w;
scanf("%d%d", &h, &w);
char s[w + 10];
for(i = 0; i < w + 2; ++i) printf("#");
printf("\n");
for(i = 0; i < h; ++i) {
scanf("%s", s);
printf("#%s#\n", s);
}
for(i = 0; i < w + 2; ++i) printf("#");
return 0;
}
|
There are two (6-sided) dice: a red die and a blue die. When a red die is rolled, it shows i with probability p_i percents, and when a blue die is rolled, it shows j with probability q_j percents.
Petr and tourist are playing the following game. Both players know the probabilistic distributions of the two dice. First, Petr chooses a die in his will (without showing it to tourist), rolls it, and tells tourist the number it shows. Then, tourist guesses the color of the chosen die. If he guesses the color correctly, tourist wins. Otherwise Petr wins.
If both players play optimally, what is the probability that tourist wins the game?
Constraints
* 0 ≤ p_i, q_i ≤ 100
* p_1 + ... + p_6 = q_1 + ... + q_6 = 100
* All values in the input are integers.
Input
The input is given from Standard Input in the following format:
p_1 p_2 p_3 p_4 p_5 p_6
q_1 q_2 q_3 q_4 q_5 q_6
Output
Print the probability that tourist wins. The absolute error or the relative error must be at most 10^{-9}.
Examples
Input
25 25 25 25 0 0
0 0 0 0 50 50
Output
1.000000000000
Input
10 20 20 10 20 20
20 20 20 10 10 20
Output
0.550000000000
|
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
double p[6];
double q[6];
double ans = 1.0;
void test(double prob){
double cur = 0;
for(int i = 0; i < 6; i++){
cur += max(prob*p[i],(1.0-prob)*q[i]);
}
ans = min(ans,cur);
}
int main(){
for(int i = 0; i < 6; i++) cin >> p[i];
for(int i = 0; i < 6; i++) cin >> q[i];
for(int i = 0; i < 6; i++) p[i] /= 100.0;
for(int i = 0; i < 6; i++) q[i] /= 100.0;
test(0);
test(1);
for(int i = 0; i < 6; i++){
if(p[i] + q[i] < 0.00000001) continue;
test((p[i])/(p[i]+q[i]));
test((q[i])/(p[i]+q[i]));
}
printf("%.10lf\n", ans);
}
|
We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.
Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.
Find the number of boxes that may contain the red ball after all operations are performed.
Constraints
* 2≤N≤10^5
* 1≤M≤10^5
* 1≤x_i,y_i≤N
* x_i≠y_i
* Just before the i-th operation is performed, box x_i contains at least 1 ball.
Input
The input is given from Standard Input in the following format:
N M
x_1 y_1
:
x_M y_M
Output
Print the number of boxes that may contain the red ball after all operations are performed.
Examples
Input
3 2
1 2
2 3
Output
2
Input
3 3
1 2
2 3
2 3
Output
1
Input
4 4
1 2
2 3
4 1
3 4
Output
3
|
n,m=map(int,input().split())
cnt=[1]*n
res=[0]*n
res[0]=1
for i in range(m):
x,y=map(int,input().split())
if res[x-1]==1:
res[y-1]=1
if cnt[x-1]==1:
res[x-1]=0
cnt[x-1]-=1
cnt[y-1]+=1
print(sum(res))
|
There are a total of W x H squares, with H rows vertically and W columns horizontally. Some squares are marked. Create a program that reads the marked state of each square and outputs the maximum rectangular area consisting of only the unmarked squares.
The input data consists of one line of W characters, given H lines. For example, the following data is given.
.. *.... **.
..........
** .... ***.
.... * .....
.. * .......
... ** .....
. *. * ......
..........
.. **......
. * .. * .....
One line of input data represents the square of one line. Of the character strings in the input data,. (Period) indicates unmarked squares, and * (asterisk) indicates marked squares. The input data string does not contain any characters other than periods, asterisks, and line breaks.
In the above example, the rectangle indicated by 0 in the figure below is the largest.
.. *.... **.
..........
** .... ***.
.... * 00000
.. * ..00000
... ** 00000
. *. *. 00000
..... 00000
.. **. 00000
. * .. * 00000
Therefore, if you output 35, the answer will be correct. If all the squares are marked, output 0.
Input
Given multiple datasets. Each dataset starts with a line of H and W separated by spaces, followed by an H x W rectangle. Both H and W shall be 500 or less.
The input ends with a line containing two 0s. The number of datasets does not exceed 20.
Output
For each dataset, output the area of the largest rectangle on one line.
Example
Input
10 10
...*....**
..........
**....**..
........*.
..*.......
**........
.*........
..........
....*..***
.*....*...
10 10
..*....*..
.*.*...*..
*****..*..
*...*..*..
*...*..*..
..........
****.*...*
..*..*...*
.*...*...*
****..***.
2 3
...
...
0 0
Output
28
12
6
|
import java.util.*;
public class Main {
public static void main(String[] args) {
new Main().run();
}
String table[];
void run() {
Scanner sc = new Scanner(System.in);
for (;;) {
int R = sc.nextInt();
int C = sc.nextInt();
if (R == 0 && C == 0)
break;
table = new String[R];
for (int r = 0; r < R; r++) {
table[r] = sc.next();
}
System.out.println(solve(R, C));
}
}
int LargestRect(int a[]) {
int best = 0;
Stack<Integer> pos = new Stack<Integer>();
Stack<Integer> height = new Stack<Integer>();
pos.add(-1);
height.add(-1);
for (int i = 0; i < a.length; i++) {
if (height.peek() <= a[i]) {
pos.add(i);
height.add(a[i]);
} else {
int last_pos = -1;
while (height.peek() > a[i]) {
best = Math.max(best, (height.peek()) * (i - pos.peek()));
height.pop();
last_pos = pos.pop();
}
pos.add(last_pos);
height.add(a[i]);
}
}
return best;
}
int solve(int R, int C) {
int temp[][] = new int[R][C];
for (int c = 0; c < C; c++) {
int len = 0;
for (int r = 0; r < R; r++) {
if (table[r].charAt(c) == '.')
len++;
else
len = 0;
temp[r][c] = len;
}
}
int a[] = new int[C + 1];
a[C] = -1;
int res = 0;
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++)
a[c] = temp[r][c];
res = Math.max(res, LargestRect(a));
}
return res;
}
}
|
Gaku decided to observe the ant's nest as a free study during the summer vacation. The transparent observation case that his grandpa prepared for his grandchildren is very unique and looks like Figure 1.
Ant nest
Figure 1
This case consists of two congruent convex polygons s1 and s2 and some rectangles. Place one of the rectangular faces other than s1 and s2 so that it touches the floor. Gogo, who started observing, noticed that the height of the soil changed depending on how the bottom was selected, even though the amount of soil contained was the same (Fig. 2).
Ant nest
Figure 2
Gogo wanted to know how high it would be depending on how the case was placed. Create a program that outputs the maximum value of the soil height by inputting the shape of the convex polygon s1, the distance d between s1 and s2, and the volume V of the soil. The soil shall level as soon as the bottom of the case is placed on the floor. The s1 shape of the transparent case is given by n vertices on the two-dimensional coordinate plane. These vertices are entered in a counterclockwise order. n is 3 or more and 100 or less, and d and V are integers of 1 or more and 10,000 or less, respectively. In addition, x and y of the coordinates (x, y) of the vertices of the polygon shall be integers of -1,000 or more and 1,000 or less, respectively. V does not exceed the volume of the case.
input
A sequence of multiple datasets is given as input. The end of the input is indicated by three zero lines. Each dataset is as follows.
1st line n d V (integer integer integer; half-width space delimited)
Coordinates of the first vertex on the second line x y (integer integer; half-width space delimited)
Coordinates of the second vertex on the third line
::
n + 1 Coordinates of the nth vertex on the 1st line
The number of datasets does not exceed 20.
output
Outputs the maximum soil height for each input dataset. The answer must not have an error greater than 0.00001.
Example
Input
4 1 1
0 0
1 0
1 2
0 2
0 0 0
Output
1.000000
|
#include<iostream>
#include<vector>
#include<complex>
#include<algorithm>
using namespace std;
typedef double R;
typedef complex<R> P;
typedef vector<P> G;
#define REP(i, n) for(int i=0;i<(int)n;i++)
#define RREP(i, n) for(int i=(int)(n)-1;i>=0;i--)
#define X real()
#define Y imag()
const R EPS = 1e-8;
const R INF = 1e8;
inline int sig(const R &x){return abs(x)<EPS ? 0 : x > 0 ? 1 : -1;}
inline R inp(const P &a, const P &b){return (conj(a)*b).X;}
inline R outp(const P &a, const P &b){return (conj(a)*b).Y;}
inline int ccw(const P &s, const P &t, const P &p){return sig(outp(t-s, p-s));}
inline P crosspoint(const P &p1, const P &p2, const P &q1, const P &q2){
R A = outp(p2-p1, q2-q1), B = outp(p2-p1, p2-q1);
if(!sig(A) && !sig(B)) return q1;
return q1 + B/A * (q2 - q1);
}
R area(const G &g){
R sum = 0;
REP(i, g.size()) sum += outp(g[i], g[(i+1)%g.size()]);
return abs(sum/2);
}
G cut(const G &g, const P &p1, const P &p2){
G res;
REP(i, g.size()){
if(ccw(p1, p2, g[i]) >= 0) res.push_back(g[i]);
if(ccw(p1, p2, g[i]) * ccw(p1, p2, g[(i+1)%g.size()]) < 0)
res.push_back(crosspoint(g[i], g[(i+1)%g.size()], p1, p2));
}
return res;
}
R calc(const G &g, R a){
R l = 0, r = INF;
REP(itr, 100){
R mid = (l+r)/2;
if(area(cut(g, P(1, mid), P(0, mid))) < a) l = mid;
else r = mid;
}
return r;
}
int n;
R d, V;
int main(){
while(cin >> n >> d >> V, n){
G g;
REP(i, n){
R x, y;
cin >> x >> y;
g.emplace_back(x, y);
}
R ans = 0;
REP(i, n){
RREP(i, n) g[i] -= g[0];
P v = g[1]/abs(g[1]);
RREP(i, n) g[i] /= v;
ans = max(ans, calc(g, V/d));
g.push_back(g[0]); g.erase(g.begin());
}
printf("%.11f\n", ans);
}
return 0;
}
|
There are n sheets of square paper of the same size. Align the bottom of these papers horizontally and arrange them in several rows. However, adjacent rows must be arranged so that the left side is not lower than the right side. For example, n When = 5, the following 7 ways of arranging are possible.
<image>
We will represent these by the number of square columns in each column. For example, when n = 5, each of them will be represented.
(5) (4, 1) (3, 2) (3, 1, 1) (2, 2, 1) (2, 1, 1, 1) (1, 1, 1, 1, 1)
It is expressed as.
When n is input, create a program that outputs all in lexicographic order. n ≤ 30. However, lexicographic order means that two arrangements (a1, a2, ..., as) are arranged (b1, For b2, ..., bt), when a1> b1 or an integer i> 1 exists and a1 = b1, ..., ai-1 = bi-1 and ai> bi holds (a1) , a2, ..., as) are arranged so that they are output before (b1, b2, ..., bt).
The input data consists of one line, with n written on the first line.
In the output, write one line in lexicographic order and insert a line break at the end. The output of (a1, a2, ..., as) is the integer a1, a2, ..., as. Output in this order separated by blanks.
Input example 1
---
Five
Output example 1
Five
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
All data sets are output in lexicographic order.
Example
Input
5
5
0
Output
5
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1
5
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1
|
#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
int a[31];
int f(int n){
if(n){
for(int i=n;i>0;--i){
if(s.empty()||s.top()>=i){
s.push(i);f(n-i);s.pop();
}
}
}
else{
if(!s.empty()){
stack<int> t(s);
int b=t.size();
for(int i=b-1;i>=0;--i){
a[i]=t.top();t.pop();
}
cout<<a[0];
for(int i=1;i<b;++i) cout<<' '<<a[i];
cout<<endl;
}
}
return 0;
}
int main(){
int n;
while(cin>>n,n){
f(n);
}
return 0;
}
|
Taro loves chocolate and when he returns from school he eats his favorite chocolate bar with a heart symbol on it. A recent pleasure is to eat all the heart symbol blocks to the end. Taro , Try to eat as many heartless blocks as possible, with all heartmark blocks connected.
<image>
However, Taro is still young, and even if he tries to eat as above, useless blocks will remain. Therefore, Taro seeks the maximum number of blocks that can be eaten when all the heart-shaped blocks are left connected. I asked you to create a program.
Taro can eat whatever way he wants, as long as all the heart-shaped blocks are connected. If one side of one block does not touch the other block, it will be separated.
Input
The input consists of multiple datasets, each dataset given in the following format:
H W
H x W numbers
H and W are integers indicating the vertical size and horizontal size of the chocolate bar, respectively. H x W numbers represent block information, '0' representing blocks without a heart mark, and blocks with a heart mark. Consists of '1'.
The end of the input is indicated by the dataset where H = W = 0. Do not output for this case.
You can assume that 1 ≤ H, W ≤ 12 and the number of heart-shaped blocks is 6 or less.
Output
For each dataset, output the maximum number of blocks that Taro can eat.
Example
Input
4 4
1 0 0 0
0 0 1 0
0 1 0 0
1 0 0 1
1 1
1
2 3
1 0 0
0 0 1
0 0
Output
7
0
2
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int INF = 1000000000;
int main() {
int H, W;
while(cin >> H >> W, H | W) {
int n = H * W;
vector<vector<int>> A(n, vector<int>(n, INF));
vector<int> heart;
for(int i = 0; i < n; ++i) A[i][i] = 0;
for(int i = 0; i < H; ++i) for(int j = 0; j < W; ++j) {
int h;
cin >> h;
if(h) heart.push_back(i * W + j);
for(bool d: {false, true}) {
int y = i + (d ? 1 : 0);
int x = j + (d ? 0 : 1);
if(y < 0 || H <= y) continue;
if(x < 0 || W <= x) continue;
A[i * W + j][y * W + x] = A[y * W + x][i * W + j] = 1;
}
}
for(int k = 0; k < n; ++k) for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j)
A[i][j] = min(A[i][j], A[i][k] + A[k][j]);
vector<vector<int>> OPT(1 << heart.size(), vector<int>(n, INF));
for(int i = 0; i < heart.size(); ++i) for(int q = 0; q < n; ++q)
OPT[1 << i][q] = A[heart[i]][q];
for(int S = 1; S < (1 << heart.size()); ++S) {
if(!(S & (S - 1))) continue;
for(int p = 0; p < n; ++p) for(int E = 1; E < S; ++E)
if(E | S == S)
OPT[S][p] = min(OPT[S][p], OPT[E][p] + OPT[S ^ E][p]);
for(int p = 0; p < n; ++p) for(int q = 0; q < n; ++q)
OPT[S][p] = min(OPT[S][p], OPT[S][q] + A[q][p]);
}
int answer = INF;
for(int S = 1; S < (1 << heart.size()); ++S) for(int q = 0; q < n; ++q)
answer = min(answer, OPT[S][q] + OPT[((1 << heart.size()) - 1) ^ S][q]);
cout << max(0, n - (answer + 1)) << endl;
}
}
|
Prime Caves
An international expedition discovered abandoned Buddhist cave temples in a giant cliff standing on the middle of a desert. There were many small caves dug into halfway down the vertical cliff, which were aligned on square grids. The archaeologists in the expedition were excited by Buddha's statues in those caves. More excitingly, there were scrolls of Buddhism sutras (holy books) hidden in some of the caves. Those scrolls, which estimated to be written more than thousand years ago, were of immeasurable value.
The leader of the expedition wanted to collect as many scrolls as possible. However, it was not easy to get into the caves as they were located in the middle of the cliff. The only way to enter a cave was to hang you from a helicopter. Once entered and explored a cave, you can climb down to one of the three caves under your cave; i.e., either the cave directly below your cave, the caves one left or right to the cave directly below your cave. This can be repeated for as many times as you want, and then you can descent down to the ground by using a long rope.
So you can explore several caves in one attempt. But which caves you should visit? By examining the results of the preliminary attempts, a mathematician member of the expedition discovered that (1) the caves can be numbered from the central one, spiraling out as shown in Figure D-1; and (2) only those caves with their cave numbers being prime (let's call such caves prime caves), which are circled in the figure, store scrolls. From the next attempt, you would be able to maximize the number of prime caves to explore.
<image>
Figure D-1: Numbering of the caves and the prime caves
Write a program, given the total number of the caves and the cave visited first, that finds the descending route containing the maximum number of prime caves.
Input
The input consists of multiple datasets. Each dataset has an integer m (1 ≤ m ≤ 106) and an integer n (1 ≤ n ≤ m) in one line, separated by a space. m represents the total number of caves. n represents the cave number of the cave from which you will start your exploration. The last dataset is followed by a line with two zeros.
Output
For each dataset, find the path that starts from the cave n and contains the largest number of prime caves, and output the number of the prime caves on the path and the last prime cave number on the path in one line, separated by a space. The cave n, explored first, is included in the caves on the path. If there is more than one such path, output for the path in which the last of the prime caves explored has the largest number among such paths. When there is no such path that explores prime caves, output "`0 0`" (without quotation marks).
Sample Input
49 22
46 37
42 23
945 561
1081 681
1056 452
1042 862
973 677
1000000 1000000
0 0
Output for the Sample Input
0 0
6 43
1 23
20 829
18 947
10 947
13 947
23 947
534 993541
Example
Input
49 22
46 37
42 23
945 561
1081 681
1056 452
1042 862
973 677
1000000 1000000
0 0
Output
0 0
6 43
1 23
20 829
18 947
10 947
13 947
23 947
534 993541
|
import java.util.Arrays;
import java.util.Scanner;
public class Main {
Scanner sc;
int n, m;
int MAX = 1000;
int ofs = MAX / 2;
int[][] dp, cave, pr;
int LIM = 1000000;
int[] tx = new int[] { 1, 0, -1, 0 };
int[] ty = new int[] { 0, -1, 0, 1 };
void run() {
while (true) {
m = ni();
n = ni();
if ( n == 0 && m == 0 )
break;
dp = new int[MAX + 1][MAX + 1];
pr = new int[MAX + 1][MAX + 1];
cave = new int[MAX + 1][MAX + 1];
int x = 0;
int y = 0;
int stx = ofs;
int sty = ofs;
int num = 1;
cave[ ofs ][ ofs ] = 1;
num++;
int t = 0;
while (num <= m) {
int an = t / 2 + 1;
for ( int i = 1; i <= an; i++ ) {
int tmpx = x + tx[ t % 4 ] * i + ofs;
int tmpy = y + ty[ t % 4 ] * i + ofs;
cave[ tmpy ][ tmpx ] = num;
if ( num == n ) {
stx = tmpx;
sty = tmpy;
}
if ( isPrime( num ) ) {
pr[ tmpy ][ tmpx ]++;
// cave[ tmpy ][ tmpx ] *= -1;
}
num++;
if ( num > m ) {
break;
}
}
x += tx[ t % 4 ] * an;
y += ty[ t % 4 ] * an;
t++;
}
// for ( int i = 0; i < cave.length; ++i ) {
// for ( int j = 0; j < cave[ 0 ].length; ++j ) {
// if ( j > 0 ) {
// System.out.print( " " );
// }
// System.out.print( String.format( "%4d", cave[ i ][ j ] ) );
// }
// System.out.println();
// }
int maxc = 0;
int maxn = 0;
dp[ sty ][ stx ] = pr[ sty ][ stx ];
for ( int i = sty; i < MAX; i++ ) {
int d = i - sty;
int start = stx - d;
start = start < 0 ? 0 : start;
int end = stx + d;
end = ( end >= ( MAX + 1 ) ) ? MAX : end;
for ( int j = start; j <= end; j++ ) {
// int dp1 = 0;
// if(j >= 1)dp1 = dp[i-1][j-1];
// int dp2 = dp[i-1][j];
// int dp3 = 0;
// if(j <MAX)dp3 = dp[i-1][j+1];
// dp[i][j] += Math.max( Math.max(dp1, dp2), dp3 );
for ( int l = -1; l <= 1; ++l ) {
if ( j + l < 0 )
continue;
if ( j + l > MAX )
continue;
dp[ i + 1 ][ j + l ] = Math.max( dp[ i + 1 ][ j + l ], dp[ i ][ j ]
+ pr[ i + 1 ][ j + l ] );
if ( maxc < dp[ i ][ j ] ) {
maxc = dp[ i ][ j ];
maxn = cave[ i ][ j ];
} else if ( maxc == dp[ i ][ j ] ) {
if ( maxn < cave[ i ][ j ] && pr[ i ][ j ] == 1 ) {
maxn = cave[ i ][ j ];
}
}
}
}
}
System.out.printf( "%d %d\n", maxc, maxn );
}
}
boolean isPrime(int n) {
if ( n == 2 )
return true;
if ( n % 2 == 0 )
return false;
for ( int i = 3; i * i <= n; i += 2 ) {
if ( n % i == 0 )
return false;
}
return true;
}
Main() {
sc = new Scanner( System.in );
}
int ni() {
return sc.nextInt();
}
public static void main(String[] args) {
new Main().run();
}
void debug(Object... os) {
System.err.println( Arrays.deepToString( os ) );
}
}
|
Mathematical expressions appearing in old papers and old technical articles are printed with typewriter in several lines, where a fixed-width or monospaced font is required to print characters (digits, symbols and spaces). Let us consider the following mathematical expression.
<image>
It is printed in the following four lines:
4 2
( 1 - ---- ) * - 5 + 6
2
3
where "- 5" indicates unary minus followed by 5. We call such an expression of lines "ASCII expression".
For helping those who want to evaluate ASCII expressions obtained through optical character recognition (OCR) from old papers, your job is to write a program that recognizes the structure of ASCII expressions and computes their values.
For the sake of simplicity, you may assume that ASCII expressions are constructed by the following rules. Its syntax is shown in Table H.1.
(1) | Terminal symbols are '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '(', ')', and ' '.
---|---
(2) | Nonterminal symbols are expr, term, factor, powexpr, primary, fraction and digit. The start symbol is expr.
(3) | A "cell" is a rectangular region of characters that corresponds to a terminal or nonterminal symbol (Figure H.1). In the cell, there are no redundant rows and columns that consist only of space characters. A cell corresponding to a terminal symbol consists of a single character. A cell corresponding to a nonterminal symbol contains cell(s) corresponding to its descendant(s) but never partially overlaps others.
(4) | Each cell has a base-line, a top-line, and a bottom-line. The base-lines of child cells of the right-hand side of rules I, II, III, and V should be aligned. Their vertical position defines the base-line position of their left-hand side cell.
Table H.1: Rules for constructing ASCII expressions (similar to Backus-Naur Form) The box indicates the cell of the terminal or nonterminal symbol that corresponds to a rectan- gular region of characters. Note that each syntactically-needed space character is explicitly indicated by the period character denoted by, here.
<image>
(5) | powexpr consists of a primary and an optional digit. The digit is placed one line above the base-line of the primary cell. They are horizontally adjacent to each other. The base-line of a powexpr is that of the primary.
(6) | fraction is indicated by three or more consecutive hyphens called "vinculum". Its dividend expr is placed just above the vinculum, and its divisor expr is placed just beneath it. The number of the hyphens of the vinculum, denoted by wh, is equal to 2 + max(w1, w2), where w1 and w2 indicate the width of the cell of the dividend and that of the divisor, respectively. These cells are centered, where there are ⌈(wh−wk)/2⌉ space characters to the left and ⌊(wh−wk)/2⌋ space characters to the right, (k = 1, 2). The base-line of a fraction is at the position of the vinculum. | (7) | digit consists of one character.
For example, the negative fraction<image> is represented in three lines:
3
- ---
4
where the left-most hyphen means a unary minus operator. One space character is required between the unary minus and the vinculum of the fraction.
The fraction <image> is represented in four lines:
3 + 4 * - 2
-------------
2
- 1 - 2
where the widths of the cells of the dividend and divisor are 11 and 8 respectively. Hence the number of hyphens of the vinculum is 2 + max(11, 8) = 13. The divisor is centered by ⌈(13−8)/2⌉ = 3 space characters (hyphens) to the left and ⌊(13−8)/2⌋ = 2 to the right.
The powexpr (42)3 is represented in two lines:
2 3
( 4 )
where the cell for 2 is placed one line above the base-line of the cell for 4, and the cell for 3 is placed one line above the base-line of the cell for a primary (42).
Input
The input consists of multiple datasets, followed by a line containing a zero. Each dataset has the following format.
n
str1
str2
.
.
.
strn
n is a positive integer, which indicates the number of the following lines with the same length that represent the cell of an ASCII expression. strk is the k-th line of the cell where each space character is replaced with a period.
You may assume that n ≤ 20 and that the length of the lines is no more than 80.
Output
For each dataset, one line containing a non-negative integer less than 2011 should be output. The integer indicates the value of the ASCII expression in modular arithmetic under modulo 2011. The output should not contain any other characters.
There is no fraction with the divisor that is equal to zero or a multiple of 2011.
Note that powexpr x0 is defined as 1, and xy (y is a positive integer) is defined as the product x×x×...×x where the number of x's is equal to y.
A fraction<image>is computed as the multiplication of x and the inverse of y, i.e., x× inv(y), under y modulo 2011. The inverse of y (1 ≤ y < 2011) is uniquely defined as the integer z (1 ≤ z < 2011) that satisfies z × y ≡ 1 (mod 2011), since 2011 is a prime number.
Example
Input
4
........4...2..........
(.1.-.----.)..*.-.5.+.6
........2..............
.......3...............
3
...3.
-.---
...4.
4
.3.+.4.*.-.2.
-------------
..........2..
...-.1.-.2...
2
...2..3
(.4..).
1
2.+.3.*.5.-.7.+.9
1
(.2.+.3.).*.(.5.-.7.).+.9
3
.2....3.
4..+.---
......5.
3
.2......-.-.3.
4..-.-.-------
..........5...
9
............1............
-------------------------
..............1..........
.1.+.-------------------.
................1........
......1.+.-------------..
..................1......
...........1.+.-------...
................1.+.2....
15
.................2......
................---.....
.......2.........5....3.
.(.---------.+.-----.)..
.....7...........3......
....---.+.1.............
.....4..................
------------------------
.......2................
......---...............
.......5.......2....2...
...(.-----.+.-----.)....
.......3.......3........
..............---.......
...............4........
2
.0....2....
3..+.4..*.5
20
............2............................2......................................
...........3............................3.......................................
..........----.........................----.....................................
............4............................4......................................
.....2.+.------.+.1...............2.+.------.+.1................................
............2............................2......................................
...........2............................2........................2..............
..........----.........................----.....................3...............
............2............................2.....................----.............
...........3............................3........................4..............
(.(.----------------.+.2.+.3.).*.----------------.+.2.).*.2.+.------.+.1.+.2.*.5
............2............................2.......................2..............
...........5............................5.......................2...............
..........----.........................----....................----.............
............6............................6.......................2..............
.........------.......................------....................3...............
............3............................3......................................
..........----.........................----.....................................
............2............................2......................................
...........7............................7.......................................
0
Output
501
502
1
74
19
2010
821
821
1646
148
81
1933
|
#include <iostream>
#include <cstdio>
#include <vector>
#include <complex>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <cstring>
#include <stack>
#include <cmath>
#include <iomanip>
#include <sstream>
#include <cassert>
using namespace std;
typedef long long ll;
typedef ll li;
typedef pair<int,int> PI;
#define EPS (1e-10L)
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define REP(i, n) rep (i, n)
#define F first
#define S second
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define SZ(a) (int)((a).size())
#define ALL(a) a.begin(),a.end()
#define CLR(a) memset((a),0,sizeof(a))
#define FOR(it,a) for(__typeof(a.begin())it=a.begin();it!=a.end();++it)
template<typename T,typename U> ostream& operator<< (ostream& out, const pair<T,U>& val){return out << "(" << val.F << ", " << val.S << ")";}
template<class T> ostream& operator<< (ostream& out, const vector<T>& val){out << "{";rep(i,SZ(val)) out << (i?", ":"") << val[i];return out << "}";}
void pkuassert(bool t){t=1/t;};
int dx[]={0,1,0,-1,1,1,-1,-1};
int dy[]={1,0,-1,0,-1,1,1,-1};
int n;
string in[20];
int inv[3000];
void normal(int &x1,int &y1,int &x2,int &y2){
set<int> x,y;
for(int i=x1;i<x2;++i)
for(int j=y1;j<y2;++j){
if(in[i][j]!='.'){
x.insert(i);
y.insert(j);
}
}
x1 = *x.begin();
x2 = *x.rbegin()+1;
y1 = *y.begin();
y2 = *y.rbegin()+1;
}
int expr(int,int,int,int);
int term(int,int,int,int);
int factor(int,int,int,int);
int powexpr(int,int,int,int);
int primary(int,int,int,int);
int digit(int x1,int y1,int x2,int y2){
normal(x1,y1,x2,y2);
//cout << "digit " << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;
int ret=0;
while(y1<y2 && isdigit(in[x1][y1]))
ret=(ret*10+in[x1][y1++]-'0')%2011;
return ret;
}
int primary(int x1,int y1,int x2,int y2){
normal(x1,y1,x2,y2);
//cout << "primary " << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;
int base;
for(int j=x1;j<x2;++j)
if(in[j][y1]!='.') base=j;
if(in[base][y1]=='(')
return expr(x1,y1+1,x2,y2-1);
return digit(x1,y1,x2,y2);
}
int fraction(int x1,int y1,int x2,int y2){
normal(x1,y1,x2,y2);
int base;
for(int j=x1;j<x2;++j)
if(in[j][y1]!='.') base=j;
int p=expr(base+1,y1,x2,y2);
int c=expr(x1,y1,base,y2);
return c*inv[p]%2011;
}
int powexpr(int x1,int y1,int x2,int y2){
normal(x1,y1,x2,y2);
//cout << "powexpr " << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;
int base;
int base2=-1;
for(int j=x1;j<x2;++j)
if(in[j][y1]!='.') base=j;
for(int j=x1;j<x2;++j)
if(in[j][y2-1]!='.') base2=j;
//cout << base << ' ' << base2 << endl;
if(base2==base) return primary(x1,y1,x2,y2);
int idx=y2-1;
while(idx>=y1 && isdigit(in[base2][idx])) --idx;
++idx;
int di=digit(base2,idx,base2+1,y2);
int pr=primary(x1,y1,x2,idx);
//cout << "pr di " << pr << ' ' << di << endl;
int ret=1;
rep(i,di) ret=(ret*pr)%2011;
return ret;
}
int factor(int x1,int y1,int x2,int y2){
normal(x1,y1,x2,y2);
//cout << "factor " << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;
int ret;
int base;
for(int j=x1;j<x2;++j)
if(in[j][y1]!='.') base=j;
if(in[base][y1]=='-' &&
y1+1<y2 && in[base][y1+1]=='.')
return ((-factor(x1,y1+2,x2,y2))%2011+2011)%2011;
if(in[base][y1]=='-' &&
y1+1<y2 && in[base][y1+1]=='-')
return fraction(x1,y1,x2,y2);
return powexpr(x1,y1,x2,y2);
}
int term(int x1,int y1,int x2,int y2){
normal(x1,y1,x2,y2);
int ret;
int base;
//cout << "term " << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;
for(int j=x1;j<x2;++j)
if(in[j][y1]!='.') base=j;
int idx=-1;
int pa=0;
for(int j=y1;j<y2;++j){
if(in[base][j]=='(') ++pa;
if(in[base][j]==')') --pa;
if(j-1>=y1 && j+1<y2 && in[base][j-1]=='.' &&
in[base][j]=='*' &&
in[base][j+1]=='.' && pa==0){
idx=j;
break;
}
}
if(idx!=-1) ret=factor(x1,y1,x2,idx-1);
else return factor(x1,y1,x2,y2);
y1 = idx+1;
while(true){
normal(x1,y1,x2,y2);
idx=-1;
int pa=0;
for(int j=y1;j<y2;++j){
if(in[base][j]=='(') ++pa;
if(in[base][j]==')') --pa;
if(j-1>=y1 && j+1<y2 && in[base][j-1]=='.' &&
in[base][j]=='*' &&
in[base][j+1]=='.' && pa==0){
idx=j;
break;
}
}
if(idx!=-1){
int t=factor(x1,y1,x2,idx-1);
ret=(ret*t)%2011;
}else{
int t=factor(x1,y1,x2,y2);
ret=(ret*t)%2011;
return ret;
}
y1 = idx+1;
}
return ret;
}
int expr(int x1,int y1,int x2,int y2){
normal(x1,y1,x2,y2);
int ret;
int base;
/*
cout << "expr " << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;
for(int i=x1;i<x2;++i){
for(int j=y1;j<y2;++j) cout << in[i][j];
cout << endl;
}
*/
for(int j=x1;j<x2;++j)
if(in[j][y1]!='.') base=j;
int idx=-1;
int pa=0;
for(int j=y1;j<y2;++j){
if(in[base][j]=='(') ++pa;
if(in[base][j]==')') --pa;
if(j-1>=y1 && j+1<y2 && in[base][j-1]=='.' &&
(in[base][j]=='+' ||
(in[base][j]=='-' &&
(j-2>=0 && in[base][j-2]!='*' &&
in[base][j-2]!='+' &&
(in[base][j-2]!='-' || (j-3>=0 && in[base][j-3]=='-'))))) &&
in[base][j+1]=='.' && pa==0){
idx=j;
break;
}
}
if(idx!=-1) ret=term(x1,y1,x2,idx-1);
else return term(x1,y1,x2,y2);
y1 = idx+1;
while(true){
normal(x1,y1,x2,y2);
char op=in[base][idx];
idx=-1;
int pa=0;
for(int j=y1;j<y2;++j){
if(in[base][j]=='(') ++pa;
if(in[base][j]==')') --pa;
if(j-1>=y1 && j+1<y2 && in[base][j-1]=='.' &&
(in[base][j]=='+' ||
(in[base][j]=='-' &&
(j-2>=0 && in[base][j-2]!='*' &&
in[base][j-2]!='+' &&
(in[base][j-2]!='-' || (j-3>=0 && in[base][j-3]=='-'))))) &&
in[base][j+1]=='.' && pa==0){
idx=j;
break;
}
}
if(idx!=-1){
int t=term(x1,y1,x2,idx-1);
if(op=='+') ret=(ret+t)%2011;
else ret=((ret-t)%2011+2011)%2011;
}
else{
int t=term(x1,y1,x2,y2);
//cout << op << ' ' << t << endl;
if(op=='+') ret=(ret+t)%2011;
else ret=((ret-t)%2011+2011)%2011;
return ret;
}
y1 = idx+1;
}
return ret;
}
void solve(){
rep(i, n) cin >> in[i];
//rep(i, n) cout << in[i] << endl;
cout << expr(0,0,n,SZ(in[0])) << endl;
}
int main(int argc, char *argv[])
{
rep(i,2011)rep(j,2011) if(i*j%2011==1) inv[i]=j;
//cout << 4*inv[9] << endl;
while(cin >> n && n) solve();
return 0;
}
|
Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves drawing as much as programming. So far, Yu-kun has drawn many pictures with circles and arrows. The arrows are always drawn to connect the circles. One day Yu finds out that these pictures are graphs.
It seems that circles are called vertices and arrows are called edges. Furthermore, when drawing an arrow, Yu always wrote one positive integer on it. A graph consisting of directed edges with weights in this way is called a weighted directed graph.
Today Yu-kun learned a new word, the cycle of the cycle. A cycle is a sequence of connected edges in which all vertices appear at most once, and the first and last vertices are the same. If the sum of the weights of the edges of a cycle is negative, then such a cycle is called a negative cycle.
Yu-kun, who knew a lot of new words, came up with a problem.
Problem
A weighted directed graph with no cycle is given. Select two different vertices i and j and add one directed edge with weight w (w <0) from i to j. Find i and j in the graph that create a negative cycle, and find the maximum sum of the weights of the sides that belong to that negative cycle. If such i, j does not exist, output "NA".
Constraints
The input satisfies the following conditions.
* 2 ≤ V ≤ 100000
* 1 ≤ E ≤ 500000
* -100 ≤ w <0
* 0 ≤ ci ≤ 100 (0 ≤ i ≤ E-1)
* 0 ≤ si, ti ≤ V-1 (0 ≤ i ≤ E-1)
* The same si and ti pair never appears while typing
* si and ti are different
Input
V E w
s0 t0 c0
s1 t1 c1
...
s (E-1) t (E-1) c (E-1)
The number of vertices V, the number of edges E, and the weight w of the edge to be added are given in the first line, separated by blanks.
The information of the directed edge is given as si ti ci in the following E line. (0 ≤ i ≤ E-1)
This means that there is a directed edge of the weight ci from si to ti.
Output
Output the maximum value of the sum of the weights of the sides belonging to the negative cycle, which can be created by adding the directed side of the weight w, to one line. If a negative cycle cannot be created no matter where you add an edge, output "NA".
Examples
Input
3 2 -3
0 1 1
0 2 5
Output
-2
Input
3 2 -1
0 1 1
0 2 5
Output
NA
Input
7 8 -8
0 1 5
0 4 3
1 2 10
1 3 1
3 6 6
4 3 1
4 5 2
4 6 2
Output
-1
Input
5 4 -30
0 1 1
1 3 15
1 4 4
2 1 3
Output
-12
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> edge;
#define to first
#define cost second
int main() {
cin.tie(NULL);
ios::sync_with_stdio(false);
int n, m, w;
cin >> n >> m >> w;
vector<int> in(n, 0);
vector<vector<edge>> G(n);
for(int i = 0; i < m; ++i) {
int s, t, c;
cin >> s >> t >> c;
G[s].emplace_back(t, c);
++in[t];
}
const int abs_w = abs(w);
vector<vector<int>> dp(n, vector<int>(abs_w, false));
queue<int> que;
for(int v = 0; v < n; ++v) {
if(in[v] == 0) que.push(v);
}
int ans = INT_MIN;
while(!que.empty()) {
const int v = que.front();
que.pop();
for(int i = 0; i < abs_w; ++i) {
if(dp[v][i]) {
ans = max(ans, i - abs_w);
}
}
for(const auto &e : G[v]) {
for(int i = abs_w - 1 - e.cost; i >= 0; --i) {
dp[e.to][i + e.cost] |= (i == 0 ? true : dp[v][i]);
}
if(--in[e.to] == 0) {
que.push(e.to);
}
}
}
cout << (ans == INT_MIN ? "NA" : to_string(ans)) << endl;
return 0;
}
|
You have moved to a new town. As starting a new life, you have made up your mind to do one thing: lying about your age. Since no person in this town knows your history, you don’t have to worry about immediate exposure. Also, in order to ease your conscience somewhat, you have decided to claim ages that represent your real ages when interpreted as the base-M numbers (2 ≤ M ≤ 16). People will misunderstand your age as they interpret the claimed age as a decimal number (i.e. of the base 10).
Needless to say, you don’t want to have your real age revealed to the people in the future. So you should claim only one age each year, it should contain digits of decimal numbers (i.e. ‘0’ through ‘9’), and it should always be equal to or greater than that of the previous year (when interpreted as decimal).
How old can you claim you are, after some years?
Input
The input consists of multiple datasets. Each dataset is a single line that contains three integers A, B, and C, where A is the present real age (in decimal), B is the age you presently claim (which can be a non-decimal number), and C is the real age at which you are to find the age you will claim (in decimal). It is guaranteed that 0 ≤ A < C ≤ 200, while B may contain up to eight digits. No digits other than ‘0’ through ‘9’ appear in those numbers.
The end of input is indicated by A = B = C = -1, which should not be processed.
Output
For each dataset, print in a line the minimum age you can claim when you become C years old. In case the age you presently claim cannot be interpreted as your real age with the base from 2 through 16, print -1 instead.
Example
Input
23 18 53
46 30 47
-1 -1 -1
Output
49
-1
|
#include<stdio.h>
#include<algorithm>
using namespace std;
char str[20];
char s[20];
int main(){
int a,b,c;
while(scanf("%d%d%d",&a,&b,&c),~a){
bool ok=false;
sprintf(str,"%d",b);
for(int i=2;i<17;i++){
long long tmp=0;
for(int j=0;str[j];j++){
tmp*=i;
tmp+=str[j]-'0';
}
bool OK=true;
for(int j=0;str[j];j++){
if(str[j]-'0'>=i)OK=false;
}
if(tmp==a&&OK)ok=true;
}
if(!ok){
printf("-1\n");continue;
}
for(int i=a+1;i<=c;i++){
int to=999999999;
for(int j=2;j<17;j++){
int tmp=i;
int at=0;
while(tmp){
s[at++]='0'+tmp%j;
tmp/=j;
}
ok=true;
for(int k=0;k<at;k++){
if(s[k]>'9')ok=false;
str[at-1-k]=s[k];
}
if(ok){
str[at]=0;
int val;
sscanf(str,"%d",&val);
if(b<=val)to=min(to,val);
}
}
b=to;
}
printf("%d\n",b);
}
}
|
Heiankyo is known as a town with a grid of roads.
Hokusai, a cat who lives in Heiankyo, has to go from his home to a secret place on the outskirts of town every day for patrol. However, I get tired of following the same path every day, and there is a risk of being followed, so Hokusai wants to use a different route every day as much as possible. On the other hand, Hokusai has a troublesome smell, so I don't want to go down the road away from my destination.
There are Actinidia polygama on the roads here and there in Heiankyo, and Hokusai cannot go through the road where Actinidia polygama is falling. This is because if you go through such a road, you will be sick. Fortunately, there are no Actinidia polygama at the intersection.
Hokusai wants to know the number of possible routes from his home to a secret place. Here, Hokusai's home is at (0, 0) and the secret place is at (gx, gy). The roads are laid out in a grid with x = i (i is an integer) and y = j (j is an integer).
Notes on Submission
Multiple datasets are given in the above format. The first line of input data gives the number of datasets. Create a program that outputs the output for each data set in order in the above format.
Input
The first line of input is given the coordinates of the secret location (gx, gy). All of these are integers between 1 and 15 and are given separated by a single space. The second line is given the number of sections where Actinidia polygama is falling p (0 ≤ p ≤ 100), and the following lines p are given one section for each line where Actinidia polygama is falling. The p sections are different from each other. One interval is expressed in the form of x1 y1 x2 y2 and is a line segment of length 1 parallel to the x-axis or y-axis, with (x1, y1) and (x2, y2) as endpoints. x1 and x2 are in the range [0, gx] and y1 and y2 are in the range [0, gy].
Output
Output the number of possible routes. If there is no possible route, output "Miserable Hokusai!" On one line.
Example
Input
4
2 2
0
1 1
2
0 0 0 1
0 0 1 0
4 3
4
1 0 0 0
3 3 4 3
4 1 4 0
0 2 0 3
15 15
0
Output
6
Miserable Hokusai!
5
155117520
|
//Name: Heian-Kyo Walking
//Level: 2
//Category: 動的計画法,DP
//Note:
/*
* 通れないパターンを覚えておき、グリッドグラフの最短経路数え上げをする。
*
* オーダーは O(XY log P)。
*/
#include <iostream>
#include <set>
#include <utility>
#include <vector>
using namespace std;
typedef pair<int,int> Pt;
void solve() {
int X, Y;
cin >> X >> Y;
int P;
cin >> P;
set<pair<Pt,Pt>> prohibited;
for(int i = 0; i < P; ++i) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
prohibited.insert(make_pair(Pt(x1, y1), Pt(x2, y2)));
prohibited.insert(make_pair(Pt(x2, y2), Pt(x1, y1)));
}
vector<vector<int>> dp(X+1, vector<int>(Y+1, 0));
dp[0][0] = 1;
for(int x = 0; x <= X; ++x) {
for(int y = 0; y <= Y; ++y) {
if(x > 0 && !prohibited.count(make_pair(Pt(x-1,y), Pt(x,y)))) dp[x][y] += dp[x-1][y];
if(y > 0 && !prohibited.count(make_pair(Pt(x,y-1), Pt(x,y)))) dp[x][y] += dp[x][y-1];
}
}
if(dp[X][Y] == 0) {
cout << "Miserable Hokusai!" << endl;
} else {
cout << dp[X][Y] << endl;
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int N;
cin >> N;
while(N--) solve();
return 0;
}
|
Problem statement
Given the string $ S $. Find the number of all anagrams in $ S $ that are palindromic.
An anagram of the string $ X $ is an anagram of $ Y $, which means that $ X $ is equal to $ Y $, or that the rearranged characters of $ X $ are equal to $ Y $. For example, for the string abcd, abcd and cbda are anagrams, but abed, cab and abcdd are not anagrams.
When the string $ X $ is a palindrome, it means that the reverse reading of $ X $ is equal to $ X $ itself. For example, abc and ab are not palindromes, and a and abccba are palindromes.
Constraint
* $ 1 \ leq | S | \ leq 40 $ ($ | S | $ is the length of the string $ S $)
* $ S $ contains only lowercase letters.
* The answer is guaranteed to be less than $ 2 ^ {63} $.
input
Input follows the following format.
$ S $
output
Output the number on one line.
Examples
Input
ab
Output
0
Input
abba
Output
2
|
import java.util.Scanner;
//Palindromic Anagram
public class Main{
void run(){
Scanner sc = new Scanner(System.in);
long[] f = new long[21];
f[0] = 1;
for(int i=1;i<21;i++)f[i]=f[i-1]*i;
char[] s = sc.next().toCharArray();
int N = s.length;
int[] c = new int[26];
for(char r:s)c[r-'a']++;
int odd = 0;
long res = 0;
for(int i=0;i<26;i++)odd+=c[i]%2;
if(N%2==0){
if(odd==0){
res = f[N/2];
for(int i=0;i<26;i++)if(c[i]!=0)res/=f[c[i]/2];
}
}
else {
if(odd==1){
for(int i=0;i<26;i++)if(c[i]%2==1)c[i]--;
res = f[(N-1)/2];
for(int i=0;i<26;i++)if(c[i]!=0)res/=f[c[i]/2];
}
}
System.out.println(res);
}
public static void main(String[] args) {
new Main().run();
}
}
|
Problem Statement
Mr. Hagiwara, a witch, has a very negative personality. When she feels depressed, she uses the magic of digging to make holes and cry and fill them. The magic of digging is as follows.
She first draws N line segments on the ground. And when she casts the spell, a hole is created in the area surrounded by the line. Two holes that are in a crossing / inclusion relationship are counted as one hole. However, two holes that are in contact only at the vertices are counted as separate holes.
Figures 1 and 2 show Sample Inputs 1 and 2. First, in FIG. 1, since the triangle A and the triangle B are in contact with each other only at the vertices, they are counted as separate holes. Since the B triangle and the C triangle overlap each other, they are counted as one hole. Therefore, FIG. 1 shows two holes. In Figure 2, the D rectangle is contained within the E rectangle, so these are counted as one hole. Since E also intersects the hole in the upper right, Fig. 2 shows one hole.
<image>
You are the caretaker of Mr. Hagiwara and you have to fill the myriad holes she made. Create a program to find out how many holes she made to find out how many holes she had to fill.
Constraints
* 1 <= N <= 50
* -1000 <= coordinates <= 1000
* The positions of (xai, yai) and (xbi, ybi) are different
* When two line segments intersect, the four endpoints of the two line segments will not line up in a straight line.
Input
Each data set is input in the following format.
N
xa1 ya1 xb1 yb1
xa2 ya2 xb2 yb2
...
xaN yaN xbN ybN
All inputs are represented by integers. The first line is the number of line segments. Then, line segment information is given over N lines. One line segment is represented by the endpoints (xai, yai) and (xbi, ybi) of the line segment.
Output
Output the number of holes in one line.
Examples
Input
8
5 0 5 10
5 10 0 5
0 5 5 0
10 0 10 10
10 10 5 5
5 5 10 0
10 2 15 5
15 5 10 8
Output
2
Input
11
0 0 10 0
10 0 10 10
10 10 0 10
0 10 0 0
1 2 9 2
8 1 8 9
9 8 1 8
2 9 2 1
8 11 11 8
8 11 14 10
11 8 10 14
Output
1
|
#include <cassert>// c
#include <ctime>
#include <iostream>// io
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>// container
#include <map>
#include <set>
#include <queue>
#include <bitset>
#include <stack>
#include <algorithm>// other
#include <complex>
#include <numeric>
#include <functional>
#include <random>
#include <regex>
using namespace std;
typedef long long ll;
#define ALL(c) (c).begin(),(c).end()
#define FOR(i,l,r) for(int i=(int)l;i<(int)r;++i)
#define REP(i,n) FOR(i,0,n)
#define FORr(i,l,r) for(int i=(int)r-1;i>=(int)l;--i)
#define REPr(i,n) FORr(i,0,n)
#define EACH(i,c) for(__typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define IN(l,v,r) ((l)<=(v) && (v)<(r))
#define UNIQUE(v) v.erase(unique(ALL(v)),v.end())
//debug
#define DUMP(x) cerr << #x << " = " << (x)
#define LINE() cerr<< " (L" << __LINE__ << ")"
template<typename T,typename U> T pmod(T x,U M){return (x%M+M)%M;}
stringstream ss;
// must template
typedef long double D;
const D INF = 1e12,EPS = 1e-8;
typedef complex<D> P;
#define X real()
#define Y imag()
istream& operator >> (istream& is,complex<D>& p){
D x,y;is >> x >> y;p=P(x,y);return is;
}
int sig(D a,D b=0){return a<b-EPS?-1:a>b+EPS?1:0;}
template<typename T> bool eq(const T& a,const T& b){return sig(abs(a-b))==0;}
bool compX (const P& a,const P& b){return !eq(a.X,b.X)?sig(a.X,b.X)<0:sig(a.Y,b.Y)<0;}
namespace std{
bool operator < (const P& a,const P& b){return compX(a,b);}
bool operator == (const P& a,const P& b){return eq(a,b);}
};
// a×b
D cross(const P& a,const P& b){return imag(conj(a)*b);}
// a・b
D dot(const P& a,const P& b) {return real(conj(a)*b);}
int ccw(const P& a,P b,P c){
b -= a; c -= a;
if (cross(b,c) > EPS) return +1; // counter clockwise
if (cross(b,c) < -EPS) return -1; // clockwise
if (dot(b,c) < 0) return +2; // c--a--b on line
if (norm(b) < norm(c)) return -2; // a--b--c on line
return 0; //a--c--b on line (c==b,c==a)
}
// //must template
//直線・線分
struct L : public vector<P> {
P vec() const {return this->at(1)-this->at(0);}
L(const P &a, const P &b){push_back(a); push_back(b);}
L(){push_back(P());push_back(P());}
};
istream& operator >> (istream& is,L& l){P s,t;is >> s >> t;l=L(s,t);return is;}
bool isIntersectLL(const L &l, const L &m) {
return sig(cross(l.vec(), m.vec()))!=0 || // non-parallel
sig(cross(l.vec(), m[0]-l[0])) ==0; // same line
}
bool isIntersectLS(const L &l, const L &s) {
return sig(cross(l.vec(), s[0]-l[0])* // s[0] is left of l
cross(l.vec(), s[1]-l[0]))<=0; // s[1] is right of l
}
bool isIintersectLP(const L &l, const P &p) {return sig(cross(l[1]-p, l[0]-p))==0;}
// verified by ACAC003 B
// http://judge.u-aizu.ac.jp/onlinejudge/creview.jsp?rid=899178&cid=ACAC003
bool isIntersectSS(const L &s, const L &t) {
return ccw(s[0],s[1],t[0])*ccw(s[0],s[1],t[1]) <= 0 &&
ccw(t[0],t[1],s[0])*ccw(t[0],t[1],s[1]) <= 0;
}
bool isIntersectSP(const L &s, const P &p) {
return sig(abs(s[0]-p)+abs(s[1]-p),abs(s[1]-s[0])) <=0; // triangle inequality
}
// 交点計算
// verified by AOJLIB
// http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=1092231
P crosspoint(const L &l, const L &m) {
D A = cross(l.vec(), m.vec());
D B = cross(l.vec(), l[1] - m[0]);
if (sig(A)==0 && sig(B)==0) return m[0]; // same line
if (sig(A)==0) assert(false); //交点を持たない.
return m[0] + B / A * (m[1] - m[0]);
}
typedef D Cost; Cost CINF=1e20;
struct Edge{
int f,t;Cost c;D th;
Edge(int f,int t,Cost c,D th) : f(f),t(t),c(c),th(th){
};
bool operator<(const Edge& r) const{return th<r.th;}
};
typedef vector<vector<Edge> > Graph;
Graph segmentArrangement(vector<L> ss, vector<P> &ps) {
vector<vector<D>> vs(ss.size());
REP(i,ss.size()){vs[i].push_back(0);vs[i].push_back(abs(ss[i][1]-ss[i][0]));}
REP(i,ss.size())REP(j,ps.size())if(isIntersectSP(ss[i], ps[j]))
vs[i].push_back(abs(ps[j]-ss[i][0]));
REP(i,ss.size())FOR(j,i+1,ss.size()){
L& a=ss[i],b=ss[j];
if(isIntersectSS(a,b)){
P p = crosspoint(a,b);
vs[i].push_back(abs(p-a[0]));vs[j].push_back(abs(p-b[0]));
}
}
REP(i,vs.size()){sort(ALL(vs[i]));vs[i].erase(unique(ALL(vs[i]),eq<D>),vs[i].end());}
REP(i,vs.size())REP(j,vs[i].size())ps.push_back(ss[i][0]+vs[i][j]*ss[i].vec()/abs(ss[i].vec()));
sort(ALL(ps));UNIQUE(ps);
Graph g(ps.size());
REP(i,vs.size()){
vector<D>& cut=vs[i];
REP(j,cut.size()-1){
P a = ss[i][0] + vs[i][j]*ss[i].vec()/abs(ss[i].vec()),b = ss[i][0] + vs[i][j+1]*ss[i].vec()/abs(ss[i].vec());
int f=distance(ps.begin(),lower_bound(ALL(ps),a)), t=distance(ps.begin(),lower_bound(ALL(ps),b));
g[f].emplace_back(f,t,abs(b-a),arg(b-a));
g[t].emplace_back(t,f,abs(a-b),arg(a-b));
}
}
return g;
}
typedef vector<P> Poly,ConvexPoly;
enum { OUT, ON, IN };
int contains(const Poly& ps, const P& p) {
bool in = false;int n=ps.size();
REP(i,n){
P a = ps[i] - p, b = ps[pmod(i+1,n)] - p;
if (a.Y > b.Y) swap(a, b);
if (a.Y <= 0 && 0 < b.Y)
if (cross(a, b) < 0) in = !in;
if (cross(a, b) == 0 && dot(a, b) <= 0) return ON;
}
return in ? IN : OUT;
}
vector<Poly> find_polys(const vector<P>& ps,Graph& g){
const int n=g.size();
vector<vector<bool>> used(n);
REP(i,n)used[i]=vector<bool>(g[i].size());
REP(i,n)sort(ALL(g[i]));
vector<Poly> res;
REP(i,n)REP(j,g[i].size()){
int v=i,e_idx=j;
Poly qs;
while(true){
if(used[v][e_idx])break;
used[v][e_idx] =true;
Edge& e=g[v][e_idx];
qs.push_back(ps[v]);
REP(k,g[e.t].size())if(g[e.t][k].t==v){
e_idx =(k+1)%g[e.t].size();
v=e.t;
break;
}
}
if(qs.size()>=3)res.push_back(move(qs));
}
// cerr << res.size() <<endl;
//remove ccw poly
int idx = 0;
while(idx < res.size()) {
const P diff = res[idx][1] - res[idx][0];
const P p = res[idx][0] + diff * 0.5L + diff * P(0,-1) * (2.0L * EPS /abs(diff));
if(contains(res[idx], p))++idx;
else res.erase(res.begin() + idx);
}
return res;
}
struct UnionFind{
vector<int> par,rank,ss;int size;
UnionFind(int n){
REP(i,n) par.push_back(i);
rank = vector<int>(n);ss=vector<int>(n,1);size=n;
}
int root(int x){
if(par[x] == x)return x;
return par[x] = root(par[x]);
}
bool same(int x,int y){
return root(x) == root(y);
}
void unite(int x,int y){
x = root(x);y = root(y);
if(x==y)return;
if(rank[x] < rank[y]){
par[x] = y;ss[y]+=ss[x];
}else{
par[y] = x;ss[x]+=ss[y];
}
if(rank[x] == rank[y]) rank[x]++;
size--;
}
int getS(int x){
return ss[root(x)];
}
};
int main(){
cin.tie(0); ios::sync_with_stdio(false);
ss <<fixed <<setprecision(20);
cout <<fixed <<setprecision(20);
cerr <<fixed <<setprecision(20);
int N;cin >>N;
vector<L> ls(N);REP(i,N) cin >> ls[i];
vector<P> ps;
Graph g=segmentArrangement(ls,ps);
vector<Poly> face=find_polys(ps,g);
// cerr << ps.size() <<endl;
// cerr << face.size() <<endl;
UnionFind uf(face.size());
REP(i,face.size()){
// cerr << i <<endl;
// REP(l,face[i].size())cerr << face[i][l] << endl;
REP(j,face.size())if(i!=j){
bool isin=true;
REP(k,face[j].size())
if(contains(face[i],face[j][k])!=IN)isin=false;
bool iscross=false;
REP(k,face[j].size())REP(l,face[i].size()){
L l1(face[j][k],face[j][pmod(k+1,face[j].size())]);
L l2(face[i][l],face[i][pmod(l+1,face[i].size())]);
if(isIntersectSS(l1,l2) && sig(cross(l1.vec(),l2.vec()))==0
&& max(l1[0],l1[1])!= min(l2[0],l2[1])
&& max(l2[0],l2[1])!= min(l1[0],l1[1])){
// cerr <<"!!"<<endl;
// cerr << l1[0]<<" " << l1[1] <<endl;
// cerr << l2[0]<<" " << l2[1] <<endl;
iscross=true;
}
}
// cerr << i <<" " << j <<endl;
// cerr << isin <<" " << iscross <<endl;
if(isin || iscross)uf.unite(i,j);
}
}
cout << uf.size <<endl;
return 0;
}
|
Example
Input
8
0 2
0 0
2 0
2 1
3 1
3 3
1 3
1 2
Output
1
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef pair<int,P> P1;
typedef pair<P,P> P2;
typedef long long ll;
#define pu push
#define pb push_back
#define mp make_pair
#define rep(i,x) for(int i=0;i<x;i++)
typedef complex<double> pt;
typedef pair<pt,pt> L;
typedef vector<P> poly;
const double EPS = 1e-9;
#define x real()
#define y imag()
bool eq(double a,double b){ return -EPS<a-b&&a-b<EPS; }
double dot(pt a,pt b){
return (conj(a)*b).x;
}
double cross(pt a,pt b){
return (conj(a)*b).y;
}
bool on_segment(pair<pt,pt> a,pt p){
return eq(abs(a.first-a.second)-abs(a.first-p)-abs(a.second-p),0);
}
bool contain_point(vector<pt>ps,pt p){
double sum = 0;
//arg no sum wo keisan
for(int i=0;i<ps.size();i++){
if(on_segment(mp(ps[i],ps[ (i+1)%ps.size() ]),p)) return 1;
sum += arg( (ps[ (i+1)%ps.size() ]-p) / (ps[i]-p) );
}
return (abs(sum) > 1);
}
bool LCMP(const pt& a,const pt& b){
if(eq(a.x,b.x)) return a.y < b.y;
else return a.x < b.x;
}
int ccw(pt a,pt b,pt c){
b -= a; c -= a;
if(cross(b,c) > EPS) return 1; // counter clockwise
if(cross(b,c) < -EPS) return -1; // clockwise
if(dot(b,c) < -EPS) return 2; //c-a-b
if(norm(b) < norm(c)) return -2; //a-b-c
return 0; //a-c-b
}
pt crossPoint(pt a,pt b,pt c,pt d){
double A = cross(b-a,d-c);
double B = cross(b-a,b-c);
if( fabs(A) < EPS && fabs(B) < EPS ) return c;
else if(fabs(A) >= EPS ) return c+B/A*(d-c);
else pt(1e9,1e9);
}
bool contain_segment(vector<pt>ps,pt p,pt q){
vector<pt> qs;
// if(p == pt(1,2) && q == pt(0,0)) cout << "J" << endl;
qs.pb(p); qs.pb(q);
for(int i=0;i<ps.size();i++){
//on-segment
if(ccw(p,q,ps[i]) == 0) qs.pb(ps[i]);
}
for(int i=0;i<ps.size();i++){
pt r = crossPoint(p,q,ps[i],ps[(i+1)%ps.size()]);
if(r.x > 1e8) continue;
if(ccw(p,q,r) == 0) qs.pb(r);
}
sort(qs.begin(),qs.end(),LCMP);
for(int i=1;i<qs.size();i++){
pt r = (qs[i] + qs[i-1]) / 2.0;
if(!contain_point(ps, r)) return 0;
}
return 1;
}
int n;
vector<pt>f;
ll ok[45];
int ans = 40;
void dfs(int v,int num,ll state){
if(state == (1LL<<n)-1){
ans = min(ans,num); return;
}
if(v == n) return;
if(ans <= num || num >= 10) return;
dfs(v+1,num,state);
dfs(v+1,num+1,state|ok[v]);
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++){
double X,Y;
scanf("%lf%lf",&X,&Y);
f.pb(pt(X,Y));
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j) ok[i] ^= (1LL<<j);
else{
if(contain_segment(f,f[i],f[j])){
ok[i] ^= (1LL<<j);
}
}
}
//cout << ok[i] << endl;
}//return 0;
dfs(0,0,0);
cout << ans << endl;
}
|
E: Binary Sequence-Binary Sequence-
story
I love binaries Bonald.Brvin.Bnuth! He is known as Uncle Bnuth, who is studying the nature of binary sequences at Offtunford University! By the way, if my name "Bonald.Brvin.Bnuth" is binarized from ASCII code, it will be "1000010 1101111 1101110 1100001 1101100 1100100 101110 1000010 1110010 1110110 1101001 1101110 101110 1000010 1101110 1110101 1110100 1101000"! It's fun!
I'm looking forward to it from the morning because my disciples are going to do some interesting experiments today! What are you doing?
What! I want to discover some properties by continuing to rewrite binary strings! HM! This is the scent of an important discovery! Let's start the experiment! Let's summarize more detailed settings as sentences!
problem
Given a binary sequence of length n x = (x_1, ..., x_n) (x_i \ in \\ {0,1 \\}, i = 1, ..., n). For the binary string x, we define two functions f (x) and g (x) as follows.
f (x) = Σ_ {i = 1} ^ {n} x_i = x_1 + x_2 + ... + x_n
g (x) = Σ_ {i = 1} ^ {n-1} x_i x_ {i + 1} = x_1 x_2 + x_2 x_3 + ... x_ {n-1} x_n
Now, perform the following change operation on the binary string x q times. The jth change operation is given by l_j, r_j, b_j (1 \ leq l_j \ leq r_j \ leq n, b_j \ in \\ {0,1 \\}, j = 1, ..., q). This corresponds to the operation of replacing the l_jth to r_jths of the binary string x with b_j. Find f (x) --g (x) after each change operation.
Input format
n
x
q
l_1 r_1 b_1
...
l_q r_q b_q
The first line is given the integer n that represents the length of the binary column. The second line is given a string that represents the binary column x. The third line is given the integer q, which represents the number of queries. In the following q lines, the i-th line is given information about the i-th query l_i, r_i, b_i in this order, separated by blanks.
Constraint
* 2 \ leq n \ leq 100000
* x is a character string consisting of ‘0’ and ‘1’
* | x | = n
* 1 \ leq q \ leq 100000
* 1 \ leq l_j \ leq r_j \ leq n, b_j \ in \\ {0,1 \\}, j = 1, ..., q
Output format
For each i = 1, ..., q, output the value of f (x) --g (x) after processing the i-th query on the i-line.
Input example 1
Ten
0101100110
3
3 3 1
1 6 0
2 5 1
Output example 1
2
1
2
Input example 2
8
00111100
3
8 8 1
4 5 0
7 8 1
Output example 2
2
3
2
Example
Input
10
0101100110
3
3 3 1
1 6 0
2 5 1
Output
2
1
2
|
#include <bits/stdc++.h>
using namespace std;
class LazySegT{
private:
int NN;
struct Node{
int f, g, l, r;
int lazy;
};
Node segT[2*(1<<17)-1]; // =131072
public:
LazySegT(int n){
NN = 1;
while(NN < n) NN <<= 1;
for(int i=0;i<2*NN-1;++i){
segT[i].f = segT[i].g = segT[i].l = segT[i].r = 0;
segT[i].lazy = -1;
}
}
void eval(int k, int l, int r){
if(segT[k].lazy < 0) return;
segT[k].f = (r-l) * segT[k].lazy;
segT[k].g = (r-l-1) * segT[k].lazy;
segT[k].l = segT[k].r = segT[k].lazy;
if(k < NN-1){
segT[2*k+1].lazy = segT[2*k+2].lazy = segT[k].lazy;
}
segT[k].lazy = -1;
}
void update(int a, int b, int bit, int k, int l, int r){
eval(k,l,r);
if(r <= a || b <= l) return;
if(a <= l && r <= b){
segT[k].lazy = bit;
eval(k,l,r);
}
else{
int m = (l+r) / 2;
update(a, b, bit, k*2+1, l, m);
update(a, b, bit, k*2+2, m, r);
segT[k].f = segT[k*2+1].f + segT[k*2+2].f;
segT[k].g = segT[k*2+1].g + segT[k*2+2].g + segT[k*2+1].r * segT[k*2+2].l;
segT[k].l = segT[k*2+1].l;
segT[k].r = segT[k*2+2].r;
}
}
void update(int a, int b, int c){
update(a, b, c, 0, 0, NN);
}
int query(){
eval(0, 0, NN);
return segT[0].f - segT[0].g;
}
};
int main(){
int N; cin >> N;
string X; cin >> X;
int Q; cin >> Q;
LazySegT seg(N);
for(int i=0;i<X.size();++i){
seg.update(i, i+1, X[i]-'0');
}
for(int q=0;q<Q;++q){
int l, r, b;
cin >> l >> r >> b;
--l;
seg.update(l, r, b);
cout << seg.query() << endl;
}
return 0;
}
|
G: Tree
problem
Given a tree consisting of N vertices. Each vertex of the tree is numbered from 1 to N. Of the N-1 edges, the i \ (= 1, 2, ..., N-1) edge connects the vertex u_i and the vertex v_i.
Write a program to find the number of K non-empty subgraph sets of this tree, each of which is concatenated and no two different subgraphs share vertices. However, the answer can be very large, so answer the remainder divided by 998244353.
Note that if the set of K subgraphs is the same, the ones with different order of K subgraphs are also equated.
Input format
N K
u_1 v_1
::
u_ {N-1} v_ {N-1}
Constraint
* 2 \ leq N \ leq 10 ^ {5}
* 1 \ leq K \ leq min (N, 300)
* 1 \ leq u_i, v_i \ leq N
* u_i \ neq v_i
* For i \ neq j (u_i, v_i) \ neq (u_j, v_j)
* All inputs are given as integers.
* The graph given is guaranteed to be a tree.
Output format
Print the integer that represents the answer on one line. Note that it prints too much divided by 998244353.
Input example 1
3 2
1 2
13
Output example 1
Five
There are five ways:
* \\ {1 \\} and \\ {2 \\}
* \\ {1 \\} and \\ {3 \\}
* \\ {2 \\} and \\ {3 \\}
* \\ {1, 2 \\} and \\ {3 \\}
* \\ {1, 3 \\} and \\ {2 \\}
Input example 2
4 4
1 2
13
14
Output example 2
1
There is only one way (\\ {1 \\}, \\ {2 \\}, \\ {3 \\}, \\ {4 \\}).
Input example 3
7 4
1 7
twenty one
7 4
3 4
5 7
6 3
Output example 3
166
Example
Input
3 2
1 2
1 3
Output
5
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <algorithm>
#include <utility>
#include <functional>
#include <cstring>
#include <queue>
#include <stack>
#include <math.h>
#include <iterator>
#include <vector>
#include <string>
#include <set>
#include <math.h>
#include <iostream>
#include <random>
#include<map>
#include <iomanip>
#include <time.h>
#include <stdlib.h>
#include <list>
#include <typeinfo>
#include <list>
#include <set>
#include <cassert>
#include<fstream>
#include <unordered_map>
#include <cstdlib>
#include <complex>
#include <cctype>
using namespace std;
typedef string::const_iterator State;
#define Ma_PI 3.141592653589793
#define eps 0.00000001
#define LONG_INF 1e18
#define GOLD 1.61803398874989484820458
#define MAX_MOD 1000000007
#define MOD 998244353
#define seg_size 262144
#define REP(i,n) for(long long i = 0;i < n;++i)
vector<int> vertexs[200000];
long long dp[200000][301][2] = {};
long long pre_dp[701][2] = {};
int cnter[200000];
int dfs(int now, int back) {
cnter[now] = 1;
for (int i = 0; i < vertexs[now].size(); ++i) {
if (vertexs[now][i] == back) continue;
cnter[now] += dfs(vertexs[now][i], now);
}
cnter[now] = min(cnter[now], 300);
REP(i, 601) {
REP(q, 2) {
pre_dp[i][q] = 0;
}
}
pre_dp[0][0] = 1;
pre_dp[0][1] = 1;
int now_max = 0;
for (int i = 0; i < vertexs[now].size(); ++i) {
if (vertexs[now][i] == back) continue;
for (int q = now_max; q >= 0;--q) {
long long geko_a = pre_dp[q][0];
long long geko_b = pre_dp[q][1];
pre_dp[q][0] = 0;
pre_dp[q][1] = 0;
for (int j = 0; j <= cnter[vertexs[now][i]]; ++j) {
pre_dp[q + j][0] += (geko_a * dp[vertexs[now][i]][j][0])%MOD;
pre_dp[q + j][0] %= MOD;
pre_dp[q + j + 1][0] += (geko_a * dp[vertexs[now][i]][j][1])%MOD;
pre_dp[q + j + 1][0] %= MOD;
pre_dp[q + j][1] += (geko_b * dp[vertexs[now][i]][j][1])%MOD;
pre_dp[q + j][1] %= MOD;
pre_dp[q + j+1][1] += (geko_b * dp[vertexs[now][i]][j][1]) % MOD;
pre_dp[q + j+1][1] %= MOD;
pre_dp[q + j][1] += (geko_b * dp[vertexs[now][i]][j][0])%MOD;
pre_dp[q + j][1] %= MOD;
}
}
now_max += cnter[vertexs[now][i]];
now_max = min(now_max, 300);
}
REP(i, 301) {
REP(q, 2) {
dp[now][i][q] = pre_dp[i][q];
}
}
return cnter[now];
}
int main(){
long long n, k;
cin >> n >> k;
REP(i, n-1) {
int a, b;
cin >> a >> b;
a--;
b--;
vertexs[a].push_back(b);
vertexs[b].push_back(a);
}
dfs(0, -1);
cout << (dp[0][k][0] + dp[0][k - 1][1]) % MOD << endl;
return 0;
}
|
Today's Random Number
E869120 You ran a campaign called "Today's Random Numbers" for N days. This is a project to generate a random number once a day and post the value on Twitter.
The "random numbers of the day" on day $ 1, 2, 3, \ dots, N $ were $ A_1, A_2, A_3, \ dots, A_N $, respectively.
E869120 You would be happy if today's random number is higher than yesterday's random number.
How many times in the $ N $ day did E869120 make you happy with "Today's Random Numbers"?
input
Input is given from standard input in the following format.
$ N $
$ A_1 $ $ A_2 $ $ A_3 $ $ \ dots $ $ A_N $
output
Print out the number of times E869120 was pleased with "Today's Random Numbers" in one line in $ N $ days.
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 100000 \ (= 10 ^ 5) $
* $ 1 \ leq A_i \ leq 1000000000 \ (= 10 ^ 9) $
* All inputs are integers.
Input example 1
Five
8 6 9 1 20
Output example 1
2
On the 3rd and 5th days, E869120 is happy.
Input example 2
6
3 3 4 3 3 4
Output example 2
2
On the 3rd and 6th days, E869120 is happy.
Input example 3
Ten
10 9 8 7 6 5 4 3 2 1
Output example 3
0
E869120 You will not be happy with "Today's Random Numbers".
Example
Input
5
8 6 9 1 20
Output
2
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
int main() {
int n;
cin >> n;
int a;
cin >> a;
int ret = 0;
for (int i = 0; i < n - 1; i++) {
int x;
cin >> x;
if (a < x)ret++;
a = x;
}
cout << ret << endl;
return 0;
}
|
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $S$, find the smallest sub-array size (smallest window length) where the sum of the sub-array is greater than or equal to $S$. If there is not such sub-array, report 0.
Constraints
* $1 \leq N \leq 10^5$
* $1 \leq S \leq 10^9$
* $1 \leq a_i \leq 10^4$
Input
The input is given in the following format.
$N$ $S$
$a_1$ $a_2$ ... $a_N$
Output
Print the smallest sub-array size in a line.
Examples
Input
6 4
1 2 1 2 3 2
Output
2
Input
6 6
1 2 1 2 3 2
Output
3
Input
3 7
1 2 3
Output
0
|
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
int main(){
int N,S;
scanf("%d %d",&N,&S);
int* table = new int[N];
for(int i = 0; i < N; i++)scanf("%d",&table[i]);
int ans = BIG_NUM,left = 0,right = 0,tmp_sum = 0;
while(true){
while(true){
tmp_sum += table[right];
if(tmp_sum >= S){
break;
}else if(right == N-1){
break;
}
right++;
}
if(tmp_sum < S)break;
while(true){
ans = min(ans,right-left+1);
tmp_sum -= table[left];
left++;
if(tmp_sum < S){
break;
}else if(left == right+1){
break;
}
}
if(ans == 1 || left == N || right == N-1)break;
right += 1;
}
if(ans == BIG_NUM){
printf("0\n");
}else{
printf("%d\n",ans);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.