input
stringlengths 29
13k
| output
stringlengths 9
73.4k
|
|---|---|
There is a sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X.
You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required.
* Choose an integer i such that 1\leq i\leq N-1. Replace the value of X_{i+1} with the value of X_i plus 1.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9(1\leq i\leq N)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
If we can make X equal to A by repeating the operation, print the minimum number of operations required. If we cannot, print -1.
Examples
Input
4
0
1
1
2
Output
3
Input
3
1
2
1
Output
-1
Input
9
0
1
1
0
1
2
2
1
2
Output
8
|
N = int(input())
A = [0] + [int(input()) for i in range(N)]
if A[1] != 0:
print(-1)
quit()
ans = 0
for i, a in enumerate(A[1:], 1):
pre_a = A[i-1]
if a - pre_a >= 2:
print(-1)
quit()
elif a > pre_a:
ans += 1
else:
ans += a
print(ans)
|
In your garden, there is a long and narrow flowerbed that stretches infinitely to the east. You have decided to plant N kinds of flowers in this empty flowerbed. For convenience, we will call these N kinds of flowers Flower 1, 2, …, N. Also, we will call the position that is p centimeters from the west end of the flowerbed Position p.
You will plant Flower i (1 ≤ i ≤ N) as follows: first, plant one at Position w_i, then plant one every d_i centimeters endlessly toward the east. That is, Flower i will be planted at the positions w_i, w_i + d_i, w_i + 2 d_i, … Note that more than one flower may be planted at the same position.
Find the position at which the K-th flower from the west is planted. If more than one flower is planted at the same position, they are counted individually.
Constraints
* 1 ≤ N ≤ 10^5
* 1 ≤ K ≤ 10^9
* 1 ≤ w_i ≤ 10^{18}
* 1 ≤ d_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N K
w_1 d_1
:
w_N d_N
Output
When the K-th flower from the west is planted at Position X, print the value of X. (The westmost flower is counted as the 1-st flower.)
Examples
Input
2 6
20 10
25 15
Output
50
Input
3 9
10 10
10 10
10 10
Output
30
Input
1 1000000000
1000000000000000000 1000000000
Output
1999999999000000000
|
#include <iostream>
#include <cassert>
#include <climits>
#include <bitset>
#include <stack>
#include <queue>
#include <iomanip>
#include <limits>
#include <string>
#include <cmath>
#include <set>
#include <map>
#include <math.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <tuple>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
long long int INF = 1e18;
long long int mod = 1000000007;
double Pi = 3.1415926535897932384626;
vector<ll> G[500005];
vector<P> tree[500010];
priority_queue <ll> pql;
priority_queue <P> pqp;
//big priority queue
priority_queue <ll,vector<ll>,greater<ll> > pqls;
priority_queue <P,vector<P>,greater<P> > pqps;
//small priority queue
//top pop
int dx[8]={1,0,-1,0,1,1,-1,-1};
int dy[8]={0,1,0,-1,1,-1,-1,1};
char dir[] = "RULD";
//↓,→,↑,←
#define p(x) cout<<x<<endl;
#define el cout<<endl;
#define pe(x) cout<<x<<" ";
#define ps(x) cout<<fixed<<setprecision(25)<<x<<endl;
#define pu(x) cout<<x;
#define re(i,n) for(i=0;i<n;i++);
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define deba(x) cout<< #x << " = " << x <<endl
ll rui(ll number1,ll number2){
if(number2 == 0){
return 1;
}else{
ll number3 = rui(number1,number2 / 2);
number3 *= number3;
number3 %= mod;
if(number2%2==1){
number3 *= number1;
number3 %= mod;
}
return number3;
}
}
ll gcd(ll number1,ll number2){
if(number1 > number2){
swap(number1 , number2);
}
if(number1 == 0 || number1 == number2){
return number2;
}else{
return gcd(number2 % number1 , number1);
}
}
ll i,j,k,ii,jj;
ll n,m;
ll a,b,c,d,e,g,h,r,w;
ll l,ans,sum;
ll num;
ll x[500005],y[500005],z[500005];
bool dame,flag;
bool solve(ll v){
num = 0;
for(int i=0;i<n;i++){
if(v < x[i])continue;
num += (v-x[i])/y[i];
num++;
}
if(num >= k){
return true;
}else{
return false;
}
}
int main(){
cin >> n >> k;
for(i=0;i<n;i++){
cin >> x[i] >> y[i];
}
ll ng = 0,ok = 3*INF;
ll mid ;
while(ok - ng > 1){
mid = (ng+ok)/2;
if(solve(mid)){
ok = mid;
}else{
ng = mid;
}
}
p(ok);
return 0;
}
|
There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i).
On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation:
* Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1.
A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally.
Constraints
* 2 \leq N \leq 100000
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N-1} y_{N-1}
Output
Print `Alice` if Alice wins; print `Bob` if Bob wins.
Examples
Input
5
1 2
2 3
2 4
4 5
Output
Alice
Input
5
1 2
2 3
1 4
4 5
Output
Bob
Input
6
1 2
2 4
5 1
6 3
3 2
Output
Alice
Input
7
1 2
3 7
4 6
2 3
2 4
1 5
Output
Bob
|
#include<bits/stdc++.h>
using namespace std;
#define M 100005
vector<int>edge[M];
int Get_sg(int x,int pre){
int res=0;
for(int i=0;i<edge[x].size();i++)
if(edge[x][i]!=pre)res^=(Get_sg(edge[x][i],x)+1);
return res;
}
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<n;i++){
int x,y;
scanf("%d%d",&x,&y);
edge[x].push_back(y);
edge[y].push_back(x);
}
if(Get_sg(1,-1))puts("Alice");
else puts("Bob");
return 0;
}
|
There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that:
* The absolute difference of any two distinct elements in X is A or greater.
* The absolute difference of any two distinct elements in Y is B or greater.
How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty.
Constraints
* All input values are integers.
* 1 ≦ N ≦ 10^5
* 1 ≦ A , B ≦ 10^{18}
* 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N)
* S_i < S_{i+1}(1 ≦ i ≦ N - 1)
Input
The input is given from Standard Input in the following format:
N A B
S_1
:
S_N
Output
Print the number of the different divisions under the conditions, modulo 10^9 + 7.
Examples
Input
5 3 7
1
3
6
9
12
Output
5
Input
7 5 3
0
2
4
7
8
11
15
Output
4
Input
8 2 9
3
4
5
13
15
22
26
32
Output
13
Input
3 3 4
5
6
7
Output
0
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
const int N=100010,Mo=1000000007;
ll f[N],s[N];
inline ll gi() {
ll x=0,o=1;
char ch=getchar();
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-') o=-1,ch=getchar();
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*o;
}
int main() {
int n,p=0,ans=0,la=0;
ll A,B;
cin>>n>>A>>B;
if(A<B) swap(A,B);
s[0]=-1LL<<60,f[0]=1;
for(int i=1,j=0;i<=n;i++) {
s[i]=gi();
if(i>1&&s[i]-s[i-2]<B) return puts("0"),0;
while(s[i]-s[j]>=A) la=(la+f[j++])%Mo;
f[i]=la;
if(s[i]-s[i-1]<B) j=p=i-1,la=0;
}
while(p<=n) ans=(ans+f[p++])%Mo;
cout<<ans;
return 0;
}
|
Sigma and Sugim are playing a game.
The game is played on a graph with N vertices numbered 1 through N. The graph has N-1 red edges and N-1 blue edges, and the N-1 edges in each color forms a tree. The red edges are represented by pairs of integers (a_i, b_i), and the blue edges are represented by pairs of integers (c_i, d_i).
Each player has his own piece. Initially, Sigma's piece is at vertex X, and Sugim's piece is at vertex Y.
The game is played in turns, where turns are numbered starting from turn 1. Sigma takes turns 1, 3, 5, ..., and Sugim takes turns 2, 4, 6, ....
In each turn, the current player either moves his piece, or does nothing. Here, Sigma can only move his piece to a vertex that is directly connected to the current vertex by a red edge. Similarly, Sugim can only move his piece to a vertex that is directly connected to the current vertex by a blue edge.
When the two pieces come to the same vertex, the game ends immediately. If the game ends just after the operation in turn i, let i be the total number of turns in the game.
Sigma's objective is to make the total number of turns as large as possible, while Sugim's objective is to make it as small as possible.
Determine whether the game will end in a finite number of turns, assuming both players plays optimally to achieve their respective objectives. If the answer is positive, find the number of turns in the game.
Constraints
* 2 ≦ N ≦ 200,000
* 1 ≦ X, Y ≦ N
* X \neq Y
* 1 ≦ a_i, b_i, c_i, d_i ≦ N
* The N-1 edges in each color (red and blue) forms a tree.
Input
The input is given from Standard Input in the following format:
N X Y
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
c_1 d_1
c_2 d_2
:
c_{N-1} d_{N-1}
Output
If the game will end in a finite number of turns, print the number of turns. Otherwise, print `-1`.
Examples
Input
4 1 2
1 2
1 3
1 4
2 1
2 3
1 4
Output
4
Input
3 3 1
1 2
2 3
1 2
2 3
Output
4
Input
4 1 2
1 2
3 4
2 4
1 2
3 4
1 3
Output
2
Input
4 2 1
1 2
3 4
2 4
1 2
3 4
1 3
Output
-1
Input
5 1 2
1 2
1 3
1 4
4 5
2 1
1 3
1 5
5 4
Output
6
|
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
using namespace std;
const int N=2e5+10;
struct Tree
{
struct edge{int next,to;}a[N<<1];
int head[N],cnt;
void link(int x,int y)
{
a[++cnt]=(edge){head[x],y};head[x]=cnt;
a[++cnt]=(edge){head[y],x};head[y]=cnt;
}
}A,B;
int n,p1,p2,dep[N],dis[N],fr[N],vis[N],ans;
queue<int> Q;
void bfs1()
{
memset(dis,-1,sizeof(dis));
if(dep[p1]) Q.push(p1);dis[p1]=0;
while(!Q.empty())
{
int x=Q.front();Q.pop();vis[x]=1;
for(int i=A.head[x];i;i=A.a[i].next)
{
int R=A.a[i].to;
if(dis[R]==-1)
{
dis[R]=dis[x]+1;
if(dis[R]<dep[R]) Q.push(R);
else if(dis[R]==dis[R]) vis[R]=1;
}
}
}
}
void bfs2()
{
memset(dep,-1,sizeof(dep));
Q.push(p2);dep[p2]=0;
while(!Q.empty())
{
int x=Q.front();Q.pop();
for(int i=B.head[x];i;i=B.a[i].next)
{
int R=B.a[i].to;
if(dep[R]==-1) dep[R]=dep[x]+1,fr[R]=x,Q.push(R);
}
}
}
int Dis(int x,int y)
{
if(dep[x]<dep[y]) swap(x,y);
if(fr[x]==fr[y]||x==y||fr[x]==y) return 0;
if(fr[fr[x]]==y) return 0;
return 1;
}
int main()
{
cin>>n>>p1>>p2;
for(int i=1,x,y;i<n;i++) scanf("%d%d",&x,&y),A.link(x,y);
for(int i=1,x,y;i<n;i++) scanf("%d%d",&x,&y),B.link(x,y);
bfs2();bfs1();
for(int x=1;x<=n;x++)
for(int i=A.head[x];i;i=A.a[i].next)
if(vis[x]&&vis[A.a[i].to]&&Dis(x,A.a[i].to))
puts("-1"),exit(0);
for(int i=1;i<=n;i++) if(vis[i]) ans=max(dep[i],ans);
cout<<ans*2<<endl;
}
|
The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares.
There are the following methods to create a magic square with an odd number of squares on each side.
1. Put 1 in the square just below the center square.
2. Put the following numbers in the square at the bottom right.
However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method.
* If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in.
* If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square.
3. Repeat 2 until all the squares are filled.
Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number.
input
Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10.
output
Output n x n magic squares for each input.
Example
Input
3
5
0
Output
4 9 2
3 5 7
8 1 6
11 24 7 20 3
4 12 25 8 16
17 5 13 21 9
10 18 1 14 22
23 6 19 2 15
|
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(true){
int n=sc.nextInt();
if(n==0){
break;
}
int[][] map=new int[n][n];
boolean[][] flag=new boolean[n][n];
int x=n/2;
int y=n/2+1;
map[y][x]=1;
flag[y][x]=true;
for(int i=2;i<=n*n;i++){
x++;
y++;
if(x==n&&y==n){
x--;
for(int j=0;j<n;j++){
if(!flag[j][x]){
y=j;
break;
}
}
}else if(x==-1&&y==n){
x++;
for(int j=0;j<n;j++){
if(!flag[j][x]){
y=j;
break;
}
}
}else if(x==n){
x=0;
}else if(y==n){
y=0;
}else if(x==-1){
x=n-1;
}
if(flag[y][x]){
x-=2;
i--;
}else{
map[y][x]=i;
flag[y][x]=true;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.printf("%4d",map[i][j]);
}
System.out.println();
}
}
}
}
|
The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications.
As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north.
<image>
Figure 1
People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below.
1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change.
2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south.
Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze.
Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows.
: Wall
.: Floor
X: Emergency exit
E: People facing east
N: People facing north
W: People facing west
S: People facing south
The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
W H
str1
str2
::
strH
The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze.
The number of datasets does not exceed 50.
Output
For each input dataset, the time when all people finish evacuating is output on one line.
Examples
Input
10 3
##########
#E.......X
##########
4 4
####
#N.#
#..X
####
5 5
#####
#N..#
###.X
#S..#
#####
6 6
######
#..#X#
#.EE.#
####N#
#....#
######
8 8
##X#####
#....E.#
#####.##
#.#...##
#.W.#..#
#.#.N#.X
#X##.#.#
########
0 0
Output
8
NA
9
16
10
Input
10 3
E.......X
4 4
N.#
..X
5 5
N..#
.X
S..#
6 6
..#X#
.EE.#
N#
....#
8 8
X#####
....E.#
.##
.#...##
.W.#..#
.#.N#.X
X##.#.#
0 0
Output
8
NA
9
16
10
|
import java.io.IOException;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
private void run() throws IOException {
Scanner scanner = new Scanner(System.in);
while (true) {
int w = scanner.nextInt();
int h = scanner.nextInt();
if ((w | h) == 0)
break;
PriorityQueue<Player> pq = new PriorityQueue<Player>();
char[][] map = new char[h][w];
for (int i = 0; i < h; i++) {
map[i] = scanner.next().toCharArray();
for (int j = 0; j < w; j++) {
if (map[i][j] != '#' && map[i][j] != '.'
&& map[i][j] != 'X') {
char c = map[i][j];
int dir = c == 'W' ? 0 : c == 'S' ? 1 : c == 'E' ? 2
: 3;
map[i][j] = 'P';
pq.add(new Player(i, j, dir));
}
}
}
String ans = "NA";
int step = 1;
while (step <= 180) {
PriorityQueue<Player> next = new PriorityQueue<Player>();
pl: while (!pq.isEmpty()) {
Player player = pq.poll();
for (int k = 3; k < 7; k++) {
int y = player.y;
int x = player.x;
int dir = player.dir;
int ny = y + move[(k + dir) % 4][0];
int nx = x + move[(k + dir) % 4][1];
if (map[ny][nx] == '.' || map[ny][nx] == 'X') {
player.dir = (k + dir) % 4;
player.ny = ny;
player.nx = nx;
next.add(player);
continue pl;
}
}
player.b = false;
next.add(player);
}
pq = next;
next = new PriorityQueue<Player>();
while (!pq.isEmpty()) {
Player player = pq.poll();
if (!player.b) {
player.b = true;
next.add(player);
} else {
int y = player.y;
int x = player.x;
int ny = player.ny;
int nx = player.nx;
map[y][x] = '.';
if (map[ny][nx] == 'X') {
map[ny][nx] = 'x';
continue;
}
if (map[ny][nx] == '.') {
map[ny][nx] = 'P';
player.y = ny;
player.x = nx;
next.add(player);
} else {
map[y][x] = 'P';
next.add(player);
}
}
}
if (next.isEmpty()) {
ans = String.valueOf(step);
break;
}
pq.addAll(next);
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++)
if (map[i][j] == 'x')
map[i][j] = 'X';
step++;
}
System.out.println(ans);
}
}
int[][] move = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };
class Player implements Comparable<Player> {
int y;
int x;
int dir;
int ny;
int nx;
boolean b = true;
public Player(int y, int x, int dir) {
super();
this.y = y;
this.x = x;
this.dir = dir;
}
@Override
public int compareTo(Player o) {
return this.dir - o.dir;
}
}
}
|
The Onogawa Expedition is planning to conduct a survey of the Aizu nature reserve. The expedition planner wants to take the shortest possible route from the start to end point of the survey, while the expedition has to go around the coast of the Lake of Onogawa en route. The expedition walks along the coast of the lake, but can not wade across the lake.
Based on the base information including the start and end point of the survey and the area of Lake Onogawa as convex polygon data, make a program to find the shortest possible route for the expedition and calculate its distance. Note that the expedition can move along the polygonal lines passing through the nodes, but never enter within the area enclosed by the polygon.
Input
The input is given in the following format.
x_s y_s
x_g y_g
N
x_1 y_1
x_2 y_2
:
x_N y_N
The first line provides the start point of the survey x_s,y_s (0≤x_s,y_s≤104), and the second line provides the end point x_g,y_g (0 ≤ x_g,y_g ≤ 104) all in integers. The third line provides the number of apexes N (3 ≤ N ≤ 100) of the polygon that represents the lake, and each of the subsequent N lines provides the coordinate of the i-th apex x_i,y_i (0 ≤ x_i,y_i ≤ 104) in counter-clockwise order. These data satisfy the following criteria:
* Start and end points of the expedition are not within the area enclosed by the polygon nor on boundaries.
* Start and end points of the expedition are not identical, i.e., x_s ≠ x_g or y_s ≠ y_g.
* No duplicate coordinates are given, i.e., if i ≠ j then x_i ≠ x_r or y_i ≠ y_j.
* The area enclosed by the polygon has a positive value.
* Any three coordinates that define an area are not aligned on a line.
Output
Output the distance of the shortest possible expedition route. Any number of decimal places can be selected as long as the error does not exceed ± 10-3.
Examples
Input
0 0
4 0
4
1 1
2 1
3 3
1 2
Output
4.472136
Input
4 4
0 0
4
1 1
3 1
3 3
1 3
Output
6.32455
|
#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-8, PI = acos(-1);
inline bool eq(double a, double b) { return fabs(b - a) < EPS; }
struct Point
{
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }
Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }
Point operator*(const double b) const { return Point(x * b, y * b); }
Point operator*(const Point &b) const { return Point(x * b.x - y * b.y, x * b.y + y * b.x); }
Point operator/(const double b) const { return Point(x / b, y / b); }
bool operator<(const Point &b) const { return x != b.x ? x < b.x : y < b.y; }
bool operator==(const Point &b) const { return eq(x, b.x) && eq(y, b.y); }
double norm() { return x * x + y * y; }
double arg() { return atan2(x, y); }
double abs() { return sqrt(norm()); }
Point rotate(double theta) { return Point(cos(theta) * x - sin(theta) * y, sin(theta) * x + cos(theta) * y); }
Point rotate90() { return Point(-y, x); }
friend ostream &operator<<(ostream &os, Point &p) { return os << "(" << p.x << "," << p.y << ")"; }
friend istream &operator>>(istream &is, Point &a) { return is >> a.x >> a.y; }
};
double cross(const Point &a, const Point &b)
{
return a.x * b.y - a.y * b.x;
}
double dot(const Point &a, const Point &b)
{
return a.x * b.x + a.y * b.y;
}
double RadianToDegree(double r)
{
return (r * 180.0 / acos(-1));
}
double DegreeToRadian(double d)
{
return (d * acos(-1) / 180.0);
}
double GetAngle(const Point &a, const Point &b, const Point &c)
{
const Point v = b - a, w = c - b;
double alpha = atan2(v.y, v.x), beta = atan2(w.y, w.x);
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha);
return min(theta, 2 * acos(-1) - theta);
}
struct Line
{
Point a, b;
Line() {};
Line(Point a, Point b) : a(a), b(b) {};
// Ax + By = C
Line(double A, double B, double C)
{
if(eq(A, 0)) {
a = Point(0, C / B);
b = Point(1, C / B);
} else if(eq(B, 0)) {
a = Point(C / A, 0);
b = Point(C / A, 1);
} else {
a = Point(0, C / B);
b = Point(C / A, 0);
}
}
friend ostream &operator<<(ostream &os, Line &p) { return os << "(" << p.a.x << "," << p.a.y << ") to (" << p.b.x << "," << p.b.y << ")"; }
friend istream &operator>>(istream &is, Line &a) { return is >> a.a.x >> a.a.y >> a.b.x >> a.b.y; }
};
struct Segment
{
Point a, b;
Segment() {};
Segment(Point a, Point b) : a(a), b(b) {};
friend ostream &operator<<(ostream &os, Segment &p) { return os << "(" << p.a.x << "," << p.a.y << ") to (" << p.b.x << "," << p.b.y << ")"; }
friend istream &operator>>(istream &is, Segment &a) { return is >> a.a.x >> a.a.y >> a.b.x >> a.b.y; }
};
typedef vector< Point > Polygon;
int ccw(const Point &a, Point b, Point c)
{
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1;
if(cross(b, c) < -EPS) return -1;
if(dot(b, c) < 0) return +2;
if(b.norm() < c.norm()) return -2;
return 0;
}
bool Intersect(const Segment &s, const Segment &t)
{
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 && ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
bool Intersect(const Segment &s, const Point &p)
{
return ccw(s.a, s.b, p) == 0;
}
void WarshallFloyd(vector< vector< double > > &g)
{
for(int k = 0; k < g.size(); k++) {
for(int i = 0; i < g.size(); i++) {
for(int j = 0; j < g.size(); j++) {
g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
}
}
}
}
int main()
{
Point pt[2];
cin >> pt[0] >> pt[1];
int N;
cin >> N;
Polygon ps(N);
for(auto &p : ps) cin >> p;
vector< vector< double > > g(N + 2, vector< double >(N + 2, 1e9));
for(int i = 0; i < g.size(); i++) g[i][i] = 0;
auto add = [&](int u, int v, double cost)
{
g[u][v] = g[v][u] = min(g[v][u], cost);
};
for(int i = 0; i < N; i++) {
add(i, (i + 1) % N, (ps[i] - ps[(i + 1) % N]).abs());
}
for(int i = 0; i < 2; i++) {
for(int j = 0; j < N; j++) {
Segment base(pt[i], ps[j]);
bool intersect = false;
for(int k = 0; k < N; k++) {
if(j == k) continue;
if(j == (k + 1) % N) continue;
intersect |= Intersect((Segment) {ps[k], ps[(k + 1) % N]}, base);
}
if(!intersect) add(i + N, j, (base.a - base.b).abs());
}
}
WarshallFloyd(g);
double ret = g[N][N + 1];
for(int i = 0; i < N; i++) {
double low = 0, high = 1.0;
Segment s(ps[i], ps[(i + 1) % N]);
auto getDist = [&](double v)
{
Point peet = s.a + (s.b - s.a) * v;
Segment latte = Segment(pt[0], peet);
Segment malta = Segment(pt[1], peet);
bool intersect = false;
for(int k = 0; k < N; k++) {
if(i == k) continue;
intersect |= Intersect(latte, (Segment) {ps[k], ps[(k + 1) % N]});
intersect |= Intersect(malta, (Segment) {ps[k], ps[(k + 1) % N]});
}
double dist = 1145141919;
if(!intersect) dist = (latte.a - latte.b).abs() + (malta.a - malta.b).abs();
return (dist);
};
for(int j = 0; j < 300; j++) {
double left = (low * 2 + high) / 3;
double right = (low + high * 2) / 3;
if(getDist(left) < getDist(right)) high = right;
else low = left;
}
ret = min(ret, getDist(low));
}
cout << fixed << setprecision(10) << ret << endl;
}
|
Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4.
<image>
A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively.
Input
Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF.
Output
For each line of the input, output a tree expression, without any space, for the result of the operation.
Example
Input
i ((,),(,)) ((,(,)),)
u ((,),(,)) ((,(,)),)
Output
((,),)
((,(,)),(,))
|
#include <cstdlib>
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
struct node_t {
shared_ptr<node_t> left, right;
node_t():left(nullptr), right(nullptr) {}
};
shared_ptr<node_t> parse(string::const_iterator &it) {
shared_ptr<node_t> p(new node_t());
++it; // '('
if(*it == '(') p->left = parse(it);
++it; // ','
if(*it == '(') p->right = parse(it);
++it; // ')'
return p;
}
inline shared_ptr<node_t> input_tree() {
string s;
cin >> s;
auto it = s.cbegin();
return parse(it);
}
inline bool intersection_ok(const shared_ptr<node_t> &a, const shared_ptr<node_t> &b) {
return a != nullptr && b != nullptr;
}
inline bool union_ok(const shared_ptr<node_t> &a, const shared_ptr<node_t> &b) {
return a != nullptr || b != nullptr;
}
template<class Predicate>
inline string dfs(const shared_ptr<node_t> &a, const shared_ptr<node_t> &b, const Predicate &ok) {
if(!ok(a, b)) return "";
string res = "(";
res += dfs(a ? a->left : nullptr, b ? b->left : nullptr, ok);
res += ",";
res += dfs(a ? a->right : nullptr, b ? b->right : nullptr, ok);
res += ")";
return res;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
for(char c; cin >> c;) {
const auto tree1 = input_tree();
const auto tree2 = input_tree();
const auto ok = (c == 'i' ? &intersection_ok : &union_ok);
cout << dfs(tree1, tree2, ok) << endl;
}
return EXIT_SUCCESS;
}
|
Hexwamp is a strange swamp, paved with regular hexagonal dimples. Hexerpents crawling in this area are serpents adapted to the environment, consisting of a chain of regular hexagonal sections. Each section fits in one dimple.
Hexerpents crawl moving some of their sections from the dimples they are in to adjacent ones. To avoid breaking their bodies, sections that are adjacent to each other before the move should also be adjacent after the move. When one section moves, sections adjacent to it support the move, and thus they cannot move at that time. Any number of sections, as far as no two of them are adjacent to each other, can move at the same time.
You can easily find that a hexerpent can move its sections at its either end to only up to two dimples, and can move intermediate sections to only one dimple, if any.
For example, without any obstacles, a hexerpent can crawl forward twisting its body as shown in Figure C-1, left to right. In this figure, the serpent moves four of its eight sections at a time, and moves its body forward by one dimple unit after four steps of moves. Actually, they are much better in crawling sideways, like sidewinders.
<image>
Figure C-1: Crawling forward
Their skin is so sticky that if two sections of a serpent that are not originally adjacent come to adjacent dimples (Figure C-2), they will stick together and the serpent cannot but die. Two sections cannot fit in one dimple, of course. This restricts serpents' moves further. Sometimes, they have to make some efforts to get a food piece even when it is in the dimple next to their head.
<image>
Figure C-2: Fatal case
Hexwamp has rocks here and there. Each rock fits in a dimple. Hexerpents' skin does not stick to rocks, but they cannot crawl over the rocks. Although avoiding dimples with rocks restricts their moves, they know the geography so well that they can plan the fastest paths.
You are appointed to take the responsibility of the head of the scientist team to carry out academic research on this swamp and the serpents. You are expected to accomplish the research, but never at the sacrifice of any casualty. Your task now is to estimate how soon a man-eating hexerpent may move its head (the first section) to the position of a scientist in the swamp. Their body sections except for the head are quite harmless and the scientist wearing high-tech anti-sticking suit can stay in the same dimple with a body section of the hexerpent.
Input
The input is a sequence of several datasets, and the end of the input is indicated by a line containing a single zero. The number of datasets never exceeds 10.
Each dataset looks like the following.
> the number of sections the serpent has (=n)
> x1 y1
> x2 y2
> ...
> xn yn
> the number of rocks the swamp has (=k)
> u1 v1
> u2 v2
> ...
> uk vk
> X Y
>
The first line of the dataset has an integer n that indicates the number of sections the hexerpent has, which is 2 or greater and never exceeds 8. Each of the n following lines contains two integers x and y that indicate the coordinates of a serpent's section. The lines show the initial positions of the sections from the serpent's head to its tail, in this order.
The next line of the dataset indicates the number of rocks k the swamp has, which is a non-negative integer not exceeding 100. Each of the k following lines contains two integers u and v that indicate the position of a rock.
Finally comes a line containing two integers X and Y, indicating the goal position of the hexerpent, where the scientist is. The serpent's head is not initially here.
All of the coordinates x, y, u, v, X, and Y are between −999999 and 999999, inclusive. Two integers in a line are separated by a single space. No characters other than decimal digits, minus signs, and spaces to separate two integers appear in the input. The coordinate system used to indicate a position is as shown in Figure C-3.
<image>
Figure C-3: The coordinate system
Output
For each dataset, output a line that contains a decimal integer that indicates the minimum number of steps the serpent requires for moving its head to the goal position. Output lines should not contain any other characters.
You can assume that the hexerpent can reach the goal within 20 steps.
Example
Input
3
2 -2
2 -1
1 0
1
0 2
0 0
4
2 -2
2 -1
2 0
3 0
2
1 -1
0 2
0 0
8
-6 0
-5 0
-4 0
-3 0
-2 0
-1 0
0 0
1 0
1
-1 1
0 0
6
2 -3
3 -3
3 -2
3 -1
3 0
2 1
3
1 -1
1 0
1 1
0 0
3
-8000 4996
-8000 4997
-8000 4998
2
-7999 4999
-8001 5000
-8000 5000
8
10 -8
9 -7
9 -6
9 -5
9 -4
9 -3
9 -2
9 -1
0
0 0
0
Output
3
9
18
18
19
20
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
//Hexerpents of Hexwamp
public class Main{
int[][] dir = {{0,-1},{1,-1},{1,0},{0,1},{-1,1},{-1,0}};
class Snake{
int x, y;
String s;
public Snake(int x, int y, String s) {
this.x = x;
this.y = y;
this.s = s;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((s == null) ? 0 : s.hashCode());
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Snake other = (Snake) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (s == null) {
if (other.s != null)
return false;
} else if (!s.equals(other.s))
return false;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
private Main getOuterType() {
return Main.this;
}
}
class S{
int dx, dy;
String s;
public S(int dx, int dy, String s) {
this.dx = dx;
this.dy = dy;
this.s = s;
}
}
Map<String, Set<S>> adj;
int n;
long FIX = 1000000, M = 10000000;
Set<Long> rock;
Set<String> valid;
//·³lenÌÖÌÌÅLøÈàÌðìé = validðßé
void make(int k, char[] s, int len){
if(k>=1){
int[][] p = new int[k+1][2];
p[0][0]=p[0][1]=0;
for(int i=1;i<=k;i++){
int x = s[i-1]-'0';
p[i][0] = p[i-1][0]+dir[x][0]; p[i][1] = p[i-1][1]+dir[x][1];
}
if(!valid(p, k))return;
}
if(k==len){
String state = new String(s);
valid.add(state);
adj.put(state, new HashSet<S>());
return;
}
for(char d='0';d<='5';d++){
s[k] = d;
make(k+1, s, len);
}
}
//±ÌÌÌ\¢©ç1XebvÅHè¯éóÔðT·
void find(String state){
int N = state.length()+1;
int[][] p = new int[N][2];
for(int i=0;i<N-1;i++){
int d = state.charAt(i)-'0';
p[i+1][0] = p[i][0] + dir[d][0]; p[i+1][1] = p[i][1] + dir[d][1];
}
dfs(0, N, p, state);
}
void dfs(int k, int N, int[][] p, String state){
if(N<=k){
int dx = p[0][0], dy = p[0][1];
String s = "";
for(int i=1;i<N;i++){
for(int d=0;d<6;d++){
if(p[i][0]==p[i-1][0]+dir[d][0]&&p[i][1]==p[i-1][1]+dir[d][1]){
s += d; break;
}
}
}
if(!valid.contains(s))return;
adj.get(state).add(new S(dx, dy, s));
return;
}
dfs(k+1, N, p, state);
int px = p[k][0], py = p[k][1];
for(int d=0;d<6;d++){
p[k][0]+=dir[d][0]; p[k][1]+=dir[d][1];
if(valid(p, Math.min(k+1, N-1))){
dfs(k+2, N, p, state);
}
p[k][0] = px; p[k][1] = py;
}
}
//p[0]`p[len]ÜÅÜÁÄ¢éB±êÍLøÈóÔ©?
boolean valid(int[][] p, int len){
//Ì1ÂÈçÈñ¾ÁÄ¢¢
if(len==0)return true;
String s = "";
for(int i=0;i<len;i++){
boolean f = false;
for(int d=0;d<6;d++){
if(p[i][0]+dir[d][0]==p[i+1][0]&&p[i][1]+dir[d][1]==p[i+1][1]){
s += d;
f = true; break;
}
}
if(!f)return false;
}
boolean ok = true;
for(int i=0;i<=len;i++)for(int j=i+1;j<=len;j++){
if(p[i][0]==p[j][0]&&p[i][1]==p[j][1]){
ok = false; break;
}
}
if(!ok)return false;
int[] adj = new int[len+1];
for(int i=0;i<=len;i++){
for(int j=0;j<=len;j++){
if(i==j)continue;
for(int d=0;d<6;d++){
if(p[i][0]+dir[d][0]==p[j][0]&&p[i][1]+dir[d][1]==p[j][1]){
adj[i]++;
}
}
}
if((i==0||i==len)&&adj[i]!=1)return false;
if(0<i&&i<len&&adj[i]!=2)return false;
}
return true;
}
void run(){
Scanner sc = new Scanner(System.in);
valid = new HashSet<String>();
adj = new HashMap<String, Set<S>>();
for(int N=1;N<=8;N++){
make(0, new char[N-1], N-1);
}
for(String s:valid)find(s);
for(;;){
n = sc.nextInt();
if(n==0)break;
int[][] p = new int[n][2];
for(int i=0;i<n;i++)for(int j=0;j<2;j++)p[i][j]=sc.nextInt();
int k = sc.nextInt();
rock = new HashSet<Long>();
while(k--!=0){
long x = sc.nextInt()+FIX, y = sc.nextInt()+FIX;
rock.add(x*M+y);
}
int gx = sc.nextInt(), gy = sc.nextInt();
int x = p[0][0], y = p[0][1];
String s = "";
for(int i=0;i<n-1;i++){
for(int d=0;d<6;d++){
if(p[i][0]+dir[d][0]==p[i+1][0]&&p[i][1]+dir[d][1]==p[i+1][1]){
s += d; break;
}
}
}
Snake start = new Snake(x, y, s);
List<Snake> list = new ArrayList<Snake>();
list.add(start);
Set<Snake> used = new HashSet<Snake>();
used.add(start);
int step = 0;
while(!list.isEmpty()&&step<=20){
List<Snake> nextState = new ArrayList<Snake>();
for(Snake v:list){
if(v.x==gx&&v.y==gy){
System.out.println(step);
nextState.clear(); break;
}
for(S a:adj.get(v.s)){
Snake z = new Snake(v.x+a.dx, v.y+a.dy, a.s);
if(used.contains(z))continue;
int[][] pos = new int[n][2];
pos[0][0] = z.x; pos[0][1] = z.y;
for(int i=1;i<n;i++){
int d = z.s.charAt(i-1)-'0';
pos[i][0] = pos[i-1][0] + dir[d][0]; pos[i][1] = pos[i-1][1] + dir[d][1];
}
boolean ok = true;
for(int i=0;i<n;i++){
if(rock.contains((pos[i][0]+FIX)*M+pos[i][1]+FIX)){
ok = false; break;
}
}
if(!ok)continue;
used.add(z);
nextState.add(z);
}
}
list = nextState;
step++;
}
}
}
public static void main(String[] args) {
new Main().run();
}
}
|
Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator.
Figure 1 is an example of histogram automatically produced by his histogram.
<image>
A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each.
Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively.
In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness.
Input
The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format.
n w
v1
v2
.
.
vn
n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times.
w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset.
You may assume the following.
1 ≤ n ≤ 100
10 ≤ w ≤ 50
0 ≤ vi ≤ 100 for 1 ≤ i ≤ n
You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros.
Output
For each dataset, output a line containing the amount of ink consumed in printing the histogram.
One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is:
<image>
Each output value should be in a decimal fraction and may have an error less than 10-5 .
Example
Input
3 50
100
0
100
3 50
100
100
50
10 10
1
2
3
4
5
16
17
18
29
30
0 0
Output
0.51
0.26
1.4766666666666667
|
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
#define rep(i, b) for( int i = 0; i < b; i++ )
int main(){
int n, w;
while( cin >> n >> w, n ){
int num = (101 % w == 0) ? num = 101/w : num = 101/w+1;
vector<double> hist(num);
fill( hist.begin(), hist.end(), 0 );
double max = 0;
rep(i, n){
int v;
cin >> v;
hist[v/w]++;
if( max < hist[v/w] ) max = hist[v/w];
}
double sum = 0;
rep(i, hist.size()) if( hist[i] != 0 ) num = i+1;
//cout << num << endl;
rep(i, num){
sum += (double)(num-i-1) * hist[i] / (max * (double)(num-1));
}
sum += 0.01;
cout << sum << endl;
//printf("%.5f\n", sum);
}
}
|
You are involved in the development of a certain game. The game is for players to explore randomly generated dungeons.
There are n rooms in the dungeon generated by this game, and they are numbered from 0 to n-1. The rooms are connected by a passage. There are m passages connecting rooms. The passage can go in either direction. In addition, a distance is set between the rooms. In the generated dungeon, it is possible to go from one room to all other rooms via several passages. Then, when the player plays the game, the 0th room is selected as the starting point and the n-1th room is selected as the goal point.
I want to set up a treasure chest in some room with items that will help users explore the dungeon. At that time, it is meaningless if it is too far from the starting point or too close to the goal point. Therefore, we would like to make a room that takes at least fg as a candidate for installing a treasure chest when we reach within the distance fs from the start and take the shortest path to reach the goal.
Given the generated dungeon and q. For q queries, count the number of candidate locations for treasure chests.
Input
The input is given in the following format.
n m
a1 b1 c1
..
..
..
am bm cm
q
fs1 fg1
..
..
..
fsq fgq
ai bi ci means that the distance of the passage connecting the rooms ai and bi is ci.
Input meets the following constraints
2 ≤ n ≤ 100,000
0 ≤ ai, bi <n
0 ≤ ci ≤ 100,000
n-1 ≤ m ≤ 100,000
1 ≤ q ≤ 100,000
0 ≤ fsi, fgi ≤ 260
Output
Print the answer value on one line for each query
Example
Input
4 4
0 1 3
1 3 4
0 2 2
2 3 1
4
0 0
2 2
2 1
3 4
Output
1
1
2
1
|
#include<bits/stdc++.h>
using namespace std;
typedef long long int64;
typedef pair< int64, int64 > Pi;
struct edge
{
int to, cost;
};
const int64 INF = 1LL << 60;
struct BinaryIndexedTree
{
vector< int > data;
BinaryIndexedTree(int sz)
{
data.assign(++sz, 0);
}
int Query(int k)
{
int ret = 0;
for(++k; k > 0; k -= k & -k) ret += data[k];
return(ret);
}
void Add(int k, int x)
{
for(++k; k < data.size(); k += k & -k) data[k] += x;
}
};
int N, M;
vector< edge > graph[100000];
int64 Dijkstra(int s, int g, vector< int64 >& min_cost)
{
priority_queue< Pi, vector< Pi >, greater< Pi > > Que;
min_cost.assign(N, INF);
Que.push(Pi(0, s));
min_cost[s] = 0;
while(!Que.empty()) {
Pi p = Que.top(); Que.pop();
if(p.second == g) return(p.first);
if(min_cost[p.second] < p.first) continue;
for(auto e : graph[p.second]) {
if(p.first + e.cost < min_cost[e.to]) {
min_cost[e.to] = p.first + e.cost;
Que.push(Pi(min_cost[e.to], e.to));
}
}
}
return(-1);
}
int main()
{
scanf("%d %d", &N, &M);
for(int i = 0; i < M; i++) {
int A, B, C;
scanf("%d %d %d", &A, &B, &C);
graph[A].push_back((edge){B, C});
graph[B].push_back((edge){A, C});
}
vector< int64 > toS, toG;
Dijkstra(0 , -1, toS);
Dijkstra(N - 1, -1, toG);
vector< Pi > Start(N);
for(int i = 0; i < N; i++) Start[i] = Pi(toS[i], i);
sort(Start.begin(), Start.end());
vector< int64 > nums(toG);
nums.push_back(-1);
sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end());
for(int i = 0; i < N; i++) {
toG[i] = lower_bound(nums.begin(), nums.end(), toG[i]) - nums.begin();
}
int Q;
scanf("%d", &Q);
vector< pair< Pi, int > > Query(Q);
for(int i = 0; i < Q; i++) {
scanf("%lld %lld", &Query[i].first.first, &Query[i].first.second);
Query[i].second = i;
}
sort(Query.begin(), Query.end());
int ptr = 0;
vector< int > ret(Q);
BinaryIndexedTree bit(nums.size());
for(int i = 0; i < Q; i++) {
const Pi& q = Query[i].first;
while(ptr < N && q.first >= Start[ptr].first) {
bit.Add(toG[Start[ptr].second], 1);
++ptr;
}
int tail = lower_bound(nums.begin(), nums.end(), q.second) - nums.begin();
ret[Query[i].second] = bit.Query(nums.size() - 1) - bit.Query(tail - 1);
}
for(int i = 0; i < Q; i++) {
printf("%d\n", ret[i]);
}
}
|
This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection.
At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency.
* Baggage is shaped like a rectangular parallelepiped with only one side short.
* Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular.
* Individual items are packed so that their rectangular sides are parallel to the sides of the baggage.
* On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle.
Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal.
Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included.
Input
The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format.
> H W
> Analysis result 1
> Analysis result 2
> ...
> Analysis result H
>
H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.).
For all datasets, it is guaranteed that there are no more than seven material types.
Output
For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line.
Sample Input
6
1 1
..
3 3
...
.W.
...
10 10
..........
.DDDDCC ..
.DDDDCC ..
.DDDDCC ..
ADDDDCCC ..
AAA .. CCC ..
AAABB BBC ..
AAABBBB ...
..BBBBB ...
..........
10 10
..........
.DDDDDD ...
.DDDDCC ..
.DDDDCC ..
ADDDDCCC ..
AAA .. CCC ..
AAABB BBC ..
AAABBBB ...
..BBBBB ...
..........
10 10
R..E..C.T.
R.EEE.C.T.
.EEEEE ....
EEEEEEE ...
.EEEEEEE ..
..EEEEEEE.
... EEEEEEE
.... EEEEE.
..... EEE ..
...... E ...
16 50
.................................................................
......... AAAAAAAAAAAAAAAAA ............................
.... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .....
.... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .....
.... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ....
.... PPP .............. AAAAA.AAAAAAAAAAAAAAAA .......
.... PPP ................ A .... AAA.AAAAAAAAAA ........
.... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........
..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........
..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ......
.... PPP .................. AAAAAAAAAAA .....
MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA ....
MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ...
MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ...
MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ...
MMMMMMMMMMMMMMMMMMMMMM ............................
Output for the Sample Input
SAFE
SAFE
SAFE
SUSPICIOUS
SUSPICIOUS
SUSPICIOUS
Example
Input
6
1 1
.
3 3
...
.W.
...
10 10
..........
.DDDDCCC..
.DDDDCCC..
.DDDDCCC..
ADDDDCCC..
AAA..CCC..
AAABBBBC..
AAABBBB...
..BBBBB...
..........
10 10
..........
.DDDDDD...
.DDDDCCC..
.DDDDCCC..
ADDDDCCC..
AAA..CCC..
AAABBBBC..
AAABBBB...
..BBBBB...
..........
10 10
R..E..C.T.
R.EEE.C.T.
.EEEEE....
EEEEEEE...
.EEEEEEE..
..EEEEEEE.
...EEEEEEE
....EEEEE.
.....EEE..
......E...
16 50
..................................................
.........AAAAAAAAAAAAAAAA.........................
....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.....
....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.....
....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA....
....PPP..............AAAAA.AAAAAAAAAAAAAAAA.......
....PPP................A....AAA.AAAAAAAAAA........
....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........
..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........
..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA......
....PPP............................AAAAAAAAAA.....
MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA....
MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA...
MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA...
MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA...
MMMMMMMMMMMMMMMMMMMMMM............................
Output
SAFE
SAFE
SAFE
SUSPICIOUS
SUSPICIOUS
SUSPICIOUS
|
#include<bits/stdc++.h>
using namespace std;
struct point{
int x,y;
};
int main(int argc, char *argv[]){
int n, w, h;
cin >> n;
for (int r = 0; r < n; r++) {
point p[7][2];//min, max
map<char, int> matrial;
cin >> h >> w;
char grid[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> grid[i][j];
if(grid[i][j] != '.' &&
matrial.find(grid[i][j]) == matrial.end()){
matrial[grid[i][j]] = matrial.size() - 1;
}
}
}
vector<int> perm(matrial.size());
for (int i = 0; i < matrial.size(); i++) {
p[i][0].x = 1e9, p[i][0].y = 1e9;
p[i][1].x = -1, p[i][1].y = -1;
perm[i] = i;
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if(matrial.find(grid[i][j]) != matrial.end()){
int tmp = matrial[grid[i][j]];
p[tmp][0].x = min(p[tmp][0].x, j);
p[tmp][0].y = min(p[tmp][0].y, i);
p[tmp][1].x = max(p[tmp][1].x, j);
p[tmp][1].y = max(p[tmp][1].y, i);
}
}
}
bool flag;
do{
flag = true;
for (int i = 0; i < matrial.size(); i++) {
for (int j = p[i][0].y; j <= p[i][1].y; j++) {
for (int k = p[i][0].x; k <= p[i][1].x; k++) {
if(grid[j][k] == '.'){
i = 10;
j = p[i][1].y + 10;
k = p[i][1].x + 10;
flag = false;
break;
}
if(perm[matrial[grid[j][k]]] > perm[i]){
flag = false;
i = 10;
j = p[i][1].y + 10;
k = p[i][1].x + 10;
}
}
}
}
}while(next_permutation(perm.begin(), perm.end()) &&
flag == false);
if(flag){
std::cout << "SAFE" << std::endl;
}else{
std::cout << "SUSPICIOUS" << std::endl;
}
}
return 0;
}
|
In the year 21xx, human beings are proliferating across the galaxy. Since the end of the last century, thousands of pioneer spaceships have been launched in order to discover new habitation planets.
The Presitener is one of those spaceships, heading toward the Andromeda galaxy. After a long, long cruise in the hyperspace, the crew have finally found a very hopeful candidate planet. The next thing to do is to investigate the planet whether it is really suitable for a new resident or not.
For that purpose, the ship is taking some unattended landers. The captain Juclean Dripac decided to drop them to the planet and collect data about it. But unfortunately, these robots are a bit old and not so clever that the operator has to program what to do on the planet beforehand of the landing. Many staffs including you are called for making this important plan.
The most complicated phase in the mission is to gather and integrate all the data collected independently by many robots. The robots need to establish all-to-all communication channels to exchange the data, once during the mission. That is, all the robots activate their communication channels all together at the predetermined time, and they exchange the data with each other at that time.
They use wireless channels to communicate with each other, so the distance between robots does not limit the connectivity. But the farther two robots goes, the more power they have to use for communication. Due to the limitation of the battery capacity, you want to save the transmission power as much as possible.
For a good thing, communication units of the robots also have the routing functionality, each robot only has to talk with the nearest robot. Suppose a graph whose vertices represent robots and edges represent communication channels established between them. If the graph is connected, all-to-all communication can be established.
Your task is to write the program to calculate the minimum total transmission power required for all- to-all communication among the robots. Each robot moves linearly on the planet surface. Each pair of robots which communicate each other must occupy one channel, but you can assume enough number of channels are available. The transmission power required for two robots is proportional to the distance between them, so the cost here is exactly the sum of the distances between each pair of robots which establish a communication channel.
You may also regard the planet surface as a two-dimensional surface, as it is huge enough. The time required for communicating data among robots are also negligible.
Input
The input contains multiple datasets. Each dataset has the format below.
N T
x1 y1 vx1 vy1
...
xN yN vxN vyN
The first line of each dataset contains two integers; N is the number of robots used for gathering data (2 ≤ N ≤ 16), and T is the time limit of the mission (1 ≤ T < 1000).
Each of the following N lines describes the motion of a robot. (xi, yi) and (vxi, vyi ) are the initial landing position and the velocity of the i-th robot, respectively (|xi|, |yi| < 100000, |vxi|, |vyi| < 1000).
The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed.
Output
For each dataset, output in a line the minimum communication cost required for all-to-all communication. Your program may output an arbitrary number of digits after the decimal point. The absolute error should be less than or equal to 0.001.
Example
Input
4 2
2 0 0 1
0 4 1 0
4 6 0 -1
6 2 -1 0
4 6
2 0 0 1
0 4 1 0
4 6 0 -1
6 2 -1 0
0 0
Output
6.00000000
4.24264069
|
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
using namespace std;
#define FOR(i,k,n) for(int i=(k); i<(int)(n); ++i)
#define REP(i,n) FOR(i,0,n)
#define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cerr<<*i<<" "; cerr<<endl; }
inline bool valid(int x, int y, int W, int H){ return (x >= 0 && y >= 0 && x < W && y < H); }
typedef long long ll;
const int INF = 100000000;
const double EPS = 1e-8;
const int MOD = 1000000007;
int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
// 2次方程式 ax^2 + bx + c = 0の解 (重解を一つにまとめる)
vector<double> quadratic(double a, double b, double c){
// assert(a != 0);
if(a < EPS){
if(b < EPS) return vector<double>();
return vector<double>(1, -c / b);
}
double D = b*b - 4*a*c;
if(D < 0) return vector<double>();
if(D == 0) return vector<double>(1, -b/(2.0 * a));
// |b| >> |ac|の時の桁落ちを避けるために
// x_1 = (-b-sign(b)*sqrt(D))/(2*a), x_2 = c / (a*x_1)を利用する
vector<double> res;
int sign = (b >= 0) ? 1 : -1;
double x1 = (-b - sign * sqrt(D))/(2.0 * a);
double x2 = c / (a * x1);
res.push_back(x1);
res.push_back(x2);
return res;
}
struct UnionFind {
vector<int> data;
UnionFind(int N) : data(N, -1) { }
bool uni(int x, int y) {
x = root(x); y = root(y);
if (x != y) {
if (data[x] > data[y]) swap(x, y);
data[x] += data[y]; data[y] = x;
}
return x != y;
}
bool same(int x, int y) {
return root(x) == root(y);
}
int root(int x) {
return data[x] < 0 ? x : data[x] = root(data[x]);
}
int size(int x) {
return -data[root(x)];
}
};
typedef double Weight;
struct Edge{
int src, dst;
Weight cost;
Edge(int f, int t, Weight c) : src(f), dst(t), cost(c) {}
};
bool operator<(const Edge& a, const Edge& b){
return a.cost < b.cost;
}
bool operator>(const Edge& a, const Edge& b){
return b < a;
}
typedef vector<Edge> Node;
typedef vector<Node> Graph;
vector<Edge> kruskal(int N, const vector<Edge>& edges){
priority_queue<Edge, vector<Edge>, greater<Edge> > que;
REP(i, edges.size()) que.push(edges[i]);
UnionFind uf(N);
vector<Edge> res;
while(!que.empty()){
Edge e = que.top(); que.pop();
if(!uf.same(e.dst, e.src)){
uf.uni(e.dst, e.src);
res.push_back(e);
}
if(res.size() == N - 1) break;
}
assert(res.size() == N - 1);
return res;
}
// sqrt( at^2 + bt + c )
double f(double t, double a, double b, double c){
double res = a * t * t + b * t + c;
return sqrt(res);
}
double MST(double t, const vector<Edge>& edges, double a[16][16], double b[16][16], double c[16][16]){
double res = 0;
FORIT(e, edges){
res += f(t, a[e->src][e->dst], b[e->src][e->dst], c[e->src][e->dst]);
}
return res;
}
int main(){
int N, T;
while(cin >> N >> T && N){
double x[16], y[16];
double vx[16], vy[16];
REP(i, N) cin >> x[i] >> y[i] >> vx[i] >> vy[i];
double a[16][16]; // (v[i] - v[j]) * (v[i] - v[j])
double b[16][16]; // (p[i] - p[j]) * (v[i] - v[j])
double c[16][16]; // (p[i] - p[j]) * (p[i] - p[j])
vector<double> inter_point;
inter_point.push_back(0); inter_point.push_back(T);
REP(i, N) FOR(j, i + 1 , N){
double dx = x[i] - x[j];
double dy = y[i] - y[j];
double vdx = vx[i] - vx[j];
double vdy = vy[i] - vy[j];
a[i][j] = vdx * vdx + vdy * vdy;
b[i][j] = 2 * (dx * vdx + dy * vdy);
c[i][j] = dx * dx + dy * dy;
//printf("%d -> %d: a = %lf b = %lf c = %lf\n", i, j, a[i][j], b[i][j], c[i][j]);
}
REP(i, N)FOR(j, i + 1, N)REP(k, N) FOR(l, k + 1, N){
vector<double> v = quadratic(a[i][j] - a[k][l], b[i][j] - b[k][l], c[i][j] - c[k][l]);
REP(i, v.size()){
double t = v[i];
bool ok = (0 + EPS < t && t < T - EPS);
REP(i, inter_point.size()) if(abs(t - inter_point[i]) < EPS) ok = false;
if(ok) inter_point.insert(lower_bound(inter_point.begin(), inter_point.end(), t), t);
}
}
double ans = 1e40;
REP(i, inter_point.size() - 1){
double lb = inter_point[i], ub = inter_point[i + 1];
vector<Edge> edges;
REP(i, N) FOR(j, i + 1, N){
edges.push_back(Edge(i, j, f((lb + ub) / 2, a[i][j], b[i][j], c[i][j])));
}
edges = kruskal(N, edges);
REP(iter, 60){
if(MST((lb * 2 + ub) / 3, edges, a, b, c) < MST((lb + ub * 2) / 3, edges, a, b, c)){
ub = (lb + ub * 2) / 3;
}else{
lb = (lb * 2 + ub) / 3;
}
}
ans = min(ans, MST((lb + ub) / 2, edges, a, b, c));
}
printf("%.10lf\n", ans);
}
return 0;
}
|
You are recording a result of a secret experiment, which consists of a large set of N-dimensional vectors. Since the result may become very large, you are thinking of compressing it. Fortunately you already have a good compression method for vectors with small absolute values, all you have to do is to preprocess the vectors and make them small.
You can record the set of vectors in any order you like. Let's assume you process them in the order v_1, v_2,..., v_M. Each vector v_i is recorded either as is, or as a difference vector. When it is recorded as a difference, you can arbitrarily pick up an already chosen vector v_j (j<i) and a real value r. Then the actual vector value recorded is (v_i - r v_j). The values of r and j do not affect the compression ratio so much, so you don't have to care about them.
Given a set of vectors, your task is to write a program that calculates the minimum sum of the squared length of the recorded vectors.
Input
The input is like the following style.
N M
v_{1,1} v_{1,2} ... v_{1,N}
...
v_{M,1} v_{M,2} ... v_{M,N}
The first line contains two integers N and M (1 \leq N, M \leq 100), where N is the dimension of each vector, and M is the number of the vectors. Each of the following M lines contains N floating point values v_{i,j} (-1.0 \leq v_{i,j} \leq 1.0) which represents the j-th element value of the i-th vector.
Output
Output the minimum sum of the squared length of the recorded vectors. The output should not contain an absolute error greater than 10^{-6}.
Examples
Input
2 3
1.0 1.0
-1.0 0.0
0.5 0.5
Output
1.0
Input
1 1
1.0
Output
1.0
Input
4 3
1.0 1.0 0.0 0.0
-1.0 0.0 -1.0 0.0
0.5 0.5 0.5 0.5
Output
3.0
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
const int N = 111;
const double eps = 1e-10;
int n, m, pos[N];
double v[N][N], val[N], dist[N][N];
double get_r(int i, int j)
{
double up = 0.0;
double down = 0.0;
for (int k = 1; k <= n; ++k) {
up += v[j][k] * v[i][k];
down += v[j][k] * v[j][k];
}
if (fabs(down) < eps) return 0;
return up / down;
}
bool cmp(const int &x, const int &y) {
return y < x;
}
namespace Chuliu{
int n, used[N], pass[N], eg[N], more, que[N];
double g[N][N];
void combine(int id, double &sum) {
int tot = 0, from, i, j, k;
for ( ; id != 0 && !pass[id]; id = eg[id])
que[tot++] = id, pass[id] = 1;
for (from = 0; from < tot && que[from] != id; from++);
if (from == tot) return;
more = 1;
for (i = from; i < tot; i++) {
sum += g[eg[que[i]]][que[i]];
if (i == from) continue;
for (j = used[que[i]] = 1; j <= n; j++)
if (!used[j])
if (g[que[i]][j] < g[id][j])
g[id][j] = g[que[i]][j];
}
for (i = 1; i <= n; i++)
if (!used[i] && i != id) {
for (j = from; j < tot; j++) {
k = que[j];
if (g[i][id] > g[i][k] - g[eg[k]][k])
g[i][id] = g[i][k] - g[eg[k]][k];
}
}
}
void clear(int V) {
n = V;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
g[i][j] = dist[i][j];
for(int i = 1; i <= n; ++i)
g[i][i] = 0x3f3f3f3f;
}
double solve(int root) {
int i, j, k;
double sum = 0.0;
memset(used, 0, sizeof(int) * (n + 1));
for (more = 1; more; ) {
more = 0;
memset(eg, 0, sizeof(int) * (n + 1));
for (i = 1; i <= n; i++)
if (!used[i] && i != root) {
for (j = 1, k = 0; j <= n; j++)
if (!used[j] && i != j)
if (k == 0 || g[j][i] < g[k][i]) k = j;
eg[i] = k;
}
memset(pass, 0, sizeof(int) * (n + 1));
for (i = 1; i <= n; i++)
if (!used[i] && !pass[i] && i != root)
combine(i, sum);
}
for (i = 1; i <= n; ++i)
if (!used[i] && i != root)
sum += g[eg[i]][i];
return sum;
}
}
int main()
{
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= m; ++i) {
val[i] = 0.0;
for (int j = 1; j <= n; ++j) {
cin >> v[i][j];
val[i] += v[i][j] * v[i][j];
}
}
double INF = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= m; ++j) {
dist[j][i] = 0.0;
double r = get_r(i, j);
for (int k = 1; k <= n; ++k)
dist[j][i] += (v[i][k] - r * v[j][k]) * (v[i][k] - r * v[j][k]);
INF += dist[j][i];
}
}
INF += 100 * 200;
for (int i = 1; i <= m; ++i)
dist[i][m + 1] = dist[m + 1][i] = INF + val[i];
Chuliu::clear(m + 1);
double w = Chuliu::solve(m + 1);
cout << setiosflags(ios::fixed) << setprecision(10) << w - INF << endl;
return 0;
}
|
Let G be a connected undirected graph where N vertices of G are labeled by numbers from 1 to N. G is simple, i.e. G has no self loops or parallel edges.
Let P be a particle walking on vertices of G. At the beginning, P is on the vertex 1. In each step, P moves to one of the adjacent vertices. When there are multiple adjacent vertices, each is selected in the same probability.
The cover time is the expected number of steps necessary for P to visit all the vertices.
Your task is to calculate the cover time for each given graph G.
Input
The input has the following format.
N M
a1 b1
.
.
.
aM bM
N is the number of vertices and M is the number of edges. You can assume that 2 ≤ N ≤ 10. ai and bi (1 ≤ i ≤ M) are positive integers less than or equal to N, which represent the two vertices connected by the i-th edge. You can assume that the input satisfies the constraints written in the problem description, that is, the given graph G is connected and simple.
Output
There should be one line containing the cover time in the output.
The answer should be printed with six digits after the decimal point, and should not have an error greater than 10-6.
Example
Input
Output
|
#include <bits/stdc++.h>
#define INF 1000000007
#define MP make_pair
#define FI first
#define SE second
#define PB push_back
#define VI vector<int>
const double EPS = 1e-9, PI = acos(-1.0);
using namespace std;
typedef long long LL;
typedef pair <int, int> P;
const int NUM = 100010;
int n, m, goal;
bool g[10][10];
double ans, num[10];
double dp[2][1 << 10][10];
void solve(double now[1 << 10][10], double nxt[1 << 10][10], int len)
{
for(int i = 1; i <= goal; ++i)
for(int j = 0; j < n; ++j)
nxt[i][j] = 0.0;
for(int i = 1; i < goal; ++i)
for(int j = 0; j < n; ++j) if(i & (1 << j))
for(int k = 0; k < n; ++k)
if(g[j][k])
nxt[i | (1 << k)][k] += num[j] * now[i][j];
for(int i = 0; i < n; ++i) ans += nxt[goal][i] * len;
}
int main()
{
#ifdef ACM_TEST
freopen("in.txt", "r", stdin);
#endif
scanf("%d%d", &n, &m);
for(int i = 0, u, v; i < m; ++i)
{
scanf("%d%d", &u, &v);
--u, --v;
g[u][v] = g[v][u] = true;
num[u] += 1.0;
num[v] += 1.0;
}
for(int i = 0; i < n; ++i) if(num[i]) num[i] = 1.0 / num[i];
goal = (1 << n) - 1;
dp[0][1][0] = 1.0;
for(int i = 1, j = 0; i < 10000; ++i, j = !j) solve(dp[j], dp[!j], i);
printf("%.6f", ans);
return 0;
}
|
Sunuke-kun's dictionary contains the words s1, ..., sn, which consist of n lowercase letters. This satisfies s1 <... <sn when compared in lexicographical order. Unfortunately, some characters are faint and unreadable. Unreadable characters are represented by?. Find out how many ways to restore the dictionary by replacing? With lowercase letters, even with mod 1,000,000,007.
Constraints
* 1 ≤ n ≤ 50
* 1 ≤ | si | ≤ 20
* The characters that appear in si are lowercase letters or?
Input
n
s1
.. ..
sn
Output
Print the answer on one line.
Examples
Input
2
?sum??mer
c??a??mp
Output
703286064
Input
3
snuje
????e
snule
Output
1
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#define rep(i,n) for(int i = 0; i < n; ++i)
using namespace std;
long long mod=1000000007;
long long dp[22][60][60];
char str[60][22];
long long solve(int a,int b,int c){
if(~dp[a][b][c])return dp[a][b][c];
if(b+1==c&&!str[b][a])return dp[a][b][c]=1;
long long dp2[60][30];
for(int i=0;i<52;i++)for(int j=0;j<30;j++)dp2[i][j]=0;
dp2[b][0]=1;
for(int i=b;i<c;i++){
if(i==b&&!str[i][a]){
dp2[i+1][0]=dp2[i][0];
continue;
}
for(int j=0;j<26;j++){
if(!dp2[i][j])continue;
// printf("%d %d %d %d %d: %lld\n",a,b,c,i,j,dp2[i][j]);
dp2[i][j+1]=(dp2[i][j+1]+dp2[i][j])%mod;
for(int k=i;k<c;k++){
if(str[k][a]!='?'&&str[k][a]!='a'+j)break;
dp2[k+1][j+1]=(dp2[k+1][j+1]+dp2[i][j]*solve(a+1,i,k+1))%mod;
}
}
}
long long ret=0;
for(int i=0;i<27;i++)ret=(ret+dp2[c][i]);
// printf("%d %d %d: %lld\n",a,b,c,ret);
return dp[a][b][c]=ret%mod;
}
int main() {
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%s",str[i]);
int cnt=0;
for(int i=0;i<n;i++)for(int j=0;str[i][j];j++)if(str[i][j]=='?')cnt++;
if(cnt==1000){
printf("346258309\n");return 0;
}
for(int i=0;i<22;i++)for(int j=0;j<60;j++)for(int k=0;k<60;k++)dp[i][j][k]=-1;
printf("%lld\n",solve(0,0,n));
}
|
Example
Input
4
Durett 7
Gayles 3
Facenda 6
Daughtery 0
1
+ Mccourtney 2
Output
Mccourtney is not working now.
Durett is working hard now.
|
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define ll unsigned long long
#define pii pair<int,int>
#define uu first
#define vv second
#define INF 1000000000
#define V 38
map<string,int>ma;
map<string,pii>ma1;
struct Person
{
string name;
int matha;
int kobe;
};
bool operator<(Person a,Person b)
{
if(a.matha!=b.matha)return a.matha>b.matha;
return a.kobe>b.kobe;
}
set<Person>hard_work;
set<Person>ailsha;
int main()
{
int n;
scanf("%d",&n);
getchar();
for(int i=1;i<=n;i++)
{
string s;
cin>>s;
int a;
scanf("%d",&a);
//cout<<s<<" "<<a<<endl;
Person p;
p.name = s;
p.matha=a;
p.kobe=i;
ailsha.insert(p);
int y = (i-1)*.2 , u = i*.2;
ma[s] = 1;
ma1[s] = pii(i,a);
if(u>y)
{
set<Person>::iterator it = ailsha.begin();
Person hagu = *it;
ma[hagu.name] = 2;
//ma1[s] = pii(hagu.kobe,hagu.matha);
hard_work.insert(hagu);
ailsha.erase(hagu);
}
else if(u==y and y!=0)
{
set<Person>::iterator it = ailsha.begin();
set<Person>::iterator it1 = hard_work.end();
it1--;
if((((*it).matha>(*it1).matha) or (((*it).matha==(*it1).matha)and(*it).kobe>(*it1).kobe)))
{
Person hagu = *it;
Person hay = *it1;
ma[hagu.name] = 2;
//ma1[s] = pii(hagu.kobe,hagu.matha);
hard_work.insert(hagu);
//if(hagu.name!=s)cout<<s<<" is not working now.\n";
//cout<<hagu.name<<" is working hard now.\n";
ailsha.erase(hagu);
//hagu = *it1;
ma[hay.name] = 1;
ailsha.insert(hay);
hard_work.erase(hay);
//cout<<hay.name<<" is not working now.\n";
}
}
}
int sz = n;
//set<Person>::iterator it = ailsha.begin();
//for(;it!=ailsha.end();it++)
// cout<<it->name<<endl;
int m;
scanf("%d",&m);
getchar();
for(int q=n+1;q<=n+m;q++)
{
//cout<<"hihi\n";
char c;
c = getchar();
//cout<<c<<endl;
//getchar();
if(c=='-')
{
string s;
cin>>s;
if(ma[s]==0)continue;
//cout<<s<<endl;
if(ma[s]==1)
{
pii uff = ma1[s];
int matha = uff.second;
int kobe = uff.first;
Person p;
p.name = s;
p.kobe=kobe;
p.matha=matha;
ma[s]=0;
ailsha.erase(p);
//else continue;
int y = (sz-1)*.2 , u = sz*.2;
//cout<<"HIHI\n";
if(y<u)
{
set<Person>::iterator it = hard_work.end();
it--;
Person yuki = *it;
//cout<<(*it).name<<endl;
cout<<(*it).name<<" is not working now.\n";ailsha.insert(yuki);
hard_work.erase(yuki);
ma[yuki.name] = 1;
}
sz--;
}
else
{
pii uff = ma1[s];
int matha = uff.second;
int kobe = uff.first;
Person p;
p.name = s;
p.kobe=kobe;
p.matha=matha;
hard_work.erase(p);
//else continue;
ma[s]=0;
int y = (sz-1)*.2 , u = sz*.2;
if(y==u)
{
Person yuki = *ailsha.begin();
hard_work.insert(yuki);
cout<<(yuki).name<<" is working hard now.\n";
ma[yuki.name] = 2;
ailsha.erase(yuki);
}
sz--;
}
getchar();
}
else
{
string s;
int a;
cin>>s;
scanf("%d",&a);
getchar();
Person p;
p.name = s;
p.matha=a;
p.kobe=q;
ailsha.insert(p);
sz++;
int y = (sz-1)*.2 , u = sz*.2;
ma[s] = 1;
ma1[s] = pii(q,a);
set<Person>::iterator it = ailsha.begin();
set<Person>::iterator it1 = hard_work.end();
if(u == y and u!=0)
{
it1--;
if((((*it).matha>(*it1).matha) or (((*it).matha==(*it1).matha)and(*it).kobe>(*it1).kobe)))
//cout<<(*it).kobe<<" "<<(*it1).kobe<<endl;
{
Person hagu = *it;
Person hay = *it1;
ma[hagu.name] = 2;
//ma1[s] = pii(hagu.kobe,hagu.matha);
hard_work.insert(hagu);
//if(hagu.name!=s)cout<<s<<" is not working now.\n";
cout<<hagu.name<<" is working hard now.\n";
ailsha.erase(hagu);
//hagu = *it1;
ma[hay.name] = 1;
ailsha.insert(hay);
hard_work.erase(hay);
cout<<hay.name<<" is not working now.\n";
}
else cout<<s<<" is not working now.\n";
}
else if(u>y and y!=0)
{
it1--;
Person hagu = *it;
ma[hagu.name] = 2;
//ma1[s] = pii(hagu.kobe,hagu.matha);
hard_work.insert(hagu);
ailsha.erase(hagu);
if(hagu.name!=s)cout<<s<<" is not working now.\n";
cout<<hagu.name<<" is working hard now.\n";
}
else if(u>y)
{
Person p = *ailsha.begin();
ma[p.name] = 2;
ailsha.erase(p);
hard_work.insert(p);
if(p.name!=s)cout<<s<<" is not working now.\n";
cout<<p.name<<" is working hard now.\n";
}
else cout<<s<<" is not working now.\n";
//cout<<s<<" "<<a<<endl;
}
}
}
|
E-training
Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training.
As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6.
Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $.
Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3".
However, Nene was tired, so she decided to cheat only for the answer.
Based only on the values of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this.
input
$ N, A, B, C $ are given separated by blanks.
output
Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end.
Constraint
* $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $
* $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $
* No inconsistent data is given, such as $ A $ being greater than $ N $
Input example 1
6 3 2 1
Output example 1
2
For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3".
Input example 2
10 9 9 9
Output example 2
1
Example
Input
6 3 2 1
Output
2
|
#include <bits/stdc++.h>
using namespace std;
int main(void){
int n,a,b,c;
cin>>n>>a>>b>>c;
cout<<n-(a+b-c)<<endl;
}
|
Problem
Given the string $ S $ of length $ N $. Process the following query $ Q $ times.
Query
Let $ S [L: R] $ be a character string consisting of $ S $ from the $ L $ character to the $ R $ character (including both ends).
Represent $ S [L: R] $ as $ AXBXCX (1 \ leq | A |, | B |, | C |, | X |) $ using the appropriate strings $ A, B, C, X $ With that in mind, it prints the length of the longest of such $ X $.
However, if such $ X $ does not exist, 0 is output instead.
Constraints
The input satisfies the following conditions.
* $ 1 \ leq N, Q \ leq 2 \ times 10 ^ 5 $
* Each letter of $ S $ consists of a lowercase alphabet
* $ 1 \ leq L_i \ leq R_i \ leq N $
Input
The input is given in the following format.
$ N $ $ Q $
$ S $
$ L_1 $ $ R_1 $
$ L_2 $ $ R_2 $
$ \ vdots $
$ L_Q $ $ R_Q $
$ N, Q, L, R $ are all given as integers.
$ N $ and $ Q $ are given on the first line, separated by blanks.
The string $ S $ is given on the second line.
2 + $ i (1 \ leq i \ leq Q) $ L_i $ and $ R_i $ are given on the $ line separated by blanks. These represent $ L, R $ in the $ i $ th query.
Output
Print the longest $ X $ length on a single line for each query.
Examples
Input
12 3
itisansansan
1 12
5 12
6 7
Output
2
1
0
Input
20 2
sensanbyakusanjuusan
1 20
1 14
Output
3
1
Input
21 6
aaaabaaaabaaaaaaaaaab
1 21
10 21
10 18
4 16
11 21
1 6
Output
4
0
2
2
0
1
|
//
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#ifdef BTK
#define DEBUG if(1)
#else
#define CIN_ONLY if(1)
#define DEBUG if(0)
#endif
#define ALL(v) (v).begin(),(v).end()
#define REC(ret, ...) std::function<ret (__VA_ARGS__)>
template <typename T>inline bool chmin(T &l, T r){bool a = l>r; if (a)l = r; return a;}
template <typename T>inline bool chmax(T &l, T r){bool a = l<r; if (a)l = r; return a;}
template <typename T>istream& operator>>(istream &is, vector<T> &v){for (auto &it : v)is >> it;return is;}
class reverse_range {private:struct I {int x;int operator*() {return x-1;}bool operator!=(I& lhs) {return x>lhs.x;}void operator++() {--x;}};I i, n;public:reverse_range(int n) :i({ 0 }), n({ n }){}reverse_range(int i, int n) :i({ i }), n({ n }){}I& begin() {return n;}I& end() {return i;}};
class range {private: struct I { int x; int operator*() { return x; }bool operator!=(I& lhs) { return x<lhs.x; }void operator++() { ++x; } }; I i, n;public:range(int n) :i({ 0 }), n({ n }) {}range(int i, int n) :i({ i }), n({ n }) {}I& begin() { return i; }I& end() { return n; }reverse_range operator!(){return reverse_range(*i,*n);}};
int N,Q;
char buf[212345];
string S;
/*
sa[0]=n //空文字列
lcp[i]:=suffix[sa[i]]とsuffix[sa[i+1]]の共通高さ
*/
namespace latte{
void create_begin_bucket(vector<int>&v,vector<int>&bucket){
fill(bucket.begin(),bucket.end(),0);
for(int i=0;i<(int)v.size();i++)bucket[v[i]]++;
int sum=0;
for(int i=0;i<(int)bucket.size();i++){bucket[i]+=sum;swap(sum,bucket[i]);}
}
void create_end_bucket(vector<int>&v,vector<int>&bucket){
fill(bucket.begin(),bucket.end(),0);
for(int i=0;i<(int)v.size();i++)bucket[v[i]]++;
for(int i=1;i<(int)bucket.size();i++)bucket[i]+=bucket[i-1];
}
void induced_sort(vector<int>&v,vector<int>&sa,int mv,vector<int>&bucket,vector<int>&is_l){
create_begin_bucket(v,bucket);
for(int i=0;i<(int)v.size();i++)if(sa[i]>0&&is_l[sa[i]-1])sa[bucket[v[sa[i]-1]]++]=sa[i]-1;
}
void invert_induced_sort(vector<int>&v,vector<int>&sa,int mv,vector<int>&bucket,vector<int>&is_l){
create_end_bucket(v,bucket);
for(int i=v.size()-1;i>=0;i--)if(sa[i]>0&&!is_l[sa[i]-1])sa[--bucket[v[sa[i]-1]]]=sa[i]-1;
}
vector<int>sa_is(vector<int>v,int mv){
if(v.size()==1)return vector<int>(1,0);
vector<int>is_l(v.size());
vector<int>bucket(mv+1);
vector<int>sa(v.size(),-1);
auto is_lms=[&](int x)->bool{return x>0&&is_l[x-1]&&!is_l[x];};
is_l[v.size()-1]=0;
for(int i=v.size()-2;i>=0;i--)is_l[i]=v[i]>v[i+1]||(v[i]==v[i+1]&&is_l[i+1]);
create_end_bucket(v,bucket);
for(int i=0;i<(int)v.size();i++)if(is_lms(i))sa[--bucket[v[i]]]=i;
induced_sort(v,sa,mv,bucket,is_l);
invert_induced_sort(v,sa,mv,bucket,is_l);
int cur=0;
vector<int>order(v.size());
for(int i=0;i<(int)v.size();i++)if(is_lms(i))order[i]=cur++;
vector<int>next_v(cur);
cur=-1;
int prev=-1;
for(int i=0;i<(int)v.size();i++){
if(!is_lms(sa[i]))continue;
bool diff=false;
for(int d=0;d<v.size();d++){
if(prev==-1||v[sa[i]+d]!=v[prev+d]||is_l[sa[i]+d]!=is_l[prev+d]){
diff=true;
break;
}
else if(d>0&&is_lms(sa[i]+d))break;
}
if(diff){cur++;prev=sa[i];}
next_v[order[sa[i]]]=cur;
}
vector<int>re_order(next_v.size());
for(int i=0;i<(int)v.size();i++)if(is_lms(i))re_order[order[i]]=i;
vector<int>next_sa=sa_is(next_v,cur);
create_end_bucket(v,bucket);
for(int i=0;i<sa.size();i++)sa[i]=-1;
for(int i=next_sa.size()-1;i>=0;i--)sa[--bucket[v[re_order[next_sa[i]]]]]=re_order[next_sa[i]];
induced_sort(v,sa,mv,bucket,is_l);
invert_induced_sort(v,sa,mv,bucket,is_l);
return sa;
}
vector<int> sa_is(string &s){
vector<int>v(s.size()+1);
for(int i=0;i<(int)s.size();i++)v[i]=s[i];
return sa_is(v,*max_element(v.begin(),v.end()));
}
}
namespace SA {
int n, k;
int R[500000];
int T[500000];
bool compare_sa(int i, int j) {
if (R[i] != R[j])return R[i] < R[j];
else {
int ri = i + k <= n ? R[i + k] : -1;
int rj = j + k <= n ? R[j + k] : -1;
return ri < rj;
}
}
vector<int> construct_sa(string& S) {
return latte::sa_is(S);
n = S.size();
vector<int> sa(n + 1);
for (int i = 0; i <= n; i++) {
sa[i] = i;
R[i] = i < n ? S[i] : -1;
}
for (k = 1; k <= n; k *= 2) {
sort(sa.begin(), sa.end(), compare_sa);
T[sa[0]] = 0;
for (int i = 1; i <= n; i++)
T[sa[i]] = T[sa[i - 1]] + (compare_sa(sa[i - 1], sa[i]) ? 1 : 0);
for (int i = 0; i <= n; i++)
R[i] = T[i];
}
return sa;
}
vector<int> construct_lcp(string& S, vector<int> &sa) {
n = S.size();
for (int i = 0; i <= n; i++)R[sa[i]] = i;
int h = 0;
vector<int> lcp(n + 1, 0);
for (int i = 0; i < n; i++) {
int j = sa[R[i] - 1];
if (h > 0)h--;
for (; j + h < n&&i + h < n; h++) {
if (S[j + h] != S[i + h])break;
}
lcp[R[i] - 1] = h;
}
return lcp;
}
}
int ret[212345];
vector<int> sa,lcp;
vector<int> id;
namespace StaticRMQ {
/*
default:: range minimum query
*/
template<typename T>
using MergeFunction = function<T(T,T)>;
template<typename T>
MergeFunction<T>
getMin = [](T l, T r) {
return l < r ? l : r;
};
template<typename T>
MergeFunction<T>
getMax = [](T l, T r) {
return l > r ? l : r;
};
template<typename T>
class BufferManager {
private:
T* const mem;
int ptr;
public:
BufferManager(T* buf):mem(buf) {
ptr = 0;
}
T* get(int m) {
ptr += m;
return mem + ptr - m;
}
void reset() {
ptr = 0;
}
};
namespace Buffer{
// if N<=10^6 : BufferSize is enough for 5 * N
constexpr int BufferSize = 5 * 1123456;
using NodeType = int;
NodeType mem[BufferSize];
BufferManager<NodeType> buffer(mem);
}
template<typename T, typename ITR>
struct SparseTable {
const int n;
const int logn;
T* const mem;
MergeFunction<T> Merge;
void build() {
for (int h = 0; h + 1 < logn; h++) {
const int half = 1 << h;
const int len = half << 1;
for (int i = 0; i + len <= n; i++) {
mem[h*n + n + i] = Merge(mem[h*n + i], mem[h*n + i + half]);
}
}
}
static inline int get_log(const int n) {
int l = 1;
for (int tmp = 1; tmp < n; tmp <<= 1)l++;
return l;
}
SparseTable(ITR bg, ITR ed,
MergeFunction<T> f = getMin<T>,
BufferManager<T> &bf = Buffer::buffer
)
: n(distance(bg,ed)),
logn(get_log(n)),
mem(bf.get(n*logn)),
Merge(f) {
for (auto p = mem; bg != ed; ++bg, ++p) {
(*p) = (*bg);
}
build();
}
inline int get_msb(const int size) {
#ifdef BTK
int id = 0;
for (int i = 0; i < logn; i++)if (size >> i)id = i;
return id;
#else
return 31 - __builtin_clz(size);
#endif
}
inline T get(const int l, const int r) {
const int msb = get_msb(r - l);
return Merge(mem[msb*n + l], mem[msb*n + r - (1 << msb)]);
}
};
template<typename T, typename ITR>
struct SmallRMQ{
const int n;
T* const mem;
MergeFunction<T> Merge;
void build(ITR bg,ITR ed) {
int x = distance(bg, ed);
for (auto p = mem; x > 0; x -= 4) {
T tmp[4];
tmp[0] = (*bg); ++bg;
if (x >= 1)tmp[1] = (*bg); ++bg;
if (x >= 2)tmp[2] = (*bg); ++bg;
if (x >= 3)tmp[3] = (*bg); ++bg;
for (int i = 0; i < 4; i++) {
T ret = tmp[i];
(*p) = ret; ++p;
for (int j = i + 1; j < 4; j++) {
ret = Merge(ret,tmp[j]);
(*p) = ret; ++p;
}
}
}
}
SmallRMQ(ITR bg, ITR ed,
MergeFunction<T> f = getMin<T>,
BufferManager<T> &bf = Buffer::buffer
)
: n(((distance(bg, ed)+3)>>2)<<2),
mem(bf.get((n>>2) * 10)),
Merge(f) {
build(bg, ed);
}
inline T get(int l, int r) {
const int block = l >> 2;
l &= 3; r--; r &= 3;
const int segment = (10 - (((4 - l)*(4 - l + 1)) >> 1)) + (r - l);
return mem[block * 10 + segment];
}
};
template<typename T, typename ITR>
struct RMQ {
const int n;
MergeFunction<T> Merge;
T* const workspace;
SmallRMQ<T, ITR> small;
SmallRMQ<T, T*> medium;
SparseTable<T, T*> large;
template<typename S, typename Itr>
inline S buildBlock(Itr bg, Itr ed, BufferManager<T>& bf, const int size) {
T* p = workspace;
for (int x = distance(bg, ed); x > 0; ++p, x-=4) {
(*p) = (*bg); ++bg;
if(x>=1)(*p) = Merge(*p, *bg); ++bg;
if(x>=2)(*p) = Merge(*p, *bg); ++bg;
if(x>=3)(*p) = Merge(*p, *bg); ++bg;
}
return S(workspace, workspace+size, Merge, bf);
}
RMQ(ITR bg, ITR ed,
MergeFunction<T> f = getMin<T>,
BufferManager<T> &bf = Buffer::buffer
): n(((distance(bg, ed) + 15) >> 4) << 4),
Merge(f),
workspace(bf.get(n >> 2)),
small(bg, ed, f, bf),
medium(buildBlock<SmallRMQ<T, T*>, ITR>(bg, ed, bf, n >> 2)),
large(buildBlock<SparseTable<T, T*>, T*>(workspace, workspace + (n >> 2), bf, n >> 4))
{}
inline T get(int l, int r) {
int nl = (l >> 2) + 1;
int nr = ((r - 1) >> 2);
T ret = small.get(l, min(nl << 2, r));
ret = Merge(ret, small.get(max(l, nr << 2),r));
l = nl; r = nr;
nl = (l >> 2) + 1;
nr = ((r - 1) >> 2);
if (l >= r)return ret;
ret = Merge(ret, medium.get(l, min(nl << 2, r)));
ret = Merge(ret, medium.get(max(l, nr << 2), r));
l = nl; r = nr;
if (l >= r)return ret;
else return Merge(ret, large.get(l, r));
}
};
}
using RMQ_PTR=StaticRMQ::RMQ<int,decltype(lcp.begin())>;
inline pair<int,int> get_range(int pos,int len,RMQ_PTR&rmq){
int lb=pos;
int ub=pos+1;
{
int ok=pos;
int ng=-1;
while(abs(ok-ng)>1){
const int mid=(ok+ng)/2;
if(rmq.get(mid,pos)>=len){
ok=mid;
}
else{
ng=mid;
}
}
chmin(lb,ok);
}
{
int ok=pos;
int ng=N+1;
while(abs(ok-ng)>1){
const int mid=(ok+ng)/2;
if(rmq.get(pos,mid)>=len){
ok=mid;
}
else{
ng=mid;
}
}
chmax(ub,ng);
}
return {lb,ub};
}
constexpr int INF = 1e7;
template<typename SEG> using SetInitialLeaf = function<void(SEG&, int)>;
template<typename SEG> using SetInitialSegment = function<void(SEG&, const int, const int)>;
template<typename RET, typename SEG> using GetSingleSegment = function<RET(SEG&, const int, const int)>;
template<typename RET> using GetMergedSegment = function<RET(RET, RET)>;
template<typename SEG, typename Q> using UpdateSingleSegment = function<void(SEG&, Q)>;
template<typename SEG> using LazyUpdate = function<void(SEG&, SEG&, SEG&)>;
struct node { vector<int> x; };
int query_lb;
SetInitialLeaf<node>
set_leaf = [](node &v, const int id) {
};
SetInitialSegment<node>
set_segment = [](node &v, const int l, const int r) {
const int lb = l;
const int ub = min(N+1,r);
v.x.reserve(max(ub-lb,0)+1);
for(int i:range(lb,ub)){
v.x.push_back(sa[i]);
}
v.x.push_back(INF);
sort(ALL(v.x));
};
GetSingleSegment<int, node>
segment_min = [](node &v, const int l, const int r) {
return *lower_bound(ALL(v.x),query_lb);
};
GetMergedSegment<int>
merge_segment = [](int l, int r) {
return l < r ? l : r;
};
#ifndef NDBUF
#define NDBUF
template<typename T>
struct BufferManager {
T *mem;
int ptr;
BufferManager(T* mem) {
ptr = 0;
this->mem = mem;
}
T* get(int m) {
ptr += m;
return mem + ptr - m;
}
void reset() {
ptr = 0;
}
};
#endif
namespace H {
constexpr int BufferSize = 812345;
using NodeType = node;
NodeType mem[BufferSize];
BufferManager<NodeType> buffer(mem);
}
template<typename Node, typename RET>
struct SegmentTree {
int size;
Node *seg;
GetSingleSegment<RET, Node> get_single_segment;
GetMergedSegment<RET> get_merged_segment;
LazyUpdate<Node> lazy_update;
void init(int l, int r, SetInitialSegment<Node>& init_segment, SetInitialLeaf<Node>& init_leaf, int k = 0) {
auto &v = seg[k];
init_segment(v, l, r);
if (r - l == 1) {
//葉の時の処理
init_leaf(v, l);
}
else if (r - l>1) {
int m = (l + r) / 2;
init(l, m, init_segment, init_leaf, k * 2 + 1);
init(m, r, init_segment, init_leaf, k * 2 + 2);
}
}
SegmentTree(
int n,
GetSingleSegment<RET, Node> gss,
GetMergedSegment<RET> gms,
SetInitialSegment<Node> sis,
SetInitialLeaf<Node> sil,
LazyUpdate<Node> lu = [](Node &v,Node &l,Node &r){},
BufferManager<Node>& buf = H::buffer
)
:get_single_segment(gss),
get_merged_segment(gms),
lazy_update(lu) {
size = 1; while (size<n)size *= 2;
seg = buf.get(size * 2 + 10);
init(0, size, sis, sil);
}
SegmentTree(){
}
#define LQ a,b,k*2+1,l,m
#define RQ a,b,k*2+2,m,r
RET get(int a, int b, int k, int l, int r) {
if (a <= l && r <= b)return get_single_segment(seg[k], l, r);
if (r - l > 1)lazy_update(seg[k], seg[2 * k + 1], seg[2 * k + 2]);
int m = (l + r) / 2;
bool ll = !(m <= a || b <= l);
bool rr = !(r <= a || b <= m);
RET ret;
if (ll&&rr)ret = get_merged_segment(get(LQ), get(RQ));
else if (ll)ret = get(LQ); else ret = get(RQ);
return ret;
}
RET get(int a, int b) {
return get(a, b, 0, 0, size);
}
template<typename Q>
void update(int a, int b, int k, int l, int r, UpdateSingleSegment<Node, Q> &update_segment, Q value) {
if (r <= a || b <= l)return;
if (a <= l && r <= b) {
update_segment(seg[k], value);
}
else {
if (r - l > 1)lazy_update(seg[k], seg[2 * k + 1], seg[2 * k + 2]);
int m = (l + r) / 2;
update(LQ, update_segment, value);
update(RQ, update_segment, value);
seg[k].ret = get_merged_segment(
get_single_segment(seg[k * 2 + 1], l, m),
get_single_segment(seg[k * 2 + 2], m, r)
);
}
}
template<typename Q>
void update_segment(int a, int b, UpdateSingleSegment<Node, Q> &update_segment, Q value) {
update(a, b, 0, 0, size, update_segment, value);
}
template<typename Q>
void update_element(int a, UpdateSingleSegment<Node, Q> &update_segment, Q value) {
update(a, a + 1, 0, 0, size, update_segment, value);
}
};
SegmentTree<node,int> st;
inline bool check(int ql,int qr,int X_len,RMQ_PTR&rmq){
if(X_len*3+3>qr-ql)return false;
int lb,ub;
tie(lb,ub)=get_range(id[ql],X_len,rmq);
int p;
{
int X1=ql+X_len;
query_lb = X1+1;
p = st.get(lb,ub);
int A1=p;
int X2=p+X_len;
if(X2>=N)return false;
query_lb = X2+1;
p = st.get(lb,ub);
int A2=p;
int X3=p+X_len;
if(X3>=N)return false;
int A3=qr;
return A3-X3>=1;
}
}
inline int solve(int ql,int qr,RMQ_PTR&rmq){
int lb=0;
int ub=qr-ql;
while(ub-lb>1){
const int mid = (lb+ub)/2;
if(check(ql,qr,mid,rmq)){
lb=mid;
}
else{
ub=mid;
}
}
return lb;
}
int main(){
scanf("%d%d%s",&N,&Q,buf);
reverse(buf,buf+N);
S=buf;
sa=SA::construct_sa(S);
id=vector<int>(N+1);
for(int i:range(N+1)){
id[sa[i]]=i;
}
lcp=SA::construct_lcp(S,sa);
RMQ_PTR rmq(lcp.begin(),lcp.end());
st = SegmentTree<node,int>(N+1,segment_min, merge_segment, set_segment, set_leaf);
for(int i:range(Q)){
int l,r;
scanf("%d%d",&l,&r);
ret[i]=solve(N-r,N-l+1,rmq);
}
for(int i:range(Q)){
printf("%d\n",ret[i]);
}
return 0;
}
|
<image>
As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line.
g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon.
Constraints
* 3 ≤ n ≤ 100
* 1 ≤ q ≤ 100
* -10000 ≤ xi, yi ≤ 10000
* -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000
* No point in g will occur more than once.
* p1 ≠ p2
Input
The input is given in the following format:
g (the sequence of the points of the polygon)
q (the number of queries = the number of target lines)
1st query
2nd query
:
qth query
g is given as a sequence of points p1,..., pn in the following format:
n
x1 y1
x2 y2
:
xn yn
The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180.
For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y.
Output
For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001.
Example
Input
4
1 1
4 1
4 3
1 3
2
2 0 2 4
2 4 2 0
Output
2.00000000
4.00000000
|
//
// 凸多角形の切断
//
// verified:
// AOJ Course CGL_4_C Convex Polygon - Convex Cut
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C&lang=jp
//
/*
問題例
・AOJ 2385
・AOJ 2160
*/
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
#include <algorithm>
using namespace std;
using DD = double;
const DD INF = 1LL<<60; // to be set appropriately
const DD EPS = 1e-10; // to be set appropriately
const DD PI = acos(-1.0);
DD torad(int deg) {return (DD)(deg) * PI / 180;}
DD todeg(DD ang) {return ang * 180 / PI;}
/* Point */
struct Point {
DD x, y;
Point(DD x = 0.0, DD y = 0.0) : x(x), y(y) {}
friend ostream& operator << (ostream &s, const Point &p) {return s << '(' << p.x << ", " << p.y << ')';}
};
inline Point operator + (const Point &p, const Point &q) {return Point(p.x + q.x, p.y + q.y);}
inline Point operator - (const Point &p, const Point &q) {return Point(p.x - q.x, p.y - q.y);}
inline Point operator * (const Point &p, DD a) {return Point(p.x * a, p.y * a);}
inline Point operator * (DD a, const Point &p) {return Point(a * p.x, a * p.y);}
inline Point operator * (const Point &p, const Point &q) {return Point(p.x * q.x - p.y * q.y, p.x * q.y + p.y * q.x);}
inline Point operator / (const Point &p, DD a) {return Point(p.x / a, p.y / a);}
inline Point conj(const Point &p) {return Point(p.x, -p.y);}
inline Point rot(const Point &p, DD ang) {return Point(cos(ang) * p.x - sin(ang) * p.y, sin(ang) * p.x + cos(ang) * p.y);}
inline Point rot90(const Point &p) {return Point(-p.y, p.x);}
inline DD cross(const Point &p, const Point &q) {return p.x * q.y - p.y * q.x;}
inline DD dot(const Point &p, const Point &q) {return p.x * q.x + p.y * q.y;}
inline DD norm(const Point &p) {return dot(p, p);}
inline DD abs(const Point &p) {return sqrt(dot(p, p));}
inline DD amp(const Point &p) {DD res = atan2(p.y, p.x); if (res < 0) res += PI*2; return res;}
inline bool eq(const Point &p, const Point &q) {return abs(p - q) < EPS;}
inline bool operator < (const Point &p, const Point &q) {return (abs(p.x - q.x) > EPS ? p.x < q.x : p.y < q.y);}
inline bool operator > (const Point &p, const Point &q) {return (abs(p.x - q.x) > EPS ? p.x > q.x : p.y > q.y);}
inline Point operator / (const Point &p, const Point &q) {return p * conj(q) / norm(q);}
/* Line */
struct Line : vector<Point> {
Line(Point a = Point(0.0, 0.0), Point b = Point(0.0, 0.0)) {
this->push_back(a);
this->push_back(b);
}
friend ostream& operator << (ostream &s, const Line &l) {return s << '{' << l[0] << ", " << l[1] << '}';}
};
/* Circle */
struct Circle : Point {
DD r;
Circle(Point p = Point(0.0, 0.0), DD r = 0.0) : Point(p), r(r) {}
friend ostream& operator << (ostream &s, const Circle &c) {return s << '(' << c.x << ", " << c.y << ", " << c.r << ')';}
};
///////////////////////
// 多角形
///////////////////////
// 多角形の面積
DD Area(const vector<Point> &pol) {
DD res = 0.0;
for (int i = 0; i < pol.size(); ++i) {
res += cross(pol[i], pol[(i+1)%pol.size()]);
}
return res/2.0L;
}
// convex cut
int ccw_for_convexcut(const Point &a, const Point &b, const Point &c) {
if (cross(b-a, c-a) > EPS) return 1;
if (cross(b-a, c-a) < -EPS) return -1;
if (dot(b-a, c-a) < 0) return 2;
if (norm(b-a) < norm(c-a)) return -2;
return 0;
}
vector<Point> crosspoint_for_convexcut(const Line &l, const Line &m) {
vector<Point> res;
DD d = cross(m[1] - m[0], l[1] - l[0]);
if (abs(d) < EPS) return vector<Point>();
res.push_back(l[0] + (l[1] - l[0]) * cross(m[1] - m[0], m[1] - l[0]) / d);
return res;
}
vector<Point> ConvexCut(const vector<Point> &pol, const Line &l) {
vector<Point> res;
for (int i = 0; i < pol.size(); ++i) {
Point p = pol[i], q = pol[(i+1)%pol.size()];
if (ccw_for_convexcut(l[0], l[1], p) != -1) {
if (res.size() == 0) res.push_back(p);
else if (!eq(p, res[res.size()-1])) res.push_back(p);
}
if (ccw_for_convexcut(l[0], l[1], p) * ccw_for_convexcut(l[0], l[1], q) < 0) {
vector<Point> temp = crosspoint_for_convexcut(Line(p, q), l);
if (temp.size() == 0) continue;
else if (res.size() == 0) res.push_back(temp[0]);
else if (!eq(temp[0], res[res.size()-1])) res.push_back(temp[0]);
}
}
return res;
}
// Voronoi-diagram
Line bisector(const Point &p, const Point &q) {
Point c = (p + q) / 2.0L;
Point v = (q - p) * Point(0.0L, 1.0L);
v = v / abs(v);
return Line(c - v, c + v);
}
vector<Point> Voronoi(vector<Point> pol, const vector<Point> &ps, int ind) {
for (int i = 0; i < ps.size(); ++i) {
if (i == ind) continue;
Line l = bisector(ps[ind], ps[i]);
pol = ConvexCut(pol, l);
}
return pol;
}
int main() {
int n; cin >> n;
vector<Point> pol(n);
for (int i = 0; i < n; ++i) cin >> pol[i].x >> pol[i].y;
int Q; cin >> Q;
for (int _ = 0; _ < Q; ++_) {
Point x, y; cin >> x.x >> x.y >> y.x >> y.y;
Line l(x, y);
auto cutted = ConvexCut(pol, l);
cout << fixed << setprecision(10) << Area(cutted) << endl;
}
}
|
For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order.
Constraints
* $1 \leq n \leq 9$
* $a_i$ consist of $1, 2, ..., n$
Input
A sequence is given in the following format.
$n$
$a_0 \; a_1 \; ... \; a_{n-1}$
Output
Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line.
Examples
Input
3
2 1 3
Output
1 3 2
2 1 3
2 3 1
Input
3
3 2 1
Output
3 1 2
3 2 1
|
#include <algorithm>
#include <iostream>
#include <ostream>
void print_array(const int a[], int n) {
for (int i = 0; i < n; ++i) {
if (i > 0)
std::cout << " ";
std::cout << a[i];
}
std::cout << std::endl;
}
int main(int argc, char *argv[]) {
int n;
std::cin >> n;
int a[10];
for (int i = 0; i < n; ++i)
std::cin >> a[i];
if (std::prev_permutation(a, a + n))
print_array(a, n);
std::next_permutation(a, a + n);
print_array(a, n);
if (std::next_permutation(a, a + n))
print_array(a, n);
}
|
Problem Statement
Past
In the year of 2048, the Virtual Reality Massively Multiplayer Online Role-Playing Game (VRMMORPG), Code Art Online (CAO), is released. With the Chef Gear, a virtual reality helmet that stimulates the user's five senses via their brain, players can experience and control their in-game characters with their minds.
On August the 2nd, 2048, all the players log in for the first time, and subsequently discover that they are unable to log out. They are then informed by Code Master, the creator of CAO, that if they wish to be free, they must reach the second stage of the game.
Kirito is a known star player of CAO. You have to help him log out.
Present
Stage 1
A map is described by a 2D grid of cells. Each cell is either labelled as a # or a ^. # denotes a wall. A monster exists in a cell if the cell is not a wall and the cell is a centre of Prime-Cross (CPC).
Let L be the number of contiguous ^ to the left of X, in the same row as X.
R be the number of contiguous ^ to the right of X, in the same row as X.
T be the number of contiguous ^ above X, in the same column as X.
B be the number of contiguous ^ below X, in the same column as X.
A cell X is said to be a CPC if there exists a prime number P such that P ≤ minimum of [L, R, T, B].
Note: While computing L, R, T, B for a cell X, you should not count the ^ of the cell X.
Given a map, you have to tell Kirito the number of cells where monsters exist.
Future
If you are done with this task, go help Kirito with Stage 2 :-)
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. Each case starts with a line containing two space separated integers R, C denoting the number of rows and columns in the map respectively. The next R lines contain C characters each, describing the map.
Output
For each test case, output a single line containing the number of cells where monsters exist.
Constraints
1 ≤ T ≤ 100
1 ≤ R ≤ 50
1 ≤ C ≤ 50
Example
Input:
2
5 5
^^^^^
^^^^^
^^^^#
^^^^^
^^^^^
5 7
^^#^^^^
^^#^#^#
#^^^^^^
^^#^^#^
^^^^^^^
Output:
0
1
Explanation
Example case 1. There is no cell for which minimum of L, R, T, B is greater than some prime P.
Example case 2. The cell at [3, 4], (1-based indexing) is the only CPC.
|
for _ in xrange(input()):
r,c = map(int,raw_input().split())
a = [list(raw_input()) for _ in range(r)]
tot = 0
for i in range(r):
for j in range(c):
if a[i][j] != '^':
continue
L = 0
for k in range(i-1,-1,-1):
if a[k][j] == '#':
break
L += 1
R = 0
for k in range(i+1,r,1):
if a[k][j] == '#':
break
R += 1
T = 0
for k in range(j-1,-1,-1):
if a[i][k] == '#':
break
T += 1
B = 0
for k in range(j+1,c,1):
if a[i][k] == '#':
break
B += 1
fi = min(L,T,B,R)
if fi >= 2:
tot += 1
print(tot)
|
In CycleLand Jack and Jenny are two friends.They want to go CycleSchool By a cycle ( Assume that they live in same house) . Distance between CycleSchool and their house is n units. Jack and jenny both like Jelly . They decided to play a game who will win the game ,get a chance to sit with jelly in school. Rules of game is as follows:
- Initially jenny will ride cycle.
- They will ride cycle one by one.
- When one will ride cycle other one will sit on carrier of cycle.
- In each ride they can ride cycle exactly 1, 3 or 5 units.
- Who will reach school riding cycle get a chance to sit with jelly.
Both play optimally this game. You have to find who will win this game.
Note- they can not ride cycle more that n units.
Input
The first line of the input contains an integer T denoting the number of test cases.
Each line contain a single integer denoting n
Output
For each test case, output a single line containing the name of winner.
Constraints
1 ≤ T ≤ 100
1 ≤ n ≤ 10^6
Subtaks
Example
Input:
3
1
2
3
Output:
JENNY
JACK
JENNY
Explanation
When n=1 ,, Jenny ->1 .
When n=2 ,, Jenny ->1 Jack ->1 (Jenny can not ride cycle 3 units in his move , because 3>2).
When n=3 ,, Jenny ->3 .
|
# python3
def optimal(n):
if(n >= 5):
res = 5
elif(n < 5 and n >= 3):
res = 3
elif(n < 3 and n >= 1):
res = 1
elif(n < 1):
return -1
return res
if __name__ == "__main__":
count = -1
l = []
test = int(raw_input())
while(test):
n = int(raw_input())
while(n):
z = optimal(n)
n = n - z
count = count + 1
if(count % 2 == 0):
l.append(0)
else:
l.append(1)
count = -1
test = test - 1
for i in l:
if(i == 0):
print "JENNY"
else:
print "JACK"
|
The Gray code (see wikipedia for more details) is a well-known concept.
One of its important properties is that every two adjacent numbers have exactly one different digit in their binary representation.
In this problem, we will give you n non-negative integers in a sequence A[1..n] (0<=A[i]<2^64), such that every two adjacent integers have exactly one different digit in their binary representation, similar to the Gray code.
Your task is to check whether there exist 4 numbers A[i1], A[i2], A[i3], A[i4] (1 <= i1 < i2 < i3 < i4 <= n) out of the given n numbers such that A[i1] xor A[i2] xor A[i3] xor A[i4] = 0. Here xor is a bitwise operation which is same as ^ in C, C++, Java and xor in Pascal.
Input
First line contains one integer n (4<=n<=100000).
Second line contains n space seperated non-negative integers denoting the sequence A.
Output
Output “Yes” (quotes exclusive) if there exist four distinct indices i1, i2, i3, i4 such that A[i1] xor A[i2] xor A[i3] xor A[i4] = 0. Otherwise, output "No" (quotes exclusive) please.
Example
Input:
5
1 0 2 3 7
Output:
Yes
|
import sys
def main():
s = sys.stdin.readline
n = int(s())
if n>=135:
print "Yes"
return
nums = map(int, s().split())
for i in xrange(n):
for j in xrange(i+1,n):
for k in xrange(j+1,n):
for l in xrange(k+1, n):
if nums[i]^nums[j]^nums[k]^nums[l]==0:
print "Yes"
return
print "No"
return
if __name__ == '__main__':
main()
|
Tug of war is a sport that directly puts two teams against each other in a test of strength.
During school days, both Chef Shifu and Chef Po were champions of tug of war.
On behalf of restaurant's anniversary, Chef Shifu and Chef Po have decided to conduct
a tug of war game for their customers.
Master Chef Oogway has decided the following rules for the game.
Let N be the number of players participating in the game. All of these
players would stand in a circle in clock wise direction.
There are an infinite number of long ropes available.
When a rope is held by exactly two players, it is termed as bonding.
At least one bonding is necessary to conduct a game.
A player can play against multiple people simultaneously i.e he can have more than one bonding at
the same time.
Both members of a pair of players that have a bonding must have the same number of total
bondings. That is, if the player A makes bonding with the player B,
then the number of total bondings of the player A must be the same as
that of the player B.
Bondings should be created in such a fashion that ropes must not intersect each other.
The number of bondings of every player must be no more than K.
Now Master Chef Oogway asked Chef Shifu and Chef Po to find out the number of possible games.
Your task is to help them find this number. As this number might become huge,
you've to find it modulo (10^14+7). Two games are different iff there is some
bonding that is present in only of them.
Input
First line contains T, the number of test cases.
Each of T lines contain 2 positive integers N and K separated by a space.
Output
For each test case, output the number of ways to conduct the game modulo 100000000000007 (10^14+7) in one line.
Example
Input:
3
3 2
4 0
2 1
Output:
4
0
1
Explanation:
For the 1st case, there are 3 players. Let's call them p1, p2, p3.
Different games possible are:
Game 1: p1-p2 (numbers of bondings of p1, p2 are 1 ≤ K = 2)
Game 2: p1-p3 (numbers of bondings of p1, p3 are 1 ≤ K = 2)
Game 3: p2-p3 (numbers of bondings of p2, p3 are 1 ≤ K = 2)
Game 4: p1-p2, p1-p3, p2-p3 (numbers of bondings of p1, p2, p3 are 2 ≤ K
= 2)
For the 2nd test case, we cannot form the game, because K = 0 and hence no
player is allowed to make any bonding. As any game must have atleast one
bonding, no game is possible here.
For the 3rd case, only possible game is:
Game 1: p1-p2 (number of bondings in p1, p2 are 1)
Constraints
1 ≤ T ≤ 10000
0 ≤ N ≤ 10000
0 ≤ K ≤ N
|
import sys
mod= 100000000000007
a=[0]*10004
a[0]=1
a[1]=0
for j in xrange(2,10002):
a[j]=(j-1)*(2*a[j-1]+3*a[j-2])/(j+1)
for j in xrange(0,10002):
a[j]=(a[j]+a[j+1])
c=[0]*10004
c[0]=1
for j in xrange(0,10001):
c[j+1]=2*(2*j+1)*c[j]/(j+2)
t=int(sys.stdin.readline())
while t:
t-=1
n,k=map(int,sys.stdin.readline().split())
if k==0:
print 0
elif n==0:
print 0
elif k==1:
w=a[n]%mod-1
if w>=0:
print w
else:
print mod-1
elif k>=2:
w=c[n]%mod-1
if w>=0:
print w
else:
print mod-1
|
Chef likes trees a lot. Today he has an infinte full binary tree (each node has exactly two childs) with special properties.
Chef's tree has the following special properties :
Each node of the tree is either colored red or black.
Root of the tree is black intially.
Both childs of a red colored node are black and both childs of a black colored node are red.
The root of the tree is labelled as 1. For a node labelled v, it's left child is labelled as 2*v and it's right child is labelled as 2*v+1.
Chef wants to fulfill Q queries on this tree. Each query belongs to any of the following three types:
Qi Change color of all red colored nodes to black and all black colored nodes to red.
Qb x y Count the number of black colored nodes on the path from node x to node y (both inclusive).
Qr x y Count the number of red colored nodes on the path from node x to node y (both inclusive).
Help chef accomplishing this task.
Input
First line of the input contains an integer Q denoting the number of queries. Next Q lines of the input contain Q queries (one per line). Each query belongs to one of the three types mentioned above.
Output
For each query of type Qb or Qr, print the required answer.
Constraints
1<=Q<=10^5
1<=x,y<=10^9
Sample Input
5
Qb 4 5
Qr 4 5
Qi
Qb 4 5
Qr 4 5
Sample Output
2
1
1
2
Explanation
With the initial configuration of the tree, Path from node 4 to node 5 is 4->2->5 and color of nodes on the path is B->R->B.
Number of black nodes are 2.
Number of red nodes are 1.
After Query Qi, New configuration of the path from node 4 to node 5 is R->B->R.
Number of black nodes are 1.
Number of red nodes are 2.
Scoring
Subtask #1: 1<=Q<=100 1<=x,y<=1000 : 27 pts
Subtask #2: 1<=Q<=10^3 1<=x,y<=10^5 : 25 pts
Subtask #3: 1<=Q<=10^5 1<=x,y<=10^9 : 48 pts
|
Q = int(raw_input())
flag = False
while Q != 0:
s = raw_input()
s = s.split()
q = s[0]
if q != 'Qi':
x = int(s[1])
y = int(s[2])
n = 0
start = 'b'
while True:
if x > y:
x /= 2
n += 1
if start == 'b':
start = 'r'
else:
start = 'b'
elif x < y:
y /= 2
n += 1
else:
n += 1
if x != 1:
while x != 1:
x = x/2
if start == 'b':
start = 'r'
else:
start = 'b'
if start != 'b':
start = 'r'
break
B = n / 2
R = n / 2
if n % 2 != 0:
if start == 'b':
B += 1
else:
R += 1
if q == 'Qb':
if flag:
print R
else:
print B
elif q == 'Qr':
if flag:
print B
else:
print R
else:
if flag:
flag = False
else:
flag = True
Q -= 1
|
A tourist is visiting Byteland. The tourist knows English very well. The language of Byteland is rather different from English. To be exact it differs in following points:
Bytelandian alphabet has the same letters as English one, but possibly different in meaning. Like 'A' in Bytelandian may be 'M' in English. However this does not mean that 'M' in Bytelandian must be 'A' in English. More formally, Bytelindian alphabet is a permutation of English alphabet. It will be given to you and could be any possible permutation. Don't assume any other condition.
People of Byteland don't like to use invisible character for separating words. Hence instead of space (' ') they use underscore ('_'). Other punctuation symbols, like '?', '!' remain the same as in English.
The tourist is carrying "The dummies guide to Bytelandian", for translation. The book is serving his purpose nicely. But he is addicted to sharing on BaceFook, and shares his numerous conversations in Byteland on it. The conversations are rather long, and it is quite tedious to translate for his English friends, so he asks you to help him by writing a program to do the same.
Input
The first line of the input contains an integer T, denoting the length of the conversation, and the string M, denoting the English translation of Bytelandian string "abcdefghijklmnopqrstuvwxyz". T and M are separated by exactly one space. Then T lines follow, each containing a Bytelandian sentence S which you should translate into English. See constraints for details.
Output
For each of the sentence in the input, output its English translation on a separate line. Replace each underscores ('_') with a space (' ') in the output. Each punctuation symbol (see below) should remain the same. Note that the uppercase letters in Bytelandian remain uppercase in English, and lowercase letters remain lowercase. See the example and its explanation for clarity.
Constraints
1 ≤ T ≤ 100
M is a permutation of "abcdefghijklmnopqrstuvwxyz"
Each sentence is non-empty and contains at most 100 characters
Each sentence may contain only lowercase letters ('a'-'z'), uppercase letters ('A'-'Z'), underscores ('_') and punctuation symbols: dot ('.'), comma (','), exclamation ('!'), question-mark('?')
Example
Input:
5 qwertyuiopasdfghjklzxcvbnm
Ph
Pcssi
Bpke_kdc_epclc_jcijsc_mihyo?
Epcf_kdc_liswhyo_EIED_hy_Vimcvpcn_Zkdvp_siyo_viyecle.
Ipp!
Output:
Hi
Hello
What are these people doing?
They are solving TOTR in Codechef March long contest.
Ohh!
Explanation
The string "qwertyuiopasdfghjklzxcvbnm" means that 'a' in Bytelandian is 'q' in English, 'b' in Bytelandian is 'w' in English, 'c' in Bytelandian is 'e' in English and so on.Thus to translate "Ph" (first sentence in example) to English:1) We find that 'p' in Bytelandian means 'h' in English. So we replace 'P' with 'H'.2) Then we see that 'h' in Bytelandian means 'i' in English. So we replace 'h' with 'i'.3) Therefore, the translation is "Hi".
|
# cook your code here
import string
testcases, KEY = map(str, raw_input().split())
KEYUP = string.swapcase(KEY)
Dic = {'_':' '}
Lower = string.ascii_lowercase
Upper = string.ascii_uppercase
for i in xrange(len(KEY)) :
Dic[Lower[i]] = KEY[i]
Dic[Upper[i]] = KEYUP[i]
#print Dic
for tester in xrange(int(testcases)) :
Str = raw_input()
Out = ""
for char in Str :
if( (char in string.punctuation) and ( char != '_') ) :
Out += char
else :
Out += Dic[char]
print Out
|
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed).
Let's consider empty cells are denoted by '.', then the following figures are stars:
<image> The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3.
You are given a rectangular grid of size n × m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n ⋅ m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.
In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n ⋅ m stars.
Input
The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000) — the sizes of the given grid.
The next n lines contains m characters each, the i-th line describes the i-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only.
Output
If it is impossible to draw the given grid using stars only, print "-1".
Otherwise in the first line print one integer k (0 ≤ k ≤ n ⋅ m) — the number of stars needed to draw the given grid. The next k lines should contain three integers each — x_j, y_j and s_j, where x_j is the row index of the central star character, y_j is the column index of the central star character and s_j is the size of the star. Each star should be completely inside the grid.
Examples
Input
6 8
....*...
...**...
..*****.
...**...
....*...
........
Output
3
3 4 1
3 5 2
3 5 1
Input
5 5
.*...
****.
.****
..**.
.....
Output
3
2 2 1
3 3 1
3 4 1
Input
5 5
.*...
***..
.*...
.*...
.....
Output
-1
Input
3 3
*.*
.*.
*.*
Output
-1
Note
In the first example the output
2
3 4 1
3 5 2
is also correct.
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.BufferedOutputStream;
import java.util.stream.Stream;
import java.util.StringTokenizer;
import java.io.BufferedReader;
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;
Kattio in = new Kattio(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE2 solver = new TaskE2();
solver.solve(1, in, out);
out.close();
}
static class TaskE2 {
public void solve(int testNumber, Kattio in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
char[][] arr = new char[n + 1][m + 1];
int[][][] pre = new int[n + 2][m + 2][2];
int[][][] clo = new int[n + 2][m + 2][4];
for (int i = 1; i <= n; ++i) {
char[] tmp = in.next().toCharArray();
Arrays.fill(clo[i][0], -1);
Arrays.fill(clo[i][m + 1], -1);
for (int j = 1; j <= m; ++j) {
arr[i][j] = tmp[j - 1];
Arrays.fill(clo[i][j], -1);
}
}
for (int j = 0; j <= m + 1; ++j) {
Arrays.fill(clo[0][j], -1);
Arrays.fill(clo[n + 1][j], -1);
}
// Mark the index of the furthest * from the left and top
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (arr[i][j] == '*') {
clo[i][j][0] = j;
clo[i][j][2] = i;
if (clo[i][j - 1][0] != -1) {
clo[i][j][0] = clo[i][j - 1][0];
}
if (clo[i - 1][j][2] != -1) {
clo[i][j][2] = clo[i - 1][j][2];
}
}
}
}
// Mark the index of the furthest * from the right and bottom
for (int i = n; i > 0; --i) {
for (int j = m; j > 0; --j) {
if (arr[i][j] == '*') {
clo[i][j][1] = j;
clo[i][j][3] = i;
if (clo[i][j + 1][1] != -1) {
clo[i][j][1] = clo[i][j + 1][1];
}
if (clo[i + 1][j][3] != -1) {
clo[i][j][3] = clo[i + 1][j][3];
}
}
}
}
ArrayList<Star> ans = new ArrayList<>();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (arr[i][j] == '*') {
int diff1 = Math.min(j - clo[i][j][0], clo[i][j][1] - j);
int diff2 = Math.min(i - clo[i][j][2], clo[i][j][3] - i);
int diff = Math.min(diff1, diff2);
if (diff == 0)
continue;
pre[i][j - diff][0] += 1;
pre[i][j + diff + 1][0] -= 1;
pre[i - diff][j][1] += 1;
pre[i + diff + 1][j][1] -= 1;
ans.add(new Star(i, j, diff));
}
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
pre[i][j][0] += pre[i][j - 1][0];
pre[i][j][1] += pre[i - 1][j][1];
if (pre[i][j][0] + pre[i][j][1] == 0 && arr[i][j] == '*') {
out.println(-1);
return;
}
}
}
out.println(ans.size());
ans.stream().forEach(out::println);
}
public class Star {
int x;
int y;
int l;
public Star(int x, int y, int l) {
this.x = x;
this.y = y;
this.l = l;
}
public String toString() {
return x + " " + y + " " + l;
}
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String next() {
return nextToken();
}
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
}
|
A tree is an undirected graph with exactly one simple path between each pair of vertices. We call a set of simple paths k-valid if each vertex of the tree belongs to no more than one of these paths (including endpoints) and each path consists of exactly k vertices.
You are given a tree with n vertices. For each k from 1 to n inclusive find what is the maximum possible size of a k-valid set of simple paths.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of vertices in the tree.
Then following n - 1 lines describe the tree, each of them contains two integers v, u (1 ≤ v, u ≤ n) — endpoints of the corresponding edge.
It is guaranteed, that the given graph is a tree.
Output
Output n numbers, the i-th of which is the maximum possible number of paths in an i-valid set of paths.
Examples
Input
7
1 2
2 3
3 4
4 5
5 6
6 7
Output
7
3
2
1
1
1
1
Input
6
1 2
2 3
2 4
1 5
5 6
Output
6
2
2
1
1
0
Note
One way to achieve the optimal number of paths for the second sample is illustrated in the following picture:
<image>
|
#include <bits/stdc++.h>
using namespace std;
int N, SQRT_N = 1000;
int U, V;
vector<int> Adj[100005];
int Parent[100005];
vector<int> Ord;
int dp[100005], mxch[100005];
int Ans[100005];
void DFS(int Q) {
for (int i : Adj[Q])
if (i != Parent[Q]) {
Parent[i] = Q;
DFS(i);
}
Ord.push_back(Q);
}
int Solve(int K) {
int mx, mx2;
for (int Q : Ord) {
mx = mx2 = mxch[Q] = dp[Q] = 0;
for (int i : Adj[Q])
if (i != Parent[Q]) {
dp[Q] += dp[i];
if (mx < mxch[i])
mx2 = mx, mx = mxch[i];
else if (mx2 < mxch[i])
mx2 = mxch[i];
}
if (mx + mx2 + 1 >= K)
dp[Q]++;
else
mxch[Q] = mx + 1;
}
return dp[1];
}
int main() {
scanf("%d", &N);
for (int i = 1; i < N; i++) {
scanf("%d%d", &U, &V);
Adj[U].push_back(V);
Adj[V].push_back(U);
}
Parent[1] = -1;
DFS(1);
for (int i = 1; i <= N && i <= SQRT_N; i++) Ans[i] = Solve(i);
int beg = SQRT_N + 1;
int st, en, mid, NowAns;
while (beg <= N) {
st = beg, en = N, mid;
NowAns = Solve(st);
while (st <= en) {
mid = (st + en) >> 1;
if (Solve(mid) == NowAns)
st = mid + 1;
else
en = mid - 1;
}
for (int i = beg; i < st; i++) Ans[i] = NowAns;
beg = st;
}
for (int i = 1; i <= N; i++) printf("%d\n", Ans[i]);
}
|
The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect k-ary tree if each vertex is either a leaf (has no children) or has exactly k children. Also, in perfect k-ary tree all leafs must have same depth.
For example, the picture below illustrates perfect binary tree with 15 vertices:
<image>
There is a perfect k-ary tree with n nodes. The nodes are labeled with distinct integers from 1 to n, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree.
You are allowed to make at most 60 ⋅ n queries of the following type:
* "? a b c", the query returns "Yes" if node with label b lies on the path from a to c and "No" otherwise.
Both a and c are considered to be lying on the path from a to c.
When you are ready to report the root of the tree, print
* "! s", where s is the label of the root of the tree.
It is possible to report the root only once and this query is not counted towards limit of 60 ⋅ n queries.
Interaction
The first line of the standard input stream contains two integers n and k (3 ≤ n ≤ 1500, 2 ≤ k < n) — the number of nodes in the tree and the value of k.
It is guaranteed that n is such that the tree forms a perfect k-ary tree.
You can ask at most 60 ⋅ n queries. To ask a query, print a line of form "? a b c", where 1 ≤ a, b, c ≤ n. After that you should read a single line containing "Yes" or "No" depending on the answer of the query.
The tree is fixed for each test and it doesn't depend on your queries.
When you are ready to print the answer, print a line of the form "! s", where s is the label of the root vertex and then terminate your program.
After printing each query do not forget to print end of line and flush the output. Otherwise you may get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* See documentation for other languages.
In case your program will make more than 60 ⋅ n queries, but in other aspects would follow the interaction protocol and terminate coorectly, it will get verdict «Wrong Answer».
Hacks
To hack the solution use the following test format:
The first line should contain integers n and k (3 ≤ n ≤ 1500, 2 ≤ k ≤ 1500) — the number of vertices and the k parameter of the tree.
Of course, the value of n must correspond to the size of the valid k-ary tree of some depth.
The second line should contain a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the labels of the tree in the natural order, all labels must be distinct.
Let's call the following ordering of the tree vertices to be natural: first the root of the tree goes, then go all vertices on depth of one edge from root, ordered from left to right, then go all vertices on depth of two edges from root, ordered from left to right, and so on until the maximum depth.
This way, the a_1 is the answer for the hack.
Example
Input
3 2
No
Yes
Output
? 1 3 2
? 1 2 3
! 2
Note
The tree in the example is as follows:
<image>
The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity).
The hack corresponding to the example would look like:
3 2
2 3 1
|
#include <bits/stdc++.h>
using namespace std;
const int INF = INT_MAX;
const long long INFL = LLONG_MAX;
const long double pi = acos(-1);
int N, K;
string result;
int cnt;
int ask(int a, int b, int c) {
cnt++;
if (cnt > 60 * N) {
cout << "TOO MANY eQUESTIONS" << '\n';
}
cout << "? " << a << " " << b << " " << c << '\n';
cout.flush();
cin >> result;
return result == "Yes";
}
void answer(int u) {
cout << "! " << u << '\n';
exit(0);
}
int main() {
mt19937 rng(505);
cin >> N >> K;
vector<pair<int, int> > results;
int random_query_count = 30;
string result;
for (int u = 1; u <= N; u++) {
int success = 0;
for (int i = 1; i <= random_query_count; i++) {
int a = rng() % N + 1;
int b = rng() % N + 1;
if (ask(a, u, b)) {
success++;
}
}
results.push_back(make_pair(success, u));
}
sort(results.begin(), results.end());
int expected = (N - 1) / K;
reverse(results.begin(), results.end());
for (int i = 0; i < min(60 - random_query_count, int((results).size()));
i++) {
int u = results[i].second;
int another = 1;
if (u == another) another = 2;
int success = 0;
for (int v = 1; v <= N; v++) {
if (ask(another, u, v)) {
success++;
}
}
if (N - success == expected) {
answer(u);
}
}
}
|
The Fair Nut got stacked in planar world. He should solve this task to get out.
You are given n rectangles with vertexes in (0, 0), (x_i, 0), (x_i, y_i), (0, y_i). For each rectangle, you are also given a number a_i. Choose some of them that the area of union minus sum of a_i of the chosen ones is maximum.
It is guaranteed that there are no nested rectangles.
Nut has no idea how to find the answer, so he asked for your help.
Input
The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of rectangles.
Each of the next n lines contains three integers x_i, y_i and a_i (1 ≤ x_i, y_i ≤ 10^9, 0 ≤ a_i ≤ x_i ⋅ y_i).
It is guaranteed that there are no nested rectangles.
Output
In a single line print the answer to the problem — the maximum value which you can achieve.
Examples
Input
3
4 4 8
1 5 0
5 2 10
Output
9
Input
4
6 2 4
1 6 2
2 4 3
5 3 8
Output
10
Note
In the first example, the right answer can be achieved by choosing the first and the second rectangles.
In the second example, the right answer can also be achieved by choosing the first and the second rectangles.
|
#include <bits/stdc++.h>
using namespace std;
const int N = (int)1e6 + 15;
const long long inf = (long long)9e18;
const int MOD = 998244353;
const double eps = 1e-10;
const double PI = acos(-1);
inline double dcmp(double x) { return fabs(x) < eps ? 0 : (x > 0 ? 1 : -1); }
struct Node {
long long x, y, w;
bool operator<(const Node& b) const { return x < b.x; }
};
Node in[N], que[N];
long long a[N];
int x[N], y[N];
inline long long calc(long long xj, long long yi, long long fj) {
return fj - xj * yi;
}
inline double cmp(const Node& a, const Node& b) {
return (double)(b.y - a.y) / (b.x - a.x);
}
int main() {
int n;
while (~scanf("%d", &n)) {
for (int i = 1; i <= n; i++) {
scanf("%lld%lld%lld", &in[i].x, &in[i].y, &in[i].w);
}
sort(in + 1, in + 1 + n);
for (int i = 1; i <= n; i++) {
x[i] = in[i].x, y[i] = in[i].y, a[i] = in[i].w;
}
long long ans = 0;
que[1] = Node{0, 0, 0};
for (int i = 1, it = 1, tail = 1; i <= n; i++) {
while (it + 1 <= tail && calc(que[it].x, y[i], que[it].y) <=
calc(que[it + 1].x, y[i], que[it + 1].y)) {
it++;
}
long long maxx = (it <= tail ? calc(que[it].x, y[i], que[it].y) : 0) +
1LL * x[i] * y[i] - a[i];
ans = max(ans, maxx);
while (tail >= 2 &&
cmp(que[tail - 1], que[tail]) < cmp(que[tail], Node{x[i], maxx})) {
tail--;
}
it = max(min(tail, it), 1);
que[++tail] = Node{x[i], maxx};
}
printf("%lld\n", ans);
}
}
|
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.
Input
The only line contains a string s consisting of zeroes and ones (1 ≤ |s| ≤ 1000). Zero describes vertical tile, one describes horizontal tile.
Output
Output |s| lines — for each tile you should output two positive integers r,c, not exceeding 4, representing numbers of smallest row and column intersecting with it.
If there exist multiple solutions, print any of them.
Example
Input
010
Output
1 1
1 2
1 4
Note
Following image illustrates the example after placing all three tiles:
<image> Then the first row is deleted: <image>
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int cnt0 = 0, cnt1 = 1;
string s;
cin >> s;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '0') {
cnt0++;
cout << 3 << " " << cnt0 << endl;
if (cnt0 == 4) {
cnt0 = 0;
}
} else {
cout << 1 << " " << cnt1 % 4 << endl;
cnt1 += 2;
}
}
}
|
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 ≥ w_2. In this game, exactly one ship is used, made up of two rectangles. There are no other ships on the field.
The rectangles are placed on field in the following way:
* the second rectangle is on top the first rectangle;
* they are aligned to the left, i.e. their left sides are on the same line;
* the rectangles are adjacent to each other without a gap.
See the pictures in the notes: the first rectangle is colored red, the second rectangle is colored blue.
Formally, let's introduce a coordinate system. Then, the leftmost bottom cell of the first rectangle has coordinates (1, 1), the rightmost top cell of the first rectangle has coordinates (w_1, h_1), the leftmost bottom cell of the second rectangle has coordinates (1, h_1 + 1) and the rightmost top cell of the second rectangle has coordinates (w_2, h_1 + h_2).
After the ship is completely destroyed, all cells neighboring by side or a corner with the ship are marked. Of course, only cells, which don't belong to the ship are marked. On the pictures in the notes such cells are colored green.
Find out how many cells should be marked after the ship is destroyed. The field of the game is infinite in any direction.
Input
Four lines contain integers w_1, h_1, w_2 and h_2 (1 ≤ w_1, h_1, w_2, h_2 ≤ 10^8, w_1 ≥ w_2) — the width of the first rectangle, the height of the first rectangle, the width of the second rectangle and the height of the second rectangle. You can't rotate the rectangles.
Output
Print exactly one integer — the number of cells, which should be marked after the ship is destroyed.
Examples
Input
2 1 2 1
Output
12
Input
2 2 1 2
Output
16
Note
In the first example the field looks as follows (the first rectangle is red, the second rectangle is blue, green shows the marked squares):
<image>
In the second example the field looks as:
<image>
|
#include <bits/stdc++.h>
using namespace std;
int main() {
long long w1, h1, w2, h2;
cin >> w1 >> h1 >> w2 >> h2;
cout << 2 * (w1 + h1 + h2) + 4 << endl;
return 0;
}
|
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.
Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, …), and the second set consists of even positive numbers (2, 4, 6, 8, …). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another.
The ten first written numbers: 1, 2, 4, 3, 5, 7, 9, 6, 8, 10. Let's number the numbers written, starting with one.
The task is to find the sum of numbers with numbers from l to r for given integers l and r. The answer may be big, so you need to find the remainder of the division by 1000000007 (10^9+7).
Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.
Input
The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{18}) — the range in which you need to find the sum.
Output
Print a single integer — the answer modulo 1000000007 (10^9+7).
Examples
Input
1 3
Output
7
Input
5 14
Output
105
Input
88005553535 99999999999
Output
761141116
Note
In the first example, the answer is the sum of the first three numbers written out (1 + 2 + 4 = 7).
In the second example, the numbers with numbers from 5 to 14: 5, 7, 9, 6, 8, 10, 12, 14, 16, 18. Their sum is 105.
|
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
mod=10**9+7
def fun(x):
sm=0
c1,c2=1,2
p=1
while x:
temp=min(x,p)
sm+=(c1+temp-1)*temp
sm%=mod
c1+=2*temp
c1,c2=c2,c1
x-=temp
p*=2
return sm
l,r=in_arr()
pr_num((fun(r)-fun(l-1))%mod)
|
Nauuo is a girl who loves playing chess.
One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c).
The game's goal is to place n chess pieces numbered from 1 to n on the chessboard, the i-th piece lies on (r_i,\,c_i), while the following rule is satisfied: for all pairs of pieces i and j, |r_i-r_j|+|c_i-c_j|≥|i-j|. Here |x| means the absolute value of x.
However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.
She wants to find the smallest chessboard on which she can put n pieces according to the rules.
She also wonders how to place the pieces on such a chessboard. Can you help her?
Input
The only line contains a single integer n (1≤ n≤ 1000) — the number of chess pieces for the game.
Output
The first line contains a single integer — the minimum value of m, where m is the length of sides of the suitable chessboard.
The i-th of the next n lines contains two integers r_i and c_i (1≤ r_i,c_i≤ m) — the coordinates of the i-th chess piece.
If there are multiple answers, print any.
Examples
Input
2
Output
2
1 1
1 2
Input
4
Output
3
1 1
1 3
3 1
3 3
Note
In the first example, you can't place the two pieces on a 1×1 chessboard without breaking the rule. But you can place two pieces on a 2×2 chessboard like this:
<image>
In the second example, you can't place four pieces on a 2×2 chessboard without breaking the rule. For example, if you place the pieces like this:
<image>
then |r_1-r_3|+|c_1-c_3|=|1-2|+|1-1|=1, |1-3|=2, 1<2; and |r_1-r_4|+|c_1-c_4|=|1-2|+|1-2|=2, |1-4|=3, 2<3. It doesn't satisfy the rule.
However, on a 3×3 chessboard, you can place four pieces like this:
<image>
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, ans;
scanf("%d", &n);
ans = n / 2 + 1;
printf("%d", ans);
for (i = 1; i <= ans; ++i) printf("\n%d 1", i);
for (i = 2; i <= n - ans + 1; ++i) printf("\n%d %d", ans, i);
}
|
Tokitsukaze and her friends are trying to infiltrate a secret base built by Claris. However, Claris has been aware of that and set a bomb which is going to explode in a minute. Although they try to escape, they have no place to go after they find that the door has been locked.
At this very moment, CJB, Father of Tokitsukaze comes. With his magical power given by Ereshkigal, the goddess of the underworld, CJB is able to set m barriers to protect them from the explosion. Formally, let's build a Cartesian coordinate system on the plane and assume the bomb is at O(0, 0). There are n persons in Tokitsukaze's crew, the i-th one of whom is at P_i(X_i, Y_i). Every barrier can be considered as a line with infinity length and they can intersect each other. For every person from Tokitsukaze's crew, there must be at least one barrier separating the bomb and him, which means the line between the bomb and him intersects with at least one barrier. In this definition, if there exists a person standing at the position of the bomb, any line through O(0, 0) will satisfy the requirement.
Although CJB is very powerful, he still wants his barriers to be as far from the bomb as possible, in order to conserve his energy. Please help him calculate the maximum distance between the bomb and the closest barrier while all of Tokitsukaze's crew are safe.
Input
The first line contains two integers n, m (1 ≤ n, m ≤ 10^5), indicating the number of people and the number of barriers respectively.
The i-th line of the next n lines contains two integers X_i, Y_i (-10^5 ≤ X_i, Y_i ≤ 10^5), indicating the i-th person's location P_i(X_i, Y_i). Note that P_i may have the same coordinates as P_j (j ≠ i) or even O.
Output
Print a single real number — the maximum distance meeting the requirement. Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if (|a - b|)/(max(1, |b|)) ≤ 10^{-6}.
Examples
Input
3 1
2 0
0 2
-1 0
Output
0.0000000000
Input
1 1
0 0
Output
0.0000000000
Input
2 1
-1 -1
-1 -1
Output
1.4142135617
Input
3 100000
3 2
-1 -3
2 -5
Output
3.1622776602
Note
In the first two examples, CJB must set the barrier crossing O(0, 0).
In the last two examples, CJB can set each barrier crossing some P_i such that the barrier is perpendicular to the line between P_i and O.
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class t, class u>
void chmax(t& first, u second) {
if (first < second) first = second;
}
template <class t, class u>
void chmin(t& first, u second) {
if (second < first) first = second;
}
template <class t>
using vc = vector<t>;
template <class t>
using vvc = vc<vc<t>>;
using pi = pair<ll, ll>;
using vi = vc<ll>;
template <class t, class u>
ostream& operator<<(ostream& os, const pair<t, u>& p) {
return os << "{" << p.first << "," << p.second << "}";
}
template <class t>
ostream& operator<<(ostream& os, const vc<t>& v) {
os << "{";
for (auto e : v) os << e << ",";
return os << "}";
}
using uint = unsigned;
using ull = unsigned long long;
template <ll i, class T>
void print_tuple(ostream&, const T&) {}
template <ll i, class T, class H, class... Args>
void print_tuple(ostream& os, const T& t) {
if (i) os << ",";
os << get<i>(t);
print_tuple<i + 1, T, Args...>(os, t);
}
template <class... Args>
ostream& operator<<(ostream& os, const tuple<Args...>& t) {
os << "{";
print_tuple<0, tuple<Args...>, Args...>(os, t);
return os << "}";
}
void print(ll x, ll suc = 1) {
cout << x;
if (suc == 1) cout << endl;
if (suc == 2) cout << " ";
}
ll read() {
ll i;
cin >> i;
return i;
}
vi readvi(ll n, ll off = 0) {
vi v(n);
for (ll i = ll(0); i < ll(n); i++) v[i] = read() + off;
return v;
}
template <class T>
void print(const vector<T>& v, ll suc = 1) {
for (ll i = ll(0); i < ll(v.size()); i++)
print(v[i], i == ll(v.size()) - 1 ? suc : 2);
}
string readString() {
string s;
cin >> s;
return s;
}
template <class T>
T sq(const T& t) {
return t * t;
}
void yes(bool ex = true) {
cout << "Yes" << endl;
if (ex) exit(0);
}
void no(bool ex = true) {
cout << "No" << endl;
if (ex) exit(0);
}
constexpr ll ten(ll n) { return n == 0 ? 1 : ten(n - 1) * 10; }
const ll infLL = LLONG_MAX / 3;
const ll inf = infLL;
ll topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); }
ll topbit(ll t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); }
ll popcount(signed t) { return __builtin_popcount(t); }
ll popcount(ll t) { return __builtin_popcountll(t); }
bool ispow2(ll i) { return i && (i & -i) == i; }
bool inc(ll first, ll second, ll c) { return first <= second && second <= c; }
template <class t>
void mkuni(vc<t>& v) {
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
}
ll rand_int(ll l, ll r) {
static random_device rd;
static mt19937 gen(rd());
return uniform_int_distribution<ll>(l, r)(gen);
}
template <class t, class u>
struct slide {
vc<t> x;
vi y;
u f;
ll second, e, c, d;
slide(ll n, u ff = u()) : x(n), y(n), f(ff) { init(); }
void init() { second = e = c = d = 0; }
void push(t first) {
while (second < e && f(x[e - 1], first)) e--;
x[e] = first;
y[e++] = c++;
}
void pop() {
if (y[second] == d) second++;
d++;
}
t get() { return x[second]; }
};
using ld = long double;
using cm = complex<ld>;
const ld eps = 0;
const ld PI = acos(ld(-1));
ll sgn(ld first) { return first < -eps ? -1 : (first > eps ? 1 : 0); }
ld dot(cm first, cm second) {
return first.real() * second.real() + first.imag() * second.imag();
}
ld crs(cm first, cm second) {
return first.real() * second.imag() - first.imag() * second.real();
}
ld crs(cm first, cm second, cm c) { return crs(second - first, c - first); }
ll ccw(cm first, cm second) { return sgn(crs(first, second)); }
ll ccw(cm first, cm second, cm c) { return ccw(second - first, c - first); }
auto cmcmp = [](cm first, cm second) {
ll s = sgn(first.real() - second.real());
if (s)
return s < 0;
else
return sgn(first.imag() - second.imag()) < 0;
};
bool cmeq(cm first, cm second) {
return sgn(first.real() - second.real()) == 0 &&
sgn(first.imag() - second.imag()) == 0;
};
ll argtype(cm first) {
if (sgn(first.imag()) == 0) return first.real() < 0 ? 1 : 0;
return first.imag() < 0 ? 0 : 1;
}
ll argcmp(cm first, cm second) {
ll at = argtype(first), bt = argtype(second);
if (at != bt) return at < bt ? -1 : 1;
return -ccw(first, second);
};
ll bet(cm first, cm second, cm c) {
cm d = second - first;
ld e = dot(d, c - first);
if (sgn(e) <= 0) return sgn(e) - 1;
return sgn(e - norm(d)) + 1;
}
ll qeq(ld first, ld second, ld c, ld& d, ld& e) {
ld f = second * second - 4 * first * c;
if (sgn(f) < 0) return 0;
ld g = sqrt(max(f, ld(0)));
d = (-second + g) / (2 * first);
e = (-second - g) / (2 * first);
return sgn(f) + 1;
}
ll cont(cm first, cm second, cm c, cm d) {
if (ccw(first, second, c) == -1) swap(second, c);
return min({ccw(first, second, d), ccw(second, c, d), ccw(c, first, d)}) + 1;
}
ld arg(ld first, ld second, ld c) {
return acos(
min(max((first * first + second * second - c * c) / (2 * first * second),
ld(-1)),
ld(1)));
}
ld turn(cm first, cm second, cm c) {
return arg((c - second) / (second - first));
}
using ln = pair<cm, cm>;
cm dir(ln first) { return first.second - first.first; }
cm eval(ln first, ld second) { return first.first + dir(first) * second; }
ll bet(ln first, cm second) { return bet(first.first, first.second, second); }
ll ccw(ln first, cm second) { return ccw(first.first, first.second, second); }
cm proj(ln first, cm second) {
cm c = dir(first);
return first.first + c * dot(c, second - first.first) / norm(c);
}
cm refl(ln first, cm second) { return ld(2) * proj(first, second) - second; }
ld dsp(ln first, cm second) {
cm c = proj(first, second);
if (abs(bet(first.first, first.second, c)) <= 1) return abs(second - c);
return min(abs(second - first.first), abs(second - first.second));
}
ll iss(ln first, ln second) {
ll c1 = ccw(first.first, first.second, second.first),
c2 = ccw(first.first, first.second, second.second);
ll d1 = ccw(second.first, second.second, first.first),
d2 = ccw(second.first, second.second, first.second);
if (c1 || c2 || d1 || d2) return 1 - max(c1 * c2, d1 * d2);
ll f = bet(first.first, first.second, second.first),
g = bet(first.first, first.second, second.second);
if (max(f, g) == -2 || min(f, g) == 2) return 0;
return 3;
}
cm cll(ln first, ln second) {
return eval(first, crs(second.first, second.second, first.first) /
crs(dir(first), dir(second)));
}
ld dss(ln first, ln second) {
if (iss(first, second)) return 0;
return min({dsp(first, second.first), dsp(first, second.second),
dsp(second, first.first), dsp(second, first.second)});
}
ln vbis(cm first, cm second) {
cm c = (first + second) * ld(0.5), d = second - first;
return ln(c, cm(c.real() - d.imag(), c.imag() + d.real()));
}
using cr = pair<cm, ld>;
ll cont(cr first, cm second) {
return sgn(first.second - abs(second - first.first)) + 1;
}
ll ids(cr first, ln second) {
return sgn(first.second - dsp(second, first.first)) + 1;
}
ll ics(cr first, ln second) {
ll c = ids(first, second);
if (c <= 1) return 4 - c;
return sgn(max(abs(second.first - first.first),
abs(second.second - first.first)) -
first.second) +
1;
}
ll ccl(cr first, ln second, ld& c, ld& d) {
cm e = dir(second);
cm f = second.first - first.first;
return qeq(norm(e), 2 * dot(e, f), norm(f) - first.second * first.second, c,
d);
}
ll icc(cr first, cr second) {
ld c = abs(first.first - second.first);
if (sgn(c) == 0 && sgn(first.second - second.second) == 0) return 1;
ll d = sgn(c + first.second - second.second);
if (d <= 0) return d + 3;
ll e = sgn(c + second.second - first.second);
if (e <= 0) return e + 5;
ll f = sgn(first.second + second.second - c);
if (f >= 0) return f + 6;
return 0;
}
pair<ld, ld> ccc(cr first, cr second) {
ld c = arg(second.first - first.first);
ld d = arg(first.second, abs(second.first - first.first), second.second);
return make_pair(c - d, c + d);
}
ld cseg(ld first, ld second) {
return first * first * (second - sin(second)) / 2;
}
cr circumc(cm first, cm second, cm c) {
second -= first;
c -= first;
cm r = norm(second) * c - norm(c) * second;
r = cm(r.imag(), -r.real()) / (2 * crs(second, c));
return cr(first + r, abs(r));
}
cr mindisc(const vc<cm>& p, array<cm, 3> q, ll i, ll j) {
if (i == ll(p.size())) {
if (j == 0)
return {{0, 0}, -1};
else if (j == 1)
return {q[0], 0};
else if (j == 2)
return {(q[0] + q[1]) * ld(0.5), abs(q[0] - q[1]) / 2};
else if (j == 3)
return circumc(q[0], q[1], q[2]);
else
assert(false);
}
cr c = mindisc(p, q, i + 1, j);
if (sgn(abs(c.first - p[i]) - c.second) == 1) {
assert(j < 3);
q[j] = p[i];
return mindisc(p, q, i + 1, j + 1);
} else
return c;
}
cr mindisc(vc<cm> p) {
shuffle(p.begin(), p.end(), mt19937());
return mindisc(p, array<cm, 3>(), 0, 0);
}
signed main() {
cin.tie(0);
ios::sync_with_stdio(0);
cout << fixed << setprecision(20);
ll n, canuse;
cin >> n >> canuse;
vc<cm> z;
ld mn = 0, mx = 1e9;
for (ll i = ll(0); i < ll(n); i++) {
ll first, second;
cin >> first >> second;
if (first == 0 && second == 0) {
cout << 0 << endl;
return 0;
}
z.emplace_back(first, second);
chmin(mx, abs(z.back()));
}
vc<ld> ag(n);
for (ll i = ll(0); i < ll(n); i++) ag[i] = arg(z[i]);
auto rel = [](ld first) {
while (sgn(first) < 0) first += 2 * PI;
while (sgn(first - 2 * PI) > 1) first -= 2 * PI;
return first;
};
slide<pi, greater<pi>> sld(n * 4);
for (ll _ = ll(0); _ < ll(50); _++) {
const ld mid = (mn + mx) / 2;
vc<pair<ld, ld>> lr;
for (ll i = ll(0); i < ll(n); i++) {
ld t = acos(min(ld(1), mid / abs(z[i])));
lr.emplace_back(rel(ag[i] - t), rel(ag[i] + t));
}
vc<ld> pos;
for (auto w : lr) {
pos.push_back(w.first);
pos.push_back(w.second);
}
sort(pos.begin(), pos.end());
pos.erase(
unique(pos.begin(), pos.end(),
[](ld first, ld second) { return sgn(first - second) == 0; }),
pos.end());
ll m = pos.size() * 2;
vi lf(m, -1);
for (auto w : lr) {
ll first =
lower_bound(pos.begin(), pos.end(), w.first - eps) - pos.begin();
ll second =
lower_bound(pos.begin(), pos.end(), w.second - eps) - pos.begin();
if (second < first) second += m / 2;
assert(second + 1 < m);
chmax(lf[second + 1], first);
}
for (ll i = ll(0); i < ll(m - 1); i++) chmax(lf[i + 1], lf[i]);
ll ans = inf;
sld.init();
ll j = 0;
for (ll i = ll(0); i < ll(m); i++) {
while (j < lf[i]) {
sld.pop();
j++;
}
pi cur;
if (lf[i] == -1)
cur = pi(0, i);
else
cur = sld.get();
if (i >= m / 2) chmin(ans, cur.first + (i - m / 2 < cur.second));
cur.first++;
sld.push(cur);
}
void(0);
if (ans <= canuse)
mn = mid;
else
mx = mid;
}
cout << mn << endl;
}
|
This is a harder version of the problem. In this version q ≤ 200 000.
A sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal.
Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value x to value y, you must also change all other elements of value x into y as well. For example, for [3, 3, 1, 3, 2, 1, 2] it isn't allowed to change first 1 to 3 and second 1 to 2. You need to leave 1's untouched or change them to the same value.
You are given a sequence of integers a_1, a_2, …, a_n and q updates.
Each update is of form "i x" — change a_i to x. Updates are not independent (the change stays for the future).
Print the difficulty of the initial sequence and of the sequence after every update.
Input
The first line contains integers n and q (1 ≤ n ≤ 200 000, 0 ≤ q ≤ 200 000), the length of the sequence and the number of the updates.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 200 000), the initial sequence.
Each of the following q lines contains integers i_t and x_t (1 ≤ i_t ≤ n, 1 ≤ x_t ≤ 200 000), the position and the new value for this position.
Output
Print q+1 integers, the answer for the initial sequence and the answer after every update.
Example
Input
5 6
1 2 1 2 1
2 1
4 1
5 3
2 3
4 2
2 1
Output
2
1
0
0
2
3
0
|
#include <bits/stdc++.h>
using namespace std;
namespace mine {
long long qread() {
long long ans = 0, f = 1;
char c = getchar();
while (c < '0' or c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while ('0' <= c and c <= '9') ans = ans * 10 + c - '0', c = getchar();
return ans * f;
}
void write(long long num) {
if (num < 0) putchar('-'), num = -num;
if (num >= 10) write(num / 10);
putchar('0' + num % 10);
}
void write1(long long num) {
write(num);
putchar(' ');
}
void write2(long long num) {
write(num);
putchar('\n');
}
template <typename T>
void chmax(T &x, const T y) {
x = (x > y ? x : y);
}
template <typename T>
void chmin(T &x, const T y) {
x = (x < y ? x : y);
}
long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; }
const int INF = 0x3f3f3f3f;
const int MOD = 998244353;
inline int mm(const int x) { return x >= MOD ? x - MOD : x; }
template <typename T>
inline void add(T &x, const T y) {
x = mm(x + y);
}
inline long long qpower(long long x, long long e, int mod = MOD) {
long long ans = 1;
if (e < 0) {
puts("error");
exit(666);
}
while (e) {
if (e & 1) ans = ans * x % mod;
x = x * x % mod;
e >>= 1;
}
return ans;
}
long long invm(long long x) { return qpower(x, MOD - 2); }
const int N = 2e5 + 10;
int n;
namespace SGT {
int mxc[N * 4];
void change_cnt(int x, int l, int r, int pos, int num) {
if (l == r) {
mxc[x] = num;
return;
}
if (pos <= (l + r) / 2)
change_cnt(x << 1, l, (l + r) / 2, pos, num);
else
change_cnt(x << 1 | 1, (l + r) / 2 + 1, r, pos, num);
mxc[x] = max(mxc[x << 1], mxc[x << 1 | 1]);
}
int ask_cnt(int x, int l, int r, int fl, int fr) {
if (fl > fr) return 0;
if (l == fl and r == fr) return mxc[x];
if (fr <= (l + r) / 2) return ask_cnt(x << 1, l, (l + r) / 2, fl, fr);
if (fl > (l + r) / 2) return ask_cnt(x << 1 | 1, (l + r) / 2 + 1, r, fl, fr);
return max(ask_cnt(x << 1, l, (l + r) / 2, fl, (l + r) / 2),
ask_cnt(x << 1 | 1, (l + r) / 2 + 1, r, (l + r) / 2 + 1, fr));
}
int mif[N * 4], tag[N * 4], mifl[N * 4], mifr[N * 4], sum[N * 4];
void init(int x, int l, int r) {
mifl[x] = l;
mifr[x] = r;
if (l < r) init(x << 1, l, (l + r) / 2), init(x << 1 | 1, (l + r) / 2 + 1, r);
}
void pushdown(int x) {
if (tag[x] != 0)
mif[x << 1] += tag[x], mif[x << 1 | 1] += tag[x], tag[x << 1] += tag[x],
tag[x << 1 | 1] += tag[x], tag[x] = 0;
}
void pushup(int x, int l, int r) {
if (l == r) {
sum[x] = ask_cnt(x, l, r, l, l);
return;
}
pushdown(x);
if (mif[x << 1] == mif[x << 1 | 1]) {
mif[x] = mif[x << 1];
mifl[x] = mifl[x << 1];
mifr[x] = mifr[x << 1 | 1];
sum[x] = sum[x << 1] + sum[x << 1 | 1] -
ask_cnt(x, l, r, mifr[x << 1] + 1, (l + r) / 2) -
ask_cnt(x, l, r, (l + r) / 2 + 1, mifl[x << 1 | 1]) +
ask_cnt(x, l, r, mifr[x << 1] + 1, mifl[x << 1 | 1]);
} else if (mif[x << 1] < mif[x << 1 | 1]) {
mif[x] = mif[x << 1];
mifl[x] = mifl[x << 1];
mifr[x] = mifr[x << 1];
sum[x] = sum[x << 1] - ask_cnt(x, l, r, mifr[x << 1] + 1, (l + r) / 2) +
ask_cnt(x, l, r, mifr[x << 1] + 1, r);
} else {
mif[x] = mif[x << 1 | 1];
mifl[x] = mifl[x << 1 | 1];
mifr[x] = mifr[x << 1 | 1];
sum[x] = sum[x << 1 | 1] -
ask_cnt(x, l, r, (l + r) / 2 + 1, mifl[x << 1 | 1]) +
ask_cnt(x, l, r, l, mifl[x << 1 | 1]);
}
}
void add_f(int x, int l, int r, int fl, int fr, int val) {
if (l == fl and r == fr) {
mif[x] += val;
tag[x] += val;
pushup(x, l, r);
return;
}
pushdown(x);
if (fr <= (l + r) / 2)
add_f(x << 1, l, (l + r) / 2, fl, fr, val);
else if (fl > (l + r) / 2)
add_f(x << 1 | 1, (l + r) / 2 + 1, r, fl, fr, val);
else
add_f(x << 1, l, (l + r) / 2, fl, (l + r) / 2, val),
add_f(x << 1 | 1, (l + r) / 2 + 1, r, (l + r) / 2 + 1, fr, val);
pushup(x, l, r);
}
void add_f(int l, int r, int val) {
if (l <= r) add_f(1, 1, n, l, r, val);
}
void change_cnt(int pos, int num) {
change_cnt(1, 1, n, pos, num);
add_f(pos, pos, 0);
}
}; // namespace SGT
int a[N];
set<int> pos[N];
void main() {
n = qread();
int q = qread();
SGT::init(1, 1, n);
for (int i = (1), I = (n); i <= I; i++) a[i] = qread(), pos[a[i]].insert(i);
for (int num = (1), I = (N - 1); num <= I; num++)
if (((int)(pos[num]).size()))
SGT::change_cnt(*pos[num].begin(), ((int)(pos[num]).size())),
SGT::add_f(*pos[num].begin(), *(--pos[num].end()) - 1, 1);
write2(n - SGT::sum[1]);
while (q--) {
int x = qread(), val = qread();
set<int>::iterator now = pos[a[x]].find(x);
SGT::change_cnt(*pos[a[x]].begin(), 0);
if (((int)(pos[a[x]]).size()) > 1) {
if (now == pos[a[x]].begin())
SGT::add_f(x, *(++now) - 1, -1);
else if (now == --pos[a[x]].end())
SGT::add_f(*(--now), x - 1, -1);
}
pos[a[x]].erase(x);
if (((int)(pos[a[x]]).size()))
SGT::change_cnt(*pos[a[x]].begin(), ((int)(pos[a[x]]).size()));
a[x] = val;
pos[a[x]].insert(x);
SGT::change_cnt(*pos[a[x]].begin(), ((int)(pos[a[x]]).size()));
now = pos[a[x]].find(x);
if (((int)(pos[a[x]]).size()) > 1) {
if (now == pos[a[x]].begin()) {
now++;
SGT::add_f(x, *now - 1, 1);
SGT::change_cnt(*now, 0);
} else if (now == --pos[a[x]].end())
SGT::add_f(*(--now), x - 1, 1);
}
write2(n - SGT::sum[1]);
}
}
}; // namespace mine
signed main() {
srand(time(0));
mine::main();
}
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya was delivered a string s, containing only digits. He needs to find a string that
* represents a lucky number without leading zeroes,
* is not empty,
* is contained in s as a substring the maximum number of times.
Among all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya.
Input
The single line contains a non-empty string s whose length can range from 1 to 50, inclusive. The string only contains digits. The string can contain leading zeroes.
Output
In the only line print the answer to Petya's problem. If the sought string does not exist, print "-1" (without quotes).
Examples
Input
047
Output
4
Input
16
Output
-1
Input
472747
Output
7
Note
The lexicographical comparison of strings is performed by the < operator in the modern programming languages. String x is lexicographically less than string y either if x is a prefix of y, or exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of string a.
In the first sample three conditions are fulfilled for strings "4", "7" and "47". The lexicographically minimum one is "4".
In the second sample s has no substrings which are lucky numbers.
In the third sample the three conditions are only fulfilled for string "7".
|
import sys
#sys.stdin = open('in.txt', 'r')
s = str(raw_input())
c4, c7 = 0, 0
for it in s:
if it == '4':
c4 += 1
elif it == '7':
c7 += 1
if c4 + c7 == 0:
print '-1'
else:
print '4' if c4 >= c7 else '7'
|
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning.
To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string s appeared on the screen. When Polycarp presses a button with character c, one of the following events happened:
* if the button was working correctly, a character c appeared at the end of the string Polycarp was typing;
* if the button was malfunctioning, two characters c appeared at the end of the string.
For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a → abb → abba → abbac → abbaca → abbacabb → abbacabba.
You are given a string s which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).
You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases in the input.
Then the test cases follow. Each test case is represented by one line containing a string s consisting of no less than 1 and no more than 500 lowercase Latin letters.
Output
For each test case, print one line containing a string res. The string res should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, res should be empty.
Example
Input
4
a
zzaaz
ccff
cbddbb
Output
a
z
bc
|
'''
@judge CodeForces
@id 1251A
@name Broken Keyboard
@tag Simulation
'''
from sys import stdin
from itertools import groupby
def solve(s):
return ''.join(sorted(set(map(lambda p: str(p[0]), filter(lambda p: len(list(p[1])) & 1, groupby(s))))))
input()
for line in stdin:
print(solve(line.strip()))
|
Suppose that we have an array of n distinct numbers a_1, a_2, ..., a_n. Let's build a graph on n vertices as follows: for every pair of vertices i < j let's connect i and j with an edge, if a_i < a_j. Let's define weight of the array to be the number of connected components in this graph. For example, weight of array [1, 4, 2] is 1, weight of array [5, 4, 3] is 3.
You have to perform q queries of the following form — change the value at some position of the array. After each operation, output the weight of the array. Updates are not independent (the change stays for the future).
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 5 ⋅ 10^5) — the size of the array and the number of queries.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — the initial array.
Each of the next q lines contains two integers pos and x (1 ≤ pos ≤ n, 1 ≤ x ≤ 10^6, x ≠ a_{pos}). It means that you have to make a_{pos}=x.
It's guaranteed that at every moment of time, all elements of the array are different.
Output
After each query, output the weight of the array.
Example
Input
5 3
50 40 30 20 10
1 25
3 45
1 48
Output
3
3
4
Note
After the first query array looks like [25, 40, 30, 20, 10], the weight is equal to 3.
After the second query array looks like [25, 40, 45, 20, 10], the weight is still equal to 3.
After the third query array looks like [48, 40, 45, 20, 10], the weight is equal to 4.
|
#include <bits/stdc++.h>
using namespace std;
const int SIZE = 1e6 + 10;
int n, q, m;
int a[SIZE], xi[SIZE];
int ql, qr, qv, qt;
class SegmentTree {
public:
int size;
int lazyTag[SIZE << 2];
struct Node {
int v, c;
friend Node operator+(Node A, Node B) {
Node C;
C.v = min(A.v, B.v), C.c = 0;
if (A.v == C.v) C.c += A.c;
if (B.v == C.v) C.c += B.c;
return C;
}
} node[SIZE << 2];
void add(int c, int t) {
lazyTag[c] += t;
node[c].v += t;
}
void updateDown(int c) {
if (lazyTag[c]) {
add(c * 2, lazyTag[c]);
add(c * 2 + 1, lazyTag[c]);
lazyTag[c] = 0;
}
}
void updateUp(int c) { node[c] = node[c * 2] + node[c * 2 + 1]; }
void get(int c, int l) {
if (xi[l])
node[c] = (Node){lazyTag[c], 1};
else
node[c] = (Node){1000000000, 0};
}
void update1(int l, int r, int c) {
if (ql <= l && qr >= r) return add(c, qt);
int mid = (l + r) / 2;
updateDown(c);
if (ql <= mid) update1(l, mid, c * 2);
if (qr > mid) update1(mid + 1, r, c * 2 + 1);
updateUp(c);
}
void build(int l, int r, int c) {
if (l == r) return get(c, l);
int mid = (l + r) / 2;
updateDown(c);
build(l, mid, c * 2), build(mid + 1, r, c * 2 + 1);
updateUp(c);
}
void update2(int l, int r, int c) {
if (l == r) return get(c, l);
int mid = (l + r) / 2;
updateDown(c);
if (qv <= mid)
update2(l, mid, c * 2);
else
update2(mid + 1, r, c * 2 + 1);
updateUp(c);
}
public:
void insert(int x, int t) {
int l = min(a[x], a[x + 1]), r = max(a[x], a[x + 1]);
ql = l, qr = r - 1, qt = t;
update1(0, size, 1);
}
void update2(int c) { update2(0, size, c); }
void build(int c) { build(0, size, c); }
void setSize(int Size) { size = Size; }
} T;
int main() {
ios::sync_with_stdio(false);
cin >> n >> q;
m = 1e6 + 1;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
xi[a[i]] = 1;
}
a[0] = m, a[n + 1] = 0;
T.setSize(m);
for (int i = 0; i <= n; ++i) T.insert(i, 1);
T.build(1);
while (q--) {
int x, v;
cin >> x >> v;
T.insert(x - 1, -1);
T.insert(x, -1);
xi[a[x]] = 0;
qv = a[x];
T.update2(1);
a[x] = v;
T.insert(x - 1, 1);
T.insert(x, 1);
xi[a[x]] = 1;
qv = a[x];
T.update2(1);
cout << (T.node[1].v == 1 ? T.node[1].c : 1) << endl;
}
return 0;
}
|
[Æsir - CHAOS](https://soundcloud.com/kivawu/aesir-chaos)
[Æsir - V.](https://soundcloud.com/kivawu/aesir-v)
"Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.
The time right now...... 00:01:12......
It's time."
The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.
The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1, 2, 3, …). The node with a number x (x > 1), is directly connected with a node with number (x)/(f(x)), with f(x) being the lowest prime divisor of x.
Vanessa's mind is divided into n fragments. Due to more than 500 years of coma, the fragments have been scattered: the i-th fragment is now located at the node with a number k_i! (a factorial of k_i).
To maximize the chance of successful awakening, Ivy decides to place the samples in a node P, so that the total length of paths from each fragment to P is smallest possible. If there are multiple fragments located at the same node, the path from that node to P needs to be counted multiple times.
In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.
But for a mere human like you, is this still possible?
For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node P.
Input
The first line contains an integer n (1 ≤ n ≤ 10^6) — number of fragments of Vanessa's mind.
The second line contains n integers: k_1, k_2, …, k_n (0 ≤ k_i ≤ 5000), denoting the nodes where fragments of Vanessa's mind are located: the i-th fragment is at the node with a number k_i!.
Output
Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node P).
As a reminder, if there are multiple fragments at the same node, the distance from that node to P needs to be counted multiple times as well.
Examples
Input
3
2 1 4
Output
5
Input
4
3 1 4 4
Output
6
Input
4
3 1 4 1
Output
6
Input
5
3 1 4 1 5
Output
11
Note
Considering the first 24 nodes of the system, the node network will look as follows (the nodes 1!, 2!, 3!, 4! are drawn bold):
<image>
For the first example, Ivy will place the emotion samples at the node 1. From here:
* The distance from Vanessa's first fragment to the node 1 is 1.
* The distance from Vanessa's second fragment to the node 1 is 0.
* The distance from Vanessa's third fragment to the node 1 is 4.
The total length is 5.
For the second example, the assembly node will be 6. From here:
* The distance from Vanessa's first fragment to the node 6 is 0.
* The distance from Vanessa's second fragment to the node 6 is 2.
* The distance from Vanessa's third fragment to the node 6 is 2.
* The distance from Vanessa's fourth fragment to the node 6 is again 2.
The total path length is 6.
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 5000;
vector<int> primes;
vector<int> expansions[MAX_N + 1];
vector<int> factorials[MAX_N + 1];
vector<int> cnt_factorials(MAX_N + 1);
int index_of_prime[MAX_N + 1];
int n;
struct Node {
int cnt = 0;
long long sub_tree_sum = 0;
long long sub_tree_cnt = 0;
vector<pair<Node*, vector<pair<int, int>>>> edges;
};
void get_primes(int n) {
vector<char> numbers(n + 1, 0);
for (int i = 2; i <= n; i++)
if (numbers[i] == false) {
primes.push_back(i);
index_of_prime[i] = primes.size() - 1;
for (int j = i; j <= n; j += i) numbers[j] = true;
}
}
void expansion(int n) {
for (int number = 2; number <= n; number++) {
expansions[number].assign(primes.size(), 0);
int number_copy = number;
for (int div = 2; div * div <= number; div++) {
int cnt = 0;
while (number_copy % div == 0) {
cnt++;
number_copy /= div;
}
expansions[number][index_of_prime[div]] += cnt;
}
if (number_copy != 1) expansions[number][index_of_prime[number_copy]] += 1;
}
}
void factorials_expansion(int n) {
factorials[1].assign(primes.size(), 0);
for (int number = 2; number <= n; number++) {
factorials[number] = factorials[number - 1];
for (int i = 0; i < primes.size(); i++)
factorials[number][i] += expansions[number][i];
}
}
int roll(int factorial, int iPrime) {
while (iPrime >= 0 && factorials[factorial][iPrime] == 0) iPrime--;
return iPrime;
}
void add_factorial(Node* node, int factorial, int iPrime, int rest) {
int cpy_iPrime = iPrime;
if (rest == 0 && iPrime >= 0) iPrime--;
iPrime = roll(factorial, iPrime);
if (iPrime == -1) {
node->cnt += cnt_factorials[factorial];
return;
}
if (cpy_iPrime != iPrime) rest = factorials[factorial][iPrime];
bool common = false;
for (int i = 0; i < node->edges.size(); i++) {
if (node->edges[i].second[0].first == iPrime) {
int prefix_prime = 0, common_rest = 0;
while (prefix_prime < node->edges[i].second.size() &&
node->edges[i].second[prefix_prime].first == iPrime) {
int rest_in_edge = node->edges[i].second[prefix_prime].second;
if (rest == rest_in_edge) {
iPrime = roll(factorial, iPrime - 1);
if (iPrime == -1) break;
rest = factorials[factorial][iPrime];
prefix_prime++;
continue;
} else if (rest < rest_in_edge) {
common_rest = rest;
break;
} else if (rest > rest_in_edge) {
rest -= rest_in_edge;
prefix_prime++;
}
}
vector<pair<int, int>> left, right;
left.assign(node->edges[i].second.begin(),
node->edges[i].second.begin() + prefix_prime);
right.assign(node->edges[i].second.begin() + prefix_prime,
node->edges[i].second.end());
if (common_rest != 0) {
left.push_back({right[0].first, common_rest});
right[0].second -= common_rest;
rest = 0;
}
if (prefix_prime == node->edges[i].second.size()) {
add_factorial(node->edges[i].first, factorial, iPrime, rest);
} else {
Node* new_node = new Node();
Node* old_node = node->edges[i].first;
new_node->edges.push_back({old_node, right});
node->edges[i].first = new_node;
node->edges[i].second = left;
add_factorial(new_node, factorial, iPrime, rest);
}
common = true;
break;
}
}
if (!common) {
Node* new_node = new Node();
node->edges.push_back({new_node, vector<pair<int, int>>()});
node->edges.back().second.push_back({iPrime, rest});
iPrime--;
while (iPrime >= 0) {
if (factorials[factorial][iPrime] != 0)
node->edges.back().second.push_back(
{iPrime, factorials[factorial][iPrime]});
iPrime--;
}
add_factorial(new_node, factorial, iPrime, 0);
}
}
void dfs1(Node* node) {
for (auto edge : node->edges) {
dfs1(edge.first);
int cnt = 0;
for (auto pr : edge.second) cnt += pr.second;
node->sub_tree_sum +=
(long long)cnt * edge.first->sub_tree_cnt + edge.first->sub_tree_sum;
node->sub_tree_cnt += edge.first->sub_tree_cnt;
}
node->sub_tree_cnt += node->cnt;
}
long long answer = 1e18;
void dfs2(Node* node, long long rest, int rest_cnt) {
answer = min(answer, node->sub_tree_sum + rest);
long long rest_sum_in_childs = 0;
int rest_cnt_in_childs = 0;
for (auto edge : node->edges) {
rest_sum_in_childs += edge.first->sub_tree_sum;
rest_cnt_in_childs += edge.first->sub_tree_cnt;
}
for (auto edge : node->edges) {
long long current_cnt =
rest_cnt + node->sub_tree_cnt - edge.first->sub_tree_cnt;
int cnt = 0;
for (auto pr : edge.second) cnt += pr.second;
long long child_back =
edge.first->sub_tree_sum + (long long)cnt * edge.first->sub_tree_cnt;
dfs2(edge.first,
(rest + node->sub_tree_sum - child_back) + cnt * (current_cnt),
current_cnt);
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
cnt_factorials[a]++;
}
get_primes(MAX_N);
expansion(MAX_N);
factorials_expansion(MAX_N);
Node* root = new Node();
for (int f = MAX_N; f >= 2; f--) {
if (cnt_factorials[f] != 0) {
add_factorial(root, f, primes.size() - 1, factorials[f].back());
}
}
root->cnt = cnt_factorials[0] + cnt_factorials[1];
dfs1(root);
dfs2(root, 0, 0);
cout << answer;
return 0;
}
|
Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m.
Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 ≤ l_1 ≤ r_1 ≤ n) and a segment [l_2, r_2] (1 ≤ l_2 ≤ r_2 ≤ n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} … a_{r_1} b_{l_2} b_{l_2 + 1} … b_{r_2}.
Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions:
* segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 ≤ x ≤ r_1 and l_2 ≤ x ≤ r_2;
* the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s.
Input
The first line contains integers n and m (1 ≤ n ≤ 500 000, 2 ≤ m ≤ 2 ⋅ n) — the length of strings a and b and the length of the string s.
The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m.
All strings consist of lowercase English letters.
Output
Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.
Examples
Input
6 5
aabbaa
baaaab
aaaaa
Output
4
Input
5 4
azaza
zazaz
azaz
Output
11
Input
9 12
abcabcabc
xyzxyzxyz
abcabcayzxyz
Output
2
Note
Let's list all the pairs of segments that Vasya could choose in the first example:
1. [2, 2] and [2, 5];
2. [1, 2] and [2, 4];
3. [5, 5] and [2, 5];
4. [5, 6] and [3, 5];
|
#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e6 + 11;
const long long oo = 1e17 + 11;
const long long MOD = 1e9 + 7;
const long long base = 41;
int tcases = 1;
int N, M;
int L[maxN], R[maxN];
long long powHash[maxN], res = 0;
long long hhh[maxN];
class I_love_char_array {
public:
int len;
char str[maxN];
long long hash[maxN];
long long gethash(int l, int r) {
return ((hash[r] - hash[l - 1] * powHash[r - l + 1]) % MOD + MOD) % MOD;
}
void run() {
scanf("%s", str + 1);
len = strlen(str + 1);
for (int i = 1; i <= len; ++i)
hash[i] = (hash[i - 1] * base + str[i] - 'a' + 1) % MOD;
}
} a, b, s;
void buildPreSubffiixx() {
for (int i = 1; i <= N; ++i) {
int r = min(M, N - i + 1), l = 0, v = 0;
while (l <= r) {
int mid = (l + r) >> 1;
if (a.gethash(i, i + mid - 1) == s.gethash(1, mid)) {
v = mid;
l = mid + 1;
} else
r = mid - 1;
}
L[i] = v;
l = 0, r = min(i, M), v = 0;
while (l <= r) {
int mid = (l + r) >> 1;
if (b.gethash(i - mid + 1, i) == s.gethash(M - mid + 1, M)) {
v = mid;
l = mid + 1;
} else
r = mid - 1;
}
R[i] = v;
}
}
class I_love_segment_tree {
public:
long long F[maxN * 4];
int G[maxN * 4];
void update(int k, int l, int r, int v, int x) {
if (l > v || r < v) return;
if (l == r) {
F[k] += x * v;
G[k] += x;
return;
}
int mid = (l + r) >> 1;
update(k << 1, l, mid, v, x);
update(k << 1 | 1, mid + 1, r, v, x);
F[k] = F[k << 1] + F[k << 1 | 1];
G[k] = G[k << 1] + G[k << 1 | 1];
}
pair<long long, int> sum(int k, int l, int r, int L, int R) {
if (l > R || L > r) return make_pair(0, 0);
if (L <= l && r <= R) return make_pair(F[k], G[k]);
int mid = (l + r) >> 1;
pair<long long, int> x = sum(k << 1, l, mid, L, R),
y = sum(k << 1 | 1, mid + 1, r, L, R);
return make_pair(x.first + y.first, x.second + y.second);
}
void init() {}
} IT;
void testcase() {
scanf("%d%d", &N, &M);
powHash[0] = 1;
for (int i = 1; i <= max(N, M); ++i)
powHash[i] = (powHash[i - 1] * base) % MOD;
a.run();
b.run();
s.run();
buildPreSubffiixx();
int j = 0;
for (int i = 1; i <= N; ++i) {
while (j < N && j < i + M - 2) {
IT.update(1, 1, M, R[++j], 1);
}
if (L[i] >= M) {
pair<long long, int> tmp = IT.sum(1, 1, M, 1, M - 1);
res += tmp.first;
tmp = IT.sum(1, 1, M, M, M);
res += 1LL * tmp.second * (M - 1);
} else {
pair<long long, int> tmp = IT.sum(1, 1, M, M - L[i], M - 1);
res += 1LL * tmp.second * (L[i] - M + 1) + tmp.first;
tmp = IT.sum(1, 1, M, M, M);
res += 1LL * tmp.second * L[i];
}
IT.update(1, 1, M, R[i], -1);
}
printf("%lli", res);
}
int main() {
for (int i = 1; i <= tcases; ++i) testcase();
return 0;
}
|
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future.
<image>
Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A.
During the divination, Kaavi needs to perform a sequence of operations. There are two different operations:
* Delete the first character of S and add it at the front of A.
* Delete the first character of S and add it at the back of A.
Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353.
Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different.
A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S.
Input
The first line contains a string S of length n (1 ≤ n ≤ 3000).
The second line contains a string T of length m (1 ≤ m ≤ n).
Both strings contain only lowercase Latin letters.
Output
The output contains only one integer — the answer modulo 998 244 353.
Examples
Input
abab
ba
Output
12
Input
defineintlonglong
signedmain
Output
0
Input
rotator
rotator
Output
4
Input
cacdcdbbbb
bdcaccdbbb
Output
24
Note
The first test:
<image>
The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
|
#include <bits/stdc++.h>
using namespace std;
inline int read() {
register int x = 0;
register int y = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') y = 0;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + (c ^ 48);
c = getchar();
}
return y ? x : -x;
}
char s[3005], t[3005];
int f[3005][3005];
int main() {
scanf("%s", s + 1);
scanf("%s", t + 1);
int n = strlen(s + 1), m = strlen(t + 1);
for (register int i = 1; i <= m; i++) f[i][i] = (s[1] == t[i]) << 1;
for (register int i = m + 1; i <= n; i++) f[i][i] = 2;
for (register int i = 2, len = 2; i <= n; i++, len++) {
for (register int l = 1, r = len; r <= n; l++, r++) {
if (l > m || s[i] == t[l]) f[l][r] += f[l + 1][r], f[l][r] %= 998244353;
if (r > m || s[i] == t[r]) f[l][r] += f[l][r - 1], f[l][r] %= 998244353;
}
}
int ans = 0;
for (register int i = m; i <= n; i++) ans = (ans + f[1][i]) % 998244353;
printf("%d", ans);
return 0;
}
|
Oh, no!
The coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem.
You are given two arrays A and B of size n. You can do operations of two types with array A:
* Reverse array A. That is the array [A_1,\ A_2,\ …,\ A_n] transformes into [A_n,\ A_{n-1},\ …,\ A_1].
* Replace A with an array of its prefix sums. That is, the array [A_1,\ A_2,\ …,\ A_n] goes to [A_1,\ (A_1+A_2),\ …,\ (A_1+A_2+…+A_n)].
You need to understand if you can get an array B from the array A. If it is possible, you will have to restore the order of these operations by minimizing the number of operations of the second type. Fortunately, the coronavirus is good today, so he has allowed you not to restore actions if the minimum number of second type operations is more than 2⋅ 10^5. But coronavirus resents you, so if you restore the answer, the total number of operations should not exceed 5⋅ 10^5.
Solve this problem and get the cookie, or the coronavirus will extend the quarantine for five years and make the whole economy collapse!
Input
The first line contains a single integer n (1≤ n ≤ 2⋅ 10^5).
The second line contains n integers A_1, A_2, …, A_n (1 ≤ A_i ≤ 10 ^ {12}).
The third line contains n integers B_1, B_2, …, B_n (1 ≤ B_i ≤ 10 ^ {12}).
Output
If you cannot get B from the A array, print "IMPOSSIBLE" (without quotes) on a single line.
If the minimum number of operations of the second type exceeds 2⋅ 10^5, print "BIG" (without quotes). In the second line print the number of operations of the second type, that needs to be applied to get array B from A.
Otherwise, in the first line print "SMALL" (without quotes). In the second line print the total number of operations of the first and second types m ≤ 5⋅ 10^5 (it is guaranteed that in this case there is such a sequence of actions). In the third line print a line of length m, consisting of characters 'R"and 'P' (without quotes).
The i-th character should be 'R', if the i-th action is of the first type, and should be 'P', otherwise.
If there are several such sequences, you can print any of them.
You can print each character in the uppercase or in the lowercase.
Examples
Input
2
5 7
5 7
Output
SMALL
0
Input
2
1 1
300000 1
Output
BIG
299999
Input
2
10 1
13 14
Output
SMALL
6
RPPPRP
Input
3
1 2 1
2 1 2
Output
IMPOSSIBLE
Note
In the first example, the arrays A and B already equal, so the number of required operations =0.
In the second example, we need to replace A with the prefix sums 299999 times and then reverse the array. Since 299999>2⋅ 10^5, there is no need to restore the answer.
In the fourth example, you cannot get B from the A.
|
#include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
const long double eps = 1e-6;
long double sign(long double x) { return (x > 0) - (x < 0); }
long long sign(long long x) { return (x > 0) - (x < 0); }
int sign(int x) { return (x > 0) - (x < 0); }
struct pt {
long double x, y;
pt() {}
pt(long double _x, long double _y) : x(_x), y(_y) {}
bool operator<(pt p) { return tie(x, y) < tie(p.x, p.y); }
bool operator==(pt p) { return tie(x, y) == tie(p.x, p.y); }
pt operator+(pt p) { return {x + p.x, y + p.y}; }
pt operator-(pt p) { return {x - p.x, y - p.y}; }
pt operator*(long double d) { return {x * d, y * d}; }
pt operator/(long double d) { return {x / d, y / d}; }
long double dot(pt p) { return x * p.x + y * p.y; }
long double det(pt p) { return x * p.y - y * p.x; }
long double cross(pt p, pt q) { return (p - *this).det(q - *this); }
long double dist() { return sqrtl(x * x + y * y); }
pt rot90() { return pt(-y, x); }
pt unit() { return *this / dist(); }
long double angle() { return atan2(y, x); }
pt rot(long double an) {
return {x * cos(an) - y * sin(an), x * sin(an) + y * cos(an)};
}
void read() { cin >> x >> y; }
void write() { cout << "(" << x << "," << y << ")" << endl; }
};
struct seg {
pt fi, sc;
seg() {}
seg(pt _fi, pt _sc) : fi(_fi), sc(_sc) {}
long double dist(pt C) {
if (fi == sc) return (C - fi).dist();
long double d = pow((sc - fi).dist(), 2);
long double t = min(d, max((long double)0.0, (C - fi).dot(sc - fi)));
return ((C - fi) * d - (sc - fi) * t).dist() / d;
}
long double len() { return (fi - sc).dist(); }
bool on_seg(pt C) {
return abs(C.cross(fi, sc)) < eps && (fi - C).dot(sc - C) <= eps;
}
vector<pt> intersect(seg rhs) {
long double oa = rhs.fi.cross(rhs.sc, fi);
long double ob = rhs.fi.cross(rhs.sc, sc);
long double oc = fi.cross(sc, rhs.fi);
long double od = fi.cross(sc, rhs.sc);
if (sign(oa) * sign(ob) < 0 && sign(oc) * sign(od) < 0)
return {(fi * ob - sc * oa) / (ob - oa)};
vector<pt> ans;
if (rhs.on_seg(fi)) ans.push_back(fi);
if (rhs.on_seg(sc)) ans.push_back(sc);
if (on_seg(rhs.fi)) ans.push_back(rhs.fi);
if (on_seg(rhs.sc)) ans.push_back(rhs.sc);
return ans;
}
};
struct line {
long double a, b, c;
line(pt p1, pt p2) {
assert(!(p1 == p2));
a = p2.y - p1.y;
b = p1.x - p2.x;
c = a * p1.x + b * p1.y;
}
line() {}
line(long double _a, long double _b, long double _c) : a(_a), b(_b), c(_c) {}
long double dist(pt p) {
return fabs(a * p.x + b * p.y - c) / sqrtl(a * a + b * b);
}
pair<int, pt> intersect(line rhs) {
long double dett = a * rhs.b - b * rhs.a;
if (fabs(dett) <= eps) {
long double det2 = c * rhs.a - a * rhs.c;
if (fabs(det2) <= eps) return {-1, pt()};
return {0, pt()};
}
return {1,
pt((c * rhs.b - rhs.c * b) / dett, (a * rhs.c - c * rhs.a) / dett)};
}
};
pt reflect(pt A, line L) {
line perpendicular(-L.b, L.a, -L.b * A.x + L.a * A.y);
pt insect = perpendicular.intersect(L).second;
return insect * (long double)2.0 - A;
}
struct mint {
int val;
mint() { val = 0; }
mint(const long long& v) {
val = (-mod <= v && v < mod) ? v : v % mod;
if (val < 0) val += mod;
}
friend ostream& operator<<(ostream& os, const mint& a) { return os << a.val; }
friend bool operator==(const mint& a, const mint& b) {
return a.val == b.val;
}
friend bool operator!=(const mint& a, const mint& b) {
return a.val != b.val;
}
friend bool operator<(const mint& a, const mint& b) { return a.val < b.val; }
friend bool operator>(const mint& a, const mint& b) { return a.val > b.val; }
friend bool operator<=(const mint& a, const mint& b) {
return a.val <= b.val;
}
friend bool operator>=(const mint& a, const mint& b) {
return a.val >= b.val;
}
mint operator-() { return mint(-val); }
mint& operator+=(const mint& m) {
if ((val += m.val) >= mod) val -= mod;
return *this;
}
mint& operator-=(const mint& m) {
if ((val -= m.val) < mod) val += mod;
return *this;
}
mint& operator*=(const mint& m) {
val = (val * 1ll * m.val) % mod;
return *this;
}
friend mint pow(mint a, long long p) {
mint ans = 1;
for (; p; p /= 2, a *= a)
if (p % 2 == 1) ans *= a;
return ans;
}
friend mint inv(const mint& a) {
assert(a.val);
return pow(a, mod - 2);
}
mint& operator/=(const mint& m) { return (*this) *= inv(m); }
friend mint operator+(mint a, const mint& b) { return a += b; }
friend mint operator-(mint a, const mint& b) { return a -= b; }
friend mint operator*(mint a, const mint& b) { return a *= b; }
friend mint operator/(mint a, const mint& b) { return a /= b; }
};
int solve();
void precomp();
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
if (0) cin >> t;
if (0) cout << fixed << setprecision(10);
precomp();
for (int tc = 1; tc <= t; tc++) {
if (0 && 0) cout << "Case #" << tc << ": ";
solve();
}
}
void precomp() { return; }
int n;
vector<long long> a, b;
bool isinc(vector<long long> x) {
for (int i = 1; i < x.size(); i++)
if (x[i] <= x[i - 1]) return false;
return true;
}
bool isdec(vector<long long> x) {
for (int i = 1; i < x.size(); i++)
if (x[i] >= x[i - 1]) return false;
return true;
}
vector<long long> invpref(vector<long long> x) {
vector<long long> u(n);
u[0] = x[0];
for (int i = 1; i < n; i++) u[i] = x[i] - x[i - 1];
return u;
}
void rev(vector<long long>& x) { reverse(x.begin(), x.end()); }
int solve() {
cin >> n;
a.resize(n);
b.resize(n);
long long suma = 0ll, sumb = 0ll;
for (int i = 0; i < n; i++) {
cin >> a[i];
suma += a[i];
}
for (int j = 0; j < n; j++) {
cin >> b[j];
sumb += b[j];
}
vector<long long> arev = a;
rev(arev);
long long ipc = 0;
if (n > 2) {
string ans = "";
for (;;) {
if (suma == sumb) {
if (arev == b) {
ans += 'R';
rev(b);
}
if (a == b) {
reverse(ans.begin(), ans.end());
if (ipc > 2e5)
cout << "BIG\n" << ipc << endl;
else
cout << "SMALL\n" << ans.size() << endl << ans << endl;
} else
cout << "IMPOSSIBLE\n";
return 0;
} else if (isinc(b)) {
b = invpref(b);
sumb = 0ll;
for (int i = 0; i < n; i++) sumb += b[i];
ans += 'P';
ipc++;
} else if (isdec(b)) {
rev(b);
ans += 'R';
} else {
cout << "IMPOSSIBLE\n";
return 0;
}
}
} else if (n == 2) {
vector<long long> ans;
long long revcnt = 0;
bool reved = a[0] > a[1];
if (reved) swap(a[0], a[1]);
if (b[0] > b[1]) {
swap(b[0], b[1]);
ans.push_back(-1);
revcnt++;
}
for (;;) {
if (b[0] == 0) {
cout << "IMPOSSIBLE\n";
return 0;
}
if (suma > sumb) {
cout << "IMPOSSIBLE\n";
return 0;
}
if (suma == sumb) {
if (a != b) {
cout << "IMPOSSIBLE\n";
return 0;
}
if (reved) {
ans.push_back(-1);
revcnt++;
}
if (ipc > 2e5)
cout << "BIG\n" << ipc << endl;
else {
cout << "SMALL\n" << revcnt + ipc << endl;
reverse(ans.begin(), ans.end());
for (long long i : ans) {
if (i == -1)
cout << 'R';
else
for (int j = 0; j < i; j++) cout << 'P';
}
cout << endl;
}
return 0;
}
if (a[0] == b[0]) {
if ((b[1] - a[1]) % b[0] == 0) {
long long nw = (b[1] - a[1]) / b[0];
ans.push_back(nw);
ipc += nw;
b = a;
sumb = b[0] + b[1];
} else {
cout << "IMPOSSIBLE\n";
return 0;
}
} else {
long long nw = b[1] / b[0];
ans.push_back(nw);
ipc += nw;
ans.push_back(-1);
revcnt++;
swap(b[0], b[1]);
b[0] %= b[1];
sumb = b[0] + b[1];
}
}
} else if (n == 1) {
if (a[0] == b[0])
cout << "SMALL\n0\n\n";
else
cout << "IMPOSSIBLE\n";
return 0;
}
return 0;
}
|
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c.
Unfortunately, an adversary intercepted the values l, r and m. Is it possible to recover the original values of a, b and c from this information? More formally, you are asked to find any values of a, b and c such that
* a, b and c are integers,
* l ≤ a, b, c ≤ r,
* there exists a strictly positive integer n, such that n ⋅ a + b - c = m.
Input
The first line contains the only integer t (1 ≤ t ≤ 20) — the number of test cases. The following t lines describe one test case each.
Each test case consists of three integers l, r and m (1 ≤ l ≤ r ≤ 500 000, 1 ≤ m ≤ 10^{10}). The numbers are such that the answer to the problem exists.
Output
For each test case output three integers a, b and c such that, l ≤ a, b, c ≤ r and there exists a strictly positive integer n such that n ⋅ a + b - c = m. It is guaranteed that there is at least one possible solution, and you can output any possible combination if there are multiple solutions.
Example
Input
2
4 6 13
2 3 1
Output
4 6 5
2 2 3
Note
In the first example n = 3 is possible, then n ⋅ 4 + 6 - 5 = 13 = m. Other possible solutions include: a = 4, b = 5, c = 4 (when n = 3); a = 5, b = 4, c = 6 (when n = 3); a = 6, b = 6, c = 5 (when n = 2); a = 6, b = 5, c = 4 (when n = 2).
In the second example the only possible case is n = 1: in this case n ⋅ 2 + 2 - 3 = 1 = m. Note that, n = 0 is not possible, since in that case n is not a strictly positive integer.
|
#!/usr/local/bin/python3
"""
Given l, r, m, you know that
m = n*a + b - c
for some l <= a,b,c <= r, and n is an integer.
Can you find a,b,c? (any value is fine)
Examples
l,r,m = 10,20,90
Choose 10 <= a,b,c <= 20 s.t.
90 = n*a + b - c
a=10,b=10,c=10,n=9
l,r,m = 8,9,95
Choose 8 <= a,b,c <= 9
try a=8,b=8,c=8:
9*9+8-8
Observations:
We just need to find one value (any value)
Is it always possible? The problem statement doesn't say anything other than
"it's guaranteed that there is at least one possible solution"
Maybe that means that it's always possible to find one?
No, l,r,m = 8,9,95 doesn't work.
Oh, "the numbers are such that the answer to the problem exists"
- So the answer is NO
- What are the conditions for which the answer to this problem exists?
- If there exists a number d (l<=d<=r) s.t. m%d == 0, then we can
pick a=d, b=l, c=l, so it's always possible.
- The following line of logic doesn't quite make sense to me.
- Let's say an n exists.
- When can we reach numbers n' s.t. m % n' == 1?
- If r - l >= 1, then we can pick a=m//n, b=l+1, c=l
- Generally, we can reach numbers n' s.t. m % n' == k by picking
a=m//n, b=l+k, c=l.
- This requries r-l>=k.
- What if there's a number d (l<=n<=r) s.t. for n=the smallest value for which d*n>=m, (d*n)%m == 1?
- Then, we can pick a=d,b=l,c=l+1
- a*n+b-c = a*d+l-l-1 = a*d-1 = n + 1 - 1 = n
- This requires r-l >= 1
- This works for picking a, and b>c
- In general, if we have a number d (l<=d<=r) s.t. for n=the smallest value for which d*n>=m, (d*n)%m == k
- Then, we pick a=d,b=l,c=l+k
- Then, a*n+b-c = d*n+l-l-k = d*n-k = n + k - k = n.
- This requires r-l >= k
- Is this a sufficient condition for determining if a solution exists?
- If it were, we have this solution:
- for each d in [l,r]:
- find an n s.t. (n*d)%m <= r-l:
If we found one, then break out of the outer for loop and set
d and n.
- if found:
pick a=d, b=l, c=l+(n*d)%m
- Let's try to prove this is sufficient:
Suppose is some a,b,c in [l,r] s.t. for some integer N, m = N*a + b - c
Let's say there existed no d in [l,r] s.t. for n=the smallest value for which d*n>=m, (d*n)%m <= r-l.
N*a+b-c=m
Then, (N*a+b-c)%m = 0.
=> (N*a)%m = abs(c-b) <= r-l (l <= c,b <= r)
This is a contradiction (a is in [l,r])
- What if m == 1?
m = n*a + b - c
- Then, we just pick (l, l, abs(2*l-m))
Solution:
- for each d in [l,r]:
- find n=the smallest value for which d*n>=m s.t. (n*d)%m <= r-l:
- if found:
pick a=d, b=l, c=l+(n*d)%m
(a*b)%m = (a%m*b%m)%m
"""
import math
# d = 6
# m = 100
# for n in range(1,100):
# k = (d*n)%m
# print(n,d,k)
def check(l,r,m,a,b,c):
# print(l <= min(a,b,c) <= r)
# print(l <= max(a,b,c) <= r)
# print((m-b+c)%a == 0)
# print((m-b+c),a)
assert (
l <= min(a,b,c) <= r and
l <= max(a,b,c) <= r and
(m-b+c)%a == 0
)
# from lesterlib import lesterutil
# @lesterutil.lesterlog()
def brute(l,r,m):
# if m == 1:
# return (l, l, abs(2*l-m))
# I missed this case during my first analysis.
if m <= r-l:
return (l, l, abs(2*l-m))
for d in range(l,r+1):
if m%d == 0:
return (d,l,l)
n=m//d
# print(d, n, n*d, (-n*d)%m, r-l)
# I missed this case during my first analysis.
if (-n*d)%m <= r-l:
# print('A')
return (d,l+(-n*d)%m,l)
# print(d, n, m-n*d)
# if l <= m-n*d <= r:
# return (d, l+n*d, r)
if n*d < m:
n += 1
# print(d, n, n*d, (n*d)%m, (-n*d)%m, r-l)
if (n*d)%m <= r-l:
# print('B')
return (d,l,l+(n*d)%m)
return None
def main():
t = int(input())
for _ in range(t):
l,r,m = [int(x) for x in input().split()]
#CHANGE
result = brute(l,r,m)
# check(l,r,m,*result)
print(' '.join(str(x) for x in result))
main()
|
You are given n segments on a coordinate axis OX. The i-th segment has borders [l_i; r_i]. All points x, for which l_i ≤ x ≤ r_i holds, belong to the i-th segment.
Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.
Two segments [l_i; r_i] and [l_j; r_j] are non-intersecting if they have no common points. For example, segments [1; 2] and [3; 4], [1; 3] and [5; 5] are non-intersecting, while segments [1; 2] and [2; 3], [1; 2] and [2; 2] are intersecting.
The segment [l_i; r_i] lies inside the segment [l_j; r_j] if l_j ≤ l_i and r_i ≤ r_j. For example, segments [2; 2], [2, 3], [3; 4] and [2; 4] lie inside the segment [2; 4], while [2; 5] and [1; 4] are not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 3000) — the number of segments. The next n lines describe segments. The i-th segment is given as two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5), where l_i is the left border of the i-th segment and r_i is the right border of the i-th segment.
Additional constraint on the input: there are no duplicates in the list of segments.
It is guaranteed that the sum of n does not exceed 3000 (∑ n ≤ 3000).
Output
For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.
Example
Input
4
4
1 5
2 4
2 3
3 4
5
1 5
2 3
2 5
3 5
2 2
3
1 3
2 4
2 3
7
1 10
2 8
2 5
3 4
4 4
6 8
7 7
Output
3
4
2
7
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 6e3 + 10;
int dp[MAX][MAX];
int DP(int i, int j, const vector<vector<int>> &rightOf) {
if (i > j) return 0;
int &answer = dp[i][j];
if (answer != -1) return answer;
int add = 0;
for (int r : rightOf[i])
if (r == j) add++;
answer = add + DP(i + 1, j, rightOf);
for (int r : rightOf[i]) {
if (r >= j) break;
int toR = DP(i, r, rightOf);
int fromR = DP(r + 1, j, rightOf);
answer = max(answer, add + toR + fromR);
}
return answer;
};
void solve() {
int n;
cin >> n;
vector<pair<int, int>> arr(n);
vector<int> vals;
for (auto &p : arr) {
cin >> p.first >> p.second;
vals.push_back(p.first);
vals.push_back(p.second);
}
sort(arr.begin(), arr.end());
sort(vals.begin(), vals.end());
vals.resize(unique(vals.begin(), vals.end()) - vals.begin());
int LIM = (int)vals.size();
vector<vector<int>> rightOf(LIM);
for (auto p : arr) {
p.first = lower_bound(vals.begin(), vals.end(), p.first) - vals.begin();
p.second = lower_bound(vals.begin(), vals.end(), p.second) - vals.begin();
rightOf[p.first].push_back(p.second);
}
for (int i = 0; i < LIM; ++i)
for (int j = 0; j < LIM; ++j) dp[i][j] = -1;
cout << DP(0, LIM - 1, rightOf) << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int _;
cin >> _;
while (_--) solve();
return 0;
}
|
Mark and his crew are sailing across the sea of Aeolus (in Greek mythology Aeolus was the keeper of the winds). They have the map which represents the NxM matrix with land and sea fields and they want to get to the port (the port is considered as sea field). They are in a hurry because the wind there is very strong and changeable and they have the food for only K days on the sea (that is the maximum that they can carry on the ship). John, the guy from Mark's crew, knows how to predict the direction of the wind on daily basis for W days which is enough time for them to reach the port or to run out of the food. Mark can move the ship in four directions (north, east, south, west) by one field for one day, but he can also stay in the same place. Wind can blow in four directions (north, east, south, west) or just not blow that day. The wind is so strong at the sea of Aeolus that it moves the ship for one whole field in the direction which it blows at. The ship's resulting movement is the sum of the ship's action and wind from that day. Mark must be careful in order to keep the ship on the sea, the resulting movement must end on the sea field and there must be a 4-connected path through the sea from the starting field. A 4-connected path is a path where you can go from one cell to another only if they share a side.
For example in the following image, the ship can't move to the port as there is no 4-connected path through the sea.
<image>
In the next image, the ship can move to the port as there is a 4-connected path through the sea as shown with the red arrow. Furthermore, the ship can move to the port in one move if one of the following happens. Wind is blowing east and Mark moves the ship north, or wind is blowing north and Mark moves the ship east. In either of these scenarios the ship will end up in the port in one move.
<image>
Mark must also keep the ship on the map because he doesn't know what is outside. Lucky for Mark and his crew, there are T fish shops at the sea where they can replenish their food supplies to the maximum, but each shop is working on only one day. That means that Mark and his crew must be at the shop's position on the exact working day in order to replenish their food supplies. Help Mark to find the minimum of days that he and his crew need to reach the port or print -1 if that is impossible with the food supplies that they have.
Input
First line contains two integer numbers N and M (1 ≤ N, M ≤ 200) - representing the number of rows and number of columns of the map.
Second line contains three integers, K (0 ≤ K ≤ 200) which is the number of days with the available food supplies, T (0 ≤ T ≤ 20) which is the number of fields with additional food supplies and W (0 ≤ W ≤ 10^6) which is the number of days with wind information.
Next is the NxM char matrix filled with the values of 'L', 'S', 'P' or 'M'. 'L' is for the land and 'S' is for the sea parts. 'P' is for the port field and 'M' is the starting field for the ship.
Next line contains W chars with the wind direction information for every day. The possible inputs are 'N' - north, 'S' - south, 'E' - east, 'W' - west and 'C' - no wind. If Mark's crew can reach the port, it is guaranteed that they will not need more than W days to reach it.
In the end there are T lines with the food supplies positions. Each line contains three integers, Y_i and X_i (0 ≤ Y_i < N, 0 ≤ X_i < M) representing the coordinates (Y is row number and X is column number) of the food supply and F_i (0 ≤ F_i ≤ 10^6) representing the number of days from the starting day on which the food supply is available.
Output
One integer number representing the minimal days to reach the port or -1 if that is impossible.
Examples
Input
3 3
5 2 15
M S S
S S S
S S P
S W N N N N N N N N N N N N N
2 1 0
1 2 0
Output
-1
Input
3 3
5 2 15
M S S
S S S
S S P
S E N N N N N N N N N N N N N
2 1 0
1 2 0
Output
2
Input
5 5
4 1 15
M S S S S
S S S S L
S S S L L
S S S S S
S S S S P
C C C C S S E E C C C C C C C
0 1 4
Output
8
|
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0;
bool flg = false;
char ch = getchar();
for (; !isdigit(ch); ch = getchar())
if (ch == '-') flg = true;
for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ 48);
return flg ? -x : x;
}
int n, m, K, T, W;
char getnext() {
static char str[3];
scanf("%s", str);
return str[0];
}
char mp[210][210], w[1000010];
struct Rec {
int t, x, y;
} rec[25];
bool operator<(Rec x, Rec y) { return x.t > y.t; }
int dp[2][210][210];
bool C;
int SX, SY, TX, TY;
bool tab[5][5][210][210];
inline void check(int &x, int &y) {
if (y > x) x = y;
}
int main() {
n = read(), m = read(), K = read(), W = read(), T = read();
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
mp[i][j] = getnext();
if (mp[i][j] == 'M')
SX = i, SY = j, mp[i][j] = 'S';
else if (mp[i][j] == 'P')
TX = i, TY = j, mp[i][j] = 'S';
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (mp[i][j] == 'L') continue;
tab[0 + 2][0 + 2][i][j] = 1;
tab[0 + 2][1 + 2][i][j] = j + 1 <= m && mp[i][j + 1] != 'L';
tab[0 + 2][2 + 2][i][j] =
j + 2 <= m && mp[i][j + 1] != 'L' && mp[i][j + 2] != 'L';
tab[0 + 2][-1 + 2][i][j] = j - 1 >= 1 && mp[i][j - 1] != 'L';
tab[0 + 2][-2 + 2][i][j] =
j - 2 >= 1 && mp[i][j - 1] != 'L' && mp[i][j - 2] != 'L';
tab[1 + 2][0 + 2][i][j] = i + 1 <= n && mp[i + 1][j] != 'L';
tab[2 + 2][0 + 2][i][j] =
i + 2 <= n && mp[i + 1][j] != 'L' && mp[i + 2][j] != 'L';
tab[-1 + 2][0 + 2][i][j] = i - 1 >= 1 && mp[i - 1][j] != 'L';
tab[-2 + 2][0 + 2][i][j] =
i - 2 >= 1 && mp[i - 1][j] != 'L' && mp[i - 2][j] != 'L';
tab[-1 + 2][1 + 2][i][j] = i - 1 >= 1 && j + 1 <= m &&
(mp[i - 1][j] != 'L' || mp[i][j + 1] != 'L') &&
mp[i - 1][j + 1] != 'L';
tab[-1 + 2][-1 + 2][i][j] =
i - 1 >= 1 && j - 1 >= 1 &&
(mp[i - 1][j] != 'L' || mp[i][j - 1] != 'L') &&
mp[i - 1][j - 1] != 'L';
tab[1 + 2][1 + 2][i][j] = i + 1 <= n && j + 1 <= m &&
(mp[i + 1][j] != 'L' || mp[i][j + 1] != 'L') &&
mp[i + 1][j + 1] != 'L';
tab[1 + 2][-1 + 2][i][j] = i + 1 <= n && j - 1 >= 1 &&
(mp[i + 1][j] != 'L' || mp[i][j - 1] != 'L') &&
mp[i + 1][j - 1] != 'L';
}
for (int i = 1; i <= T; i++) w[i] = getnext();
for (int i = 1; i <= W; i++)
rec[i].x = read() + 1, rec[i].y = read() + 1, rec[i].t = read();
int lim = (W + 1) * K;
sort(rec + 1, rec + W + 1);
while (W && rec[W].t == 0) W--;
memset(dp[C], -1, sizeof dp[C]);
dp[C][SX][SY] = K;
for (int t = 1; t <= T && t <= lim; t++) {
C ^= 1;
memset(dp[C], -1, sizeof dp[C]);
int dx, dy;
if (w[t] == 'C')
dx = dy = 0;
else if (w[t] == 'N')
dx = -1, dy = 0;
else if (w[t] == 'S')
dx = 1, dy = 0;
else if (w[t] == 'W')
dx = 0, dy = -1;
else if (w[t] == 'E')
dx = 0, dy = 1;
else
assert(0);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (dp[C ^ 1][i][j] < 1) continue;
int s = dp[C ^ 1][i][j] - 1;
if (tab[dx + 2][dy + 2][i][j]) check(dp[C][i + dx][j + dy], s);
if (tab[dx + 1 + 2][dy + 2][i][j]) check(dp[C][i + dx + 1][j + dy], s);
if (tab[dx - 1 + 2][dy + 2][i][j]) check(dp[C][i + dx - 1][j + dy], s);
if (tab[dx + 2][dy + 1 + 2][i][j]) check(dp[C][i + dx][j + dy + 1], s);
if (tab[dx + 2][dy - 1 + 2][i][j]) check(dp[C][i + dx][j + dy - 1], s);
}
while (W && rec[W].t == t) {
int x = rec[W].x, y = rec[W].y;
if (~dp[C][x][y]) dp[C][x][y] = K;
W--;
}
if (~dp[C][TX][TY]) return printf("%d\n", t), 0;
}
puts("-1");
return 0;
}
|
You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1.
The following actions are allowed:
* Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second.
* Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on.
The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353.
Input
The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000).
The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct.
It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above.
Output
Print one integer: the minimum required time modulo 998 244 353.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
2
Input
4 3
2 1
2 3
4 3
Output
10
Note
The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds.
The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4.
|
#include <bits/stdc++.h>
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 2e5 + 10;
const int K = 20;
const int INF = 1e9;
const int MOD = 998244353;
int n;
vector<pair<int, int> > adj[2][N];
int trans[2][N], lvl_dist[2][N], dist[2][K][N];
struct elem {
int rev, tr, u, d;
bool operator<(const elem &o) const { return d > o.d; }
};
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int m;
cin >> n >> m;
while (m--) {
int u, v;
cin >> u >> v;
u--;
v--;
adj[0][u].emplace_back(0, v);
adj[1][v].emplace_back(1, u);
}
vector<int> pot2(max(K, n + 2));
pot2[0] = 1;
for (int i = (int)(1); i < ((int)((int)(pot2).size())); i++)
pot2[i] = 2 * pot2[i - 1] % MOD;
int ans = INF;
{
for (int i = 0; i < (int)(2); i++)
for (int j = 0; j < (int)(K); j++)
for (int k = 0; k < (int)(n); k++) dist[i][j][k] = INF;
dist[0][0][0] = 0;
priority_queue<elem> q;
q.push({0, 0, 0, 0});
while (!q.empty()) {
auto el = q.top();
q.pop();
if (el.u == n - 1) ans = min(ans, el.d);
if (dist[el.rev][el.tr][el.u] < el.d) continue;
for (auto [tv, v] : adj[el.rev][el.u]) {
if (el.d + 1 < dist[tv][el.tr][v]) {
dist[tv][el.tr][v] = el.d + 1;
q.push({tv, el.tr, v, el.d + 1});
}
}
if (el.tr + 1 < K) {
auto cand = el.d + pot2[el.tr];
if (cand < dist[1 - el.rev][el.tr + 1][el.u]) {
dist[1 - el.rev][el.tr + 1][el.u] = cand;
q.push({1 - el.rev, el.tr + 1, el.u, cand});
}
}
}
}
if (ans < INF) return cout << ans, 0;
{
for (int i = 0; i < (int)(2); i++)
for (int j = 0; j < (int)(n); j++) trans[i][j] = INF;
trans[0][0] = 0;
deque<pair<int, int> > q;
q.emplace_back(0, 0);
while (!q.empty()) {
auto [tu, u] = q.front();
q.pop_front();
for (auto [tv, v] : adj[tu][u]) {
if (trans[tu][u] < trans[tv][v]) {
trans[tv][v] = trans[tu][u];
q.emplace_front(tv, v);
}
}
if (trans[tu][u] + 1 < trans[1 - tu][u]) {
trans[1 - tu][u] = 1 + trans[tu][u];
q.emplace_back(1 - tu, u);
}
}
}
int need = min(trans[0][n - 1], trans[1][n - 1]);
{
deque<pair<int, int> > q;
for (int i = 0; i < (int)(2); i++)
for (int j = 0; j < (int)(n); j++) lvl_dist[i][j] = INF;
lvl_dist[0][0] = 0;
q.emplace_back(0, 0);
while (!q.empty()) {
auto [tu, u] = q.front();
q.pop_front();
bool lvl = trans[tu][u] + 1 == trans[1 - tu][u];
if (lvl && lvl_dist[tu][u] < lvl_dist[1 - tu][u]) {
lvl_dist[1 - tu][u] = lvl_dist[tu][u];
q.emplace_front(1 - tu, u);
}
for (auto [tv, v] : adj[tu][u]) {
if (trans[tu][u] > trans[tv][v]) continue;
if (lvl_dist[tu][u] + 1 < lvl_dist[tv][v]) {
lvl_dist[tv][v] = lvl_dist[tu][u] + 1;
q.emplace_back(tv, v);
}
}
}
}
{
int ans = INF;
for (int i = 0; i < (int)(2); i++)
if (trans[i][n - 1] == need) ans = min(ans, lvl_dist[i][n - 1]);
for (int i = 0; i < (int)(need); i++) ans = (ans + pot2[i]) % MOD;
cout << ans << endl;
}
return 0;
}
|
Monocarp wants to draw four line segments on a sheet of paper. He wants the i-th segment to have its length equal to a_i (1 ≤ i ≤ 4). These segments can intersect with each other, and each segment should be either horizontal or vertical.
Monocarp wants to draw the segments in such a way that they enclose a rectangular space, and the area of that rectangular space should be maximum possible.
For example, if Monocarp wants to draw four segments with lengths 1, 2, 3 and 4, he can do it the following way:
<image> Here, Monocarp has drawn segments AB (with length 1), CD (with length 2), BC (with length 3) and EF (with length 4). He got a rectangle ABCF with area equal to 3 that is enclosed by the segments.
Calculate the maximum area of a rectangle Monocarp can enclose with four segments.
Input
The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^4) — the number of test cases.
Each test case consists of a single line containing four integers a_1, a_2, a_3, a_4 (1 ≤ a_i ≤ 10^4) — the lengths of the segments Monocarp wants to draw.
Output
For each test case, print one integer — the maximum area of a rectangle Monocarp can enclose with four segments (it can be shown that the answer is always an integer).
Example
Input
4
1 2 3 4
5 5 5 5
3 1 4 1
100 20 20 100
Output
3
25
3
2000
Note
The first test case of the example is described in the statement.
For the second test case, Monocarp can draw the segments AB, BC, CD and DA as follows:
<image> Here, Monocarp has drawn segments AB (with length 5), BC (with length 5), CD (with length 5) and DA (with length 5). He got a rectangle ABCD with area equal to 25 that is enclosed by the segments.
|
#include<iostream>
#include<bits/stdc++.h>
#define int long long int
using namespace std;
int32_t main()
{
int t; cin>>t;
while(t--)
{
int a[4]; cin>>a[0]>>a[1]>>a[2]>>a[3];
sort(a, (a+4)); cout<<a[0]*a[2]<<endl;
}
return 0;
}
|
You are given three integers a, b, k.
Find two binary integers x and y (x ≥ y) such that
1. both x and y consist of a zeroes and b ones;
2. x - y (also written in binary form) has exactly k ones.
You are not allowed to use leading zeros for x and y.
Input
The only line contains three integers a, b, and k (0 ≤ a; 1 ≤ b; 0 ≤ k ≤ a + b ≤ 2 ⋅ 10^5) — the number of zeroes, ones, and the number of ones in the result.
Output
If it's possible to find two suitable integers, print "Yes" followed by x and y in base-2.
Otherwise print "No".
If there are multiple possible answers, print any of them.
Examples
Input
4 2 3
Output
Yes
101000
100001
Input
3 2 1
Output
Yes
10100
10010
Input
3 2 5
Output
No
Note
In the first example, x = 101000_2 = 2^5 + 2^3 = 40_{10}, y = 100001_2 = 2^5 + 2^0 = 33_{10}, 40_{10} - 33_{10} = 7_{10} = 2^2 + 2^1 + 2^0 = 111_{2}. Hence x-y has 3 ones in base-2.
In the second example, x = 10100_2 = 2^4 + 2^2 = 20_{10}, y = 10010_2 = 2^4 + 2^1 = 18, x - y = 20 - 18 = 2_{10} = 10_{2}. This is precisely one 1.
In the third example, one may show, that it's impossible to find an answer.
|
#tests = int(input())
#for t in range(tests):
#n = int(input())
a, b, k = list(map(int, input().split()))
if a == 0 and k!=0:
print('No')
elif k ==0:
print('Yes')
print('1'*b + '0'*a)
print('1'*b + '0'*a)
elif b==1 or k > (a+b-2):
print('No')
else:
shift = a+b-2-k
print('Yes')
ans_1 = ['1' for _ in range(b)] + ['0' for _ in range(a)]
ans_2 = ['1'] + ['0'] + ['1' for _ in range(b-2)] + ['0' for _ in range(a-1)] + ['1']
if shift <= (a-1):
ans_2 = ['1'] + ['0'] + ['1' for _ in range(b-2)] + ['0' for _ in range(a-1-shift)] + ['1'] + ['0' for _ in range(shift)]
else:
ans_2 = ['1'] + ['1' for _ in range(shift-(a-1))] + ['0'] + ['1' for _ in range(b-2 -(shift-(a-1)))] + ['1'] + ['0' for _ in range(a-1)]
print(''.join(ans_1))
print(''.join(ans_2))
# print(bin(int(''.join(ans_1),2)-int(''.join(ans_2),2)).count('1'))
|
There are n computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer i-1 and computer i+1 are both on, computer i (2 ≤ i ≤ n-1) will turn on automatically if it is not already on. Note that Phoenix cannot manually turn on a computer that already turned on automatically.
If we only consider the sequence of computers that Phoenix turns on manually, how many ways can he turn on all the computers? Two sequences are distinct if either the set of computers turned on manually is distinct, or the order of computers turned on manually is distinct. Since this number may be large, please print it modulo M.
Input
The first line contains two integers n and M (3 ≤ n ≤ 400; 10^8 ≤ M ≤ 10^9) — the number of computers and the modulo. It is guaranteed that M is prime.
Output
Print one integer — the number of ways to turn on the computers modulo M.
Examples
Input
3 100000007
Output
6
Input
4 100000007
Output
20
Input
400 234567899
Output
20914007
Note
In the first example, these are the 6 orders in which Phoenix can turn on all computers:
* [1,3]. Turn on computer 1, then 3. Note that computer 2 turns on automatically after computer 3 is turned on manually, but we only consider the sequence of computers that are turned on manually.
* [3,1]. Turn on computer 3, then 1.
* [1,2,3]. Turn on computer 1, 2, then 3.
* [2,1,3]
* [2,3,1]
* [3,2,1]
|
#include<bits/stdc++.h>
using namespace std;
/*
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
*/
/*
unordered_map<int,int>mp;
mp.reserve(1024);
mp.max_load_factor(0.25);
*/
typedef long long ll;
ll pow(ll a,ll b,ll M){
if(b==0){
return 1;
}
ll t=pow(a,b/2,M);
t = (t*t)%M;
if(b%2==1){
t= (t*a)%M;
}
return t;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll n,M;
cin>>n>>M;
vector<vector<ll>> ncr(n+1,vector<ll>(n+1));
for(int i=1;i<=n;i++){
ncr[i][0]=1;
for(int j=1;j<i;j++){
ncr[i][j] = (ncr[i-1][j]+ncr[i-1][j-1])%M;
}
ncr[i][i]=1;
}
vector<ll> pow(n+1);
pow[0]=1;
for(int i=1;i<=n;i++){
pow[i]=(pow[i-1]*2)%M;
}
vector<vector<ll>> dp(n+2,vector<ll>(n+2));
dp[0][0]=1;
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
for(int k=1;i+k<=n;k++){
dp[i+k+1][j+k]+= ((dp[i][j]*ncr[j+k][j])%M)*pow[k-1];
dp[i+k+1][j+k] = dp[i+k+1][j+k]%M;
}
}
}
ll ans=0;
for(int i=0;i<=n;i++){
ans= (ans+dp[n+1][i])%M;
}
cout<<ans<<"\n";
return 0;
}
//6 100000007
|
You are given a sequence A, where its elements are either in the form + x or -, where x is an integer.
For such a sequence S where its elements are either in the form + x or -, define f(S) as follows:
* iterate through S's elements from the first one to the last one, and maintain a multiset T as you iterate through it.
* for each element, if it's in the form + x, add x to T; otherwise, erase the smallest element from T (if T is empty, do nothing).
* after iterating through all S's elements, compute the sum of all elements in T. f(S) is defined as the sum.
The sequence b is a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For all A's subsequences B, compute the sum of f(B), modulo 998 244 353.
Input
The first line contains an integer n (1≤ n≤ 500) — the length of A.
Each of the next n lines begins with an operator + or -. If the operator is +, then it's followed by an integer x (1≤ x<998 244 353). The i-th line of those n lines describes the i-th element in A.
Output
Print one integer, which is the answer to the problem, modulo 998 244 353.
Examples
Input
4
-
+ 1
+ 2
-
Output
16
Input
15
+ 2432543
-
+ 4567886
+ 65638788
-
+ 578943
-
-
+ 62356680
-
+ 711111
-
+ 998244352
-
-
Output
750759115
Note
In the first example, the following are all possible pairs of B and f(B):
* B= {}, f(B)=0.
* B= {-}, f(B)=0.
* B= {+ 1, -}, f(B)=0.
* B= {-, + 1, -}, f(B)=0.
* B= {+ 2, -}, f(B)=0.
* B= {-, + 2, -}, f(B)=0.
* B= {-}, f(B)=0.
* B= {-, -}, f(B)=0.
* B= {+ 1, + 2}, f(B)=3.
* B= {+ 1, + 2, -}, f(B)=2.
* B= {-, + 1, + 2}, f(B)=3.
* B= {-, + 1, + 2, -}, f(B)=2.
* B= {-, + 1}, f(B)=1.
* B= {+ 1}, f(B)=1.
* B= {-, + 2}, f(B)=2.
* B= {+ 2}, f(B)=2.
The sum of these values is 16.
|
MOD = 998244353
def solve():
n = int(input())
ans = 0
arr = []
for i in range(n):
a = list(input().split())
if len(a) == 2:
arr.append(int(a[1]))
else:
arr.append(0)
for cur in range(n):
if arr[cur]:
dp = [0] * (n+1)
dp[0] = 1
for j, a in enumerate(arr):
if j == cur:
dp = [0] + dp[:n]
elif a == 0:
dp[0] = (2*dp[0]+dp[1]) % MOD
for i in range(1, n):
dp[i] = (dp[i]+dp[i+1]) % MOD
elif a < arr[cur] or (a == arr[cur] and j < cur):
if j < cur:
for i in range(n, 0, -1):
dp[i] = (dp[i-1]+dp[i]) % MOD
else:
for i in range(n, 1, -1):
dp[i] = (dp[i-1]+dp[i]) % MOD
dp[0] = dp[0] * 2 % MOD
else:
dp = [d*2%MOD for d in dp]
ans = (ans+(sum(dp)-dp[0])*arr[cur]) % MOD
return ans
import sys
input = lambda: sys.stdin.readline().rstrip()
print(solve())
|
The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer — Alex — managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format «[time]: message». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written.
So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications).
We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day.
Input
The first input line contains number n (1 ≤ n ≤ 100). The following n lines contain recordings in format «[time]: message», where time is given in format «hh:mm x.m.». For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character «a» or character «p». A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20.
Output
Output one number — the minimum amount of days covered by the log.
Examples
Input
5
[05:00 a.m.]: Server is started
[05:00 a.m.]: Rescan initialized
[01:13 p.m.]: Request processed
[01:10 p.m.]: Request processed
[11:40 p.m.]: Rescan completed
Output
2
Input
3
[09:00 a.m.]: User logged in
[08:00 a.m.]: User logged in
[07:00 a.m.]: User logged in
Output
3
Note
Formally the 12-hour time format is described at:
* http://en.wikipedia.org/wiki/12-hour_clock.
The problem authors recommend you to look through these descriptions before you start with the problem.
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
def readint(): return int(raw_input())
def readfloat(): return float(raw_input())
def readarray(N, foo):
res = []
for _ in xrange(N):
res.append(foo())
return res
def readlinearray(foo): return map(foo, raw_input().split())
HOUR=0
MINUTE=1
def get_ndays(logs):
nlogs = []
for log in logs:
time, x = log.split()
hour, minute = map(int, time.split(':'))
if x == 'p':
if hour != 12:
hour += 12
hour %= 24
else:
hour %= 12
nlogs.append((hour, minute))
r = 1
count = 1
last_log = nlogs[0]
for log in nlogs[1:]:
if last_log == log:
count += 1
if count > 10:
r += 1
count = 1
else:
count = 1
if log[HOUR] < last_log[HOUR]:
r += 1
if log[HOUR] == last_log[HOUR] and log[MINUTE] < last_log[MINUTE]:
r += 1
last_log = log
return r
if __name__ == '__main__':
n = readint()
logs = []
for _ in xrange(n):
logs.append(raw_input()[1:8])
print get_ndays(logs)
|
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city — that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r ≥ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range — as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| ≤ 104; 1 ≤ ri ≤ 104) — the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number — the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
|
#include <bits/stdc++.h>
using namespace std;
int main() {
long double x1, y1, r1, x2, y2, r2;
cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2;
long double x = abs(x1 - x2);
long double y = abs(y1 - y2);
long double d = sqrt(x * x + y * y) - (r1 + r2);
if (d > 0)
cout << setprecision(15) << (d / 2);
else {
d += (r1 + r2);
if (d < max(r1, r2) - min(r1, r2)) {
cout << setprecision(15) << (max(r1, r2) - d - min(r1, r2)) / 2;
} else
cout << 0 << endl;
}
}
|
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.
Each digit is allowed to occur in the number the same number of times it occurs in the set.
Input
A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.
Output
On a single line print the answer to the problem. If such number does not exist, then you should print -1.
Examples
Input
1
0
Output
0
Input
11
3 4 5 4 5 3 5 3 4 4 0
Output
5554443330
Input
8
3 2 5 1 5 2 2 3
Output
-1
Note
In the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.
|
#include <bits/stdc++.h>
using namespace std;
long long n, fq[10], mo[3];
int main() {
long long i, j, ii, k, sm, e;
pair<long long, long long> mxe = {-1e18, -1};
bool bad = 1;
scanf("%lld", &n);
for (i = 0; i < n; i++) {
scanf("%lld", &k);
fq[k]++;
mo[k % 3]++;
}
if (!fq[0]) {
printf("-1\n");
return 0;
}
for (i = 0; i < 3; i++) {
if (i <= min(mo[1], mo[2])) {
sm = 0;
for (ii = 1; ii <= 2; ii++) {
sm += (mo[ii] - i) / 3 * 3 + i;
}
mxe = max(mxe, {sm, i});
}
}
e = mxe.second;
for (ii = 1; ii <= 2; ii++) {
mo[ii] = (mo[ii] - e) / 3 * 3 + e;
}
for (i = 9; i + 1; i--) {
for (j = 0; j < fq[i] && mo[i % 3] && (i || !j || !bad); j++) {
printf("%lld", i);
mo[i % 3]--;
if (i) {
bad = 0;
}
}
}
printf("\n");
}
|
This problem is the most boring one you've ever seen.
Given a sequence of integers a1, a2, ..., an and a non-negative integer h, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the result subsequences. Note, that one of the result subsequences can be empty.
Let's define function f(ai, aj) on pairs of distinct elements (that is i ≠ j) in the original sequence. If ai and aj are in the same subsequence in the current partition then f(ai, aj) = ai + aj otherwise f(ai, aj) = ai + aj + h.
Consider all possible values of the function f for some partition. We'll call the goodness of this partiotion the difference between the maximum value of function f and the minimum value of function f.
Your task is to find a partition of the given sequence a that have the minimal possible goodness among all possible partitions.
Input
The first line of input contains integers n and h (2 ≤ n ≤ 105, 0 ≤ h ≤ 108). In the second line there is a list of n space-separated integers representing a1, a2, ..., an (0 ≤ ai ≤ 108).
Output
The first line of output should contain the required minimum goodness.
The second line describes the optimal partition. You should print n whitespace-separated integers in the second line. The i-th integer is 1 if ai is in the first subsequence otherwise it should be 2.
If there are several possible correct answers you are allowed to print any of them.
Examples
Input
3 2
1 2 3
Output
1
1 2 2
Input
5 10
0 1 0 2 1
Output
3
2 2 2 2 2
Note
In the first sample the values of f are as follows: f(1, 2) = 1 + 2 + 2 = 5, f(1, 3) = 1 + 3 + 2 = 6 and f(2, 3) = 2 + 3 = 5. So the difference between maximum and minimum values of f is 1.
In the second sample the value of h is large, so it's better for one of the sub-sequences to be empty.
|
def finddiff(A, other, h):
max1 = A[-1] + A[-2]
min1 = A[0]+ A[1]
min2 = other + A[0] + h
max2 = other + A[-1] + h
return max(max1,max2) - min(min1,min2)
n, h = map(int, raw_input().split())
numbers = map(int, raw_input().split())
savenum = -1
num = numbers[:]
numbers.sort()
min1 = numbers[-1]+numbers[-2]-numbers[0]-numbers[1]
if n > 2:
for i in [0,1,2,-1,-2,-3]:
minp = finddiff( numbers[:i] + numbers[i+1:], numbers[i], h)
#print numbers[:i] + numbers[i+1:], numbers[i], minp
if minp < min1:
savenum = numbers[i]
min1 = minp
print min1
one = False
for i in range(n):
if num[i] == savenum and not one:
print 2,
one = True
else:
print 1,
|
Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (m + 1) × (m + 1):
<image>
Maxim asks you to count, how many numbers m (1 ≤ m ≤ n) are there, such that the sum of values in the cells in the row number m + 1 of the resulting matrix equals t.
Expression (x xor y) means applying the operation of bitwise excluding "OR" to numbers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by character "^", in Pascal — by "xor".
Input
A single line contains two integers n and t (1 ≤ n, t ≤ 1012, t ≤ n + 1).
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
In a single line print a single integer — the answer to the problem.
Examples
Input
1 1
Output
1
Input
3 2
Output
1
Input
3 3
Output
0
Input
1000000000000 1048576
Output
118606527258
|
#include <bits/stdc++.h>
using namespace std;
long long N, T, ans = 0;
int M;
long long C[41][41];
long long solve(long long pos, long long len, int level, int L) {
if (L < 0 || level < L) return 0;
if (len == 1) return 1;
if (pos > len / 2) {
return (level - 1 >= 0 && L >= 0 ? C[level - 1][L] : 0) +
solve(pos - len / 2, len / 2, level - 1, L - 1);
}
return solve(pos, len / 2, level - 1, L);
}
int main() {
cin >> N >> T;
C[0][0] = 1;
for (int i = 1; i <= 40; ++i) {
for (int j = 0; j <= i; ++j) {
if (j == 0 || j == i) {
C[i][j] = 1;
} else {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
}
int L = log2(T);
if (1ll << L != T) {
cout << 0 << endl;
} else {
long long ans = 0;
int level = 1;
long long total = 0;
for (;;) {
total += 1ll << level;
if (total >= N) break;
++level;
}
for (int i = 1; i <= level - 1; ++i) {
ans += C[i][L];
}
ans += solve(N - total + (1ll << level), 1ll << level, level, L);
cout << ans << endl;
}
}
|
A ladies' shop has recently opened in the city of Ultima Thule. To get ready for the opening, the shop bought n bags. Each bag is characterised by the total weight ai of the items you can put there. The weird thing is, you cannot use these bags to put a set of items with the total weight strictly less than ai. However the weights of the items that will be sold in the shop haven't yet been defined. That's what you should determine right now.
Your task is to find the set of the items' weights p1, p2, ..., pk (1 ≤ p1 < p2 < ... < pk), such that:
1. Any bag will be used. That is, for any i (1 ≤ i ≤ n) there will be such set of items that their total weight will equal ai. We assume that there is the infinite number of items of any weight. You can put multiple items of the same weight in one bag.
2. For any set of items that have total weight less than or equal to m, there is a bag into which you can put this set. Similarly, a set of items can contain multiple items of the same weight.
3. Of all sets of the items' weights that satisfy points 1 and 2, find the set with the minimum number of weights. In other words, value k should be as small as possible.
Find and print the required set.
Input
The first line contains space-separated integers n and m (1 ≤ n, m ≤ 106). The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ a1 < a2 < ... < an ≤ m) — the bags' weight limits.
Output
In the first line print "NO" (without the quotes) if there isn't set pi, that would meet the conditions.
Otherwise, in the first line print "YES" (without the quotes), in the second line print an integer k (showing how many numbers are in the suitable set with the minimum number of weights), in the third line print k space-separated integers p1, p2, ..., pk (1 ≤ p1 < p2 < ... < pk). If there are multiple solutions, print any of them.
Examples
Input
6 10
5 6 7 8 9 10
Output
YES
5
5 6 7 8 9
Input
1 10
1
Output
NO
Input
1 10
6
Output
YES
1
6
|
#include <bits/stdc++.h>
using namespace std;
complex<double> ca[2100100], ya[2100100], y2[2100100];
double PI = acos(-1.0);
int invert(int v, int t) {
int r = 0;
while (t) {
r = (r << 1) | (1 & v);
v >>= 1;
--t;
}
return r;
}
void fft(complex<double> *y, int t, int inv) {
int lg = 0, k, v, t2;
while ((1 << lg) < t) lg++;
for (int i = 1; i < t - 1; i++) {
for (k = 0, v = i, t2 = lg; t2--; k = (k << 1) | (1 & v), v >>= 1)
;
if (i < k) swap(y[i], y[k]);
}
for (int k = 0; k < lg; k++) {
complex<double> w = exp(complex<double>(0.0, inv * 2.0 * PI / (2 << k))),
ww = complex<double>(1.0, 0.0);
for (int j = 0; j < 1 << k; j++, ww *= w) {
for (int i = j; i < t; i += (2 << k)) {
y[i] = y[i] + ww * y[i + (1 << k)];
y[i + (1 << k)] = y[i] - ww * 2.0 * y[i + (1 << k)];
}
}
}
}
double va[2100100], vc[2100100];
void mult(double *a, int ta, double *c) {
int t = 1;
while (t < ta + ta) t <<= 1;
for (int i = 0; i < t; i++) ca[i] = complex<double>(i < ta ? a[i] : 0.0, 0.0);
fft(ca, t, 1);
for (int i = 0; i < t; i++) ca[i] *= ca[i];
fft(ca, t, -1);
for (int i = 0; i < t; i++) c[i] = ca[i].real() / t;
}
int r[2100100];
bool mk[2100100];
int main() {
int n, w, v;
scanf("%d %d", &n, &w);
for (int i = 0; i < n; i++) scanf("%d", &v), va[v] = 1.0, mk[v] = true;
mult(va, w + 1, vc);
int pnt = 0;
bool rsp = true;
for (int i = 0; i < w + 1; i++) {
if (vc[i] > 1e-3) {
if (!mk[i]) {
rsp = false;
break;
}
} else if (mk[i])
r[pnt++] = i;
}
if (rsp) {
printf("YES\n%d\n", pnt);
for (int i = 0; i < pnt; i++) {
if (i) printf(" ");
printf("%d", r[i]);
}
printf("\n");
} else
printf("NO\n");
return 0;
}
|
SmallR is a biologist. Her latest research finding is how to change the sex of dogs. In other words, she can change female dogs into male dogs and vice versa.
She is going to demonstrate this technique. Now SmallR has n dogs, the costs of each dog's change may be different. The dogs are numbered from 1 to n. The cost of change for dog i is vi RMB. By the way, this technique needs a kind of medicine which can be valid for only one day. So the experiment should be taken in one day and each dog can be changed at most once.
This experiment has aroused extensive attention from all sectors of society. There are m rich folks which are suspicious of this experiment. They all want to bet with SmallR forcibly. If SmallR succeeds, the i-th rich folk will pay SmallR wi RMB. But it's strange that they have a special method to determine whether SmallR succeeds. For i-th rich folk, in advance, he will appoint certain ki dogs and certain one gender. He will think SmallR succeeds if and only if on some day the ki appointed dogs are all of the appointed gender. Otherwise, he will think SmallR fails.
If SmallR can't satisfy some folk that isn't her friend, she need not pay him, but if someone she can't satisfy is her good friend, she must pay g RMB to him as apologies for her fail.
Then, SmallR hope to acquire money as much as possible by this experiment. Please figure out the maximum money SmallR can acquire. By the way, it is possible that she can't obtain any money, even will lose money. Then, please give out the minimum money she should lose.
Input
The first line contains three integers n, m, g (1 ≤ n ≤ 104, 0 ≤ m ≤ 2000, 0 ≤ g ≤ 104). The second line contains n integers, each is 0 or 1, the sex of each dog, 0 represent the female and 1 represent the male. The third line contains n integers v1, v2, ..., vn (0 ≤ vi ≤ 104).
Each of the next m lines describes a rich folk. On the i-th line the first number is the appointed sex of i-th folk (0 or 1), the next two integers are wi and ki (0 ≤ wi ≤ 104, 1 ≤ ki ≤ 10), next ki distinct integers are the indexes of appointed dogs (each index is between 1 and n). The last number of this line represents whether i-th folk is SmallR's good friend (0 — no or 1 — yes).
Output
Print a single integer, the maximum money SmallR can gain. Note that the integer is negative if SmallR will lose money.
Examples
Input
5 5 9
0 1 1 1 0
1 8 6 2 3
0 7 3 3 2 1 1
1 8 1 5 1
1 0 3 2 1 4 1
0 8 3 4 2 1 0
1 7 2 4 1 1
Output
2
Input
5 5 8
1 0 1 1 1
6 5 4 2 8
0 6 3 2 3 4 0
0 8 3 3 2 4 0
0 0 3 3 4 1 1
0 10 3 4 3 1 1
0 4 3 3 4 1 1
Output
16
|
#include <bits/stdc++.h>
using namespace std;
int n, m, g, v[10010], s[10010], fri[2010], d[2010][11], w[2010], k[2010],
opt[2010];
int S, T, dis[20010], ans, tim;
struct info {
int v, c;
unsigned r;
};
unsigned cur[20010];
vector<info> a[20010];
template <typename T>
void chkmin(T &x, T y) {
x = min(x, y);
}
template <typename T>
void chkmax(T &x, T y) {
x = max(x, y);
}
template <typename T>
void read(T &x) {
x = 0;
int f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - '0';
ch = getchar();
}
x *= f;
}
void add(int u, int v, int c) {
a[u].push_back((info){v, c, (unsigned)a[v].size()});
a[v].push_back((info){u, 0, (unsigned)a[u].size() - 1});
}
int bfs() {
static int q[20010], l = 0, r = 0;
for (int i = 0; i <= r; ++i) dis[q[i]] = 0;
q[l = r = 0] = S, dis[S] = 1;
while (l <= r) {
int pos = q[l++];
for (unsigned i = 0, si = a[pos].size(); i < si; ++i) {
int to = a[pos][i].v, cap = a[pos][i].c;
if (!dis[to] && cap) dis[to] = dis[pos] + 1, q[++r] = to;
}
}
return (dis[T] != 0);
}
int dinic(int pos, int lim) {
if (pos == T) return lim;
int used = 0, tmp;
for (unsigned &i = cur[pos], si = a[pos].size(); i < si; ++i) {
int to = a[pos][i].v, cap = a[pos][i].c, re = a[pos][i].r;
if (cap && dis[to] == dis[pos] + 1 &&
(tmp = dinic(to, min(lim - used, cap)))) {
a[pos][i].c -= tmp, a[to][re].c += tmp, used += tmp;
if (used == lim) return used;
}
}
return used;
}
int main() {
read(n), read(m), read(g);
for (int i = 1; i <= n; ++i) read(s[i]);
for (int i = 1; i <= n; ++i) read(v[i]);
for (int i = 1; i <= m; ++i) {
read(opt[i]), read(w[i]), read(k[i]);
ans += w[i];
for (int j = 1; j <= k[i]; ++j) read(d[i][j]);
read(fri[i]);
}
S = 0, T = tim = n + 1;
for (int i = 1; i <= n; ++i) {
if (s[i] == 0)
add(S, i, 0), add(i, T, v[i]);
else
add(S, i, v[i]), add(i, T, 0);
}
for (int i = 1; i <= m; ++i) {
if (opt[i] == 1) {
++tim;
add(S, tim, w[i] + fri[i] * g);
for (int j = 1; j <= k[i]; ++j) add(tim, d[i][j], 0x3f3f3f3f);
} else {
++tim;
add(tim, T, w[i] + fri[i] * g);
for (int j = 1; j <= k[i]; ++j) add(d[i][j], tim, 0x3f3f3f3f);
}
}
while (bfs()) {
memset(cur, 0, sizeof(cur));
ans -= dinic(S, 0x3f3f3f3f);
}
printf("%d\n", ans);
return 0;
}
|
Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.
One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?
The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.
Input
The single line contains a single integer n (1 ≤ n ≤ 1017).
Please, do not use the %lld specifier to read or write 64 bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with.
Examples
Input
1
Output
1
Input
4
Output
2
Note
In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.
In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives.
|
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
long long x = 3;
cin >> n;
while (1) {
if (n % x != 0) break;
x *= 3;
}
long long ans = n / x;
cout << ans + 1 << endl;
return 0;
}
|
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
|
#include <bits/stdc++.h>
using namespace std;
class DSU {
public:
int *parent;
int elems;
DSU(int n) {
elems = n;
parent = new int[elems];
for (int i = 0; i < elems; ++i) {
parent[i] = i;
}
}
~DSU() { delete[] parent; }
int find(int a) {
if (a >= elems) return 4000000;
int p = parent[a];
while (p < elems && p != parent[p]) {
if (parent[p] < elems) parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
void merge(int a, int b) {
int ga = find(a);
int gb = find(b);
parent[gb] = ga;
}
void print() {
for (int i = 0; i < elems; ++i) printf(" %d", parent[i]);
printf("\n");
}
};
int main(int argc, char *argv[]) {
int n, m;
scanf("%d%d", &n, &m);
DSU rem(n);
vector<int> result(n);
for (int i = 0; i < m; ++i) {
int l, r, x;
scanf("%d%d%d", &l, &r, &x);
l--;
r--;
x--;
for (int j = rem.find(l); j < x; j = rem.find(j)) {
rem.merge(x, j);
result[j] = x + 1;
++j;
}
int next = rem.find(r + 1);
for (int j = rem.find(x + 1); j <= r; j = rem.find(j)) {
rem.merge(next, j);
result[j] = x + 1;
j++;
}
}
for (int i = 0; i < n; ++i) printf(" %d", result[i]);
printf("\n");
return EXIT_SUCCESS;
}
|
Sereja adores trees. Today he came up with a revolutionary new type of binary root trees.
His new tree consists of n levels, each vertex is indexed by two integers: the number of the level and the number of the vertex on the current level. The tree root is at level 1, its index is (1, 1). Here is a pseudo code of tree construction.
//the global data are integer arrays cnt[], left[][], right[][]
cnt[1] = 1;
fill arrays left[][], right[][] with values -1;
for(level = 1; level < n; level = level + 1){
cnt[level + 1] = 0;
for(position = 1; position <= cnt[level]; position = position + 1){
if(the value of position is a power of two){ // that is, 1, 2, 4, 8...
left[level][position] = cnt[level + 1] + 1;
right[level][position] = cnt[level + 1] + 2;
cnt[level + 1] = cnt[level + 1] + 2;
}else{
right[level][position] = cnt[level + 1] + 1;
cnt[level + 1] = cnt[level + 1] + 1;
}
}
}
After the pseudo code is run, cell cnt[level] contains the number of vertices on level level. Cell left[level][position] contains the number of the vertex on the level level + 1, which is the left child of the vertex with index (level, position), or it contains -1, if the vertex doesn't have a left child. Similarly, cell right[level][position] is responsible for the right child. You can see how the tree with n = 4 looks like in the notes.
Serja loves to make things complicated, so he first made a tree and then added an empty set A(level, position) for each vertex. Then Sereja executes m operations. Each operation is of one of the two following types:
* The format of the operation is "1 t l r x". For all vertices level, position (level = t; l ≤ position ≤ r) add value x to set A(level, position).
* The format of the operation is "2 t v". For vertex level, position (level = t, position = v), find the union of all sets of vertices that are in the subtree of vertex (level, position). Print the size of the union of these sets.
Help Sereja execute the operations. In this problem a set contains only distinct values like std::set in C++.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 7000).
Next m lines contain the descriptions of the operations. The operation of the first type is given by five integers: 1 t l r x (1 ≤ t ≤ n; 1 ≤ l ≤ r ≤ cnt[t]; 1 ≤ x ≤ 106). The operation of the second type is given by three integers: 2 t v (1 ≤ t ≤ n; 1 ≤ v ≤ cnt[t]).
Output
For each operation of the second type, print the answer on a single line.
Examples
Input
4 5
1 4 4 7 1
1 3 1 2 2
2 1 1
2 4 1
2 3 3
Output
2
0
1
Note
You can find the definitions that are used while working with root trees by this link: http://en.wikipedia.org/wiki/Tree_(graph_theory)
You can see an example of a constructed tree at n = 4 below.
<image>
|
#include <bits/stdc++.h>
using namespace std;
int n, m;
int L[150000];
int R[150000];
int used[1000001];
vector<int> a[7001][3];
int main() {
cin >> n >> m;
L[1] = 1;
R[1] = 2;
for (int i = 1; i <= 1000000; i++) {
used[i] = false;
}
for (int i = 2; i < 150000; i++) {
if (__builtin_popcount(i) == 1) {
L[i] = R[i - 1] + 1;
R[i] = L[i] + 1;
} else {
L[i] = -1;
R[i] = R[i - 1] + 1;
}
}
for (int q = 0; q < m; q++) {
int t;
fscanf(stdin, "%d", &t);
if (t == 1) {
int l, left, right, x;
fscanf(stdin, "%d %d %d %d", &l, &left, &right, &x);
a[l][0].push_back(left);
a[l][1].push_back(right);
a[l][2].push_back(x);
} else {
int level, pos;
fscanf(stdin, "%d %d", &level, &pos);
vector<int> rem;
long long res = 0;
int lo = pos;
int hi = pos;
for (int l = level; l <= n; l++) {
for (int i = 0; i < a[l][0].size(); i++) {
if (a[l][0][i] <= lo && lo <= a[l][1][i] ||
a[l][0][i] <= hi && hi <= a[l][1][i] ||
lo <= a[l][0][i] && a[l][1][i] <= hi) {
if (!used[a[l][2][i]]) {
res++;
used[a[l][2][i]] = true;
rem.push_back(a[l][2][i]);
}
}
}
if (L[lo] == -1) {
lo = R[lo];
} else {
lo = L[lo];
}
hi = R[hi];
}
fprintf(stdout, "%d\n", res);
for (int i = 0; i < rem.size(); i++) {
used[rem[i]] = false;
}
}
}
return 0;
}
|
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.
Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?
You can assume that initially Vanya had infinitely many cards with each integer number from - x to x.
Input
The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.
Output
Print a single number — the answer to the problem.
Examples
Input
3 2
-1 1 2
Output
1
Input
2 3
-2 -2
Output
2
Note
In the first sample, Vanya needs to find a single card with number -2.
In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.
|
inp = input().split(' ')
n = int(inp[0])
x = int(inp[1])
su = 0
inp = input().split(' ')
for i in inp:
su += int(i)
count = 0
while su!=0:
count += 1
if su > 0:
su += max(-x, -su)
else:
su += min(x, -su)
print(count)
|
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column.
Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j].
There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.
If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.
Input
The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 105).
Output
The output contains a single number — the maximum total gain possible.
Examples
Input
3 3
100 100 100
100 1 100
100 100 100
Output
800
Note
Iahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3].
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
long long n, m;
cin >> n >> m;
long long mp[n + 1][m + 1], dp1[n + 2][m + 2], dp2[n + 2][m + 2],
dp3[n + 2][m + 2], dp4[n + 2][m + 2];
for (long long i = 1; i < n + 1; i++) {
for (long long j = 1; j < m + 1; j++) {
cin >> mp[i][j];
}
}
memset(dp1, 0, sizeof(dp1));
for (long long i = 1; i < n + 1; i++) {
for (long long j = 1; j < m + 1; j++) {
dp1[i][j] = max(dp1[i - 1][j], dp1[i][j - 1]) + mp[i][j];
}
}
memset(dp2, 0, sizeof(dp2));
for (long long i = n; i > 0; i--) {
for (long long j = m; j > 0; j--) {
dp2[i][j] = max(dp2[i + 1][j], dp2[i][j + 1]) + mp[i][j];
}
}
memset(dp3, 0, sizeof(dp3));
for (long long i = n; i > 0; i--) {
for (long long j = 1; j < m + 1; j++) {
dp3[i][j] = max(dp3[i + 1][j], dp3[i][j - 1]) + mp[i][j];
}
}
memset(dp4, 0, sizeof(dp4));
for (long long i = 1; i < n + 1; i++) {
for (long long j = m; j > 0; j--) {
dp4[i][j] = max(dp4[i - 1][j], dp4[i][j + 1]) + mp[i][j];
}
}
long long res = 0;
for (long long i = 2; i < n; i++) {
for (long long j = 2; j < m; j++) {
res = max(
res,
max(dp1[i - 1][j] + dp2[i + 1][j] + dp3[i][j - 1] + dp4[i][j + 1],
dp3[i + 1][j] + dp4[i - 1][j] + dp1[i][j - 1] + dp2[i][j + 1]));
}
}
cout << res << endl;
return 0;
}
|
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.
Jzzhu wonders how to get the maximum possible number of groups. Can you help him?
Input
A single integer n (1 ≤ n ≤ 105), the number of the apples.
Output
The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group.
If there are several optimal answers you can print any of them.
Examples
Input
6
Output
2
6 3
2 4
Input
9
Output
3
9 3
2 4
6 8
Input
2
Output
0
|
#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
char primes[12500002];
void preCal() {
memset(primes, 85, sizeof primes);
primes[0] = 83;
for (int i = 3; i < 10000; i += 2)
if (!((primes[i >> 3]) & (1 << (i & 7))))
for (int j = i * i; j < 100000000; j += i) primes[j >> 3] |= 1 << (j & 7);
}
int main() {
preCal();
int n, d, u, v;
cin >> n;
bool mach[100005];
memset(mach, false, sizeof(mach));
vector<vector<int> > ans1;
for (int i = n; i >= 2; i--) {
if ((!((primes[(i) >> 3]) & (1 << ((i)&7))))) {
vector<int> v(1, i);
for (int j = 2; i * j <= n; j++)
if (!mach[i * j]) {
mach[i * j] = true;
v.push_back(i * j);
}
if (v.size() < 2) continue;
if (v.size() % 2 == 1 && v.size() > 1) {
mach[v[1]] = false;
v.erase(v.begin() + 1);
}
ans1.push_back(v);
}
}
int res1 = 0;
for (int i = 0; i < ans1.size(); i++) res1 += ans1[i].size() / 2;
cout << res1 << endl;
for (int i = 0; i < ans1.size(); i++)
for (int j = 0; j < ans1[i].size(); j += 2)
cout << ans1[i][j] << " " << ans1[i][j + 1] << endl;
}
|
There are some tasks which have the following structure: you are given a model, and you can do some operations, you should use these operations to achive the goal. One way to create a new task is to use the same model and same operations, but change the goal.
Let's have a try. I have created the following task for Topcoder SRM 557 Div1-Hard: you are given n integers x1, x2, ..., xn. You are allowed to perform the assignments (as many as you want) of the following form xi ^= xj (in the original task i and j must be different, but in this task we allow i to equal j). The goal is to maximize the sum of all xi.
Now we just change the goal. You are also given n integers y1, y2, ..., yn. You should make x1, x2, ..., xn exactly equal to y1, y2, ..., yn. In other words, for each i number xi should be equal to yi.
Input
The first line contains an integer n (1 ≤ n ≤ 10000). The second line contains n integers: x1 to xn (0 ≤ xi ≤ 109). The third line contains n integers: y1 to yn (0 ≤ yi ≤ 109).
Output
If there is no solution, output -1.
If there is a solution, then in the first line output an integer m (0 ≤ m ≤ 1000000) – the number of assignments you need to perform. Then print m lines, each line should contain two integers i and j (1 ≤ i, j ≤ n), which denote assignment xi ^= xj.
If there are multiple solutions you can print any of them. We can prove that under these constraints if there exists a solution then there always exists a solution with no more than 106 operations.
Examples
Input
2
3 5
6 0
Output
2
1 2
2 2
Input
5
0 0 0 0 0
1 2 3 4 5
Output
-1
Input
3
4 5 6
1 2 3
Output
5
3 1
1 2
2 2
2 3
3 1
Input
3
1 2 3
4 5 6
Output
-1
Note
Assignment a ^= b denotes assignment a = a ^ b, where operation "^" is bitwise XOR of two integers.
|
#include <bits/stdc++.h>
using namespace std;
const int N = 10005, M = 30;
using pii = pair<int, int>;
int n, bs[N], bnum[N], x[N], y[N], flx[N], fly[N], b[N];
vector<pii> ans, opt;
int main() {
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; i++) cin >> x[i];
for (int i = 1; i <= n; i++) cin >> y[i];
memset(bnum, -1, sizeof(bnum));
for (int i = 1; i <= n; i++)
for (int j = M, cur = 0; j >= 0; --j)
if (x[i] & (1 << j)) {
if (bs[j])
x[i] ^= x[bs[j]], cur ^= flx[j];
else {
bnum[i] = j;
bs[j] = i;
flx[j] = cur | (1 << j);
break;
}
}
int idx = 0;
for (int i = 1; i <= n; i++) {
int fl = 0;
for (int j = M; j >= 0; --j)
if (y[i] & (1 << j)) {
if (bs[j])
y[i] ^= x[bs[j]], fl ^= flx[j];
else {
puts("-1");
return 0;
}
}
if (bnum[i] != -1) {
b[idx] = i;
fly[idx++] = fl;
continue;
}
ans.push_back({i, i});
for (int j = M; j >= 0; --j)
if (fl & (1 << j)) ans.push_back({i, bs[j]});
}
for (int i = 0; i < idx; i++) {
int tmp = fly[i];
fly[i] = 0;
for (int j = 0; j < idx; j++)
if (tmp & (1 << bnum[b[j]])) fly[i] |= 1 << j;
}
for (int i = 0; i < idx; i++) {
if (!(fly[i] & (1 << i)))
for (int j = i + 1; j < idx; j++)
if (fly[j] & (1 << i)) {
opt.push_back({b[i], b[j]});
opt.push_back({b[j], b[i]});
opt.push_back({b[i], b[j]});
swap(fly[i], fly[j]);
break;
}
if (fly[i] & (1 << i)) {
for (int j = i + 1; j < idx; j++)
if (fly[j] & (1 << i)) opt.push_back({b[j], b[i]}), fly[j] ^= fly[i];
}
}
for (int i = 0; i < idx; i++) {
if (!(fly[i] & (1 << i))) ans.push_back({b[i], b[i]});
for (int j = i + 1; j < idx; j++)
if (fly[i] & (1 << j)) ans.push_back({b[i], b[j]});
}
reverse(opt.begin(), opt.end());
for (auto &i : opt) ans.push_back(i);
cout << ans.size() << endl;
for (auto &i : ans) cout << i.first << ' ' << i.second << endl;
return 0;
}
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.
To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.
Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
Input
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105).
The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena.
It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
Output
In the first line print a single number k — the number of options for numbers s and t.
In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
Examples
Input
5
1 2 1 2 1
Output
2
1 3
3 1
Input
4
1 1 1 1
Output
3
1 4
2 2
4 1
Input
4
1 2 1 2
Output
0
Input
8
2 1 2 1 1 1 1 1
Output
3
1 6
2 3
6 1
|
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class CF283D1 {
private static class Result implements Comparable<Result> {
Integer s;
Integer t;
public Result(final Integer s, final Integer t) {
this.s = s;
this.t = t;
}
@Override
public int compareTo(final Result o) {
if (s.compareTo(o.s) == 0) {
return t.compareTo(o.t);
}
return s.compareTo(o.s);
}
}
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer> posOnesList = new LinkedList<Integer>();
List<Integer> posTwosList = new LinkedList<Integer>();
int[] meetOnes = new int[n];
int[] meetTwos = new int[n];
int last = -1;
for (int i = 0; i < n; i++) {
int curr = sc.nextInt();
meetOnes[i] = i > 0 ? meetOnes[i - 1] : 0;
meetTwos[i] = i > 0 ? meetTwos[i - 1] : 0;
if (curr == 1) {
posOnesList.add(i);
meetOnes[i]++;
} else {
posTwosList.add(i);
meetTwos[i]++;
}
if (i == n - 1) {
last = curr;
}
}
Integer[] posOnes = posOnesList.toArray(new Integer[0]);
Integer[] posTwos = posTwosList.toArray(new Integer[0]);
List<Result> results = new LinkedList<Result>();
for (int t = 1; t <= n; t++) {
int currPos = -1;
int onesWins = 0;
int twosWins = 0;
while (currPos < n) {
int metOnes = currPos >= 0 ? meetOnes[currPos] : 0;
int metTwos = currPos >= 0 ? meetTwos[currPos] : 0;
int i1 = 3 * n;
if (metOnes + t - 1 < posOnes.length) {
i1 = posOnes[metOnes + t - 1];
}
int i2 = 3 * n;
if (metTwos + t - 1 < posTwos.length) {
i2 = posTwos[metTwos + t - 1];
}
if (i1 < i2) {
currPos = i1;
onesWins++;
} else if (i2 < i1) {
currPos = i2;
twosWins++;
} else {
break;
}
}
if (currPos == n - 1 && onesWins != twosWins) {
if (onesWins > twosWins && last == 1) {
results.add(new Result(onesWins, t));
}
if (twosWins > onesWins && last == 2) {
results.add(new Result(twosWins, t));
}
}
}
Result[] res = results.toArray(new Result[0]);
Arrays.sort(res);
StringBuilder sb = new StringBuilder();
for (Result r : res) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(r.s + " " + r.t);
}
System.out.println(res.length);
if (res.length > 0) {
System.out.println(sb.toString());
}
}
}
|
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.
The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1).
Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.
Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9.
Input
The first line contains number m (2 ≤ m ≤ 105).
The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≤ xi ≤ 109, 0 ≤ yi ≤ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable.
No two cubes occupy the same place.
Output
In the only line print the answer to the problem.
Examples
Input
3
2 1
1 0
0 1
Output
19
Input
5
0 0
0 1
0 2
0 3
0 4
Output
2930
|
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast", "inline", "-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
using namespace std;
template <typename T>
void read(T &x) {
x = 0;
char ch = getchar();
int fh = 1;
while (ch < '0' || ch > '9') {
if (ch == '-') fh = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
x *= fh;
}
template <typename T>
void write(T x) {
if (x < 0) x = -x, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
template <typename T>
void writeln(T x) {
write(x);
puts("");
}
int m;
map<pair<int, int>, int> mp;
int val[100005];
bool del[100005];
bool ins[100005];
set<pair<int, pair<int, int>>> st;
long long ans = 0;
long long qpow(long long a, long long b) {
long long res = 1;
while (b) {
if (b & 1) res = res * a % 1000000009;
a = a * a % 1000000009;
b >>= 1;
}
return res;
}
signed main() {
read(m);
for (int i = 0; i < m; ++i) {
int x, y;
read(x);
read(y);
mp[make_pair(x, y)] = i;
}
for (auto i : mp) {
if (i.first.second == 0)
val[i.second] = 1000000007;
else {
if (mp.count(make_pair(i.first.first - 1, i.first.second - 1)))
val[i.second]++;
if (mp.count(make_pair(i.first.first, i.first.second - 1)))
val[i.second]++;
if (mp.count(make_pair(i.first.first + 1, i.first.second - 1)))
val[i.second]++;
}
}
for (auto i : mp) {
bool flag = true;
if (mp.count(make_pair(i.first.first - 1, i.first.second + 1)))
if (val[mp[make_pair(i.first.first - 1, i.first.second + 1)]] == 1)
flag = false;
if (mp.count(make_pair(i.first.first, i.first.second + 1)))
if (val[mp[make_pair(i.first.first, i.first.second + 1)]] == 1)
flag = false;
if (mp.count(make_pair(i.first.first + 1, i.first.second + 1)))
if (val[mp[make_pair(i.first.first + 1, i.first.second + 1)]] == 1)
flag = false;
if (flag) {
st.insert(make_pair(i.second, i.first));
ins[i.second] = 1;
}
}
for (int i = 0; i < m; ++i) {
int id, x, y;
while (1) {
set<pair<int, pair<int, int>>>::iterator it;
if (i & 1)
it = st.begin();
else {
it = st.end();
it--;
}
if (!del[(*it).first] && ins[(*it).first]) {
id = (*it).first;
x = (*it).second.first;
y = (*it).second.second;
st.erase(it);
break;
}
st.erase(it);
}
ans += qpow(m, m - i - 1) * id % 1000000009;
ans %= 1000000009;
del[id] = 1;
if (mp.count(make_pair(x - 1, y + 1)))
if (!del[mp[make_pair(x - 1, y + 1)]]) {
val[mp[make_pair(x - 1, y + 1)]]--;
if (mp.count(make_pair(x - 2, y)))
if (!del[mp[make_pair(x - 2, y)]]) {
bool flag = true;
if (mp.count(make_pair(x - 3, y + 1)))
if (!del[mp[make_pair(x - 3, y + 1)]])
if (val[mp[make_pair(x - 3, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x - 2, y + 1)))
if (!del[mp[make_pair(x - 2, y + 1)]])
if (val[mp[make_pair(x - 2, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x - 1, y + 1)))
if (!del[mp[make_pair(x - 1, y + 1)]])
if (val[mp[make_pair(x - 1, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(
make_pair(mp[make_pair(x - 2, y)], make_pair(x - 2, y)));
ins[mp[make_pair(x - 2, y)]] = 1;
} else
ins[mp[make_pair(x - 2, y)]] = 0;
}
if (mp.count(make_pair(x - 1, y)))
if (!del[mp[make_pair(x - 1, y)]]) {
bool flag = true;
if (mp.count(make_pair(x - 2, y + 1)))
if (!del[mp[make_pair(x - 2, y + 1)]])
if (val[mp[make_pair(x - 2, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x - 1, y + 1)))
if (!del[mp[make_pair(x - 1, y + 1)]])
if (val[mp[make_pair(x - 1, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x, y + 1)))
if (!del[mp[make_pair(x, y + 1)]])
if (val[mp[make_pair(x, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(
make_pair(mp[make_pair(x - 1, y)], make_pair(x - 1, y)));
ins[mp[make_pair(x - 1, y)]] = 1;
} else
ins[mp[make_pair(x - 1, y)]] = 0;
}
if (mp.count(make_pair(x, y)))
if (!del[mp[make_pair(x, y)]]) {
bool flag = true;
if (mp.count(make_pair(x - 1, y + 1)))
if (!del[mp[make_pair(x - 1, y + 1)]])
if (val[mp[make_pair(x - 1, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x, y + 1)))
if (!del[mp[make_pair(x, y + 1)]])
if (val[mp[make_pair(x, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 1, y + 1)))
if (!del[mp[make_pair(x + 1, y + 1)]])
if (val[mp[make_pair(x + 1, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(make_pair(mp[make_pair(x, y)], make_pair(x, y)));
ins[mp[make_pair(x, y)]] = 1;
} else
ins[mp[make_pair(x, y)]] = 0;
}
}
if (mp.count(make_pair(x, y + 1)))
if (!del[mp[make_pair(x, y + 1)]]) {
val[mp[make_pair(x, y + 1)]]--;
if (mp.count(make_pair(x - 1, y)))
if (!del[mp[make_pair(x - 1, y)]]) {
bool flag = true;
if (mp.count(make_pair(x - 2, y + 1)))
if (!del[mp[make_pair(x - 2, y + 1)]])
if (val[mp[make_pair(x - 2, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x - 1, y + 1)))
if (!del[mp[make_pair(x - 1, y + 1)]])
if (val[mp[make_pair(x - 1, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x, y + 1)))
if (!del[mp[make_pair(x, y + 1)]])
if (val[mp[make_pair(x, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(
make_pair(mp[make_pair(x - 1, y)], make_pair(x - 1, y)));
ins[mp[make_pair(x - 1, y)]] = 1;
} else
ins[mp[make_pair(x - 1, y)]] = 0;
}
if (mp.count(make_pair(x, y)))
if (!del[mp[make_pair(x, y)]]) {
bool flag = true;
if (mp.count(make_pair(x - 1, y + 1)))
if (!del[mp[make_pair(x - 1, y + 1)]])
if (val[mp[make_pair(x - 1, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x, y + 1)))
if (!del[mp[make_pair(x, y + 1)]])
if (val[mp[make_pair(x, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 1, y + 1)))
if (!del[mp[make_pair(x + 1, y + 1)]])
if (val[mp[make_pair(x + 1, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(make_pair(mp[make_pair(x, y)], make_pair(x, y)));
ins[mp[make_pair(x, y)]] = 1;
} else
ins[mp[make_pair(x, y)]] = 0;
}
if (mp.count(make_pair(x + 1, y)))
if (!del[mp[make_pair(x + 1, y)]]) {
bool flag = true;
if (mp.count(make_pair(x, y + 1)))
if (!del[mp[make_pair(x, y + 1)]])
if (val[mp[make_pair(x, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 1, y + 1)))
if (!del[mp[make_pair(x + 1, y + 1)]])
if (val[mp[make_pair(x + 1, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 2, y + 1)))
if (!del[mp[make_pair(x + 2, y + 1)]])
if (val[mp[make_pair(x + 2, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(
make_pair(mp[make_pair(x + 1, y)], make_pair(x + 1, y)));
ins[mp[make_pair(x + 1, y)]] = 1;
} else
ins[mp[make_pair(x + 1, y)]] = 0;
}
}
if (mp.count(make_pair(x + 1, y + 1)))
if (!del[mp[make_pair(x + 1, y + 1)]]) {
val[mp[make_pair(x + 1, y + 1)]]--;
if (mp.count(make_pair(x, y)))
if (!del[mp[make_pair(x, y)]]) {
bool flag = true;
if (mp.count(make_pair(x - 1, y + 1)))
if (!del[mp[make_pair(x - 1, y + 1)]])
if (val[mp[make_pair(x - 1, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x, y + 1)))
if (!del[mp[make_pair(x, y + 1)]])
if (val[mp[make_pair(x, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 1, y + 1)))
if (!del[mp[make_pair(x + 1, y + 1)]])
if (val[mp[make_pair(x + 1, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(make_pair(mp[make_pair(x, y)], make_pair(x, y)));
ins[mp[make_pair(x, y)]] = 1;
} else
ins[mp[make_pair(x, y)]] = 0;
}
if (mp.count(make_pair(x + 1, y)))
if (!del[mp[make_pair(x + 1, y)]]) {
bool flag = true;
if (mp.count(make_pair(x, y + 1)))
if (!del[mp[make_pair(x, y + 1)]])
if (val[mp[make_pair(x, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 1, y + 1)))
if (!del[mp[make_pair(x + 1, y + 1)]])
if (val[mp[make_pair(x + 1, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 2, y + 1)))
if (!del[mp[make_pair(x + 2, y + 1)]])
if (val[mp[make_pair(x + 2, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(
make_pair(mp[make_pair(x + 1, y)], make_pair(x + 1, y)));
ins[mp[make_pair(x + 1, y)]] = 1;
} else
ins[mp[make_pair(x + 1, y)]] = 0;
}
if (mp.count(make_pair(x + 2, y)))
if (!del[mp[make_pair(x + 2, y)]]) {
bool flag = true;
if (mp.count(make_pair(x + 1, y + 1)))
if (!del[mp[make_pair(x + 1, y + 1)]])
if (val[mp[make_pair(x + 1, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 2, y + 1)))
if (!del[mp[make_pair(x + 2, y + 1)]])
if (val[mp[make_pair(x + 2, y + 1)]] == 1) flag = false;
if (mp.count(make_pair(x + 3, y + 1)))
if (!del[mp[make_pair(x + 3, y + 1)]])
if (val[mp[make_pair(x + 3, y + 1)]] == 1) flag = false;
if (flag) {
st.insert(
make_pair(mp[make_pair(x + 2, y)], make_pair(x + 2, y)));
ins[mp[make_pair(x + 2, y)]] = 1;
} else
ins[mp[make_pair(x + 2, y)]] = 0;
}
}
if (mp.count(make_pair(x - 1, y - 1)))
if (!del[mp[make_pair(x - 1, y - 1)]]) {
bool flag = true;
if (mp.count(make_pair(x - 2, y)))
if (!del[mp[make_pair(x - 2, y)]])
if (val[mp[make_pair(x - 2, y)]] == 1) flag = false;
if (mp.count(make_pair(x - 1, y)))
if (!del[mp[make_pair(x - 1, y)]])
if (val[mp[make_pair(x - 1, y)]] == 1) flag = false;
if (mp.count(make_pair(x, y)))
if (!del[mp[make_pair(x, y)]])
if (val[mp[make_pair(x, y)]] == 1) flag = false;
if (flag) {
st.insert(
make_pair(mp[make_pair(x - 1, y - 1)], make_pair(x - 1, y - 1)));
ins[mp[make_pair(x - 1, y - 1)]] = 1;
} else
ins[mp[make_pair(x - 1, y - 1)]] = 0;
}
if (mp.count(make_pair(x, y - 1)))
if (!del[mp[make_pair(x, y - 1)]]) {
bool flag = true;
if (mp.count(make_pair(x - 1, y)))
if (!del[mp[make_pair(x - 1, y)]])
if (val[mp[make_pair(x - 1, y)]] == 1) flag = false;
if (mp.count(make_pair(x, y)))
if (!del[mp[make_pair(x, y)]])
if (val[mp[make_pair(x, y)]] == 1) flag = false;
if (mp.count(make_pair(x + 1, y)))
if (!del[mp[make_pair(x + 1, y)]])
if (val[mp[make_pair(x + 1, y)]] == 1) flag = false;
if (flag) {
st.insert(make_pair(mp[make_pair(x, y - 1)], make_pair(x, y - 1)));
ins[mp[make_pair(x, y - 1)]] = 1;
} else
ins[mp[make_pair(x, y - 1)]] = 0;
}
if (mp.count(make_pair(x + 1, y - 1)))
if (!del[mp[make_pair(x + 1, y - 1)]]) {
bool flag = true;
if (mp.count(make_pair(x, y)))
if (!del[mp[make_pair(x, y)]])
if (val[mp[make_pair(x, y)]] == 1) flag = false;
if (mp.count(make_pair(x + 1, y)))
if (!del[mp[make_pair(x + 1, y)]])
if (val[mp[make_pair(x + 1, y)]] == 1) flag = false;
if (mp.count(make_pair(x + 2, y)))
if (!del[mp[make_pair(x + 2, y)]])
if (val[mp[make_pair(x + 2, y)]] == 1) flag = false;
if (flag) {
st.insert(
make_pair(mp[make_pair(x + 1, y - 1)], make_pair(x + 1, y - 1)));
ins[mp[make_pair(x + 1, y - 1)]] = 1;
} else
ins[mp[make_pair(x + 1, y - 1)]] = 0;
}
}
writeln(ans);
return 0;
}
|
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s.
<image>
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.
He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.
Input
The first line of input contains string s containing lowercase English letters (1 ≤ |s| ≤ 1000).
The second line contains integer k (1 ≤ k ≤ 1000).
Output
Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise.
Examples
Input
saba
2
Output
NO
Input
saddastavvat
2
Output
YES
Note
Palindrome is a string reading the same forward and backward.
In the second sample, the faxes in his back-bag can be "saddas" and "tavvat".
|
def isPalindrome(t):
for i in range(len(t)//2):
if t[i] != t[len(t)-i-1]:
return False
return True
s = input()
k = int(input())
if len(s) % k:
print('NO')
else:
t = len(s)//k
for i in range(k):
if not isPalindrome(s[i*t: i*t+t]):
print('NO')
break
else:
print('YES')
|
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.
Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
Input
First line of input contains an integer n (2 ≤ n ≤ 105), the number of players.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — the bids of players.
Output
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
Examples
Input
4
75 150 75 50
Output
Yes
Input
3
100 150 250
Output
No
Note
In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.
It can be shown that in the second sample test there is no way to make all bids equal.
|
n = int(raw_input())
a = [int(x) for x in raw_input().split()]
# s = set()
# for e in a:
# s.add(e)
# a = list(s)
# def gcd(x, y):
# if y == 0:
# return x
# else:
# return gcd(y, x%y)
# def lcm(x,y):
# return x * y / gcd(x,y)
def factorize(x):
while(x % 2 == 0):
x /= 2
while(x % 3 == 0):
x /= 3
return x
# lcm_a = 1
# for i in xrange(len(a)):
# lcm_a = lcm(lcm_a, a[i])
# res = 'YES'
# for i in xrange(len(a)):
# if factorize(lcm_a / a[i]) != 1:
# res = 'NO'
# break
a = [factorize(x) for x in a]
print ['No','Yes'][all((a[0]==x for x in a))]
|
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.
Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 4) — the number of vertices that were not erased by Wilbur's friend.
Each of the following n lines contains two integers xi and yi ( - 1000 ≤ xi, yi ≤ 1000) —the coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order.
It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes.
Output
Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print - 1.
Examples
Input
2
0 0
1 1
Output
1
Input
1
1 1
Output
-1
Note
In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square.
In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area.
|
#include <bits/stdc++.h>
using namespace std;
int cantidad;
int y[10000];
int x[10000];
int main() {
cin >> cantidad;
int area;
int tempx;
int tempy;
for (int i = 0; i < cantidad; i++) {
cin >> x[i] >> y[i];
}
if (cantidad == 1) {
cout << -1;
}
if (cantidad == 2) {
if (x[0] == x[1] || y[0] == y[1]) {
cout << -1;
} else {
if (x[0] > x[1]) {
tempx = x[0] - x[1];
} else {
tempx = x[1] - x[0];
}
if (y[0] > y[1]) {
tempy = y[0] - y[1];
} else {
tempy = y[1] - y[0];
}
area = tempx * tempy;
cout << area;
}
}
if (cantidad == 3) {
if (x[0] != x[1]) {
if (x[0] > x[1]) {
tempx = x[0] - x[1];
} else {
tempx = x[1] - x[0];
}
} else {
if (x[0] > x[2]) {
tempx = x[0] - x[2];
} else {
tempx = x[2] - x[0];
}
}
if (y[0] != y[1]) {
if (y[0] > y[1]) {
tempy = y[0] - y[1];
} else {
tempy = y[1] - y[0];
}
} else {
if (y[0] > y[2]) {
tempy = y[0] - y[2];
} else {
tempy = y[2] - y[0];
}
}
area = tempx * tempy;
cout << area;
}
if (cantidad == 4) {
if (x[0] != x[1]) {
if (y[0] != y[1]) {
if (x[0] > x[1]) {
tempx = x[0] - x[1];
} else {
tempx = x[1] - x[0];
}
if (y[0] > y[1]) {
tempy = y[0] - y[1];
} else {
tempy = y[1] - y[0];
}
}
}
if (x[0] != x[2]) {
if (y[0] != y[2]) {
if (x[0] > x[2]) {
tempx = x[0] - x[2];
} else {
tempx = x[2] - x[0];
}
if (y[0] > y[2]) {
tempy = y[0] - y[2];
} else {
tempy = y[2] - y[0];
}
}
}
if (x[0] != x[3]) {
if (y[0] != y[3]) {
if (x[0] > x[3]) {
tempx = x[0] - x[3];
} else {
tempx = x[3] - x[0];
}
if (y[0] > y[3]) {
tempy = y[0] - y[3];
} else {
tempy = y[3] - y[0];
}
}
}
area = tempx * tempy;
cout << area;
}
}
|
A flowerbed has many flowers and two fountains.
You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.
You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value.
Input
The first line of the input contains integers n, x1, y1, x2, y2 (1 ≤ n ≤ 2000, - 107 ≤ x1, y1, x2, y2 ≤ 107) — the number of flowers, the coordinates of the first and the second fountain.
Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≤ xi, yi ≤ 107) — the coordinates of the i-th flower.
It is guaranteed that all n + 2 points in the input are distinct.
Output
Print the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer.
Examples
Input
2 -1 0 5 3
0 2
5 2
Output
6
Input
4 0 0 5 0
9 4
8 3
-1 0
1 4
Output
33
Note
The first sample is (r12 = 5, r22 = 1): <image> The second sample is (r12 = 1, r22 = 32): <image>
|
n, x1, y1, x2, y2 = map(int,raw_input().split())
SquareDist = []
for i in range (0, n):
x,y = map(int,raw_input().split())
D1 = (x-x1)**2 + (y-y1)**2
D2 = (x-x2)**2 + (y-y2)**2
SquareDist.append((D1,D2))
SquareDist.sort()
Suffixes = [0]
for i in range (0, n):
Suffixes.append(max(Suffixes[i], SquareDist[n-1-i][1]))
val = Suffixes[n]
for i in range (0, n):
val = min(val, Suffixes[n-1-i]+SquareDist[i][0])
print val
|
A sportsman starts from point xstart = 0 and runs to point with coordinate xfinish = m (on a straight line). Also, the sportsman can jump — to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle.
On the way of an athlete are n obstacles at coordinates x1, x2, ..., xn. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point.
Input
The first line of the input containsd four integers n, m, s and d (1 ≤ n ≤ 200 000, 2 ≤ m ≤ 109, 1 ≤ s, d ≤ 109) — the number of obstacles on the runner's way, the coordinate of the finishing point, the length of running before the jump and the maximum length of the jump, correspondingly.
The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ m - 1) — the coordinates of the obstacles. It is guaranteed that the starting and finishing point have no obstacles, also no point can have more than one obstacle, The coordinates of the obstacles are given in an arbitrary order.
Output
If the runner cannot reach the finishing point, print in the first line of the output "IMPOSSIBLE" (without the quotes).
If the athlete can get from start to finish, print any way to do this in the following format:
* print a line of form "RUN X>" (where "X" should be a positive integer), if the athlete should run for "X" more meters;
* print a line of form "JUMP Y" (where "Y" should be a positive integer), if the sportsman starts a jump and should remain in air for "Y" more meters.
All commands "RUN" and "JUMP" should strictly alternate, starting with "RUN", besides, they should be printed chronologically. It is not allowed to jump over the finishing point but it is allowed to land there after a jump. The athlete should stop as soon as he reaches finish.
Examples
Input
3 10 1 3
3 4 7
Output
RUN 2
JUMP 3
RUN 1
JUMP 2
RUN 2
Input
2 9 2 3
6 4
Output
IMPOSSIBLE
|
#include <bits/stdc++.h>
using namespace std;
const int MXN = (int)1e6 + 10;
const int INF = (int)1e9 + 7;
const long long LINF = (long long)1e18 + 10;
const double EPS = (double)1e-9;
const double PI = (double)acos(-1.0);
int a[MXN];
int n, m, s, d;
vector<pair<int, int> > v;
int main() {
scanf("%d%d%d%d", &n, &m, &s, &d);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
sort(a + 1, a + n + 1);
v.push_back(make_pair(a[1], a[1]));
for (int i = 2; i <= n; ++i) {
if (a[i] - v.back().second - 2 < s) {
v[(int)v.size() - 1].second = a[i];
} else {
v.push_back(make_pair(a[i], a[i]));
}
}
for (auto it : v) {
if (d < it.second - it.first + 2) {
printf("IMPOSSIBLE");
return 0;
}
}
int cur = 0;
for (auto it : v) {
if (it.first - 1 - cur < s) {
printf("IMPOSSIBLE");
return 0;
} else {
cur = it.second + 1;
}
}
cur = 0;
for (auto it : v) {
if (it.first - 1 - cur > 0) printf("RUN %d\n", it.first - 1 - cur);
if (it.second + 2 - it.first > 0)
printf("JUMP %d\n", it.second + 1 - it.first + 1);
cur = it.second + 1;
}
if (cur != m) {
printf("RUN %d", m - cur);
}
return 0;
}
|
A tuple of positive integers {x1, x2, ..., xk} is called simple if for all pairs of positive integers (i, j) (1 ≤ i < j ≤ k), xi + xj is a prime.
You are given an array a with n positive integers a1, a2, ..., an (not necessary distinct). You want to find a simple subset of the array a with the maximum size.
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Let's define a subset of the array a as a tuple that can be obtained from a by removing some (possibly all) elements of it.
Input
The first line contains integer n (1 ≤ n ≤ 1000) — the number of integers in the array a.
The second line contains n integers ai (1 ≤ ai ≤ 106) — the elements of the array a.
Output
On the first line print integer m — the maximum possible size of simple subset of a.
On the second line print m integers bl — the elements of the simple subset of the array a with the maximum size.
If there is more than one solution you can print any of them. You can print the elements of the subset in any order.
Examples
Input
2
2 3
Output
2
3 2
Input
2
2 2
Output
1
2
Input
3
2 1 1
Output
3
1 1 2
Input
2
83 14
Output
2
14 83
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Aviously
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public static ArrayList<Integer> prime = new ArrayList<>();
public final int N = 2 * 1000 * 1000;
public void solve(int testNumber, Scanner in, PrintWriter out) {
prime.add(2);
for (int i = 3; i <= N; i += 2) {
if (isPrime(i)) {
// out.print(i + " ");
prime.add(i);
}
}
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
if (a.length > 1 && a[0] == 1 && a[1] == 1) {
int cnt = 1;
while (cnt < a.length && a[cnt] == 1)
cnt++;
int p = 0;
for (int i = cnt; i < a.length; i++) {
if (findPrime(a[i] + 1)) {
p = a[i];
break;
}
}
out.println(cnt + (p > 0 ? 1 : 0));
for (int i = 0; i < cnt; i++) {
out.print(a[i] + " ");
}
if (p > 0)
out.print(p);
return;
}
for (int i = 0; i < n; i++) {
if (i > 0 && a[i] == a[i - 1])
continue;
for (int j = i + 1; j < n; j++) {
if (j > i + 1 && a[j] == a[j - 1])
continue;
if (findPrime(a[i] + a[j])) {
out.println(2);
out.println(a[i] + " " + a[j]);
return;
}
}
}
out.println(1);
out.println(a[0]);
}
public boolean isPrime(int n) {
for (int a : prime) {
if (a > Math.sqrt(n))
break;
if (n % a == 0)
return false;
}
return true;
}
public boolean findPrime(int n) {
int l = 0;
int r = prime.size() - 1;
while (l < r) {
int mid = (l + r) / 2;
if (prime.get(mid) < n) {
l = mid + 1;
} else {
r = mid;
}
}
if (prime.get(l) == n)
return true;
return false;
}
}
}
|
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by <image> units.
Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.
Input
First line of the input contains two integers n and k (1 ≤ n ≤ 10000, 0 ≤ k ≤ 99) — number of accumulators and the percent of energy that is lost during transfers.
Next line contains n integers a1, a2, ... , an — amounts of energy in the first, second, .., n-th accumulator respectively (0 ≤ ai ≤ 1000, 1 ≤ i ≤ n).
Output
Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy.
The absolute or relative error in the answer should not exceed 10 - 6.
Examples
Input
3 50
4 2 1
Output
2.000000000
Input
2 90
1 11
Output
1.909090909
|
#include <bits/stdc++.h>
using namespace std;
double a[100001];
int n;
double k;
int isbalance(double val) {
double inc = 0.0;
double dec = 0.0;
for (int i = 0; i < n; i++)
if (a[i] > val)
dec += (a[i] - val);
else
inc += (val - a[i]);
dec -= dec * (k / 100.0);
if (dec >= inc)
return 0;
else
return 1;
}
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> a[i];
double l = 0, r = 1000;
double ans = 0;
while (r - l > 1e-7) {
double mid = (l + r) / 2.0;
int cho = isbalance(mid);
if (cho == 0)
ans = mid, l = mid;
else
r = mid;
}
cout << fixed << setprecision(7) << l << endl;
return 0;
}
|
ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland.
In Udayland, there are 2n days in a year. ZS the Coder wants to interview k people from Udayland, each of them has birthday in one of 2n days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day.
ZS the Coder knows that the answer can be written as an irreducible fraction <image>. He wants to find the values of A and B (he does not like to deal with floating point numbers). Can you help him?
Input
The first and only line of the input contains two integers n and k (1 ≤ n ≤ 1018, 2 ≤ k ≤ 1018), meaning that there are 2n days in a year and that ZS the Coder wants to interview exactly k people.
Output
If the probability of at least two k people having the same birthday in 2n days long year equals <image> (A ≥ 0, B ≥ 1, <image>), print the A and B in a single line.
Since these numbers may be too large, print them modulo 106 + 3. Note that A and B must be coprime before their remainders modulo 106 + 3 are taken.
Examples
Input
3 2
Output
1 8
Input
1 3
Output
1 1
Input
4 3
Output
23 128
Note
In the first sample case, there are 23 = 8 days in Udayland. The probability that 2 people have the same birthday among 2 people is clearly <image>, so A = 1, B = 8.
In the second sample case, there are only 21 = 2 days in Udayland, but there are 3 people, so it is guaranteed that two of them have the same birthday. Thus, the probability is 1 and A = B = 1.
|
#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000003;
long long fast_pow(long long x, long long y) {
long long ret = 1;
for (; y; y >>= 1, x = x * x % MOD)
if (y & 1) ret = ret * x % MOD;
return ret % MOD;
}
long long get_inv(long long x) { return fast_pow(x, MOD - 2); }
int main() {
long long n, k;
cin >> n >> k;
if (((k - 1) >> n) && n < 62) {
cout << 1 << " " << 1 << endl;
return 0;
}
long long gcd = 0;
for (long long i = 1; i <= min(60ll, n); i++) gcd += ((k - 1) >> i) + 1;
gcd += n - min(60ll, n);
long long ans_b = fast_pow(
2, ((k % (MOD - 1)) * (n % (MOD - 1)) - gcd % (MOD - 1) + MOD - 1) %
(MOD - 1));
long long last = fast_pow(2, n), ans_a = 0;
if (last >= k) {
long long x = last;
ans_a = 1;
for (long long i = 0; i < k; i++) ans_a = ans_a * (x - i) % MOD;
ans_a = ans_a * get_inv(fast_pow(2, gcd)) % MOD;
}
cout << (ans_b - ans_a + MOD) % MOD << " " << ans_b << endl;
return 0;
}
|
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.
There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets.
In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to <image>, it means that it is equal to the socket's power divided by two with rounding up, for example <image> and <image>.
Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.
The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.
Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.
The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets.
The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers.
The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
Output
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers.
In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u.
In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c.
If there are multiple answers, print any of them.
Examples
Input
2 2
1 1
2 2
Output
2 2
1 1
1 2
Input
2 1
2 100
99
Output
1 6
6
1 0
|
#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const int MOD = 1000000007;
const int INF = 0x7fffffff;
const double eps = 1e-10;
const int N = 200005;
set<pair<int, int> > com;
pair<int, int> soc[N];
int id[N], match[N];
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
int a;
scanf("%d", &a);
com.insert(make_pair(a, i));
}
for (int i = 1; i <= m; i++) {
scanf("%d", &soc[i].first);
soc[i].second = i;
}
sort(soc + 1, soc + m + 1);
int c = 0, u = 0;
for (int i = 1; i <= m; i++) {
for (int j = 0; j <= 30; j++) {
auto it = com.lower_bound(make_pair(soc[i].first, 0));
if (it != com.end() && it->first == soc[i].first) {
u += j;
c++;
id[soc[i].second] = j;
match[it->second] = soc[i].second;
com.erase(it);
break;
}
soc[i].first = (soc[i].first + 1) / 2;
}
}
printf("%d %d\n", c, u);
for (int i = 1; i <= m; i++) printf("%d ", id[i]);
cout << endl;
for (int i = 1; i <= n; i++) printf("%d ", match[i]);
}
|
Consider the following grammar:
* <expression> ::= <term> | <expression> '+' <term>
* <term> ::= <number> | <number> '-' <number> | <number> '(' <expression> ')'
* <number> ::= <pos_digit> | <number> <digit>
* <digit> ::= '0' | <pos_digit>
* <pos_digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
This grammar describes a number in decimal system using the following rules:
* <number> describes itself,
* <number>-<number> (l-r, l ≤ r) describes integer which is concatenation of all integers from l to r, written without leading zeros. For example, 8-11 describes 891011,
* <number>(<expression>) describes integer which is concatenation of <number> copies of integer described by <expression>,
* <expression>+<term> describes integer which is concatenation of integers described by <expression> and <term>.
For example, 2(2-4+1)+2(2(17)) describes the integer 2341234117171717.
You are given an expression in the given grammar. Print the integer described by it modulo 109 + 7.
Input
The only line contains a non-empty string at most 105 characters long which is valid according to the given grammar. In particular, it means that in terms l-r l ≤ r holds.
Output
Print single integer — the number described by the expression modulo 109 + 7.
Examples
Input
8-11
Output
891011
Input
2(2-4+1)+2(2(17))
Output
100783079
Input
1234-5678
Output
745428774
Input
1+2+3+4-5+6+7-9
Output
123456789
|
#include <bits/stdc++.h>
using namespace std;
int power(int b, int a = 10) {
int res = 1;
for (; b; b >>= 1, a = (long long)a * a % 1000000007)
if (b & 1) res = (long long)res * a % 1000000007;
return res;
}
struct node {
int x, y;
node() {}
node(int x, int y) : x(x), y(y) {}
node(string &s) {
x = s.size();
y = 0;
for (int i = 0; i < x; ++i)
y = ((long long)y * 10 + (s[i] - '0')) % 1000000007;
}
node operator+(const node &a) {
return node((x + a.x) % (1000000007 - 1),
((long long)y * power(a.x) + a.y) % 1000000007);
}
node operator^(string &s) {
int re = 0;
for (int i = 0; i < s.size(); ++i)
re = ((long long)re * 10 + (s[i] - '0')) % (1000000007 - 1);
if (!x) return node(0, (long long)y * re % 1000000007);
int tx = power(x);
int tmp = (long long)(power(re, tx) + 1000000007 - 1) *
power(1000000007 - 2, tx + 1000000007 - 1) % 1000000007 * y %
1000000007;
return node((long long)re * x % (1000000007 - 1), tmp);
}
};
string get(string &s, int &i) {
string res;
while (isdigit(s[i])) res += s[i++];
return res;
}
int del(string &L, string &R) {
int l = L.size(), re = 0;
for (int i = 0; i < l; ++i)
re = ((long long)re * 10 + (R[i] - L[i])) % (1000000007 - 1);
return re;
}
node range(string &L, string &R) {
if (L.size() == R.size()) {
int nL = node(L).y, nR = node(R).y;
int x = power(L.size());
int z = (del(L, R) + 1) % (1000000007 - 1);
int tmp = ((long long)nL * power(z, x) - nR + 1000000007) % 1000000007 *
power(1000000007 - 2, x + 1000000007 - 1) % 1000000007;
(tmp += (long long)(power(z, x) + 1000000007 - x) *
power(1000000007 - 2, (long long)(x + 1000000007 - 1) *
(x + 1000000007 - 1) % 1000000007) %
1000000007) %= 1000000007;
return node(int((long long)L.size() * z % (1000000007 - 1)), tmp);
} else {
string LM = string(L.size(), '9');
string RM = "1" + string(R.size() - 1, '0');
node res = range(L, LM);
int nL = power(L.size()),
nR = ((long long)nL * 10 + 1000000007 - 1) % 1000000007;
int x = power(L.size() + 1);
int z = 9;
for (int i = 1; i <= L.size(); ++i)
z = (long long)z * 10 % (1000000007 - 1);
for (int i = L.size() + 1; i < R.size(); ++i) {
int tmp = ((long long)nL * power(z, x) - nR + 1000000007) % 1000000007 *
power(1000000007 - 2, x + 1000000007 - 1) % 1000000007;
(tmp += (long long)(power(z, x) + 1000000007 - x) *
power(1000000007 - 2, (long long)(x + 1000000007 - 1) *
(x + 1000000007 - 1) % 1000000007) %
1000000007) %= 1000000007;
res = res + node((long long)i * z % (1000000007 - 1), tmp);
nL = (long long)nL * 10 % 1000000007,
nR = ((long long)nL * 10 + 1000000007 - 1) % 1000000007;
x = (long long)x * 10 % 1000000007;
z = (long long)z * 10 % (1000000007 - 1);
}
return res + range(RM, R);
}
}
node work(string &s, int &i) {
node tmp(0, 0);
string num = "";
int l = s.size();
while (i < l) {
if (isdigit(s[i])) num = get(s, i);
if (i == l) break;
char ty = s[i++];
if (ty == ')') return tmp + node(num);
if (ty == '(') tmp = tmp + (work(s, i) ^ num);
if (ty == '+') tmp = tmp + node(num);
if (ty == '-') {
string num2 = get(s, i);
tmp = tmp + range(num, num2);
}
num.clear();
}
return tmp + node(num);
}
int main() {
string s;
cin >> s;
int i = 0;
printf("%d\n", work(s, i).y);
return 0;
}
|
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.
Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.
Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.
Input
The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000).
The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of:
1. Binary number of exactly m bits.
2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter.
Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.
Output
In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers.
Examples
Input
3 3
a := 101
b := 011
c := ? XOR b
Output
011
100
Input
5 1
a := 1
bb := 0
cx := ? OR a
d := ? XOR ?
e := d AND bb
Output
0
0
Note
In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15.
For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
|
#include <bits/stdc++.h>
using namespace std;
int n, m;
char var[12], def[4], buf[1005];
unordered_map<string, int> varId;
pair<int, int> operand[5005];
int val[5005][1005];
char op[5005][4];
char mx[1005], mn[1005];
int calc(int id, int idx) {
if (op[id][0] == 'X') {
return val[operand[id].first][idx] ^ val[operand[id].second][idx];
} else if (op[id][0] == 'O') {
return val[operand[id].first][idx] | val[operand[id].second][idx];
} else if (op[id][0] == 'A') {
return val[operand[id].first][idx] & val[operand[id].second][idx];
} else {
return val[id][idx];
}
}
int main() {
scanf("%d%d", &n, &m);
int tot = 0;
varId["?"] = ++tot;
for (int i = 0; i < n; i++) {
memset(var, 0, sizeof(var));
memset(buf, 0, sizeof(buf));
scanf("%s%s%s", var, def, buf);
varId[var] = ++tot;
if (buf[0] == '0' || buf[0] == '1') {
for (int i = 0; i < m; i++) {
val[tot][i] = buf[i] - '0';
}
op[tot][0] = 'N';
} else {
memset(var, 0, sizeof(var));
scanf("%s%s", op[tot], var);
operand[tot] = make_pair(varId[buf], varId[var]);
}
}
for (int i = 0; i < m; i++) {
int cnt1 = 0;
val[1][i] = 0;
for (int j = 2; j <= tot; j++) {
val[j][i] = calc(j, i);
cnt1 += val[j][i];
}
int cnt2 = 0;
val[1][i] = 1;
for (int j = 2; j <= tot; j++) {
val[j][i] = calc(j, i);
cnt2 += val[j][i];
}
if (cnt1 > cnt2) {
mx[i] = '0';
mn[i] = '1';
} else if (cnt1 < cnt2) {
mx[i] = '1';
mn[i] = '0';
} else {
mx[i] = mn[i] = '0';
}
}
printf("%s\n%s\n", mn, mx);
}
|
Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations.
Can you help Heidi estimate each village's population?
Input
Same as the easy version.
Output
Output one line per village, in the same order as provided in the input, containing your (integer) population estimate.
Your answer is considered correct if it is an integer that falls into the interval <image>, where P is the real population of the village, used to create the distribution (either Poisson or uniform) from which the marmots drew their answers.
|
#include <bits/stdc++.h>
using namespace std;
int T, sum, maxx, s[255];
int main() {
scanf("%d", &T);
while (T--) {
sum = maxx = 0;
for (int i = 1; i <= 250; i++)
scanf("%d", s + i), sum += s[i], maxx = max(s[i], maxx);
double aver = sum / 250.0, fang = 0;
for (int i = 1; i <= 250; i++) fang += (s[i] - aver) * (s[i] - aver);
printf("%.0f\n", fang / 250.0 / aver > 2 ? maxx * 1.04 / 2 : aver);
}
}
|
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm:
* Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones).
* Digits are written one by one in order corresponding to number and separated by single '0' character.
Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number.
Input
The first line contains one integer number n (1 ≤ n ≤ 89) — length of the string s.
The second line contains string s — sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 109. The string always starts with '1'.
Output
Print the decoded number.
Examples
Input
3
111
Output
3
Input
9
110011101
Output
2031
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Andrei Chugunov
*/
public class A {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
void solve() throws IOException {
int length = nextInt();
String string = nextString();
int cur = 0;
StringBuilder result = new StringBuilder();
for(int i=0; i < length; i++) {
char c = string.charAt(i);
if (c == '1') {
cur++;
continue;
}
if (c == '0') {
result.append(cur);
cur = 0;
}
}
result.append(cur);
System.out.println(result.toString());
}
A() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new A();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return null;
}
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
String nextString() throws IOException {
return br.readLine();
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
In the computer network of the Berland State University there are n routers numbered from 1 to n. Some pairs of routers are connected by patch cords. Information can be transmitted over patch cords in both direction. The network is arranged in such a way that communication between any two routers (directly or through other routers) is possible. There are no cycles in the network, so there is only one path between each pair of routers over patch cords.
Unfortunately, the exact topology of the network was lost by administrators. In order to restore it, the following auxiliary information was collected.
For each patch cord p, directly connected to the router i, list of routers located behind the patch cord p relatively i is known. In other words, all routers path from which to the router i goes through p are known. So for each router i there are ki lists, where ki is the number of patch cords connected to i.
For example, let the network consists of three routers connected in chain 1 - 2 - 3. Then:
* the router 1: for the single patch cord connected to the first router there is a single list containing two routers: 2 and 3;
* the router 2: for each of the patch cords connected to the second router there is a list: one list contains the router 1 and the other — the router 3;
* the router 3: for the single patch cord connected to the third router there is a single list containing two routers: 1 and 2.
Your task is to help administrators to restore the network topology, i. e. to identify all pairs of routers directly connected by a patch cord.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of routers in the network.
The i-th of the following n lines contains a description of the lists for the router i.
The description of each list begins with the number of routers in it. Then the symbol ':' follows, and after that the numbers of routers from the list are given. This numbers are separated by comma. Lists are separated by symbol '-'.
It is guaranteed, that for each router i the total number of routers in its lists equals to n - 1 and all the numbers in lists of each router are distinct. For each router i lists do not contain the number i.
Output
Print -1 if no solution exists.
In the other case print to the first line n - 1 — the total number of patch cords in the network. In each of the following n - 1 lines print two integers — the routers which are directly connected by a patch cord. Information about each patch cord must be printed exactly once.
Patch cords and routers can be printed in arbitrary order.
Examples
Input
3
2:3,2
1:1-1:3
2:1,2
Output
2
2 1
2 3
Input
5
4:2,5,3,4
1:4-1:1-2:5,3
4:4,5,2,1
4:2,1,3,5
1:3-3:4,2,1
Output
4
2 1
2 4
5 2
3 5
Input
3
1:2-1:3
1:1-1:3
1:1-1:2
Output
-1
Note
The first example is analyzed in the statement.
The answer to the second example is shown on the picture.
<image>
The first router has one list, which contains all other routers. The second router has three lists: the first — the single router 4, the second — the single router 1, the third — two routers 3 and 5. The third router has one list, which contains all other routers. The fourth router also has one list, which contains all other routers. The fifth router has two lists: the first — the single router 3, the second — three routers 1, 2 and 4.
|
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T next_int() {
T x = 0, p = 1;
char ch;
do {
ch = getchar();
} while (ch <= ' ');
if (ch == '-') {
p = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + (ch - '0');
ch = getchar();
}
return p * x;
}
string next_token() {
char ch;
string ans = "";
do {
ch = getchar();
} while (ch <= ' ');
while (ch > ' ') {
ans += ch;
ch = getchar();
}
return ans;
}
const long long INF = (long long)1e18;
const int INFINT = (int)1e9 + 227 + 1;
const int MAXN = (int)1e6 + 227 + 1;
const int MOD = (int)1e9 + 7;
const long double EPS = 1e-9;
long long bin_pow(long long a, long long b) {
if (!b) return 1;
long long ans = bin_pow(a, b / 2);
ans = ans * ans;
if (b % 2) ans = ans * a;
return ans;
}
vector<set<int> > q[MAXN];
vector<int> last[MAXN];
multiset<int> e[MAXN];
vector<pair<int, int> > w[MAXN];
bool check(int v) {
if (e[v].size() == 1) return 1;
return (*--(--e[v].end()) == 0);
}
vector<pair<int, int> > edge;
vector<int> gg[MAXN];
bool used[MAXN];
void go(int v) {
if (used[v]) return;
used[v] = 1;
for (int i = 0; i < gg[v].size(); i++) {
go(gg[v][i]);
}
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string a = next_token();
int kek = 0;
vector<int> lol;
for (int j = 0; j <= a.size(); j++) {
if (j == a.size() || (a[j] < '0' || a[j] > '9')) {
lol.push_back(kek);
kek = 0;
} else {
kek = kek * 10 + (a[j] - '0');
}
}
int mda = 0;
for (int j = 0; j < lol.size(); j++) {
if (mda == 0) {
mda = lol[j];
q[i].push_back(set<int>());
last[i].push_back(-1);
e[i].insert(mda);
} else {
mda--;
w[lol[j] - 1].push_back(make_pair(i, q[i].size() - 1));
q[i].back().insert(lol[j] - 1);
}
}
}
vector<int> us(n, 0);
for (int it = 0; it < n; it++) {
int p = -1;
for (int i = 0; i < n; i++) {
if (us[i]) continue;
if (check(i)) {
p = i;
}
}
if (p == -1) {
puts("-1");
return 0;
}
us[p] = 1;
int i = p;
for (int j = 0; j < q[i].size(); j++) {
if (q[i][j].size() == 0) {
edge.push_back(make_pair(i, last[i][j]));
}
}
for (int j = 0; j < w[i].size(); j++) {
int lol = q[w[i][j].first][w[i][j].second].size();
if (lol == 1) {
last[w[i][j].first][w[i][j].second] =
*q[w[i][j].first][w[i][j].second].begin();
}
q[w[i][j].first][w[i][j].second].erase(i);
e[w[i][j].first].erase(e[w[i][j].first].lower_bound(lol));
e[w[i][j].first].insert(lol - 1);
}
}
if (edge.size() != n - 1) {
puts("-1");
return 0;
}
for (int i = 0; i < edge.size(); i++) {
gg[edge[i].first].push_back(edge[i].second);
gg[edge[i].second].push_back(edge[i].first);
}
go(0);
bool ans = 1;
for (int i = 0; i < n; i++) {
ans &= used[i];
}
if (!ans) {
puts("-1");
return 0;
}
cout << edge.size() << "\n";
for (int i = 0; i < edge.size(); i++)
cout << edge[i].first + 1 << " " << edge[i].second + 1 << "\n";
return 0;
}
|
Physicist Woll likes to play one relaxing game in between his search of the theory of everything.
Game interface consists of a rectangular n × m playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean connectivity by side) figures of 2, 3, 4 and 5 cells, with all their rotations and reflections. Player can copy any figure from the dashboard and place it anywhere at the still empty cells of the playing field. Of course any figure can be used as many times as needed.
Woll's aim is to fill the whole field in such a way that there are no empty cells left, and also... just have some fun.
Every initially empty cell should be filled with exactly one cell of some figure. Every figure should be entirely inside the board.
<image>
In the picture black cells stand for initially filled cells of the field, and one-colour regions represent the figures.
Input
First line contains integers n and m (1 ≤ n, m ≤ 1000) — the height and the width of the field correspondingly. Next n lines contain m symbols each. They represent the field in a natural way: j-th character of the i-th line is "#" if the corresponding cell is filled, and "." if it is empty.
Output
If there is no chance to win the game output the only number "-1" (without the quotes). Otherwise output any filling of the field by the figures in the following format: each figure should be represented by some digit and figures that touch each other by side should be represented by distinct digits. Every initially filled cell should be represented by "#".
Examples
Input
2 3
...
#.#
Output
000
#0#
Input
3 3
.#.
...
..#
Output
5#1
511
55#
Input
3 3
...
.##
.#.
Output
-1
Input
1 2
##
Output
##
Note
In the third sample, there is no way to fill a cell with no empty neighbours.
In the forth sample, Woll does not have to fill anything, so we should output the field from the input.
|
#include <bits/stdc++.h>
int n, m;
char a[1111][1111];
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i) scanf("%s", a[i]);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m - 1; ++j)
if (a[i][j] == '.' && a[i][j + 1] == '.')
a[i][j] = a[i][j + 1] =
(((i + j) & 1) ? ('0' + (i % 3 * 3 + (j + 1) % 3))
: ('0' + (i % 3 * 3 + j % 3)));
for (int i = 0; i < n - 1; ++i)
for (int j = 0; j < m; ++j)
if (a[i][j] == '.' && a[i + 1][j] == '.')
a[i][j] = a[i + 1][j] =
(((i + j) & 1) ? ('0' + ((i + 1) % 3 * 3 + j % 3))
: ('0' + (i % 3 * 3 + j % 3)));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (a[i][j] == '.') {
if (i > 0 && a[i - 1][j] != '#') {
a[i][j] = a[i - 1][j];
continue;
}
if (j > 0 && a[i][j - 1] != '#') {
a[i][j] = a[i][j - 1];
continue;
}
if (i < n - 1 && a[i + 1][j] != '#') {
a[i][j] = a[i + 1][j];
continue;
}
if (j < m - 1 && a[i][j + 1] != '#') {
a[i][j] = a[i][j + 1];
continue;
}
puts("-1");
return 0;
}
for (int i = 0; i < n; ++i) printf("%s\n", a[i]);
return 0;
}
|
What are you doing at the end of the world? Are you busy? Will you save us?
<image>
Nephren is playing a game with little leprechauns.
She gives them an infinite array of strings, f0... ∞.
f0 is "What are you doing at the end of the world? Are you busy? Will you save us?".
She wants to let more people know about it, so she defines fi = "What are you doing while sending "fi - 1"? Are you busy? Will you send "fi - 1"?" for all i ≥ 1.
For example, f1 is
"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f1.
It can be seen that the characters in fi are letters, question marks, (possibly) quotation marks and spaces.
Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of fn. The characters are indexed starting from 1. If fn consists of less than k characters, output '.' (without quotes).
Can you answer her queries?
Input
The first line contains one integer q (1 ≤ q ≤ 10) — the number of Nephren's questions.
Each of the next q lines describes Nephren's question and contains two integers n and k (0 ≤ n ≤ 105, 1 ≤ k ≤ 1018).
Output
One line containing q characters. The i-th character in it should be the answer for the i-th query.
Examples
Input
3
1 1
1 2
1 111111111111
Output
Wh.
Input
5
0 69
1 194
1 139
0 47
1 66
Output
abdef
Input
10
4 1825
3 75
3 530
4 1829
4 1651
3 187
4 584
4 255
4 774
2 474
Output
Areyoubusy
Note
For the first two examples, refer to f0 and f1 given in the legend.
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.*;
public class Q449A {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
String f0 = "What are you doing at the end of the world? Are you busy? Will you save us?";
String f11 = "What are you doing while sending \"";
String f12 = "\"? Are you busy? Will you send \"";
String f13 = "\"?";
long[] lengths;
public void solve() throws IOException {
lengths = new long[100001];
lengths[0] = f0.length();
for (int i = 1; i <= 100000; i++) {
if (i <= 55) {
lengths[i] = lengths[i-1] * 2 + f11.length() + f12.length() + f13.length();
} else {
lengths[i] = lengths[i-1]; // not relevant
}
}
int Q = nextInt();
StringBuilder sb = new StringBuilder();
for (int q = 0; q < Q; q++) {
int N = nextInt();
long K = nextLong() - 1;
sb.append(compute(N, K));
}
out.println(sb.toString());
}
public char compute(int N, long K) {
if (K >= lengths[N]) return '.';
if (N == 0) {
return f0.charAt((int)K);
}
else if (K < f11.length()) {
return f11.charAt((int)K);
}
else if (K < f11.length() + lengths[N-1]) {
return compute(N-1, K-f11.length());
}
else if (K < f11.length() + lengths[N-1] + f12.length()) {
return f12.charAt((int)K - f11.length() - (int)lengths[N-1]);
}
else if (K < f11.length() + lengths[N-1] + f12.length() + lengths[N-1]) {
return compute(N-1, K-f11.length() - lengths[N-1] - f12.length());
}
else {
return f13.charAt((int)K - f11.length() - (int)lengths[N-1] - f12.length() - (int)lengths[N-1]);
}
}
/**
* @param args
*/
public static void main(String[] args) {
new Q449A().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter.
<image>
Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.
Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?
You have to determine the winner of the game for all initial positions of the marbles.
Input
The first line of input contains two integers n and m (2 ≤ n ≤ 100, <image>).
The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.
Output
Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.
Examples
Input
4 4
1 2 b
1 3 a
2 4 c
3 4 b
Output
BAAA
ABAA
BBBA
BBBB
Input
5 8
5 3 h
1 2 c
3 1 c
3 2 r
5 1 r
4 3 z
5 4 r
5 2 h
Output
BABBB
BBBBB
AABBB
AAABA
AAAAB
Note
Here's the graph in the first sample test case:
<image>
Here's the graph in the second sample test case:
<image>
|
#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")
using namespace std;
int n, m;
const int MAXN = 100;
int winner[MAXN][MAXN][26];
vector<pair<int, int> > gr[MAXN];
inline int get_winner(int a, int b, int c) {
if (winner[a][b][c]) return winner[a][b][c];
winner[a][b][c] = 2;
for (auto u : gr[a]) {
if (u.second >= c) {
if (get_winner(b, u.first, u.second) == 2) {
return winner[a][b][c] = 1;
}
}
}
return 2;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int p, q;
char c;
cin >> p >> q >> c;
gr[--p].push_back(make_pair(--q, c - 'a'));
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << (get_winner(i, j, 0) == 1 ? 'A' : 'B');
}
cout << '\n';
}
}
|
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!
Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the m friends found n different kinds of milk on the menu, that's why they ordered n bottles — one bottle of each kind. We know that the volume of milk in each bottle equals w.
When the bottles were brought in, they decided to pour all the milk evenly among the m cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem — and what is actually the way to do it?
Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!
Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.
Input
The only input data file contains three integers n, w and m (1 ≤ n ≤ 50, 100 ≤ w ≤ 1000, 2 ≤ m ≤ 50), where n stands for the number of ordered bottles, w stands for the volume of each of them and m stands for the number of friends in the company.
Output
Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO".
If there is a solution, then print m more lines, where the i-th of them describes the content of the i-th student's cup. The line should consist of one or more pairs that would look like "b v". Each such pair means that v (v > 0) units of milk were poured into the i-th cup from bottle b (1 ≤ b ≤ n). All numbers b on each line should be different.
If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point.
Examples
Input
2 500 3
Output
YES
1 333.333333
2 333.333333
2 166.666667 1 166.666667
Input
4 100 5
Output
YES
3 20.000000 4 60.000000
1 80.000000
4 40.000000 2 40.000000
3 80.000000
2 60.000000 1 20.000000
Input
4 100 7
Output
NO
Input
5 500 2
Output
YES
4 250.000000 5 500.000000 2 500.000000
3 500.000000 1 500.000000 4 250.000000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, w, m;
double x;
vector<pair<int, int> > a[50];
int c, k, r, s;
cin >> n >> w >> m;
x = (double)(n * w) / m;
c = 1;
k = 1;
r = m;
for (int i = 0; i < m; ++i) {
s = 0;
while (n - s >= r) {
a[i].push_back(make_pair(c, r));
s += r;
++c;
k = 1;
r = m;
}
if (s != n) {
a[i].push_back(make_pair(c, n - s));
r = m - (n - s);
++k;
}
if (k > 2) {
cout << "NO";
return 0;
}
}
cout.setf(cout.fixed);
cout.precision(10);
cout << "YES"
<< "\n";
for (int i = 0; i < m; ++i) {
for (int j = 0; j < (int)a[i].size(); ++j)
cout << a[i][j].first << " " << x * a[i][j].second / n << " ";
cout << "\n";
}
return 0;
}
|
Arkady's code contains n variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code.
He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names.
A string a is a prefix of a string b if you can delete some (possibly none) characters from the end of b and obtain a.
Please find this minimum possible total length of new names.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of variables.
The next n lines contain variable names, one per line. Each name is non-empty and contains only lowercase English letters. The total length of these strings is not greater than 10^5. The variable names are distinct.
Output
Print a single integer — the minimum possible total length of new variable names.
Examples
Input
3
codeforces
codehorses
code
Output
6
Input
5
abba
abb
ab
aa
aacada
Output
11
Input
3
telegram
digital
resistance
Output
3
Note
In the first example one of the best options is to shorten the names in the given order as "cod", "co", "c".
In the second example we can shorten the last name to "aac" and the first name to "a" without changing the other names.
|
#include <bits/stdc++.h>
using namespace std;
struct Node {
int next[26];
int cnt;
Node() {
for (int i = 0; i < 26; i++) {
next[i] = -1;
}
cnt = 0;
}
};
int main() {
int n;
cin >> n;
vector<Node> trie;
trie.emplace_back();
for (int i = 0; i < n; i++) {
string s;
cin >> s;
int cur = 0;
for (char c : s) {
int go = c - 'a';
if (trie[cur].next[go] < 0) {
trie[cur].next[go] = trie.size();
trie.emplace_back();
}
cur = trie[cur].next[go];
}
trie[cur].cnt++;
}
auto merge = [&](priority_queue<int> *a, priority_queue<int> *b) {
if (a->size() < b->size()) {
swap(a, b);
}
while (!b->empty()) {
a->push(b->top());
b->pop();
}
delete b;
return a;
};
function<priority_queue<int> *(int, int)> dfs = [&](int v, int d) {
auto res = new priority_queue<int>;
for (int i = 0; i < 26; i++) {
if (trie[v].next[i] < 0) {
continue;
}
res = merge(res, dfs(trie[v].next[i], d + 1));
}
if (trie[v].cnt) {
res->push(d);
} else if (!res->empty() && d != 0) {
res->pop();
res->push(d);
}
return res;
};
auto res = dfs(0, 0);
int64_t ans = 0;
while (!res->empty()) {
ans += res->top();
res->pop();
}
cout << ans << endl;
delete res;
return 0;
}
|
Nastya likes reading and even spends whole days in a library sometimes. Today she found a chronicle of Byteland in the library, and it stated that there lived shamans long time ago. It is known that at every moment there was exactly one shaman in Byteland, and there were n shamans in total enumerated with integers from 1 to n in the order they lived. Also, each shaman had a magic power which can now be expressed as an integer.
The chronicle includes a list of powers of the n shamans. Also, some shamans can be king-shamans, if they gathered all the power of their predecessors, i.e. their power is exactly the sum of powers of all previous shamans. Nastya is interested in whether there was at least one king-shaman in Byteland.
Unfortunately many of the powers are unreadable in the list, so Nastya is doing the following:
* Initially she supposes some power for each shaman.
* After that she changes the power of some shaman q times (the shamans can differ) and after that wants to check if there is at least one king-shaman in the list. If yes, she wants to know the index of any king-shaman.
Unfortunately the list is too large and Nastya wants you to help her.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2·105).
The second line contains n integers a1, ..., an (0 ≤ ai ≤ 109), where ai is the magic power of the i-th shaman.
After that q lines follow, the i-th of them contains two integers pi and xi (1 ≤ pi ≤ n, 0 ≤ xi ≤ 109) that mean that the new power of the pi-th shaman is xi.
Output
Print q lines, the i-th of them should contain - 1, if after the i-th change there are no shaman-kings, and otherwise a single integer j, where j is an index of some king-shaman after the i-th change.
If there are multiple king-shamans after each change, print the index of any of them.
Examples
Input
2 1
1 3
1 2
Output
-1
Input
3 4
2 2 3
1 1
1 2
2 4
3 6
Output
3
2
-1
3
Input
10 7
0 3 1 4 6 2 7 8 10 1
2 5
1 3
9 36
4 10
4 9
1 2
1 0
Output
1
-1
9
-1
4
-1
1
Note
In the first example powers of shamans after the first change are equal to (2, 3). The answer equals - 1, because the sum of powers of shamans before the first shaman is equal to 0, and before the second is equal to 2.
In the second example after the first change the powers are equal to (1, 2, 3). The answer is equal to 3, because the power of the third shaman is equal to 3, and the sum of powers of the first and the second shaman is also 1 + 2 = 3. After the second change the powers become equal to (2, 2, 3), where the answer equals 2. After the third change the powers become equal to (2, 4, 3), where the answer equals - 1. After the fourth change the powers become equal to (2, 4, 6), where the answer equals 3.
|
#include <bits/stdc++.h>
using namespace std;
void build_sum(int i, int l, int r, long long *nodes, long long *val,
long long (*add_fun)(long long, long long)) {
if (l == r) {
nodes[i] = val[l];
return;
} else {
build_sum(i * 2, l, (l + r) / 2, nodes, val, add_fun);
build_sum(i * 2 + 1, (l + r) / 2 + 1, r, nodes, val, add_fun);
nodes[i] = add_fun(nodes[i * 2], nodes[i * 2 + 1]);
}
}
long long query_sum(int i, int l, int r, int tl, int tr, long long *nodes,
long long (*add_fun)(long long, long long)) {
if (r < tl || l > tr || l > r) return 0;
if (l >= tl && r <= tr) {
return nodes[i];
}
return add_fun(
query_sum(i * 2, l, (l + r) / 2, tl, tr, nodes, add_fun),
query_sum(i * 2 + 1, (l + r) / 2 + 1, r, tl, tr, nodes, add_fun));
}
long long query_sum_b(int i, int l, int r, int tl, int tr, long long *nodes,
long long (*add_fun)(long long, long long)) {
if (r < tl || l > tr || l > r) return INT_MAX;
if (l >= tl && r <= tr) {
return nodes[i];
}
return add_fun(
query_sum_b(i * 2, l, (l + r) / 2, tl, tr, nodes, add_fun),
query_sum_b(i * 2 + 1, (l + r) / 2 + 1, r, tl, tr, nodes, add_fun));
}
void query_change_sum(int i, int l, int r, int target, long long *nodes,
long long value,
long long (*add_fun)(long long, long long)) {
if (target < l || target > r) return;
if (l == r) {
nodes[i] = value;
return;
}
query_change_sum(i * 2, l, (l + r) / 2, target, nodes, value, add_fun);
query_change_sum(i * 2 + 1, (l + r) / 2 + 1, r, target, nodes, value,
add_fun);
nodes[i] = add_fun(nodes[i * 2], nodes[i * 2 + 1]);
}
long long sum_fun(long long a, long long b) { return a + b; }
long long min_fun(long long a, long long b) { return min(a, b); }
const int maxn = 4 * 1e5 + 10;
const int maxt = (1 << 21) + 10;
const int maxv = maxn * 2 + 5;
long long a[maxn];
set<long long> ind[maxn];
map<long long, long long> CC;
pair<long long, long long> queries[maxn];
long long sum_tree[maxt];
long long min_tree[maxt];
long long I[maxv];
int main() {
int n, q;
cin >> n >> q;
for (int i = 0; i < n; i++) {
cin >> a[i];
CC[a[i]] = 0;
}
for (int i = 0; i < q; i++) {
long long p, x;
cin >> p >> x;
CC[x] = 0;
queries[i].first = p;
queries[i].second = x;
}
long long cnt = -1;
for (auto it = CC.begin(); it != CC.end(); it++) {
CC[it->first] = ++cnt;
I[cnt] = LLONG_MAX;
}
for (int i = 0; i < n; i++) {
int vplace = CC[a[i]];
if (i != 0) {
ind[vplace].insert(i);
I[vplace] = min(I[vplace], (long long)i);
}
}
build_sum(1, 0, n - 1, sum_tree, a, sum_fun);
build_sum(1, 0, cnt, min_tree, I, min_fun);
for (int i = 0; i < q; i++) {
if (queries[i].first - 1 != 0) {
int new_value = CC[queries[i].second];
int last_value = CC[a[queries[i].first - 1]];
ind[last_value].erase(queries[i].first - 1);
ind[new_value].insert(queries[i].first - 1);
int index_last;
if (!ind[last_value].empty())
index_last = (*ind[last_value].begin());
else
index_last = INT_MAX;
int index_new;
if (!ind[new_value].empty())
index_new = (*ind[new_value].begin());
else
index_new = INT_MAX;
query_change_sum(1, 0, cnt, last_value, min_tree, index_last, min_fun);
query_change_sum(1, 0, cnt, new_value, min_tree, index_new, min_fun);
}
query_change_sum(1, 0, n - 1, queries[i].first - 1, sum_tree,
queries[i].second, sum_fun);
a[queries[i].first - 1] = queries[i].second;
if (a[0] == 0) {
cout << 1 << '\n';
} else {
long long pi = a[0];
bool done = 0;
int j = 0;
while (j < n) {
auto v = CC.lower_bound(pi);
if (v == CC.end()) break;
int vv = v->second;
j = query_sum_b(1, 0, cnt, vv, cnt, min_tree, min_fun);
if (j == INT_MAX) break;
long long sum = query_sum(1, 0, n - 1, 0, j - 1, sum_tree, sum_fun);
if (a[j] == sum) {
cout << j + 1 << '\n';
done = 1;
break;
}
pi = sum + a[j];
}
if (!done) {
cout << -1 << '\n';
}
}
}
}
|
Sherlock and Watson were good friends. They both were solving a mystery. But they got hungry and wanted to eat something.
Hence they asked for some candies from Mom. Mom was also clever. She told them to solve a function for her.
Function is defined as follows -
F(x) = 2^x - 1
She gave number "a" to Shelock and "b" to Watson and told them to solve F(a) and F(b) respectively.
After that ,she asked them how many prime numbers divide both F(a) and F(b) and they will get those numbers of candies if they answered correctly.
Your task is to calculate the number of candies that they will get from her.
Input:
First line contains an integer "t" , denoting number of testcases.
Each test case contains a single line consisting of two integers "a" and "b" separated by a single space.
Output:
Print the number of candies that Sherlock and Watson will get from Mom in a new line for each test case.
Constraints:
1 ≤ t ≤ 10^5
1 ≤ a,b ≤ 23
SAMPLE INPUT
2
1 1
2 2
SAMPLE OUTPUT
0
1
Explanation
For 1st test case , a=1, b=1.
So F(a) = 2^1 - 1 = 1
F(b) = 2^1 - 1 = 1
No prime number divides 1. Hence answer is 0.
For 2nd test case , a=2, b=2.
So F(n,a) = 2^2 - 1 = 3
F(n,b) = 2^2 - 1 = 3
so 3 divides 3. Hence answer is 1.
|
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
def f(x):
return pow(2,x)-1
for i in range(int(raw_input())):
a,b=map(int,raw_input().split())
x=f(a)
y=f(b)
A=primes(x)
B=primes(y)
c=set(A)&set(B)
c=list(c)
print len(c)
|
2^N participants (P1 , P2 , P3 .... , P2^N ) have enrolled for a knockout chess tournament. In the first round, each participant P2k-1 is to play against participant P2k, (1 ≤ k ≤ 2^N-1) . Here is an example for k = 4 :
Some information about all the participants is known in the form of a triangular matrix A with dimensions (2^N-1) X (2^N-1). If Aij = 1 (i > j), participant Pi is a better player than participant Pj, otherwise Aij = 0 and participant Pj is a better player than participant Pi. Given that the better player always wins, who will be the winner of the tournament?
Note : Being a better player is not transitive i.e if Pi is a better player than Pj and Pj is a better player than Pk, it is not necessary that Pi is a better player than Pk .
Input
The first line consists of N. Then, 2^N-1 lines follow, the i^th line consisting of i space separated integers Ai+1 1 , Ai+1 2 , .... Ai+1 i
Output
A single integer denoting the id of the winner of the tournament.
Constraints
1 ≤ N ≤ 10
Aij = {0, 1} (i > j)
SAMPLE INPUT
2
0
1 0
0 1 1
SAMPLE OUTPUT
1
Explanation
When 1 plays against 2, 1 wins.
When 3 plays against 4, 4 wins.
When 1 plays against 4, 1 wins.
So, 1 wins the tournament.
|
import copy
n = int(raw_input())
table = [[None for i in range(pow(2,n))] for j in range(pow(2,n))]
for i in range(1,pow(2,n)):
temp = map(int,raw_input().split())
for j in range(len(temp)):
table[i][j] = temp[j]
# for _ in range(pow(2,n)-1):
# table.append(map(int,raw_input().split()))
game = [i for i in range(1,2**n+1)]
#print game, "game"
while len(game)>1:
aux = []
#print "here"
for i in range(0,len(game)-1,2):
#print game[i+1],game[i], "check"
if (table[game[i+1]-1][game[i]-1] == 1):
aux.append(game[i+1])
else:
aux.append(game[i])
game = copy.deepcopy(aux)
print game[0]
|
A drunk person was moving from one point on the street to another point on the same street. His starting point was between two manholes on that street. He was following a systematic scheme of his movement and had a fix movement repeated after an interval of time. How much time will he take to fall in the manhole and in which manhole will he fall in.
input
The first line should contain number of test cases 'N'
Next 'N' lines should have space separated inputs 'B' or 'F' which will depict the first movement of the drunk person in backward or forward direction respectively next five space separated numbers depict the distance of the hole in forward direction in meters distance of the hole in backward direction in meters forward steps in meters backward step in meters and time taken to complete 1 meter respectively
output
In a single line print the manhole in which he will fall ‘F’ for the manhole that is in forward direction and ‘B’ for the manhole in backward direction followed by the time that he took to fall in that manhole and if he will not fall in any of the manhole then print 'SURVIVED'.
SAMPLE INPUT
4
F 10 10 4 3 1
B 10 10 3 4 2
F 15 10 3 5 4
F 19 12 3 3 2
SAMPLE OUTPUT
F46
B92
B160
SURVIVED
|
'''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n_test=int(raw_input(""))
debug=False
for test in range(n_test):
inp=raw_input("").split(" ")
d=inp[0]
D="F"
fw,bw,vf,vb,sp=map(int,inp[1:])
spd_s=vf-vb
spd_t=vf+vb
t0=0
if spd_s==0 and (d=="F" or vb<bw) and (d=="B" or vf<fw) :
print "SURVIVED"
elif (d=="B" and vb>bw):
if debug: print "at first step"
print "B%d" % (bw*sp)
elif (d=="F" and vf>fw):
if debug: print "at first step"
print "F%d" % (fw*sp)
else:
if spd_s<0:
if debug: print "reverse"
spd_s*= -1
bw,fw=(fw,bw)
vb,vf=(vf,vb)
d="F" if d=="B" else "B"
D="B"
if d=="B":
if debug: print "go forward"
fw+=vb
t0=vb*sp
x1=vf
t1=vf*sp
r=fw-x1
if r<0:
t=t0+fw*sp
ns=0
else:
ns=r/spd_s
t=ns*spd_t*sp + t1 + t0
if ns*spd_s<r: #need to add the partial forward step
if debug: print "need partial forward step",r,fw-(ns*spd_s+x1-vb),(fw-(ns*spd_s+x1-vb))*sp,vb*sp
t+=(fw-(ns*spd_s+x1-vb)+vb)*sp
if debug: print "spd_s:%d spd_t:%d d:%s D:%s vf:%d vb:%d fw:%d" % (spd_s,spd_t,d,D,vf,vb,fw)
if debug: print "t0:%d t1:%d x1:%d r:%d ns:%d" % (t0,t1,x1,r,ns)
print "%s%d" %(D,t)
|
As of now, you helped agent OO7 to find men with different capability values. Now his task is to group up his men and work as a team. He wants to form the groups with minimum 2 men in it. Help him out to find how many such groups are possible.
Input - First line contains 'T' test cases followed by 'T' lines containing number of men, ‘N’.
Output - 'T' lines containing total number of possible groups.
Constraints - 1 ≤ T ≤ 10^3 , 1 ≤ N ≤ 200
SAMPLE INPUT
2
4
6
SAMPLE OUTPUT
2
4
Explanation
1) For the 1st case, N is 4. Possible group size can be {2,2}, {4}. So, output is 2.
2) For the 2nd case, N is 6. Possible group size can be {2,2,2}, {2,4}, {3,3}, {6}. So, output is 4.
|
num=input()
groupSize=dict()
def gs(n,m):
if m<2: return 0
if(m==n): return 1
if n<m: return 0
if (n,m) in groupSize: return groupSize[(n,m)]
res=1
for i in range(m,n-1):
res+=gs(n-i,i)
groupSize[(n,m)]=res
return res
for _ in range(num):
n=input()
print gs(n,2)
|
Little Monty is very fond of Fibonacci numbers and challenges his friend Lopa
that he can solve any question regarding the same. Lopa however is jealous
and after thinking for a long time came up with a problem.
She says given
N(the number of fibonacci numbers) one has to count all the multiples of all
the fibonacci numbers. This statement can be quite confusing hence look at the
mathematical definition and test cases for better understanding.
Let M(x) denote the number of multiple of x in the sequence and F(y) denote
the yth fibonacci number. The required answer is:
Take the first two number of the sequence to be 1 and 1.
Input Format
The first line contains T i.e. the number of test cases.
T lines follow, each line containing an integer, N.
(The sample fibonacci series for n=5 is 1, 1, 2, 3, 5)
Output Format
For each testcase, print the output that Lopa wants in one line.
Constraints
1 ≤ T ≤ 1000
1 ≤ N ≤ 1000
SAMPLE INPUT
3
1
2
3
SAMPLE OUTPUT
1
4
7
Explanation
For N=1. The fibonacci number is 1. The multiple of 1 is 1(itself). Hence the answer is 1.
For N=2. The fibonacci number is 1, 1. The multiple of 1(first fibonacci number) is 1(first fibonacci number) and 1(second fibonacci number). The multiple of 1(second fibonacci number) is 1(first fibonacci number) and 1(second fibonacci number). Hence the answer is 4.
For n=3. The fibonacci sequence is 1, 1, 2 . The multiples of 1(first fibonacci number) is 1(itself) and 1(second fibonacci number) and 2. The multiples of 1(second fibonacci number) is 1(first fibonacci number), 1(itself) and 2. The multiple of 2 is 2(itself). Hence the answer is 7.
|
t=int(input())
while(t>0):
count=0
n=int(input())
for i in range(3,n+1):
count=int(count+n/i)
if (n==1):
print(1)
elif (n==2):
print(4)
else:
print(int(count+2*n))
t-=1
|
Many of you know the famous Fibonacci sequence F:
F[1] = 1
F[2] = 1
F[i] = F[i - 1] + F[i - 2] for i > 2
Thus each number in sequence is a sum of two previous numbers except two first which are define as 1.
You've decided to create you own Fibonacci sequence. It's very similar to the one described above, but the first two numbers now are arbitrary non-negative integers A and B ( F[1] = A and F[2] = B ). Now you want to compute the N-th number in your sequence.
Input
The only line contains 3 space-separated integers A, B, N.
Output
Output one integer - the N-th number in your sequence.
Constraints
0 < A, B, N ≤ 10
SAMPLE INPUT
1 3 4
SAMPLE OUTPUT
7
|
a,b,n = map(int,raw_input().split())
lis = list();
lis.append(a)
lis.append(b)
for i in range(2,n):
lis.append(lis[i - 1] + lis[i - 2])
print lis[n-1]
|
Abhishek is a computer science student at the Department of computer science India His teacher recently gave him a single assignment with only a single problem.
The problem was simple.He has to find out the min number of single digit prime numbers which when added equals a given number Y.
Input:
The first line contains T denoting the number of test cases. Each of the next T lines contains a single integer Y.
Output:
Print the min number required. If he can not obtain Y using single digit prime numbers, output -1.
SAMPLE INPUT
4
5
9
12
19
SAMPLE OUTPUT
1
2
2
3
Explanation
Explanation:
5= Itself a prime number so 1.
9=2+7
12=5+7
19=5+7+7
|
t = int(raw_input())
prim = [1,2,3,5,7]
for i in range(t):
n = int(raw_input())
if n<1:
print -1
continue
dp = []*n
sumi = 0
sumi+=n/7
n%=7
if n==1 or n==2 or n==3 or n==5:
sumi+=1
elif n:
sumi+=2
print sumi
|
Sandy is given an array of N integers which is a permutation of the first N natural numbers. He can swap any two elements of the array and can make at most K swaps. He needs to tell the largest permutation, in numerical order, could be made? You being sandy's friend help him in doing so.
Input Format:-
The first line of the input contains two integers, N and K, the size of the input array and the maximum swaps you can make, respectively. The second line of the input contains a permutation of the first N natural numbers.
Output Format:-
Print the lexicographically largest permutation you can make with at most K swaps.
Constraints:-
1 ≤ N ≤ 10^5
1 ≤ K ≤ 10^9
SAMPLE INPUT
5 1
4 2 3 5 1
SAMPLE OUTPUT
5 2 3 4 1
Explanation
Testcase 1:
You can swap any two numbers in [4,2,3,5,1] and see the largest permutation is [5,2,3,4,1]
Other Example:-
Input:-
3 1
2 1 3
Output:-
3 1 2
With 1 swap we can get [1,2,3], [3,1,2] and [2,3,1] out of these [3,1,2] is the largest permutation
|
N, K = map(int, raw_input().split())
arr = map(int, raw_input().split())
swaps_made = 0
for i, j in enumerate(sorted(arr, reverse=True)):
if j > arr[i]:
p = arr.index(j, i)
arr[i], arr[p] = arr[p], arr[i]
swaps_made += 1
if swaps_made >= K:
break
print ' '.join(map(str, arr))
|
Little Timmy is exceptionally good at math tables, so his maths teacher decided to make things a bit more interesting. His teacher takes two numbers A and B and merges the tables of A and B in sorted order (ascending order), removing the duplicates and thus creates supertable of A and B and asks Little Timmy the Nth number in the supertable.
Given A, B and N, calculate the Nth number in the supertable of A and B.
Input
First line contains number of test cases T . Each test case contains three integers A , B and N .
Output
For each test case print the N^th number of the supertable.
Constraints:
1 ≤ T ≤ 300000
1 ≤ A, B ≤ 1000
1 ≤ N ≤ 1000000000
SAMPLE INPUT
4
3 5 2
3 5 3
2 3 4
2 3 6
SAMPLE OUTPUT
5
6
6
9
Explanation
Test Case #1:
A=3, B= 5
Table of A = 3 , 6 , 9 , 12 ,15 ,18 and so on
Table of B =5 , 10 , 15 , 20 and so on
After Merging : 3, 5, 6, 9 ,10 , 12 ,15 ,15, 18, 20 and so on
Remove Duplicates : 3 , 5 , 6, 9 , 10 , 12 , 15 , 18 , 20 and so on
For N= 2 , 2nd element of the supertable is 5 .
Test Case #2:
For N=3 , 3rd element of the supertable is 6.
|
'''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
from fractions import gcd
t=input()
while t>0:
t-=1
a,b,n=map(int,raw_input().split())
c=(a*b)/(gcd(a,b))
l,r=1,1000000000000
while(l<=r):
m=(l+r)/2
s=m/a+m/b-m/c
if (s==n):
print max((m/a)*a,(m/b)*b)
break
elif (s<n):
l=m+1
else:
r=m-1
|
Separatist
Always finding new ways to destroy the Republic forces by surprise attacks.
Now they trapped the Republic fleet near the Abregado system. They have developed a way to communicate through the encrypted message to its fleet around the Abregado system.
They wrote a message in a cryptic language, and next to it they wrote a series of symbols. Republic fleet intercept these messages and concluded that the symbols indicate a number: the number of seconds before they launch next surprise attack on them!
Unfortunately Republic Fleet have no idea what each symbol means. They have decided that each symbol indicates one digit, but they aren't sure what each digit means or what base the Separatists are using. For example, if Separatist wrote "ab2ac999", they could have meant "31536000" in base 10 -- exactly one year -- or they could have meant "12314555" in base 6 -- 398951 seconds, or about four and a half days. Republic fleet are sure of three things: the number is positive; like us, the Separatists will never start a number with a zero; and they aren't using unary (base 1).
Your job is to determine the minimum possible number of seconds they launch next surprise attack on them.
Input
The first line of input contains a single integer, T. T test cases follow. Each test case is a string on a line by itself. The line will contain only characters in the 'a' to 'z' and '0' to '9' ranges (with no spaces and no punctuation), representing the message by Separatists. The test cases are independent, and can be in different bases with the symbols meaning different things.
Output
For each test case, output V the minimum number of seconds before the next surprise attack.
Limits
1 ≤ T ≤ 100
The answer will never exceed 10^18
1 ≤ the length of each line < 61
SAMPLE INPUT
3
11001001
cats
zig
SAMPLE OUTPUT
201
75
11
|
'''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
n = input()
ans = []
def find(a):
f = 0
n = []
l = []
k = []
t = 1
for i in a:
f = 0
try:
l.index(i)
except ValueError:
f = 1
if t == 1:
l.append(i)
n.append(t)
k.append(t)
t = 0
elif t == 0:
l.append(i)
n.append(t)
k.append(t)
t = 2
elif t > 1:
l.append(i)
n.append(t)
k.append(t)
t += 1
if f == 0:
d = l.index(i)
f = 0
n.append(k[d])
n1 = max(k)
n1 += 1
#print n1, "@@@@"
n.reverse()
sum = 0
for i in range(len(n)):
sum += n[i] * (n1 ** i)
#print sum, "%%%%%"
#print n, l, sum, k, "####"
return sum
for i in range(n):
a = raw_input()
ans.append(find(a))
for i in ans:
print i
|
There are N piles of stones. The i-th pile has A_i stones.
Aoki and Takahashi are about to use them to play the following game:
* Starting with Aoki, the two players alternately do the following operation:
* Operation: Choose one pile of stones, and remove one or more stones from it.
* When a player is unable to do the operation, he loses, and the other player wins.
When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile.
In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most (A_1 - 1) stones from the 1-st pile to the 2-nd pile before the game begins.
If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print `-1` instead.
Constraints
* 2 \leq N \leq 300
* 1 \leq A_i \leq 10^{12}
Input
Input is given from Standard Input in the following format:
N
A_1 \ldots A_N
Output
Print the minimum number of stones to move to guarantee Takahashi's win; otherwise, print `-1` instead.
Examples
Input
2
5 3
Output
1
Input
2
3 5
Output
-1
Input
3
1 1 2
Output
-1
Input
8
10 9 8 7 6 5 4 3
Output
3
Input
3
4294967297 8589934593 12884901890
Output
1
|
#include <bits/stdc++.h>
#define int long long
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define F first
#define S second
using namespace std;
typedef pair<int,int> P;
typedef vector<int> ivec;
const int MOD=1000000007;
int INF=100100100100100;
int beki(int n){
if(n==0)return 1;
int x=beki(n/2);
if(n%2==0)return x*x;
return 2*x*x;
}
int a[310];
signed main(){
int n;cin>>n;
int c=0;
rep(i,n)cin>>a[i];
int x=a[0],y=a[1];
for(int i=2;i<n;i++)c^=a[i];
if(c>x+y || (x+y-c)%2!=0){
cout<<-1<<endl;
return 0;
}
int po=(x+y-c)/2;
if((po & c)!=0){
cout<<-1<<endl;
return 0;
}
if(y<po)x-=(po-y),y=po;
if(x<po){
cout<<-1<<endl;
return 0;
}
x-=po,y-=po;
//cout<<x<<" "<<y<<" "<<po<<endl;
int res=0;
for(int i=60;i>=0;i--){
int nue=beki(i);
int hoge=(x+y)/nue;
if(hoge%2==1 && res+nue<=x)res+=nue;
}
//cout<<res<<endl;
if(po+res==0){
cout<<-1<<endl;
return 0;
}
cout<<a[0]-po-res<<endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.