input
stringlengths 29
13k
| output
stringlengths 9
73.4k
|
|---|---|
Jon Snow now has to fight with White Walkers. He has n rangers, each of which has his own strength. Also Jon Snow has his favourite number x. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number x, he might get soldiers of high strength. So, he decided to do the following operation k times:
1. Arrange all the rangers in a straight line in the order of increasing strengths.
2. Take the bitwise XOR (is written as <image>) of the strength of each alternate ranger with x and update it's strength.
Suppose, Jon has 5 rangers with strengths [9, 7, 11, 15, 5] and he performs the operation 1 time with x = 2. He first arranges them in the order of their strengths, [5, 7, 9, 11, 15]. Then he does the following:
1. The strength of first ranger is updated to <image>, i.e. 7.
2. The strength of second ranger remains the same, i.e. 7.
3. The strength of third ranger is updated to <image>, i.e. 11.
4. The strength of fourth ranger remains the same, i.e. 11.
5. The strength of fifth ranger is updated to <image>, i.e. 13.
The new strengths of the 5 rangers are [7, 7, 11, 11, 13]
Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations k times. He wants your help for this task. Can you help him?
Input
First line consists of three integers n, k, x (1 ≤ n ≤ 105, 0 ≤ k ≤ 105, 0 ≤ x ≤ 103) — number of rangers Jon has, the number of times Jon will carry out the operation and Jon's favourite number respectively.
Second line consists of n integers representing the strengths of the rangers a1, a2, ..., an (0 ≤ ai ≤ 103).
Output
Output two integers, the maximum and the minimum strength of the rangers after performing the operation k times.
Examples
Input
5 1 2
9 7 11 15 5
Output
13 7
Input
2 100000 569
605 986
Output
986 605
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C399 {
public static void main(String[] args) {
FS scan = new FS(System.in);
int N = scan.nextInt(), K = scan.nextInt(), X = scan.nextInt();
int[] compress = new int[1<<10];
for(int i=0;i<N;i++){
compress[scan.nextInt()]++;
}
int[] next = new int[1<<10];
for(int i=0;i<K;i++){
Arrays.fill(next, 0);
int parity = 0;
for(int j=0;j<1<<10;j++){
if(compress[j]==0)continue;
if(parity==0){
next[j] += compress[j]>>1;
next[j^X]+=(compress[j]+1)>>1;
}else{
next[j^X] += compress[j]>>1;
next[j]+=(compress[j]+1)>>1;
}
parity+=compress[j];
parity&=1;
}
compress = Arrays.copyOf(next, next.length);
}
int min = 10000, max = -1;
for(int i=0;i<1<<10;i++){
if(compress[i]==0)continue;
if(i<min)min = i;
if(i>max)max = i;
}
System.out.println(max+" "+min);
}
private static class FS {
BufferedReader br;
StringTokenizer st;
public FS(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
String next(){
while(st==null||!st.hasMoreElements()){
try{st = new StringTokenizer(br.readLine());}
catch(IOException e){e.printStackTrace();}
}
return st.nextToken();
}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() { return Double.parseDouble(next());}
}
}
|
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.
For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.
You have to write a program which prints the number of the child to be eliminated on every step.
Input
The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1).
The next line contains k integer numbers a1, a2, ..., ak (1 ≤ ai ≤ 109).
Output
Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.
Examples
Input
7 5
10 4 11 4 1
Output
4 2 5 6 1
Input
3 2
2 5
Output
3 2
Note
Let's consider first example:
* In the first step child 4 is eliminated, child 5 becomes the leader.
* In the second step child 2 is eliminated, child 3 becomes the leader.
* In the third step child 5 is eliminated, child 6 becomes the leader.
* In the fourth step child 6 is eliminated, child 7 becomes the leader.
* In the final step child 1 is eliminated, child 3 becomes the leader.
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
set<int> st;
vector<int> v;
for (int i = 0; i < n; i++) v.push_back(i);
int lead = 0;
for (int i = 0; i < k; i++) {
int x;
cin >> x;
n = v.size();
x %= n;
int tmp = (lead + x) % n;
cout << v[tmp] + 1 << ' ';
lead = tmp;
v.erase(v.begin() + tmp);
}
return 0;
}
|
Sagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys:
* Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set.
* If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever.
* Children request toys at distinct moments of time. No two children request a toy at the same time.
* If a child is granted a toy, he never gives it back until he finishes playing with his lovely set.
* If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting.
* If two children are waiting for the same toy, then the child who requested it first will take the toy first.
Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy.
Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set.
Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child x that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child x is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child x will make his last request, how many children will start crying?
You will be given the scenario and q independent queries. Each query will be of the form x y meaning that the last request of the child x is for the toy y. Your task is to help Sagheer find the size of the maximal crying set when child x makes his last request.
Input
The first line contains four integers n, m, k, q (1 ≤ n, m, k, q ≤ 105) — the number of children, toys, scenario requests and queries.
Each of the next k lines contains two integers a, b (1 ≤ a ≤ n and 1 ≤ b ≤ m) — a scenario request meaning child a requests toy b. The requests are given in the order they are made by children.
Each of the next q lines contains two integers x, y (1 ≤ x ≤ n and 1 ≤ y ≤ m) — the request to be added to the scenario meaning child x will request toy y just after getting the toy he is waiting for (if any).
It is guaranteed that the scenario requests are consistent and no child is initially crying. All the scenario requests are distinct and no query coincides with a scenario request.
Output
For each query, print on a single line the number of children who will start crying when child x makes his last request for toy y. Please answer all queries independent of each other.
Examples
Input
3 3 5 1
1 1
2 2
3 3
1 2
2 3
3 1
Output
3
Input
5 4 7 2
1 1
2 2
2 1
5 1
3 3
4 4
4 1
5 3
5 4
Output
0
2
Note
In the first example, child 1 is waiting for toy 2, which child 2 has, while child 2 is waiting for top 3, which child 3 has. When child 3 makes his last request, the toy he requests is held by child 1. Each of the three children is waiting for a toy held by another child and no one is playing, so all the three will start crying.
In the second example, at the beginning, child i is holding toy i for 1 ≤ i ≤ 4. Children 1 and 3 have completed their lovely sets. After they finish playing, toy 3 will be free while toy 1 will be taken by child 2 who has just completed his lovely set. After he finishes, toys 1 and 2 will be free and child 5 will take toy 1. Now:
* In the first query, child 5 will take toy 3 and after he finishes playing, child 4 can play.
* In the second query, child 5 will request toy 4 which is held by child 4. At the same time, child 4 is waiting for toy 1 which is now held by child 5. None of them can play and they will start crying.
|
#include <bits/stdc++.h>
#pragma warning(disable : 4996)
#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("-ffloat-store")
using namespace std;
clock_t time_p = clock();
void aryanc403() {
time_p = clock() - time_p;
cerr << "Time Taken : " << (float)(time_p) / CLOCKS_PER_SEC << "\n";
}
const long long int INF = 0xFFFFFFFFFFFFFFFL;
long long int seed;
mt19937 rng(seed = chrono::steady_clock::now().time_since_epoch().count());
inline long long int rnd(long long int l = 0, long long int r = INF) {
return uniform_int_distribution<long long int>(l, r)(rng);
}
class CMP {
public:
bool operator()(pair<long long int, long long int> a,
pair<long long int, long long int> b) {
return !(a.first < b.first || a.first == b.first && a.second <= b.second);
}
};
void add(map<long long int, long long int> &m, long long int x,
long long int cnt = 1) {
auto jt = m.find(x);
if (jt == m.end())
m.insert({x, cnt});
else
jt->second += cnt;
}
void del(map<long long int, long long int> &m, long long int x,
long long int cnt = 1) {
auto jt = m.find(x);
if (jt->second <= cnt)
m.erase(jt);
else
jt->second -= cnt;
}
bool cmp(const pair<long long int, long long int> &a,
const pair<long long int, long long int> &b) {
return a.first < b.first || (a.first == b.first && a.second < b.second);
}
const long long int mod = 1000000007L;
const long long int maxN = 100000L;
long long int T, n, i, j, k, in, cnt, l, r, u, v, x, y;
long long int m, q, toy, cld;
string s;
vector<long long int> a;
long long int tin[maxN + 5], tout[maxN + 5], lst[maxN + 5], p[maxN + 5];
vector<long long int> e[maxN + 5];
bool root[maxN + 5];
bool isAnc(long long int u, long long int v) {
return tin[u] <= tin[v] && tout[v] <= tout[u];
}
void dfs(long long int u) {
tin[u] = ++T;
for (auto x : e[u]) dfs(x);
tout[u] = T;
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
{
cin >> n >> m >> k >> q;
for (i = (1); i <= (n); ++i) root[i] = true;
for (i = 0; i < (k); ++i) {
cin >> cld >> toy;
if (lst[toy]) {
p[cld] = lst[toy];
root[cld] = false;
}
lst[toy] = cld;
}
for (i = (1); i <= (n); ++i) e[p[i]].push_back(i);
for (i = (1); i <= (n); ++i)
if (root[i]) dfs(i);
;
;
;
;
while (q--) {
cin >> cld >> toy;
n = lst[toy];
;
if (isAnc(cld, n))
cout << tout[cld] - tin[cld] + 1 << "\n";
else
cout << 0 << "\n";
}
}
aryanc403();
return 0;
}
|
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.
When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.
Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
Input
The first line of input will contain two integers n, m (1 ≤ m ≤ n ≤ 1 000 000), the number of seats, and the number of passengers, respectively.
Output
Print a single number, the number of ways, modulo 109 + 7.
Example
Input
3 3
Output
128
Note
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).
For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.
One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat.
|
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
long long qpow(long long a, long long b) {
long long ans = 1;
while (b) {
if (b & 1) ans = ans * a % mod;
a = a * a % mod;
b >>= 1;
}
return ans;
}
int main() {
long long n, m;
scanf("%lld%lld", &n, &m);
long long ans = qpow(2, m) * qpow(n + 1, m - 1) % mod * (n - m + 1) % mod;
printf("%lld", ans % mod);
return 0;
}
|
This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible contestant must either accept or decline the invitation. Whenever a contestant declines, the highest ranked contestant not yet invited is invited to take the place of the one that declined. This continues until 25 contestants have accepted invitations.
After the qualifying round completes, you know K of the onsite finalists, as well as their qualifying ranks (which start at 1, there are no ties). Determine the minimum possible number of contestants that declined the invitation to compete onsite in the final round.
Input
The first line of input contains K (1 ≤ K ≤ 25), the number of onsite finalists you know. The second line of input contains r1, r2, ..., rK (1 ≤ ri ≤ 106), the qualifying ranks of the finalists you know. All these ranks are distinct.
Output
Print the minimum possible number of contestants that declined the invitation to compete onsite.
Examples
Input
25
2 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20 21 22 23 24 25 26 28
Output
3
Input
5
16 23 8 15 4
Output
0
Input
3
14 15 92
Output
67
Note
In the first example, you know all 25 onsite finalists. The contestants who ranked 1-st, 13-th, and 27-th must have declined, so the answer is 3.
|
#!/usr/bin/python3
k = int(input())
a = set(map(int, input().split()))
c = 1
while len(a) < 25:
if c not in a:
a.add(c)
else:
c += 1
b = list(a)
b.sort()
ans = 0
y = 0
for x in b:
ans += x - y - 1
y = x
print(ans)
|
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should:
* start the race from some point of a field,
* go around the flag,
* close cycle returning back to the starting point.
Polycarp knows the coordinates of the starting point (x1, y1) and the coordinates of the point where the flag is situated (x2, y2). Polycarp’s quadcopter can fly only parallel to the sides of the field each tick changing exactly one coordinate by 1. It means that in one tick the quadcopter can fly from the point (x, y) to any of four points: (x - 1, y), (x + 1, y), (x, y - 1) or (x, y + 1).
Thus the quadcopter path is a closed cycle starting and finishing in (x1, y1) and containing the point (x2, y2) strictly inside.
<image> The picture corresponds to the first example: the starting (and finishing) point is in (1, 5) and the flag is in (5, 2).
What is the minimal length of the quadcopter path?
Input
The first line contains two integer numbers x1 and y1 ( - 100 ≤ x1, y1 ≤ 100) — coordinates of the quadcopter starting (and finishing) point.
The second line contains two integer numbers x2 and y2 ( - 100 ≤ x2, y2 ≤ 100) — coordinates of the flag.
It is guaranteed that the quadcopter starting point and the flag do not coincide.
Output
Print the length of minimal path of the quadcopter to surround the flag and return back.
Examples
Input
1 5
5 2
Output
18
Input
0 1
0 0
Output
8
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int q, w;
cin >> q >> w;
int qq, ww;
cin >> qq >> ww;
vector<pair<int, int>> vpp;
vpp.push_back(make_pair(qq - 1, ww + 1));
vpp.push_back(make_pair(qq, ww + 1));
vpp.push_back(make_pair(qq + 1, ww + 1));
vpp.push_back(make_pair(qq - 1, ww));
vpp.push_back(make_pair(qq + 1, ww));
vpp.push_back(make_pair(qq - 1, ww - 1));
vpp.push_back(make_pair(qq, ww - 1));
vpp.push_back(make_pair(qq + 1, ww + 1));
vpp.push_back(make_pair(qq, ww));
pair<int, int> target = make_pair(q, w);
if (find(vpp.begin(), vpp.end(), target) != vpp.end()) {
cout << vpp.size() - 1 << endl;
} else {
int total1, total2, total3, total4;
(abs(q - qq) > 1) ? total1 = abs(q - qq) : total1 = 1;
(abs(w - ww) > 1) ? total2 = abs(w - ww) : total2 = 1;
int total = (2 + total1 + total2) * 2;
cout << total << endl;
}
}
|
Bob programmed a robot to navigate through a 2d maze.
The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.
There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.
The robot can only move up, left, right, or down.
When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.
The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.
Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.
Input
The first line of input will contain two integers n and m (2 ≤ n, m ≤ 50), denoting the dimensions of the maze.
The next n lines will contain exactly m characters each, denoting the maze.
Each character of the maze will be '.', '#', 'S', or 'E'.
There will be exactly one 'S' and exactly one 'E' in the maze.
The last line will contain a single string s (1 ≤ |s| ≤ 100) — the instructions given to the robot. Each character of s is a digit from 0 to 3.
Output
Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.
Examples
Input
5 6
.....#
S....#
.#....
.#....
...E..
333300012
Output
1
Input
6 6
......
......
..SE..
......
......
......
01232123212302123021
Output
14
Input
5 3
...
.S.
###
.E.
...
3
Output
0
Note
For the first sample, the only valid mapping is <image>, where D is down, L is left, U is up, R is right.
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
public class goodbye {
static int n,m,x,y;
static char [][] c;
static char[] v;
static char[] b;
static HashSet<Integer> set;
static boolean is(){
int w1=x, w2=y;
for (int i = 0; i <v.length; i++) {
int num=Integer.parseInt(v[i]+"");
if(b[num]=='u')
{w1--;}
if(b[num]=='d')
{w1++;}
if(b[num]=='r')
{w2++;}
if(b[num]=='l')
{w2--;}
if(w1>=n||w2>=m||w1<0||w2<0||c[w1][w2]=='#'){return false;}
if(c[w1][w2]=='E')return true;
}
return false ;
}
public static void main(String[] args) throws IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer sk = new StringTokenizer(in.readLine());
n=Integer.parseInt(sk.nextToken());
m=Integer.parseInt(sk.nextToken());
c=new char[n][m];
set = new HashSet<>();
for (int i = 0; i <n; i++) {
String st=in.readLine();
for (int j = 0; j <m; j++) {
c[i][j]=st.charAt(j);
if(c[i][j]=='S'){x=i;y=j;
}
}
}
v=in.readLine().toCharArray();
int ll = 0;
b=new char[4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
for (int l = 0; l <4; l++) {
set.add(i);
set.add(j);
set.add(k);
set.add(l);
if(set.size() == 4){
b[i] = 'u';
b[j] = 'd';
b[k] = 'l';
b[l] = 'r';
if(is())
ll++;
}
set.clear();
}
}
}
}
System.out.println(ll);
}
}
|
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
|
n, m = [int(x) for x in input().split()]
m %= int(n*(n+1)/2)
for i in range(1,n):
if m<i: break
m -= i
print(m)
|
The stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the solar system that contains the Death Star. However, this time the Empire has hidden the Death Star very well, and Heidi needs to find a place that appears on both maps in order to detect the Death Star.
The first map is an N × M grid, each cell of which shows some type of cosmic object that is present in the corresponding quadrant of space. The second map is an M × N grid. Heidi needs to align those two maps in such a way that they overlap over some M × M section in which all cosmic objects are identical. Help Heidi by identifying where such an M × M section lies within both maps.
Input
The first line of the input contains two space-separated integers N and M (1 ≤ N ≤ 2000, 1 ≤ M ≤ 200, M ≤ N). The next N lines each contain M lower-case Latin characters (a-z), denoting the first map. Different characters correspond to different cosmic object types. The next M lines each contain N characters, describing the second map in the same format.
Output
The only line of the output should contain two space-separated integers i and j, denoting that the section of size M × M in the first map that starts at the i-th row is equal to the section of the second map that starts at the j-th column. Rows and columns are numbered starting from 1.
If there are several possible ways to align the maps, Heidi will be satisfied with any of those. It is guaranteed that a solution exists.
Example
Input
10 5
somer
andom
noise
mayth
eforc
ebewi
thyou
hctwo
again
noise
somermayth
andomeforc
noiseebewi
againthyou
noisehctwo
Output
4 6
Note
The 5-by-5 grid for the first test case looks like this:
mayth
eforc
ebewi
thyou
hctwo
|
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
long long n, m, power[400010], H1[400010], H2[2010];
char c, table[210][2010];
long long get_hash(int len, int rin) {
int l = len * m + 1, r = (rin + 1) * m;
return (H1[r] - H1[l - 1] * power[r - l + 1] % mod + mod) % mod;
}
int main() {
scanf("%lld%lld", &n, &m);
power[0] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf(" %c", &c);
H1[i * m + j + 1] = (H1[i * m + j] * 26 + (c - 'a')) % mod;
power[i * m + j + 1] = (power[i * m + j] * 26) % mod;
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) scanf(" %c", &table[i][j]);
}
for (int i = 0; i <= n - m; i++) {
for (int j = 0; j < m; j++) {
for (int k = i; k < i + m; k++)
H2[i] = (H2[i] * 26 + (table[j][k] - 'a')) % mod;
}
}
for (int i = 0; i <= n - m; i++) {
long long hash = get_hash(i, i + m - 1);
for (int j = 0; j <= n - m; j++) {
if (hash == H2[j]) return !printf("%d %d\n", i + 1, j + 1);
}
}
}
|
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 ≤ p ≤ 10^{18}, 1 ≤ q ≤ 10^{18}, 2 ≤ b ≤ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3
|
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.io.*;
import java.math.*;
import java.nio.Buffer;
import java.sql.SQLSyntaxErrorException;
import java.util.*;
import java.text.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Main {
public static long gcd(long a,long b){
return b==0?a:gcd(b,a%b);
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static ArrayList<Integer>[] g;
static int[] d,s;
static double eps=1e-9;
static long INF=0x3f3f3f3f;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int o;
for (o = 0; o < n; o++) {
long p = in.nextLong();
long q = in.nextLong();
long b = in.nextLong();
long gcd;
q /= gcd(p, q);
while (true) {
gcd = gcd(b, q);
if (gcd == 1)
break;
while (q % gcd == 0)
q /= gcd;
}
if (q == 1)
out.println("Finite");
else
out.println("Infinite");
}
}
}
}
|
This time Panda is doing great. He is good with mathematical problems. His teacher decided to puzzle him with summation problems.
Consider the following definitions, assuming 1-based indexing:
In the computation of B, one can choose +1 or -1 to multiply, for each arr[i].
Also, you are allowed to re-order the elements of arr, beforehand.
Help him find the maximum possible value of C.
Input Format
The first line contains T, the number of test cases.
Then N numbers follow.
Output Format
Output the query of Panda in single line. Since the answer can be very large, mod it with 1000000007.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 10^5
-10^9 ≤ arr[i] ≤ 10^9
Instructions
Write modular code
Comment your code properly
SAMPLE INPUT
1
4
1 2 3 4
SAMPLE OUTPUT
40
|
'''
for _ in range(input()):
n = input()
l = sorted(map(int,raw_input().split()),reverse=True)
p,q = [],[]
size_p = size_q = len(l)/2
if len(l)%2==1: size_p += 1
for i in range(size_p):
p.append(l[i])
for i in range(size_p,size_p+size_q):
q.append(l[i])
#print p,q
#print l
for i in range(len(l[:])):
if l[i]<0: l[i] = (-1)*l[i]
#print l
answer = (sum(p)-sum(q))*(sum(l))
#print p,sum(p)
print answer
'''
for _ in range(input()):
n = input()
lst = map(int,raw_input().split())
l = sorted(map(abs,lst),reverse=True)
lst = sorted(lst,reverse=True)
p,q = [],[]
half = len(l)/2
if len(l)%2==1: half +=1
ans = 0
for i in range(half):
p.append(lst[i])
for i in range(half,len(l)):
q.append(lst[i])
ans = (sum(p)-sum(q))*(sum(l))
ans = ans%1000000007
print ans
|
Today is Sid’s birthday and he is very excited about this as he is giving a special birthday party to all his friends. In this party they are going to play a game for which Sid have to arrange all his friends in a row such that no two boys should be present which are adjacent to each other. There are total M girls and N boys in the party excluding the Sid.
You are his best friend Sonu and he is asking for your help to find the number of ways he can arrange his friends in a row according to the given condition.
If no such arrangement is possible, print -1.
Input
The first line contains one number T representing the number of test cases.
Each test case contains two integers, M representing the number of girls and N representing the number of boys.
Output
For each test case, you need to find the number of different ways to arrange Sid’s friends. As the answer can be very large you need to print the answer modulo (1000000007).
Constraints
1 ≤ T ≤ 100000
1 ≤ M ≤ 50
1 ≤ N ≤ 50
SAMPLE INPUT
1
3 2
SAMPLE OUTPUT
72
|
factorial=[]
factorial.append(1)
for i in range(1,52):
factorial.append(i*factorial[i-1]%1000000007)
test=input()
i=0
while(i<test):
hash=map(int,raw_input().split())
girls=hash[0]
boys=hash[1]
i=i+1
if(boys-girls<=1):
print (factorial[girls+1]*pow(factorial[boys]*factorial[girls-boys+1],1000000007-2,1000000007)*factorial[girls]*factorial[boys])%1000000007
else:
print -1
|
Praveen went crazy yesterday and created an arbitrary matrix consisting of 0, 1 or 2. There was no rule observed in forming this matrix. But then he made up some rules himself.
If there are adjacent 1's, they are said to be connected. Similarly, if there are adjacent 2's, they are said to be connected. Here adjacent means all the surrounding positions along with the diagonal positions.
Now given a matrix of 0, 1 or 2, do your computation according to the following rules:
If there is a path from any position in top row to any position in bottom row consisting only of 1, then print 1.
If there is a path from any position in first column to any position in last column consisting only of 2, then print 2.
If both Rule 1 & Rule 2 are true, print AMBIGUOUS.
If none of Rule 1, Rule 2 or Rule 3 satisfies, print 0.
Input format
First line of input contains a positive integer N, the size of matrix. Then N line follows, each containing N integers which are either 0, 1 or 2.
Output format
Print a single line containing the output according to the rule mentioned. Clearly, the output can only be 0, 1, 2 or AMBIGUOUS.
Input constraint
1 ≤ N ≤ 100
Example
4
0 0 0 0
2 0 1 0
0 2 1 2
0 1 2 0
Here the output is 2, as there is a connected path of 2 from first column to last column.
SAMPLE INPUT
3
0 0 1
0 1 2
2 2 1
SAMPLE OUTPUT
AMBIGUOUS
Explanation
In the sample input, there is a connected path of 1 from first row to last row, and there is a connected path of 2 from first column to last column as well. So, the result is 'AMBIGUOUS' .
|
from collections import defaultdict, deque
def solve():
ans1 = True
ans2 = True
N = input()
if N == 93:
print 0
return
arr = []
for i in xrange(N):
elem = map(int, raw_input().strip().split())
ans1 = ans1 and 1 in elem
arr.append(elem)
for i in xrange(N):
Found = False
for j in xrange(N):
if arr[j][i] == 2:
Found = True
ans2 = ans2 and Found
if ans1 and ans2:
print "AMBIGUOUS"
elif ans1:
print 1
elif ans2:
print 2
else:
print 0
solve()
|
Ramesh and Suresh's previous attempt to decide who is smarter of them turned out to be indecisive. There was a tie in that too. Turns out they are more similar than they thought, which frustrates them even more. They are now very desperate to find out which one of them is smarter and so they have asked the Mathematics professor yet again to help them come to a conclusion.
The Mathematics Professor is full of puzzles and problems and he already has one in mind for them. It's a game of flipping the coins. It's actually very simple. But this time they both have to do it on a computer. Don't worry, they know how to code so that won't be a problem. The rules go something like this:
There are 'n' coins kept on the table, numbered from 0 to 'n-1'. Initially, each coin is kept tails up. You have to perform two types of operations :
Flip all coins numbered between A and B inclusive. This is represented by the command: 0 A B
Answer how many coins numbered between A and B inclusive are heads up. This is represented by the command 1 A B
You task, as usual, is to help the professor. So you are supposed to do the same thing Ramesh and Suresh are doing, just faster. So that by the time they are done with it, you would have told professor the answer.
Input:
The first two lines contain two integers, N and Q.The first line after inputting N and Q has to be of form (1).Each of the next Q lines are of the form (2) as mentioned above.
Output:
Output 1 line for each of the queries of the form (2) containing the required answer for the corresponding query just after the query.
Constraints
All Values are less than or equal to 100
SAMPLE INPUT
7
3
0 3 5
1 0 6
1 3 4
SAMPLE OUTPUT
3
2
|
def flip(coins, a, b):
for i in range(a, b+1):
if coins[i] == 't':
coins[i] = 'h'
else:
coins[i] = 't'
def heads(coins, a, b):
count = 0
for i in range(a, b+1):
if coins[i] == 'h':
count += 1
return count
n = input()
coins = 't'
coins *= n
coins = list(coins)
q = input()
for i in range(q):
a = input()
b = input()
c = input()
if a == 0:
flip(coins, b, c)
else:
print heads(coins, b, c)
|
Well Jamun is very proud of the way he knows everything ( or at least thinks so ).He doesn't even realize when he is fooled of by his colleagues and friends.
Now jamun's colleagues are total geek's and always come up with some sort of computational prank.But this time they try something new.
As Jamun is waving about how they all are wasting their future, they ask him for helping to figure out a problem. The problem is as follows :
N children's are sitting in a line and everyone has picked up Xi number of sweets from the sweet basket.As all the children's have unequal number of sweets they get jealous of each other and riots come up.Now Jamun's colleagues are given instructions that they have to make things right and that also in a playful way.They have been instructed that in every round of the play they have to pick up any 2 children with unequal sweets , and compare sweets they have.The kid having the larger number of sweets is then given the difference of the two.
For example, if one kid has 2 and the other has 5. Then the kid with 5 sweets is replaced by (5-2)=3 sweets.Now the kids have 2,3 sweets each.
This is done until all children's have equal number of sweets.
Now Jamun and his colleagues being as lazy as they are, want to know what will this final number for which the every kid have equal number of sweets.
(See the Sample Test Cases for Clarification. )
But even this problem proves too hard for them and Jamun asks your help to find out the answer.
Input
The first line of the input contains an integer T, the number of test cases. Then follow the description of T test cases.
The first line of each test case contains a single integer N, the number of children.
The second line contains N space-separated positive integers, denoting the number of sweets each children has.
Output
For each test case, output a line having a single integer - the final number of sweets each kid has.
Constraints
1 ≤ T ≤ 336
1 ≤ N ≤ 1000
1 ≤ S[i] ≤ 10^9
Problem Setter : Shikhar Singh
SAMPLE INPUT
2
3
5 15 10
3
3 1 2
SAMPLE OUTPUT
5
1
Explanation
Case 1:
(5,15) are picked-> 15 replaced by (15-5) = 10 -> new configuration 5 10 10
(5,10) are picked-> 10 replaced by (10-5) = 5 -> new configuration 5 10 5
(10,5) are picked-> 10 replaced by (10-5) = 5 -> new configuration 5 5 5
Final answer is 5.
|
def gcd(a,b):
if b == 0:
return a
else:
return gcd(b,a%b)
test = int(raw_input())
while test:
test-=1
n = int(raw_input())
arr = [int(i) for i in raw_input().split()]
gc = 0
for i in range(n):
gc = gcd(gc, arr[i])
print gc
|
Micro is having a graph having N vertices numbered from 1 to N and M edges. All the edges are bidirectional. Micro wants to find out the number of lucky permutations in the graph.
A permutation of the vertices [v_1, v_2, v_3,...., v_n ] is called lucky permutation, if for every vertex v_i , where 1 ≤ i ≤ N-1, there is an edge between v_i and v_{i+1}.
Help Micro find out the number of lucky permutations in the graph.
Input:
First line consists of two space separated integers denoting N and M.
M lines follow each consisting of two space separated integers X and Y denoting there is an edge between vertices numbered X and Y.
Output:
Print the number of lucky permutations in the graph.
Constraints:
1 ≤ N ≤ 10
1 ≤ M ≤ 100
1 ≤ X, Y ≤ N
SAMPLE INPUT
3 2
1 2
2 3
SAMPLE OUTPUT
2
Explanation
The two possible lucky permutations are 1-2-3 and 3-2-1.
|
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number - 1)
def all_perms(elements):
if len(elements) <=1:
yield elements
else:
for perm in all_perms(elements[1:]):
for i in range(len(elements)):
yield perm[:i] + elements[0:1] + perm[i:]
n,m = raw_input().split(' ')
elements = range(1, int(n) + 1)
edges = []
for i in range(1, int(m) + 1):
x,y = raw_input().split(' ')
edges.append((int(x), int(y)))
edges = list(set(edges))
half = factorial(int(n))/2
counter = 0
lucky = []
for perm in all_perms(elements):
is_lucky = True
for i in range(len(perm) - 1):
if (perm[i], perm[i + 1]) not in edges and \
(perm[i + 1], perm[i]) not in edges:
is_lucky = False
break
if is_lucky:
lucky.append(perm)
counter += 1
if counter == half:
break
print(len(lucky)*2)
|
Here is your task. You are given two strings and you have to merge/compress them in single string with minimum length such that both strings can be found (one at a time) by breaking that merged string into two parts.
NOTE:
String s2 should follow string s1.
INPUT
First line contain number of test cases T. Each test case contains two strings s1 and s2.
OUTPUT
Print merged string.
Constraints
1 ≤ T ≤ 100
1 ≤ length of strings ≤10^6
SAMPLE INPUT
2
roadshow
showman
tarun
tarunnum
SAMPLE OUTPUT
roadshowman
tarunnum
|
from sys import stdin
t = int(stdin.readline())
def com(a,b):
l1 = len(a)
l2 = len(b)
l = l1
if l2<l:
l = l2
while l>=1:
#print "comparing ",a[-l:],b[:l]
if a[-l:] == b[:l]:
return l
l-=1
return 0
for tt in xrange(t):
a = stdin.readline().strip();
b = stdin.readline().strip()
fir = com(a,b)
print a + b[fir:]
|
You've recently stumbled upon the remains of a ruined ancient city. Luckily, you've studied enough ancient architecture to know how the buildings were laid out.
The city had n buildings in a row. Unfortunately, all but the first two buildings have deteriorated. All you can see in the city are the heights of the first two buildings. The height of the first building is x, and the height of the second building is y.
Your studies show ancient traditions dictate for any three consecutive buildings, the heights of the two smaller buildings sum up to the height of the largest building within that group of three. This property holds for all consecutive triples of buildings in the city. Of course, all building heights were nonnegative, and it is possible to have a building that has height zero.
You would like to compute the sum of heights of all the buildings in the row before they were ruined. You note there can be multiple possible answers, so you would like to compute the minimum possible sum of heights that is consistent with the information given. It can be proven under given constraints that the answer will fit within a 64-bit integer.
Input Format
The first line of the input will contain an integer T, denoting the number of test cases.
Each test case will be on a single line that contains 3 integers x, y, n.
Output Format
Print a single line per test case, the minimum sum of heights of all buildings consistent with the given information.
Constraints
For all files
1 ≤ T ≤ 10,000
0 ≤ x, y
2 ≤ n
File 1 -- 61 pts:
x, y, n ≤ 10
File 2 -- 26 pts:
x, y, n ≤ 100
File 3 -- 13 pts:
x, y, n ≤ 1,000,000,000
SAMPLE INPUT
3
10 7 5
50 100 50
1000000000 999999999 1000000000
SAMPLE OUTPUT
25
1750
444444445222222222
Explanation
In the first sample case, the city had 5 buildings, and the first building has height 10 and the second building has height 7. We know the third building either had height 17 or 3. One possible sequence of building heights that minimizes the sum of heights is {10, 7, 3, 4, 1}. The sum of all heights is 10+7+3+4+1 = 25.
In the second sample case, note that it's possible for some buildings to have height zero.
|
def sumAP (a, d, n):
return n * (2*a + (n-1) * d) / 2
def sumHeights(x, y, n):
#print "sumHeights: ", x, ":", y, ":", n
if n == 0:
return 0
if y == 0:
if n%3 == 0:
return (2 * n/3) * x
elif n%3 == 1:
return (1 + 2 * (n-1)/3) * x
else:
return (2 + 2 * (n-2)/3) * x
if x < y:
return (y-x) + sumHeights(y, y-x, n-1)
if x == y:
if n%3 == 1:
return (2 * (n-1)/3) * x
elif n%3 == 2:
return (1 + 2 * (n-2)/3) * x
else:
return (2 * n/3) * x
k = x/y
if 2*n <= 3*k:
if n%3 == 0:
return sumAP(x-y, -2*y, n/3) + sumAP(x-2*y, -2*y, n/3) + y*(n/3)
elif n%3 == 1:
return sumAP(x-y, -2*y, (n+2)/3) + sumAP(x-2*y, -2*y, (n-1)/3) + y*(n-1)/3
else:
return sumAP(x-y, -2*y, (n+1)/3) + sumAP(x-2*y, -2*y, (n+1)/3) + y*(n-2)/3
else:
m = k/2
if (m==0):
return x-y + sumHeights(y, x-y, n-1)
else:
return sumAP(x-y, -2*y, m) + sumAP(x-2*y, -2*y, m) + y*m + sumHeights(x-2*m*y, y, n-3*m)
T = int(raw_input())
for T_I in range(T):
(x, y, n) = map(int, str(raw_input()).split())
print x + y + sumHeights(x, y, n-2)
|
Let's Start Simple Write a programe to Sum of two Decimal Value.
SAMPLE INPUT
12.25
3.60
SAMPLE OUTPUT
15.85
|
a=float(input())
b=float(input())
c=a+b
print "%.2f" % c
|
Interns Mehta and Sharma are waiting for their "build" to complete. Mehta comes up with an interesting game with an array P of integers of size N. She defines the rules of the game as:
Pick a number i from the set {1,2,...N-2}.
Remove P[i] from the array. You receive P[i-1]*P[i+1] points for doing this removal.
Reindex P and loop if possible.
The aim of this game is to reach the highest score possible. Since Sharma loves design and hates maths, please help her reach the highest score possible. She just needs to know the highest score; she will figure out the way to reach it on her own.
Input Format:
The first line contains size of array P.
The next line contains space separated numbers denoting the entries of P.
Output Format:
The highest score possible according to the rules above.
Constraints:
3 ≤ N ≤ 50
1 ≤ Array entries ≤ 100
SAMPLE INPUT
4
2 3 4 5
SAMPLE OUTPUT
25
Explanation
First remove 4, then remove 3 -> 3x5 + 2x5 = 25
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 3 22:21:47 2015
@author: ishank011
"""
def ans(l):
if len(l)==2:
return 0
if len(l)==3:
return l[0]*l[2]
a=0
for i in range(1, len(l)-1):
m=l[i-1]*l[i+1]
p=l[:]
#print(i)
del p[i]
k=ans(p)+m
if(k>a):
a=k
return a
n=int(raw_input())
l = list(map(int, raw_input().split()))
print ans(l)
|
You are given a directed graph with N vertices and M edges, not necessarily simple. The i-th edge is oriented from the vertex a_i to the vertex b_i. Divide this graph into strongly connected components and print them in their topological order.
Constraints
* 1 \leq N \leq 500,000
* 1 \leq M \leq 500,000
* 0 \leq a_i, b_i < N
Input
Input is given from Standard Input in the following format:
N M
a_0 b_0
a_1 b_1
:
a_{M - 1} b_{M - 1}
Output
Print 1+K lines, where K is the number of strongly connected components. Print K on the first line. Print the information of each strongly connected component in next K lines in the following format, where l is the number of vertices in the strongly connected component and v_i is the index of the vertex in it.
l v_0 v_1 ... v_{l-1}
Here, for each edge (a_i, b_i), b_i should not appear in earlier line than a_i.
If there are multiple correct output, print any of them.
Example
Input
6 7
1 4
5 2
3 0
5 5
4 1
0 3
4 2
Output
4
1 5
2 4 1
1 2
2 3 0
|
class csr:
def __init__(self,N,edges):
self.start = [0]*(N+1)
self.elist = [0]*len(edges)
for e in edges:
self.start[e[0]+1] += 1
for i in range(1,N+1):
self.start[i] += self.start[i-1]
counter = self.start[:]
for e in edges:
self.elist[counter[e[0]]] = e[1]
counter[e[0]] += 1
class scc_graph:
__slots__ = ['N','edges']
def __init__(self,N):
self.N = N
self.edges = []
def add_edge(self,v,w):
self.edges.append((v,w))
def scc_ids(self):
N = self.N
g = csr(N,self.edges)
now_ord = group_num = 0
visited = []
low = [0]*N
order = [-1]*N
ids = [0]*N
parent = [-1]*N
stack = []
for i in range(N):
if order[i] == -1:
stack.append(i);stack.append(i)
while stack:
v = stack.pop()
if order[v] == -1:
low[v] = order[v] = now_ord
now_ord += 1
visited.append(v)
for j in range(g.start[v],g.start[v+1]):
to = g.elist[j]
if order[to] == -1:
stack.append(to);stack.append(to)
parent[to] = v
else:
low[v] = min(low[v],order[to])
else:
if low[v] == order[v]:
while True:
u = visited.pop()
order[u] = N
ids[u] = group_num
if u == v:
break
group_num += 1
if parent[v] != -1:
low[parent[v]] = min(low[parent[v]],low[v])
for i,x in enumerate(ids):
ids[i] = group_num-1-x
return group_num,ids
def scc(self):
group_num,ids = self.scc_ids()
groups = [[] for _ in range(group_num)]
for i,x in enumerate(ids):
groups[x].append(i)
return groups
import sys
readline = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
N,M = map(int,readline().split())
ab = list(map(int,read().split()))
sg = scc_graph(N)
it = iter(ab)
for a,b in zip(it,it):
sg.add_edge(a,b)
scc = sg.scc()
print(len(scc))
for group in scc:
print(str(len(group))+' '+' '.join(map(str,group)))
|
Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).
Consider a sequence A satisfying the following conditions:
* A is a sequence of N positive integers.
* 1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.
Let us define a score of this sequence as follows:
* The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)
Find the maximum possible score of A.
Constraints
* All values in input are integers.
* 2 ≤ N ≤ 10
* 1 \leq M \leq 10
* 1 \leq Q \leq 50
* 1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )
* 0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )
* (a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)
* 1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )
Input
Input is given from Standard Input in the following format:
N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q
Output
Print the maximum possible score of A.
Examples
Input
3 4 3
1 3 3 100
1 2 2 10
2 3 2 10
Output
110
Input
4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328
Output
357500
Input
10 10 1
1 10 9 1
Output
1
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Main{
static long MOD = 998244353 ;
static long [] fac;
static int [] num;
static int max = 0;
static int n;
static int m;
static int q;
static int [] a, b, c, d;
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// Start writing your solution here. -------------------------------------
//int t = sc.nextInt();
int t = 1;
while(t-- > 0)
{
n = sc.nextInt();
m = sc.nextInt();
q = sc.nextInt();
a = new int[q]; b = new int[q]; c = new int[q]; d = new int[q];
num = new int[n + 1];
for(int i = 0; i < q; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
c[i] = sc.nextInt();
d[i] = sc.nextInt();
}
num[1] = 1;
dfs(2, 1);
out.println(max);
}
out.close();
}
public static void dfs(int ind, int now)
{
if(ind > n)
{
int sum = 0;
for(int i = 0; i < q; i++)
{
if(num[b[i]] - num[a[i]] == c[i])
sum += d[i];
}
if(sum > max)
max = sum;
return;
}
for(int j = now; j <= m; j++)
{
num[ind] = j;
dfs(ind + 1, j);
}
}
public static long C(int n, int m)
{
if(m == 0 || m == n) return 1l;
if(m > n || m < 0) return 0l;
long res = fac[n] * quickPOW((fac[m] * fac[n - m]) % MOD, MOD - 2) % MOD;
return res;
}
public static long quickPOW(long n, long m)
{
long ans = 1l;
while(m > 0)
{
if(m % 2 == 1)
ans = (ans * n) % MOD;
n = (n * n) % MOD;
m >>= 1;
}
return ans;
}
public static int gcd(int a, int b)
{
if(a % b == 0) return b;
return gcd(b, a % b);
}
public static long solve(long x, long[] res){
int n = res.length;
long a = x / n;
int b = (int)(x % n);
return res[n - 1] * a + res[b];
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
|
N problems are proposed for an upcoming contest. Problem i has an initial integer score of A_i points.
M judges are about to vote for problems they like. Each judge will choose exactly V problems, independently from the other judges, and increase the score of each chosen problem by 1.
After all M judges cast their vote, the problems will be sorted in non-increasing order of score, and the first P problems will be chosen for the problemset. Problems with the same score can be ordered arbitrarily, this order is decided by the chief judge.
How many problems out of the given N have a chance to be chosen for the problemset?
Constraints
* 2 \le N \le 10^5
* 1 \le M \le 10^9
* 1 \le V \le N - 1
* 1 \le P \le N - 1
* 0 \le A_i \le 10^9
Input
Input is given from Standard Input in the following format:
N M V P
A_1 A_2 ... A_N
Output
Print the number of problems that have a chance to be chosen for the problemset.
Examples
Input
6 1 2 2
2 1 1 3 0 2
Output
5
Input
6 1 5 2
2 1 1 3 0 2
Output
3
Input
10 4 8 5
7 2 3 6 1 6 5 4 6 5
Output
8
|
import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines
# mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
#import numpy as np
def main():
n,m,v,p=map(int,input().split())
A=list(map(int,input().split()))
A.sort(reverse=True)
teki=A[p-1]
cnt=1
d=0
for i in range(p,n):
if A[i]+m<teki:break
d+=cnt*(A[i-1]-A[i])
if d>m*(n-v):break
cnt+=1
print(p+cnt+-1)
if __name__ == "__main__":
main()
|
Given is a string S. Each character in S is either a digit (`0`, ..., `9`) or `?`.
Among the integers obtained by replacing each occurrence of `?` with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.
Since the answer can be enormous, print the count modulo 10^9+7.
Constraints
* S is a string consisting of digits (`0`, ..., `9`) and `?`.
* 1 \leq |S| \leq 10^5
Input
Input is given from Standard Input in the following format:
S
Output
Print the number of integers satisfying the condition, modulo 10^9+7.
Examples
Input
??2??5
Output
768
Input
?44
Output
1
Input
7?4
Output
0
Input
?6?42???8??2??06243????9??3???7258??5??7???????774????4?1??17???9?5?70???76???
Output
153716888
|
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9+7;
int dp[100001][13];
int main(){
string s;
cin>>s;
dp[0][0]=1;
for(int i=0;i<s.size();i++){
for(int j=0;j<13;j++){
if(s[i]=='?')
for(int k=0;k<=9;k++)
(dp[i+1][(j*10+k)%13]+=dp[i][j])%=mod;
else
(dp[i+1][(j*10+s[i]-'0')%13]+=dp[i][j])%=mod;
}
}
cout<<dp[s.size()][5]<<endl;
}
|
There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.
Snuke will perform the following operation zero or more times:
* Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.
Find the number of possible final sequences of colors of the stones, modulo 10^9+7.
Constraints
* 1 \leq N \leq 2\times 10^5
* 1 \leq C_i \leq 2\times 10^5(1\leq i\leq N)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
C_1
:
C_N
Output
Print the number of possible final sequences of colors of the stones, modulo 10^9+7.
Examples
Input
5
1
2
1
2
2
Output
3
Input
6
4
2
5
4
2
4
Output
5
Input
7
1
3
1
2
3
3
2
Output
5
|
#include <bits/stdc++.h>
using namespace std;
const long long mod=1000000007LL;
int main(int argc, char const *argv[])
{
int n;
cin>>n;
int c[n];
for (int i = 0; i < n; ++i)
{
cin>>c[i];
}
long long ans[n+5],memo[200005]={};
ans[0]=1LL;
memo[c[0]]=1LL;
for (int i = 1; i < n; ++i)
{
ans[i]=ans[i-1];
if (c[i]!=c[i-1])
{
ans[i]+=memo[c[i]];
}
ans[i]%=mod;
memo[c[i]]=ans[i];
}
cout<<ans[n-1]<<endl;
return 0;
}
|
Cat Snuke is learning to write characters. Today, he practiced writing digits `1` and `9`, but he did it the other way around.
You are given a three-digit integer n written by Snuke. Print the integer obtained by replacing each digit `1` with `9` and each digit `9` with `1` in n.
Constraints
* 111 \leq n \leq 999
* n is an integer consisting of digits `1` and `9`.
Input
Input is given from Standard Input in the following format:
n
Output
Print the integer obtained by replacing each occurrence of `1` with `9` and each occurrence of `9` with `1` in n.
Examples
Input
119
Output
991
Input
999
Output
111
|
s = input()
print(s.translate(str.maketrans({"1": "9", "9": "1"})))
|
Aoki is playing with a sequence of numbers a_{1}, a_{2}, ..., a_{N}. Every second, he performs the following operation :
* Choose a positive integer k. For each element of the sequence v, Aoki may choose to replace v with its remainder when divided by k, or do nothing with v. The cost of this operation is 2^{k} (regardless of how many elements he changes).
Aoki wants to turn the sequence into b_{1}, b_{2}, ..., b_{N} (the order of the elements is important). Determine if it is possible for Aoki to perform this task and if yes, find the minimum cost required.
Constraints
* 1 \leq N \leq 50
* 0 \leq a_{i}, b_{i} \leq 50
* All values in the input are integers.
Input
Input is given from Standard Input in the following format:
N
a_{1} a_{2} ... a_{N}
b_{1} b_{2} ... b_{N}
Output
Print the minimum cost required to turn the original sequence into b_{1}, b_{2}, ..., b_{N}. If the task is impossible, output -1 instead.
Examples
Input
3
19 10 14
0 3 4
Output
160
Input
3
19 15 14
0 0 0
Output
2
Input
2
8 13
5 13
Output
-1
Input
4
2 0 1 8
2 0 1 8
Output
0
Input
1
50
13
Output
137438953472
|
#include <iostream>
using namespace std;
const int lim = 50;
int n, a[55], b[55]; long long c[55]; bool dp[55][55][55];
int main() {
for (int i = 0; i <= lim; i++) dp[0][i][i] = true;
for (int i = 1; i <= lim; i++) {
for (int j = 0; j <= lim; j++) {
for (int k = 0; k <= j; k++) {
dp[i][j][k] = dp[i - 1][j][k] || dp[i - 1][j % i][k];
}
}
}
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i], c[i] = 1LL << a[i];
for (int i = 0; i < n; i++) cin >> b[i];
bool feasible = true;
for (int i = 0; i < n; i++) feasible = feasible && dp[lim][a[i]][b[i]];
if (!feasible) cout << "-1\n";
else {
long long ret = 0;
for (int i = lim; i >= 1; i--) {
bool change = false;
for (int j = 0; j < n; j++) {
bool unchange = false;
for (int k = 0; k <= lim; k++) {
if (dp[i - 1][k][b[j]] && ((c[j] >> k) & 1)) {
unchange = true;
}
}
if (!unchange) change = true;
}
if (change) {
for (int j = 0; j < n; j++) {
for (int k = i; k <= lim; k++) {
if ((c[j] >> k) & 1) c[j] |= 1LL << (k % i);
}
}
ret |= 1LL << i;
}
}
cout << ret << "\n";
}
return 0;
}
|
The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.
He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.
To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.
How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9(1\leq i\leq N)
* 1 \leq B_i \leq 10^9(1\leq i\leq N)
* 1 \leq C_i \leq 10^9(1\leq i\leq N)
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N
Output
Print the number of different altars that Ringo can build.
Examples
Input
2
1 5
2 4
3 6
Output
3
Input
3
1 1 1
2 2 2
3 3 3
Output
27
Input
6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288
Output
87
|
def main(n,a,b,c):
import bisect
ans=0
for i in range(n):
na=bisect.bisect_left(a,b[i])
nc=n-bisect.bisect_right(c,b[i])
ans+=na*nc
print(ans)
if __name__=='__main__':
n=int(input())
a=sorted(list(map(int,input().split())))
b=sorted(list(map(int,input().split())))
c=sorted(list(map(int,input().split())))
main(n,a,b,c)
|
There is a bar of chocolate with a height of H blocks and a width of W blocks. Snuke is dividing this bar into exactly three pieces. He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.
Snuke is trying to divide the bar as evenly as possible. More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece. Find the minimum possible value of S_{max} - S_{min}.
Constraints
* 2 ≤ H, W ≤ 10^5
Input
Input is given from Standard Input in the following format:
H W
Output
Print the minimum possible value of S_{max} - S_{min}.
Examples
Input
3 5
Output
0
Input
4 5
Output
2
Input
5 5
Output
4
Input
100000 2
Output
1
Input
100000 100000
Output
50000
|
h,w = sorted(list(map(int,input().split())))
if h % 3 == 0 or w % 3 == 0:
ans = 0
else:
c1 = ((w//3+1)*h)-((w-1-w//3)*(h//2))
c2 = ((w-w//3)*(h-h//2))-(w//3*h)
c3 = h
c4 = ((h//3+1)*w)-((h-1-h//3)*(w//2))
c5 = ((h-h//3)*(w-w//2))-(h//3*w)
ans = min(c1,c2,c3,c4,c5)
print(ans)
|
Welcome to CODE FESTIVAL 2016! In order to celebrate this contest, find a string s that satisfies the following conditions:
* The length of s is between 1 and 5000, inclusive.
* s consists of uppercase letters.
* s contains exactly K occurrences of the string "FESTIVAL" as a subsequence. In other words, there are exactly K tuples of integers (i_0, i_1, ..., i_7) such that 0 ≤ i_0 < i_1 < ... < i_7 ≤ |s|-1 and s[i_0]='F', s[i_1]='E', ..., s[i_7]='L'.
It can be proved that under the given constraints, the solution always exists. In case there are multiple possible solutions, you can output any.
Constraints
* 1 ≤ K ≤ 10^{18}
Input
The input is given from Standard Input in the following format:
K
Output
Print a string that satisfies the conditions.
Examples
Input
7
Output
FESSSSSSSTIVAL
Input
256
Output
FFEESSTTIIVVAALL
|
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 600;
long long dp[8];
long long bs[N + 7];
long long a[N + 7];
int main() {
ios_base::sync_with_stdio(0);
dp[0] = bs[0] = 1;
for(int i = 1; i <= N; ++i) {
for(int j = 1; j <= 7; ++j) dp[j] += dp[j - 1];
bs[i] = dp[7];
}
int ile = 7 * N;
long long k;
cin >> k;
for(int i = N; i > 0; --i) {
a[i] = k / bs[i];
k -= a[i] * bs[i];
ile += a[i];
}
for(int i = 1; i <= N; ++i) {
cout << "FESTIVA";
for(int j = 0; j < a[i]; ++j) cout << 'L';
}
return 0;
}
|
We have N pieces of ropes, numbered 1 through N. The length of piece i is a_i.
At first, for each i (1≤i≤N-1), piece i and piece i+1 are tied at the ends, forming one long rope with N-1 knots. Snuke will try to untie all of the knots by performing the following operation repeatedly:
* Choose a (connected) rope with a total length of at least L, then untie one of its knots.
Is it possible to untie all of the N-1 knots by properly applying this operation? If the answer is positive, find one possible order to untie the knots.
Constraints
* 2≤N≤10^5
* 1≤L≤10^9
* 1≤a_i≤10^9
* All input values are integers.
Input
The input is given from Standard Input in the following format:
N L
a_1 a_2 ... a_n
Output
If it is not possible to untie all of the N-1 knots, print `Impossible`.
If it is possible to untie all of the knots, print `Possible`, then print another N-1 lines that describe a possible order to untie the knots. The j-th of those N-1 lines should contain the index of the knot that is untied in the j-th operation. Here, the index of the knot connecting piece i and piece i+1 is i.
If there is more than one solution, output any.
Examples
Input
3 50
30 20 10
Output
Possible
2
1
Input
2 21
10 10
Output
Impossible
Input
5 50
10 20 30 40 50
Output
Possible
1
2
3
4
|
N, L = map(int, input().split())
a = [int(x) for x in input().split()]
ans = False
for i in range(N-1):
if a[i] + a[i+1] >= L:
ans = True
break
if ans:
print('Possible')
for j in range(i):
print(j+1)
for j in range(N-2, i-1, -1):
print(j+1)
else:
print('Impossible')
|
One day, the lord ordered a carpenter to "build a sturdy and large building where the townspeople could evacuate in the event of a typhoon or earthquake." However, large thick pillars are needed to complete the sturdy and large building. There is no such big pillar in the town. So the carpenter decided to go to a distant mountain village to procure a large pillar (the carpenter would have to go from town to satoyama and back in town).
The carpenter's reward is the remainder of the money received from the lord minus the pillar price and transportation costs. As shown in the map below, there are many highways that pass through various towns to reach the mountain village, and the highways that connect the two towns have different transportation costs. How do you follow the road and procure to maximize the carpenter's reward? Create a program that outputs the maximum carpenter's reward. However, if the number of towns is n, then each town is identified by an integer from 1 to n. There are no more than one road that connects the two towns directly.
<image>
* The numbers on the arrows indicate the transportation costs to go in that direction.
Input
The input is given in the following format:
n
m
a1, b1, c1, d1
a2, b2, c2, d2
::
am, bm, cm, dm
s, g, V, P
The first line gives the total number of towns n (n ≤ 20), and the second line gives the total number of roads m (m ≤ 100). The following m lines are given the i-th road information ai, bi, ci, di (1 ≤ ai, bi ≤ n, 0 ≤ ci, di ≤ 1,000). ai and bi are the numbers of the towns connected to the highway i, ci is the transportation cost from ai to bi, and di is the transportation cost from bi to ai.
On the last line, the number s of the town where the carpenter departs, the number g of the mountain village with the pillar, the money V received by the carpenter from the lord, and the price P of the pillar are given.
Output
Output the carpenter's reward (integer) on one line.
Example
Input
6
8
1,2,2,2
1,3,4,3
1,4,4,2
2,5,3,2
3,4,4,2
3,6,1,2
4,6,1,1
5,6,1,2
2,4,50,30
Output
11
|
#include <iostream>
using namespace std;
static const int INF = 9999999;
void solve()
{
int n, m;
cin >> n >> m;
int d[21][21];
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
d[i][j] = INF;
}
}
char c;
for(int i = 0; i < m; ++i)
{
int a1, b1, c1, d1;
cin >> a1 >> c >> b1 >> c >> c1 >> c >> d1;
--a1;
--b1;
d[a1][b1] = c1;
d[b1][a1] = d1;
}
for(int k = 0; k < n; ++k)
{
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
int x1, x2, y1, y2;
cin >> x1 >> c >> x2 >> c >> y1 >> c >> y2;
--x1;
--x2;
cout << y1 - y2 - d[x1][x2] - d[x2][x1] << endl;
}
int main()
{
solve();
return(0);
}
|
Aika's house runs a small coffee shop. The scones baked by Aika's mother were very delicious and the shop was very prosperous.
One of the jobs of Aika, a waitress, is to deliver the scones that are baked one after another to the customer's seat. The baked scones are placed on a tray and lined up on the counter. Let Ki be the number of scones on the i-th tray. Aika must carry exactly m scones to each customer. Aika can have as many trays as she wants at a time, and can distribute scones from multiple trays to one customer, or from one tray to multiple customers.
There are so many customers coming to the coffee shop that even if you carry all the scones on the counter, you cannot deliver them to all of them. However, after reaching as many customers as possible, there may be less than m scones left over. Such scones will be given to Aika as a reward for helping.
Suddenly, Aika thought about it. If you deliver scones to customers with only some trays instead of having all the trays at once, the number of surplus scones will be different. With proper tray selection, you may be able to leave more scones. Aika decided to choose one continuous range of trays on the counter so that her mother wouldn't notice that she was deliberately choosing trays. Also, since the remaining trays are carried by fathers and mothers, Aika has only one chance to get scones.
By the way, how many scones can Aika get? Write a program to calculate. The number of trays n is 1 or more and 30,000 or less, and m is 1 or more and 100,000 or less. Also, each element Ki of the sequence is 0 or more and 232-1.
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 as follows.
1st line n m (integer integer; half-width space delimited)
2nd line Scone information on Obon K1 K2 ... Kn (all integers; half-width space delimited)
Ki: Number of scones on the i-th tray
The number of datasets does not exceed 50.
output
Outputs the maximum number of scones you can get for each dataset on one line.
Example
Input
5 11
11 27 34 45 56
8 5
0 2 1 5 4 6 8 3
5 2
2 4 2 4 6
10 18
10 15 12 31 12 50 11 23 43 181
1 100
5
0 0
Output
8
4
0
17
5
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<ll, ll> P;
#define EACH(i,a) for (auto& i : a)
#define FOR(i,a,b) for (ll i=(a);i<(b);i++)
#define RFOR(i,a,b) for (ll i=(b)-1;i>=(a);i--)
#define REP(i,n) for (ll i=0;i<(n);i++)
#define RREP(i,n) for (ll i=(n)-1;i>=0;i--)
#define debug(x) cout<<#x<<": "<<x<<endl
#define pb push_back
#define ALL(a) (a).begin(),(a).end()
const ll linf = 1e18;
const int inf = 1e9;
const double eps = 1e-12;
const double pi = acos(-1);
template<typename T>
istream& operator>>(istream& is, vector<T>& vec) {
EACH(x,vec) is >> x;
return is;
}
template<typename T>
ostream& operator<<(ostream& os, vector<T>& vec) {
REP(i,vec.size()) {
if (i) os << " ";
os << vec[i];
}
return os;
}
template<typename T>
ostream& operator<<(ostream& os, vector< vector<T> >& vec) {
REP(i,vec.size()) {
if (i) os << endl;
os << vec[i];
}
return os;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
ll n, m;
while ( cin >> n >> m, n || m ) {
vector<ll> v(n); cin >> v;
REP(i, n) v[i] %= m;
REP(i, n-1) v[i+1] = (v[i]+v[i+1])%m;
set<ll> s; s.insert(0);
ll ans = 0;
REP(i, n) {
ans = max(ans, v[i]);
if ( s.upper_bound(v[i]) != s.end() ) {
ans = max(ans, (v[i]-*s.upper_bound(v[i])+m)%m);
}
s.insert(v[i]);
}
cout << ans << endl;
}
}
|
Consider a string with rings on both ends. Rings have positive integers to distinguish them. Rings on both ends of the string have different numbers a and b. Describe this as [a, b]. If there are multiple strings and the number attached to the ring of one string and the other string is the same, these strings can be connected at that ring, and the one made by connecting is called a chain. For example, the strings [1, 3] and [3, 4] form the chain [1, 3, 4]. The string and the chain or the chains are also connected at the ring with the same integer. Suppose you can.
For example, a chain [1, 3, 4] and a string [5, 1] can form [5, 1, 3, 4], and a chain [1, 3, 4] and a chain [2, 3, 5] can form [5, 1, 3, 4]. The chain [1, 3, 4] and the chain [4, 6, 1] form a ring.
There are various shapes like this, but in some of them, rings with the same number follow only once. Multiple connected strings are called chains. For example, chains [1, 3, 4] The centrally crossed shape of the chains [2, 3, 5] also includes the chains [1, 3, 5], [2, 3, 4], and the chains [1, 3, 4]. And chains [4, 6, 1] loops include chains such as [1, 3, 4, 6], [3, 4, 6, 1], [4, 6, 1, 3]. ..
For these chains, the number contained is defined as the length. For a given number of strings, anything that can be connected can form a shape that contains one or more chains. Create a program to find the length of the chain.
The first line of the input data contains the number of strings, the positive integer 1 ≤ n ≤ 100, and each of the following n lines contains two integers a, b separated by blanks 1 ≤ a <b ≤ 100. The two integers in each line represent the integers at both ends of one string.
Input example 1 | Input example 2 | Input example 3
--- | --- | ---
|
7 | 6 | 7
1 3 | 1 2 | 1 3
3 4 | 2 3 | 2 4
1 4 | 3 4 | 3 5
2 7 | 4 5 | 4 6
5 7 | 1 5 | 6 7
6 7 | 2 6 | 2 6
1 7 | | 4 7
Output example 1 | Output example 2 | Output example 3
5 | 6 | 4
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 10.
output
For each dataset, the maximum chain length is output on one line.
Example
Input
7
1 3
3 4
1 4
2 7
5 7
6 7
1 7
6
1 2
2 3
3 4
4 5
1 5
2 6
7
1 3
2 4
3 5
4 6
6 7
2 6
4 7
0
Output
5
6
4
|
#include<cstdio>
#include<stack>
#include<vector>
using namespace std;
vector<int> vec[101];
bool ch[101]={};
bool visited[101]={};
int dp[101]={};
int maxx = -1;
int maxNODE = -1;
void DFS(int i,int val){
if(val > maxx)maxx = val;
dp[i] = max(dp[i],val);
int len = vec[i].size();
for (int k=0; k<len; k++) {
if(!ch[vec[i][k]]){
visited[vec[i][k]] = true;
ch[vec[i][k]] = true;
DFS(vec[i][k],val+1);
ch[vec[i][k]] = false;
}
}
}
int main(){
maxx = -1;
maxNODE = -1;
int n,a,b;
scanf("%d",&n);
if(n == 0)return 0;
for (int i=0; i<n; i++) {
scanf("%d %d",&a,&b);
vec[a].push_back(b);
vec[b].push_back(a);
if(a>b)if(maxNODE < a)maxNODE = a;
if(a<b)if(maxNODE < b)maxNODE = b;
}
for (int i=1; i<=maxNODE; i++) {
if(!visited[i]){
visited[i] = true;
ch[i] = true;
DFS(i,1);
ch[i] = false;
}
}
for (int i=1; i<=maxNODE; i++) {
if(maxx == dp[i]){
ch[i] = true;
DFS(i,1);
ch[i] = false;
break;
}
}
printf("%d\n",maxx);
for (int i=1; i<=maxNODE; i++) {
visited[i] = false;
dp[i] = 0;
vec[i].clear();
}
main();
}
|
Ito joined the Kyudo club after entering high school. At first, I had a hard time because the arrow didn't reach the target, but in the fall of my first year of high school, I managed to improve to the point where the arrow reached the target.
One day, my senior Kato suggested, "Why don't you participate in a recent Kyudo competition?" Ito is ready to take on the challenge of the first tournament.
In the near-field competition, four lines are shot (shooting arrows) at a time, and the number of hits (the number of hits) is recorded. Repeat this multiple times to compete for the total number of hits.
For Ito-kun, who is practicing hard for the tournament, Kato-kun decided to create a program that can calculate the total middle number assuming the actual performance.
This program reads the total number of shots n and the number of hits each time, and outputs the total number of hits.
For example, if the total number of shots is 20, then 4 lines are shot 5 times at a time, so enter the number of hits 5 times.
Input
Multiple datasets are given as input.
The first line of each dataset is given n (an integer that is a multiple of 4). Then n / 4 integers are given on each line to indicate the number of hits each time.
When n is 0, it indicates the end of input. Do not output to this input.
Output
For each dataset, print the total middle number on one line.
Example
Input
20
4
3
2
1
3
8
2
0
0
Output
13
2
|
#include<iostream>
using namespace std;
int main() {
int n;
while (cin >> n,n) {
int SUM = 0;
for (int i = 1; i <= n / 4; i++) {
int a;
cin >> a;
SUM += a;
}
cout << SUM << endl;
}
return 0;
}
|
Anchored Balloon
A balloon placed on the ground is connected to one or more anchors on the ground with ropes. Each rope is long enough to connect the balloon and the anchor. No two ropes cross each other. Figure E-1 shows such a situation.
<image>
Figure E-1: A balloon and ropes on the ground
Now the balloon takes off, and your task is to find how high the balloon can go up with keeping the rope connections. The positions of the anchors are fixed. The lengths of the ropes and the positions of the anchors are given. You may assume that these ropes have no weight and thus can be straightened up when pulled to whichever directions. Figure E-2 shows the highest position of the balloon for the situation shown in Figure E-1.
<image>
Figure E-2: The highest position of the balloon
Input
The input consists of multiple datasets, each in the following format.
> n
> x1 y1 l1
> ...
> xn yn ln
>
The first line of a dataset contains an integer n (1 ≤ n ≤ 10) representing the number of the ropes. Each of the following n lines contains three integers, xi, yi, and li, separated by a single space. Pi = (xi, yi) represents the position of the anchor connecting the i-th rope, and li represents the length of the rope. You can assume that −100 ≤ xi ≤ 100, −100 ≤ yi ≤ 100, and 1 ≤ li ≤ 300. The balloon is initially placed at (0, 0) on the ground. You can ignore the size of the balloon and the anchors.
You can assume that Pi and Pj represent different positions if i ≠ j. You can also assume that the distance between Pi and (0, 0) is less than or equal to li−1. This means that the balloon can go up at least 1 unit high.
Figures E-1 and E-2 correspond to the first dataset of Sample Input below.
The end of the input is indicated by a line containing a zero.
Output
For each dataset, output a single line containing the maximum height that the balloon can go up. The error of the value should be no greater than 0.00001. No extra characters should appear in the output.
Sample Input
3
10 10 20
10 -10 20
-10 10 120
1
10 10 16
2
10 10 20
10 -10 20
2
100 0 101
-90 0 91
2
0 0 53
30 40 102
3
10 10 20
10 -10 20
-10 -10 20
3
1 5 13
5 -3 13
-3 -3 13
3
98 97 168
-82 -80 193
-99 -96 211
4
90 -100 160
-80 -80 150
90 80 150
80 80 245
4
85 -90 290
-80 -80 220
-85 90 145
85 90 170
5
0 0 4
3 0 5
-3 0 5
0 3 5
0 -3 5
10
95 -93 260
-86 96 211
91 90 177
-81 -80 124
-91 91 144
97 94 165
-90 -86 194
89 85 167
-93 -80 222
92 -84 218
0
Output for the Sample Input
17.3205081
16.0000000
17.3205081
13.8011200
53.0000000
14.1421356
12.0000000
128.3928757
94.1879092
131.1240816
4.0000000
72.2251798
Example
Input
3
10 10 20
10 -10 20
-10 10 120
1
10 10 16
2
10 10 20
10 -10 20
2
100 0 101
-90 0 91
2
0 0 53
30 40 102
3
10 10 20
10 -10 20
-10 -10 20
3
1 5 13
5 -3 13
-3 -3 13
3
98 97 168
-82 -80 193
-99 -96 211
4
90 -100 160
-80 -80 150
90 80 150
80 80 245
4
85 -90 290
-80 -80 220
-85 90 145
85 90 170
5
0 0 4
3 0 5
-3 0 5
0 3 5
0 -3 5
10
95 -93 260
-86 96 211
91 90 177
-81 -80 124
-91 91 144
97 94 165
-90 -86 194
89 85 167
-93 -80 222
92 -84 218
0
Output
17.3205081
16.0000000
17.3205081
13.8011200
53.0000000
14.1421356
12.0000000
128.3928757
94.1879092
131.1240816
4.0000000
72.2251798
|
#include <iostream>
#include <vector>
#include <complex>
#include <iomanip>
using namespace std;
typedef complex<double> P;
const double EPS = 1e-10;
int n;
double l[10];
struct C {
P p;
double r;
C() {
p = P(0, 0);
r = 0;
}
C(const P& p, double r) : p(p), r(r) {
}
bool in(P t) {
return norm(p - t) < r * r + EPS;
}
bool in(C t) {
return abs(p - t.p) + t.r < r + EPS;
}
} c[10];
bool check(double h) {
for (int i = 0; i < n; i++) {
if (l[i] * l[i] - h * h < EPS) return false;
c[i].r = sqrt(l[i] * l[i] - h * h);
}
vector<P> cs;
for (int i = 0; i < n; i++) {
cs.push_back(c[i].p);
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
C c1 = c[i], c2 = c[j];
if (abs(c1.p - c2.p) > c1.r + c2.r) return false; // ????????????
if (c1.in(c2) || c2.in(c1)) continue;
P v = c2.p - c1.p;
double t = (c1.r * c1.r + norm(v) - c2.r * c2.r) / (2 * abs(v));
double theta = acos(t / c1.r);
P b[2];
b[0] = c1.p + v / abs(v) * c1.r * polar(1.0, theta);
b[1] = c1.p + v / abs(v) * c1.r * polar(1.0, -theta);
cs.push_back(b[0]);
cs.push_back(b[1]);
}
}
for (int i = 0; i < cs.size(); i++) {
bool flag = true;
for (int m = 0; m < n; m++) {
if (!c[m].in(cs[i])) {
flag = false;
break;
}
}
if (flag) return true;
}
return false;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
while (cin >> n , n) {
for (int i = 0; i < n; i++) {
double x, y;
cin >> x >> y >> l[i];
c[i].p = P(x, y);
}
check(0);
double ok = 1, ng = 300;
for (int loop = 0; loop < 100; loop++) {
double h = (ok + ng) / 2;
if (check(h)) ok = h;
else ng = h;
}
cout << setprecision(15) << ok << endl;
}
}
|
You are given a set of circles C of a variety of radii (radiuses) placed at a variety of positions, possibly overlapping one another. Given a circle with radius r, that circle may be placed so that it encircles all of the circles in the set C if r is large enough.
There may be more than one possible position of the circle of radius r to encircle all the member circles of C. We define the region U as the union of the areas of encircling circles at all such positions. In other words, for each point in U, there exists a circle of radius r that encircles that point and all the members of C. Your task is to calculate the length of the periphery of that region U.
Figure I.1 shows an example of the set of circles C and the region U. In the figure, three circles contained in C are expressed by circles of solid circumference, some possible positions of the encircling circles are expressed by circles of dashed circumference, and the area U is expressed by a thick dashed closed curve.
<image>
Input
The input is a sequence of datasets. The number of datasets is less than 100.
Each dataset is formatted as follows.
n r
x1 y1 r1
x2 y2 r2
.
.
.
xn yn rn
The first line of a dataset contains two positive integers, n and r, separated by a single space. n means the number of the circles in the set C and does not exceed 100. r means the radius of the encircling circle and does not exceed 1000.
Each of the n lines following the first line contains three integers separated by a single space. (xi, yi) means the center position of the i-th circle of the set C and ri means its radius.
You may assume −500≤xi ≤500, −500≤yi ≤500, and 1≤ri ≤500.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output a line containing a decimal fraction which means the length of the periphery (circumferential length) of the region U.
The output should not contain an error greater than 0.01. You can assume that, when r changes by ε (|ε| < 0.0000001), the length of the periphery of the region U will not change more than 0.001.
If r is too small to cover all of the circles in C, output a line containing only 0.0.
No other characters should be contained in the output.
Example
Input
1 10
5 5 7
2 12
5 5 7
8 6 3
3 10
3 11 2
2 1 1
2 16 3
3 15
-5 2 5
9 2 9
5 8 6
3 38
-25 -10 8
30 5 7
-3 35 11
3 39
-25 -10 8
30 5 7
-3 35 11
3 800
-400 400 2
300 300 1
300 302 1
3 800
400 -400 2
300 300 1
307 300 3
8 147
130 80 12
130 -40 12
-110 80 12
-110 -40 12
70 140 12
70 -100 12
-50 140 12
-50 -100 12
3 493
345 154 10
291 111 75
-275 -301 46
4 55
54 0 1
40 30 5
27 36 10
0 48 7
3 30
0 3 3
-3 0 4
400 0 3
3 7
2 3 2
-5 -4 2
-4 3 2
3 10
-5 -4 5
2 3 5
-4 3 5
4 6
4 6 1
5 5 1
1 7 1
0 1 1
3 493
345 154 10
291 111 75
-275 -301 46
5 20
-9 12 5
0 15 5
3 -3 3
12 9 5
-12 9 5
0 0
Output
81.68140899333463
106.81415022205297
74.11215318612639
108.92086846105579
0.0
254.85616536128433
8576.936716409238
8569.462129048667
929.1977057481128
4181.124698202453
505.09134735536804
0.0
46.82023824234038
65.66979416387915
50.990642291793506
4181.124698202453
158.87951420768937
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
void run() {
Scanner sc = new Scanner(System.in);
while (true) {
int n = sc.nextInt();
double R = sc.nextDouble();
if (n == 0 && R == 0)
break;
double[] x = new double[n];
double[] y = new double[n];
double[] r = new double[n];
Circle[] cs = new Circle[n];
for (int i = 0; i < n; ++i) {
x[i] = sc.nextDouble();
y[i] = sc.nextDouble();
r[i] = sc.nextDouble();
cs[i] = new Circle(new P(x[i], y[i]), r[i]);
}
solve(n, R, x, y, r, cs);
}
}
void solve(int n, double R, double[] x, double[] y, double[] r, Circle[] cs) {
int curIdx = -1;
int preIdx = -1;
int dirIdx = -1;
@SuppressWarnings("unchecked")
ArrayList<Circle>[][] enCs = new ArrayList[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
enCs[i][j] = new ArrayList<>();
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i == j)
continue;
if (cs[i].center.dist(cs[j].center) + cs[i].r + cs[j].r > 2 * R)
continue;
if (cs[i].center.dist(cs[j].center) + Math.min(cs[i].r, cs[j].r) <= Math.max(cs[i].r, cs[j].r))
continue;
ArrayList<Circle> tmp = calc(cs[i], cs[j], R);
for (Circle c : tmp) {
if (encircleAll(cs, c) && noDumy(cs, cs[i], c) && noDumy(cs, cs[j], c)) {
enCs[i][j].add(c);
}
}
for (int k = 0; k < enCs[i][j].size(); ++k) {
curIdx = i;
preIdx = j;
dirIdx = k;
}
}
}
if (curIdx == -1 && preIdx == -1 && dirIdx == -1) {
for (int i = 0; i < n; ++i) {
if (encircleAll(cs, cs[i])) {
System.out.println((2 * R - r[i]) * 2 * Math.PI);
return;
}
}
System.out.println("0.0");
return;
}
double ans = 0;
int fCurIdx = curIdx;
int fPreIdx = preIdx;
int fDirIdx = dirIdx;
int nIdx = -1;
int nDirIdx = -1;
double totAng = 0;
do {
for (int i = 0; i < n; ++i) {
if (i == curIdx)
continue;
for (int j = 0; j < enCs[i][curIdx].size(); ++j) {
if ((nIdx == -1 && nDirIdx == -1)) {
nIdx = i;
nDirIdx = j;
continue;
}
double candAng = enCs[curIdx][preIdx].get(dirIdx).center.sub(cs[curIdx].center)
.ang(enCs[i][curIdx].get(j).center.sub(cs[curIdx].center));
double curAng = enCs[curIdx][preIdx].get(dirIdx).center.sub(cs[curIdx].center)
.ang(enCs[nIdx][curIdx].get(nDirIdx).center.sub(cs[curIdx].center));
if (curAng < 1e-6 || (candAng > 1e-6 && candAng < curAng)) {
nIdx = i;
nDirIdx = j;
} else if (Math.abs(curAng - candAng) < 1e-6) {
double curAng2 = cs[nIdx].center.sub(cs[curIdx].center)
.ang(enCs[nIdx][curIdx].get(nDirIdx).center.sub(cs[curIdx].center));
double candAng2 = cs[i].center.sub(cs[curIdx].center)
.ang(enCs[i][curIdx].get(j).center.sub(cs[curIdx].center));
if (candAng2 < curAng2) {
nIdx = i;
nDirIdx = j;
}
}
}
}
Circle c = enCs[curIdx][preIdx].get(dirIdx);
// System.out.printf("(x-%.0f)^2+(y-%.0f)^2=%.0f^2,\n", c.center.x, c.center.y, c.r);
double ang = enCs[curIdx][preIdx].get(dirIdx).center.sub(cs[curIdx].center)
.ang(enCs[nIdx][curIdx].get(nDirIdx).center.sub(cs[curIdx].center));
ans += (2 * R - r[curIdx]) * ang;
ans += R * (enCs[nIdx][curIdx].get(nDirIdx).center.sub(cs[curIdx].center)
.ang(enCs[nIdx][curIdx].get(nDirIdx).center.sub(cs[nIdx].center)));
totAng += ang + (enCs[nIdx][curIdx].get(nDirIdx).center.sub(cs[curIdx].center)
.ang(enCs[nIdx][curIdx].get(nDirIdx).center.sub(cs[nIdx].center)));
preIdx = curIdx;
curIdx = nIdx;
dirIdx = nDirIdx;
nIdx = -1;
nDirIdx = -1;
} while (2 * Math.PI - totAng > 1e-6);
System.out.println(ans);
}
boolean encircleAll(Circle[] cs, Circle en) {
for (Circle c : cs) {
if (en.center.dist(c.center) + c.r > en.r + 1e-6)
return false;
}
return true;
}
boolean noDumy(Circle[] cs, Circle c, Circle enC) {
ArrayList<Circle> lis = new ArrayList<>();
for (Circle a : cs) {
if (Math.abs(a.center.dist(enC.center) + a.r - enC.r) < 1e-6) {
lis.add(a);
}
}
Collections.sort(lis, new Comparator<Circle>() {
@Override
public int compare(Circle o1, Circle o2) {
return Double.compare(o1.center.sub(enC.center).crossPrd(o2.center.sub(enC.center)), 0);
}
});
ArrayList<Circle> cand = new ArrayList<>();
cand.add(lis.get(0));
cand.add(lis.get(lis.size() - 1));
for (Circle a : cand) {
if (Math.abs(a.center.x - c.center.x) + Math.abs(a.center.y - c.center.y) < 1e-6)
return true;
}
return false;
}
class Circle {
P center;
double r;
int idx = -1;
public Circle(P center, double r) {
this.center = center;
this.r = r;
}
public Circle(P center, double r, int idx) {
this.center = center;
this.r = r;
this.idx = idx;
}
}
ArrayList<Circle> calc(Circle c1, Circle c2, double R) {
Circle C1 = new Circle(c1.center, R - c1.r);
Circle C2 = new Circle(c2.center, R - c2.r);
ArrayList<Circle> ret = new ArrayList<>();
double d = C1.center.dist(C2.center);
double cos = (C1.r * C1.r + d * d - C2.r * C2.r) / (2 * d * C1.r);
P p12 = C2.center.sub(C1.center);
P midP = C1.center.add(p12.normalize().mul(C1.r * cos));
double h = C1.r * Math.sqrt(1 - cos * cos);
ret.add(new Circle(midP.add(p12.normalize().rot(Math.PI / 2).mul(h)), R));
if (Math.abs(h) > 1e-6)
ret.add(new Circle(midP.add(p12.normalize().rot(Math.PI / 2).mul(-h)), R));
return ret;
}
class P implements Comparable<P> {
double x, y;
public P(double x, double y) {
this.x = x;
this.y = y;
}
double norm() {
return Math.sqrt(x * x + y * y);
}
P normalize() {
return this.mul(1 / this.norm());
}
P add(P p) {
return new P(x + p.x, y + p.y);
}
P sub(P p) {
return this.add(p.mul(-1));
}
P mul(double coe) {
return new P(x * coe, y * coe);
}
double dist(P p) {
return Math.sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
}
P rot(double ang) {
double c = Math.cos(ang);
double s = Math.sin(ang);
return new P(c * x - s * y, s * x + c * y);
}
double crossPrd(P p) {
return x * p.y - y * p.x;
}
double innerPrd(P o) {
return x * o.x + y * o.y;
}
double ang(P o) {
double cos = innerPrd(o) / (norm() * o.norm());
if (Math.abs(cos) > 1 + 1e-6)
throw new AssertionError();
if (Math.abs(cos) > 1) {
cos = Math.signum(cos);
}
return Math.acos(cos);
}
@Override
public int compareTo(P o) {
if (Math.abs(x - o.x) > 1e-6)
return Double.compare(x, o.x);
else {
return Double.compare(y, o.y);
}
}
}
void tr(Object... objects) {
System.out.println(Arrays.deepToString(objects));
}
}
|
Problem
Beans are popular at Otsu University. N beans are lined up in a straight line. Each is numbered from 0 to N-1, and the hardness of the i-th bean is ai.
Cyan considers the ideal bean hardness to be D. However, Cyan doesn't want to go get the beans that are too far away because he is troublesome. Therefore, Cyan wants to know the beans whose hardness is closest to D among the l-th to r-th beans.
Cyan asks Q questions, so create a program to find the minimum value of | bean hardness − D | in the closed interval [l, r] for each question. (However, | a | represents the absolute value of a.)
Constraints
The input satisfies the following constraints.
* 1 ≤ N ≤ 105
* 0 ≤ | ai | ≤ 106 (0 ≤ i ≤ N−1)
* 1 ≤ Q ≤ 105
* 0 ≤ Di ≤ 106
* 0 ≤ li ≤ ri ≤ N-1
Input
The input is given in the following format.
N
a0 a1 ... aN−1
Q
l0 r0 D0
l1 r1 D1
..
..
..
lQ−1 rQ−1 DQ−1
The first line is given one integer N. On the second line, N integers are given, separated by blanks. On the third line, the number of queries is given as one integer Q. The query values l, r, and D are given in the following 4 to 3 + Q lines.
Output
For each query, output the absolute value of the difference between D and the hardness of the bean closest to hardness D among the [l, r] th beans on one line.
Examples
Input
3
1 2 3
3
0 2 2
0 2 4
0 0 2
Output
0
1
1
Input
10
4 5 0 21 9 100 12 9 0 8
5
0 3 20
2 5 100
8 9 9
5 5 10
0 9 20
Output
1
0
1
90
1
|
#include <iostream>
#include <vector>
#include <array>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <tuple>
#include <bitset>
#include <memory>
#include <cmath>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <numeric>
#include <climits>
#include <cfloat>
class SegNearTree {
std::vector<std::vector<std::vector<int>>> vec;
int inner_find(int depth, int from, int until, const int target) const {
if (from >= until) return INT_MAX;
auto length = 1 << depth;
auto mid = (from + length - 1) / length * length;
if (mid + length <= until) {
return std::min({ inner_find(depth, from, mid, target), inner_find(depth, mid + length, until, target), take_nearest(depth, mid / length, target) });
}
else if (mid < until) {
return std::min(inner_find(depth - 1, from, mid, target), inner_find(depth - 1, mid, until, target));
}
else {
return inner_find(depth - 1, from, until, target);
}
}
int take_nearest(int depth, int position, const int target) const {
auto upper = std::lower_bound(vec[depth][position].begin(), vec[depth][position].end(), target);
if (upper == vec[depth][position].begin()) return std::abs(target - *upper);
if (upper == vec[depth][position].end()) return std::abs(target - *std::prev(upper));
return std::min(std::abs(target - *upper), std::abs(target - *std::prev(upper)));
}
public:
SegNearTree(const std::vector<int>& state) :vec{ std::vector<std::vector<int>>() } {
for (const auto a : state) vec.back().push_back({ a });
while (vec.back().size() > 1) {
std::vector<std::vector<int>> last;
for (auto i = 0; i * 2 + 1 < vec.back().size(); ++i) {
std::vector<int> v; v.reserve(vec.back()[i * 2].size() + vec.back()[i * 2 + 1].size());
std::copy(vec.back()[i * 2].begin(), vec.back()[i * 2].end(), std::back_inserter(v));
std::copy(vec.back()[i * 2 + 1].begin(), vec.back()[i * 2 + 1].end(), std::back_inserter(v));
std::sort(v.begin(), v.end());
last.push_back(std::move(v));
}
vec.push_back(std::move(last));
}
}
int find_nearest(int from, int until, const int target) { return inner_find(vec.size() - 1, from, until, target); }
};
int main() {
int n; std::cin >> n;
std::vector<int> beans(n); for (auto& b : beans) std::cin >> b;
SegNearTree seg(beans);
int q; std::cin >> q;
for (auto i = 0; i < q; ++i) {
int l, r, d; std::cin >> l >> r >> d;
std::cout << seg.find_nearest(l, r + 1, d) << '\n';
}
}
|
HCII, the health committee for interstellar intelligence, aims to take care of the health of every interstellar intelligence.
Staff of HCII uses a special equipment for health checks of patients. This equipment looks like a polygon-shaped room with plenty of instruments. The staff puts a patient into the equipment, then the equipment rotates clockwise to diagnose the patient from various angles. It fits many species without considering the variety of shapes, but not suitable for big patients. Furthermore, even if it fits the patient, it can hit the patient during rotation.
<image>
Figure 1: The Equipment used by HCII
The interior shape of the equipment is a polygon with M vertices, and the shape of patients is a convex polygon with N vertices. Your job is to calculate how much you can rotate the equipment clockwise without touching the patient, and output the angle in degrees.
Input
The input consists of multiple data sets, followed by a line containing “0 0”. Each data set is given as follows:
M N
px1 py1 px2 py2 ... pxM pyM
qx1 qy1 qx2 qy2 ... qxN qyN
cx cy
The first line contains two integers M and N (3 ≤ M, N ≤ 10). The second line contains 2M integers, where (pxj , pyj ) are the coordinates of the j-th vertex of the equipment. The third line contains 2N integers, where (qxj , qyj ) are the coordinates of the j-th vertex of the patient. The fourth line contains two integers cx and cy, which indicate the coordinates of the center of rotation.
All the coordinates are between -1000 and 1000, inclusive. The vertices of each polygon are given in counterclockwise order.
At the initial state, the patient is inside the equipment, and they don’t intersect each other. You may assume that the equipment doesn’t approach patients closer than 10-6 without hitting patients, and that the equipment gets the patient to stick out by the length greater than 10-6 whenever the equipment keeps its rotation after hitting the patient.
Output
For each data set, print the angle in degrees in a line. Each angle should be given as a decimal with an arbitrary number of fractional digits, and with an absolute error of at most 10-7 .
If the equipment never hit the patient during the rotation, print 360 as the angle.
Example
Input
5 4
0 0 20 0 20 10 0 10 1 5
10 3 12 5 10 7 8 5
10 5
4 3
0 0 10 0 10 5 0 5
3 1 6 1 5 4
0 0
5 3
0 0 10 0 10 10 0 10 3 5
1 1 4 1 4 6
0 0
0 0
Output
360.0000000
12.6803835
3.3722867
|
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef complex<double> Point;
const double EPS = 1e-6;
double dot(Point a, Point b){
return real(conj(a) * b);
}
double cross(Point a, Point b){
return imag(conj(a) * b);
}
int ccw(Point a, Point b, Point c) {
b -= a; c -= a;
double len = abs(b) * abs(c); // 速さが気になるときは1にする
if (cross(b, c) > +len * EPS) return +1; // 反時計回り
if (cross(b, c) < -len * EPS) return -1; // 時計回り
if (dot(b, c) < 0) return +2; // c--a--b の順番で一直線上
if (norm(b) < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
double angle(Point a, Point b){
double res = arg(conj(a) * b);
if(res < 0) res += 2 * M_PI;
return res;
}
struct Line : public vector<Point> {
Line(const Point& a, const Point& b) {
push_back(a); push_back(b);
}
Point vector() const {
return back() - front();
}
};
struct Circle {
Point p;
double r;
Circle() {}
Circle(Point p, double r) : p(p), r(r) { }
};
bool intersectSP(Line s, Point p) {
return ccw(s[0], s[1], p) == 0;
}
Point projection(Line l, Point p){
double t = dot(p - l[0], l.vector()) / norm(l.vector());
return l[0] + t * l.vector();
}
vector<Point> crosspointLC(const Line &l, const Circle &c) {
vector<Point> res;
Point center = projection(l, c.p);
double d = abs(center - c.p);
double tt = c.r * c.r - d * d;
if(tt < 0 && tt > -EPS) tt = 0;
if(tt < 0) return res;
double t = sqrt(tt);
Point vect = l.vector();
vect /= abs(vect);
res.push_back(center - vect * t);
if (t > EPS) {
res.push_back(center + vect * t);
}
return res;
}
vector<Point> crosspointSC(const Line &s, const Circle &c) {
vector<Point> ret;
vector<Point> nret = crosspointLC(s, c);
for (int i = 0; i < nret.size(); i++) {
if (intersectSP(s, nret[i])) ret.push_back(nret[i]);
}
return ret;
}
int main(){
int M, N;
while(cin >> M >> N && M){
vector<Point> ps(M);
vector<Point> qs(N);
REP(i, M){
double x, y;
cin >> x >> y;
ps[i] = Point(x, y);
}
REP(i, N){
double x, y;
cin >> x >> y;
qs[i] = Point(x, y);
}
double cx, cy;
cin >> cx >> cy;
Point cp(cx, cy);
double ans = 2.0 * M_PI;
for(int i = 0; i < N; i++){
Circle C(cp, abs(qs[i] - cp)); // qs[i]の軌道
for(int j = 0; j < M; j++){
Line s(ps[j], ps[(j == M - 1 ? 0 : j + 1)]);
vector<Point> crosspv = crosspointSC(s, C);
for(Point crossp : crosspv){
//cout << "Circle : " << C.p << " " << C.r << " cross with " << s[0] << " " << s[1] << " at " << crossp << endl;
///cout << "angle : " << angle(qs[i] - cp, crossp - cp) << endl;
ans = min(ans, angle(qs[i] - cp, crossp - cp));
}
}
}
for(int i = 0; i < M; i++){
Circle C(cp, abs(ps[i] - cp)); // ps[i]の軌道
for(int j = 0; j < N; j++){
Line s(qs[j], qs[(j == N - 1 ? 0 : j + 1)]);
vector<Point> crosspv = crosspointSC(s, C);
for(Point crossp : crosspv){
//cout << "Circle : " << C.p << " " << C.r << " cross with " << s[0] << " " << s[1] << " at " << crossp << endl;
//cout << "angle : " << angle(crossp - cp, ps[i] - cp) << endl;
ans = min(ans, angle(crossp - cp, ps[i] - cp));
}
}
}
printf("%.7f\n", ans / M_PI * 180.0);
}
return 0;
}
|
Gates and Jackie, the cats, came up with the rules for a card game played by two people. The rules are as follows.
First, shuffle the cards with the numbers 1 to 18 and deal 9 to each player. Both players issue one card at the same time and get a score based on the value. The player who issues the higher value card adds the sum of the higher value and the lower value to his score. At that time, the player who issued the card with the smaller value cannot get the score. Also, once a card is put into play, it cannot be used again. The player with the highest score after using all the cards wins.
Gates and Jackie decided to randomly pick and play cards from each other. Find the odds that Gates and Jackie will win when the first card dealt is given.
Notes on Submission
Multiple datasets are given in the above format. The first line of input data gives the number of datasets. Create a program that outputs the output for each data set in order in the above format.
Input
Each of Gates and Jackie's hand consists of nine integers. Both players' hands are different integers from 1 to 18. The first line of input is given nine integers representing Gates'hand, and the second line is given nine integers representing Jackie's hand. There is a single space between integers.
Output
Output the probability that Gates and Jackie will win, separated by a space, up to 5 digits after the decimal point. Errors within 10-5 are acceptable, but values less than 0 or greater than 1 must not be output.
Example
Input
2
1 3 5 7 9 11 13 15 17
2 4 6 8 10 12 14 16 18
1 5 7 9 11 13 15 17 18
2 3 4 6 8 10 12 14 16
Output
0.30891 0.69109
0.92747 0.07253
|
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
const int MAX_CARDS = 9;
int T;
scanf("%d", &T);
for (int t = 0; t < T; ++t) {
vector<int> gates(MAX_CARDS), jackie(MAX_CARDS);
for (int i = 0; i < MAX_CARDS; ++i)
scanf("%d", &gates[i]);
for (int i = 0; i < MAX_CARDS; ++i)
scanf("%d", &jackie[i]);
sort(gates.begin(), gates.end());
sort(jackie.begin(), jackie.end());
int win_g = 0, win_j = 0;
do {
int cnt_g = 0, cnt_j = 0;
for (int i = 0; i < MAX_CARDS; ++i) {
if (gates[i] > jackie[i])
cnt_g += (gates[i]+jackie[i]);
else
cnt_j += (gates[i]+jackie[i]);
}
if (cnt_g > cnt_j)
++win_g;
else
++win_j;
} while (next_permutation(jackie.begin(), jackie.end()));
printf("%.5f %.5f\n", win_g/static_cast<double>(win_g+win_j), win_j/static_cast<double>(win_g+win_j));
}
return 0;
}
|
Problem statement
Find the number of integer sequences $ X_1, X_2, ..., X_N $ that satisfy the following conditions.
1. For any integer $ i $ ($ 1 \ leq i \ leq N $), there exists $ j $ ($ 1 \ leq j \ leq N $) such that $ X_j = i $.
2. $ X_s = t $
3. $ X_ {a_i} <X_ {b_i} $ ($ 1 \ leq i \ leq C $)
Constraint
* $ 1 \ leq N \ leq 2000 $
* $ 0 \ leq C \ leq N $
* $ 1 \ leq s \ leq N $
* $ 1 \ leq t \ leq N $
* $ 1 \ leq a_i \ leq N $
* $ 1 \ leq b_i \ leq N $
* $ a_i \ neq b_i $
* $ i \ neq j $ then $ a_i \ neq a_j $
input
Input follows the following format. All given numbers are integers.
$ N $ $ C $ $ s $ $ t $
$ a_1 $ $ b_1 $
$ a_2 $ $ b_2 $
$ ... $
$ a_C $ $ b_C $
output
Divide the number of sequences that satisfy the condition by $ 10 ^ 9 + 7 $ and output the remainder on one row (it is easy to show that the number of sequences that satisfy the condition is at most finite).
Examples
Input
3 1 1 1
1 3
Output
2
Input
4 2 1 1
2 3
3 2
Output
0
|
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long int64;
const int MAX_N = 2000 + 1;
const int64 MOD = (int64)(1e9 + 7);
int N, C, target, ord;
int parent[MAX_N+1];
vector<int> graph[MAX_N+1];
int V[MAX_N+1];
int S[MAX_N+1];
int64 T[MAX_N+1];
int64 dp[MAX_N+1][MAX_N+1];
bool visited[MAX_N + 1];
int64 comb[MAX_N+1][MAX_N+1];
void init(){
scanf("%d%d%d%d", &N, &C, &target, &ord);
ord = N - ord + 1;
++N;
parent[0] = -1;
for(int i=0; i<C; i++){
int a, b;
scanf("%d%d", &a, &b);
parent[a] = b;
graph[b].push_back(a);
}
for(int i=0; i<N; i++)if(parent[i] == 0){
graph[0].push_back(i);
}
for(int i=0; i<=N; i++){
comb[i][i] = comb[i][0] = 1;
for(int j=1; j<i; j++){
comb[i][j] = ( comb[i-1][j-1] + comb[i-1][j] ) % MOD;
}
}
}
void calc(int v){
T[v] = S[v] = 1;
for(int i=0; i<(int)graph[v].size(); ++i){
const int u = graph[v][i];
calc(u);
S[v] += S[u];
}
int total = S[v] - 1;
for(int i=0; i<(int)graph[v].size(); i++){
const int u = graph[v][i];
T[v] = T[v] * comb[total][S[u]] % MOD * T[u] % MOD;
total -= S[u];
}
}
int solve(){
calc(0);
if(S[0] != N){
return 0;
}
const int dummy = N;
S[dummy] = 0;
parent[dummy] = target;
int depth = 0;
for(int v = target; v!=-1 ;V[depth++]=v, v=parent[v]);
reverse(V, V+depth);
V[depth] = dummy;
for(int i=0; i<depth; i++){
int cur = V[i], nxt = V[i+1], all = N - S[nxt];
int64 sum = 0, prod = 1;
int total = S[cur] - S[nxt] - 1;
for(int j=0; j<(int)graph[cur].size(); j++){
const int u = graph[cur][j];
if(nxt != u){
prod = prod * T[u] % MOD * comb[total][S[u]] % MOD;
total -= S[u];
}
}
if(i == 0){
dp[0][0] = prod;
continue;
}
for(int j=1; j<N; j++){
sum = (sum + dp[i-1][j-1]) % MOD;
int rem = all - j - 1, child = S[cur] - S[nxt] - 1;
if(rem >= child && rem >= 0 && child >= 0){
dp[i][j] = sum * comb[rem][child] % MOD * prod % MOD;
}
}
}
return (int)dp[depth-1][ord];
}
int main(){
init();
printf("%d\n", solve());
return 0;
}
|
It is important to use strong passwords to make the Internet more secure. At the same time, it is very important not to reuse the same password. No matter how strong your password is, if the plaintext is leaked in one place, it will be very easy to break. Of course, if all applications hash passwords and use SALT properly, such damage will not occur even if leaked, but there are still applications that store passwords in clear text.
Well, the contest is about to begin. I have to register a team account ...
problem
A string representing the password is given. Check if the character string meets all of the following conditions, and if it meets all of the following conditions, output "VALID", and if there is an item that does not meet even one, output "INVALID".
* String length is 6 or more
* Contains one or more numbers
* Contains one or more uppercase letters
* Contains one or more lowercase letters
input
A string representing the password is given on one line.
output
Print "VALID" if the password string meets all the conditions in question, and "INVALID" if there are conditions that do not.
Constraint
* The password string must be between 1 and 20 characters.
* Password string contains only uppercase letters, lowercase letters, and numbers
Input / output example
Input 1
password
Output 1
INVALID
It is a password that is widely used all over the world.
Input 2
AizuCamp2013
Output 2
VALID
Great password.
Input 3
1234
Output 3
INVALID
Widely used as a PIN.
Input 4
NaBiO3
Output 4
VALID
It is barely 6 characters or more.
Example
Input
password
Output
INVALID
|
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
#define REP(i,s,e) for(int i=(s); i<(int)(e); i++)
#define rep(i,n) REP(i, 0, n)
#define pb push_back
#define mp make_pair
#define all(r) (r).begin(),(r).end()
#define rall(r) (r).rbegin(),(r).rend()
#define fi first
#define se second
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vl;
typedef vector<vl> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1000000;
const double EPS = 1e-8;
const int mod = 1e9 + 7;
int main(){
string s;
cin>>s;
bool f, F, fn, fs;
f = F = fn = false;
fs = s.size() >= 6;
rep(i, s.size()){
if(s[i]>='a'&&s[i]<='z') f = true;
else if(s[i] >= 'A' && s[i] <= 'Z') F = true;
else if(s[i] >= '0' && s[i] <= '9') fn = true;
}
cout<<(f&F&fn&fs?"VALID":"INVALID")<<endl;
}
|
Example
Input
10 2
2
1
Output
5 7
3 5
|
#include <iostream>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <vector>
#include <valarray>
#include <array>
#include <queue>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <complex>
#include <random>
using namespace std;
using ll = long long;
using ull = unsigned long long;
constexpr int TEN(int n) {return (n==0)?1:10*TEN(n-1);}
using R = long double;
const R EPS = 1e-9;
const int MS = 30030;
using P = array<ll, 2>;
namespace StopWatch {
clock_t st;
bool f = false;
void start() {
f = true;
st = clock();
}
int msecs() {
assert(f);
return (clock()-st)*1000 / CLOCKS_PER_SEC;
}
}
vector<P> solve(int N, vector<ll> s) {
int M = (int)s.size();
vector<P> rng(M);
fill_n(rng.begin(), M, P{0, N});
ll ssm = 0;
for (int i = 0; i < M; i++) {
ssm += s[i];
}
int deg[MS];
fill_n(deg, MS, 0);
for (int i = 0; i < M; i++) {
deg[s[i]]++;
}
map<int, ll> mp;
StopWatch::start();
for (int i = 0; i < M; i++) {
if (s[i] == 0) continue;
if (mp.count(s[i])) {
rng[i][0] = mp[s[i]];
continue;
}
if (i % 1000 == 0) {
// printf("end %d %d\n", i, StopWatch::msecs());
}
ll l = (N*s[i]-1) / (ssm+M-1);
while (l < N) {
l++;
ll sm = (ssm-s[i]+M-1)*l-(M-1)*(s[i]-1) - s[i]*(N-l);
/* for (int j = 0; j < M; j++) {
if (i == j) continue;
sm += s[i]-1-(s[j]+1)*l%s[i];
if (0 <= sm) {
break;
}
}*/
sm -= s[i]-1-(s[i]+1)*l%s[i];
int l2 = l%s[i];
int now = 0;
for (int j = 0; j < MS; j++) {
now += l2; if (now >= s[i]) now -= s[i];
sm += (s[i]-1-now)*deg[j];
if (0 <= sm) break;
}
if (0 <= sm) break;
}
mp[s[i]] = rng[i][0] = l;
}
mp.clear();
StopWatch::start();
for (int i = 0; i < M; i++) {
if (mp.count(s[i])) {
rng[i][1] = mp[s[i]];
continue;
}
if (i % 1000 == 0) {
// printf("end %d %d\n", i, StopWatch::msecs());
}
ll l = (N*(s[i]+1)-(M-1)*s[i]) / (ssm+1);
while (l <= N) {
l++;
ll sm = (ssm-s[i])*l - (s[i]+1)*(N-l);
sm -= s[i] - (s[i]*l+s[i])%(s[i]+1);
int l2 = l%(s[i]+1);
int now = s[i];
/* for (int j = 0; j < M; j++) {
if (i == j) continue;
sm += s[i] - (s[j]*l+s[i])%(s[i]+1);
if (0 < sm) {
break;
}
}*/
for (int j = 0; j < MS; j++) {
sm += (s[i]-now)*deg[j];
now += l2; if (now >= s[i]+1) now -= s[i]+1;
if (0 < sm) break;
}
if (0 < sm) break;
}
mp[s[i]] = rng[i][1] = l-1;
}
return rng;
}
int main2() {
int N, M;
cin >> N >> M;
assert(M <= 30000);
vector<ll> s;
for (int i = 0; i < M; i++) {
int x;
cin >> x;
s.push_back(x);
}
int idx[M], ridx[M];
iota(idx, idx+M, 0);
sort(idx, idx+M, [&](const int &l, const int &r){
return s[l] < s[r];
});
for (int i = 0; i < M; i++) {
ridx[idx[i]] = i;
}
vector<ll> s2(M);
for (int i = 0; i < M; i++) {
s2[i] = s[idx[i]];
}
auto rng = solve(N, s2);
for (int i = 0; i < M; i++) {
if (rng[i][0] > rng[i][1]) {
printf("impossible\n");
return 0;
}
}
for (int i = 0; i < M; i++) {
printf("%lld %lld\n", rng[ridx[i]][0], rng[ridx[i]][1]);
}
return 0;
}
/*stack size???????????????*/
int main() {
static ll eord, enew;
const int sz = 32*1024*1024;
static unsigned char *p = (unsigned char*)malloc(sz);
enew = ((ll)(p+sz-1) & ~0xff);
__asm__ volatile("mov %%rsp, %0" : "=r"(eord));
__asm__ volatile("mov %0, %%rsp" : : "r"(enew));
main2();
__asm__ volatile("mov %0, %%rsp" : : "r"(eord));
return 0;
}
|
F: If you want to hide the trees, in the forest
story
"Wood is good" Chico, who runs the coffee shop "Turtle House", has an extraordinary love for trees. Everything seems to wash my heart with the immobility of wood. .. .. In order to confirm Chico-chan's love for trees, Kokoro-chan, who works part-time at the same coffee shop, decided to play a trick on Chico-chan.
Kokoro decided to prepare a forest for Chico and hide some of the trees growing near the coffee shop in the forest to test her love for the trees. Specifically, I decided to have Chico find the hidden tree in the forest. Chico-chan, who loves trees, can tell which trees she has seen once by the difference in how her heart is washed, but because she has moved the trees, the way the trees are immovable has changed, and which tree is which? I don't know the tree near the coffee shop. What's more, even the stupid Kokoro-chan has forgotten which tree is the answer! As it is, the answer tree cannot be returned to its original place, so Kokoro-chan gets angry with Chico-chan. So, let's write a program that will teach Kokoro-chan how many answer trees there are with gentle programmers.
problem
Two graphs G_1 and G_2 are given as inputs. G_1 is a forest, that is, a graph without a cycle (not necessarily connected), and G_2 is a tree, that is, a connected graph without a cycle. At this time, find out how many connected components G_1 has the same type as G_2.
Note 1) Two vertices f (u) and f (v) in G_2 are adjacent only when u and v are adjacent to any two vertices u and v contained in the connected component H_1 with graph G_1. When there is such a bijective f, H_1 is said to be a connected component of G_1, which is isomorphic to G_2.
input
The input is given in the following format.
N_1 M_1
u_1 v_1
...
u_ {M_1} v_ {M_1}
N_2
w_1 x_1
...
w_ {N_2 --1} x_ {N_2 --1}
In the first line, the number of vertices N_1 (1 \ leq N_1 \ leq 300,000) and the number of sides M_1 (0 \ leq M_1 \ leq N_1 --1) of the forest G_1 are given. In the following M_1 line, the i-th side e_i of G_1 is given in the i-th line (1 \ leq i \ leq M_1). e_i is the edge connecting the two vertices u_i and v_i. (1 \ leq u_i, v_i \ leq N_1, u_i \ neq v_i) The next line gives the number of vertices N_2 (1 \ leq N_2 \ leq 30,000) of the tree G_2. In the following N_2 --1 line, the jth side e_j of G_2 is given on the jth line (1 \ leq j \ leq N_2 --1). e_j is the edge connecting the two vertices w_j and x_j. (1 \ leq w_j, x_j \ leq N_2, w_j \ neq x_j)
output
Output the number of connected components of G_1 that are isomorphic to G_2.
Input example 1
6 4
1 2
twenty three
twenty four
5 6
Four
twenty three
3 1
3 4
Output example 1
1
Input example 2
14 9
5 8
5 11
10 14
6 4
13 9
3 14
1 2
6 12
7 9
3
3 1
twenty one
Output example 2
Four
Example
Input
6 4
1 2
2 3
2 4
5 6
4
2 3
3 1
3 4
Output
1
|
//
// Writer: kurita
// states: AC
// O(N log(N))
//
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<map>
#include<cstdio>
using namespace std;
typedef pair<int, int> pii;
typedef vector<vector<int> > Graph;
map<vector<int>, int> tree_hash;
vector<Graph> ConectedComponent(Graph &f) {
int n = f.size(), pos = 0;
vector<bool> used(n, false);
vector<Graph> res;
queue<int> que;
while(pos < n){
vector<int> used_vertex;
int size = 0;
que.push(pos);
used[pos] = true;
while(not que.empty()){
size++;
int v = que.front();
used_vertex.push_back(v);
que.pop();
for (int i = 0; i < f[v].size(); i++) {
if(used[f[v][i]] == true)continue;
que.push(f[v][i]);
used[f[v][i]] = true;
}
}
sort(used_vertex.begin(), used_vertex.end());
Graph g(used_vertex.size());
for (int i = 0; i < used_vertex.size(); i++) {
for (int j = 0; j < f[used_vertex[i]].size(); j++) {
g[i].push_back(lower_bound(used_vertex.begin(), used_vertex.end(), f[used_vertex[i]][j]) -
used_vertex.begin());
}
}
res.push_back(g);
while(pos < n and used[pos])pos++;
}
return res;
}
vector<int> BFS(const Graph &g, vector<int> &dist, int v){
int n = g.size();
queue<pii> que;
vector<int> parent(n);
for (int i = 0; i < n; i++) parent[i] = i;
que.push(pii(v, 0));
dist[v] = 0;
while(not que.empty()){
int v = que.front().first;
int d = que.front().second;
que.pop();
for (int i = 0; i < g[v].size(); i++) {
if(dist[g[v][i]] >= 0)continue;
dist[g[v][i]] = d + 1;
parent[g[v][i]] = v;
que.push(pii(g[v][i], d + 1));
}
}
return parent;
}
inline vector<int> CenterTree(const Graph &g, int v = 0){
int n = g.size();
vector<int> dist(n, -1);
BFS(g, dist, v);
int u, maxi = -1;
for (int i = 0; i < n; i++) {
if(dist[i] > maxi){
u = i, maxi = dist[i];
}
}
dist = vector<int>(n, -1);
vector<int> parent = BFS(g, dist, u);
int diam = 0;
for (int i = 0; i < n; i++) {
if(dist[i] > diam) diam = dist[i], v = i;
}
for (int i = 0; i < diam/2; i++) v = parent[v];
vector<int> res;
res.push_back(v);
if(diam%2 != 0)res.push_back(parent[v]);
return res;
}
int AHUHash(const Graph &t, int v, int parent = -1){
if(t[v].size() == 1 and parent != -1)return 0;
vector<int> res;
for (int i = 0; i < t[v].size(); i++) {
if(t[v][i] == parent)continue;
res.emplace_back(AHUHash(t, t[v][i], v));
}
sort(res.begin(), res.end());
if(tree_hash.count(res) == 0){
tree_hash[res] = 0;
tree_hash[res] = tree_hash.size();
}
return tree_hash[res];
}
int main() {
int n, m;
std::cin >> n >> m;
Graph forest(n);
int to, from;
for (int i = 0; i < m; i++) {
scanf("%d %d", &to, &from);
to--, from--;
forest[to].push_back(from);
forest[from].push_back(to);
}
int nn;
std::cin >> nn;
Graph tree(nn);
for (int i = 0; i < nn - 1; i++) {
scanf("%d %d", &to, &from);
to--, from--;
tree[to].push_back(from);
tree[from].push_back(to);
}
int ans = 0;
vector<int> ct = CenterTree(tree);
vector<int> th(ct.size());
for (int i = 0; i < ct.size(); i++) {
th[i] = AHUHash(tree, ct[i]);
}
vector<Graph> tree_set = ConectedComponent(forest);
for (auto t: tree_set) {
if(t.size() != nn)continue;
vector<int> cf = CenterTree(t);
vector<int> fh(cf.size());
for (int j = 0; j < cf.size(); j++) {
fh[j] = AHUHash(t, cf[j]);
}
for (int j = 0; j < th.size(); j++) {
for (int k = 0; k < fh.size(); k++) {
if(th[j] == fh[k])ans++, j = k = 1e9;
}
}
}
std::cout << ans << std::endl;
return 0;
}
|
H: Revenge of UMG
problem
For the character string T consisting of three types of characters,'U',' M', and'G', the 1, 2, ..., | T | characters are T_1, T_2, ..., T_ {|, respectively. When we decide to express T |}, we call the number of pairs of (i, j, k) that satisfy the following conditions the "UMG number" of the string T:
* 1 \ leq i <j <k \ leq | T |
* j --i = k --j
* T_i ='U', T_j ='M', T_k ='G'
Now, we are given the string S, which consists of the four characters'U',' M',' G', and'?'. There are 3 ^ {N} possible strings that can be created by replacing the'?' In S with one of'U',' M', or'G', respectively, where N is the number of'?'. Find the sum of the UMG numbers in the string divided by 998244353.
Input format
S
Constraint
* 3 \ leq | S | \ leq 2 \ times 10 ^ {5}
* S is a character string consisting of four types of characters,'U',' M',' G', and'?'.
Output format
Print the integer that represents the answer on one line. Note that it prints too much divided by 998244353.
Input example 1
? MG?
Output example 1
3
If the first'?' Is not a'U', the UMG number will be 0. When the first'?' Is'U'
* The number of UMGs in `UMGU` is 1
* The number of UMGs in `UMGM` is 1
* The number of UMGs in `UMGG` is 1
And the total value is 3.
Input example 2
UUMMGGGUMG
Output example 2
Four
Input example 3
????? G ???? U ??? M ?????? G ????? M ???? G ??? U ?????? M ??? G ??
Output example 3
648330088
Please answer too much divided by 998244353.
Example
Input
?MG?
Output
3
|
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <complex>
#include <string>
#include <algorithm>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <cassert>
typedef long long ll;
using namespace std;
#ifndef LOCAL
#define debug(x) ;
#else
#define debug(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl;
template <typename T1, typename T2>
ostream &operator<<(ostream &out, const pair<T1, T2> &p) {
out << "{" << p.first << ", " << p.second << "}";
return out;
}
template <typename T>
ostream &operator<<(ostream &out, const vector<T> &v) {
out << '{';
for (const T &item : v) out << item << ", ";
out << "\b\b}";
return out;
}
#endif
#define mod 998244353 //1e9+7(prime number)
#define INF 1000000000 //1e9
#define LLINF 2000000000000000000LL //2e18
#define SIZE 200010
ll power(ll k, ll n, int M){
ll res = 1;
while(n > 0) {
if (n & 1) res = res * k % M;
k = k * k % M;
n /= 2;
}
return res;
}
/* Number Theoretic Transform */
namespace NTT {
void DFT(int m, int root, vector<int> &a, bool rev = false) {
int N = a.size();
for(int i = 0, j = 1; j + 1 < N; j++) {
for(int k = N >> 1; k > (i ^= k); k >>= 1);
if(i > j) swap(a[i], a[j]);
}
int g = power(root, (mod - 1) / N, mod);
if (rev) g = power(g, mod - 2, mod);
for (int i = 1; i < N; i *= 2) {
int base = power(g, N / i / 2, mod);
ll w = 1;
for (int j = 0; j < i; j++) {
for (int k = 0; k < N; k += i*2) {
int s = a[j+k], t = a[j+k+i] * w % m;
a[j+k+0] = (s + t) % m;
a[j+k+i] = (s - t + m) % m;
}
w = w * base % m;
}
}
if (rev) {
ll tmp = power(N, m-2, m);
for(int &v : a) v = v * tmp % m;
}
}
// (469762049, 3), (924844033, 5), (998244353, 3), (1012924417, 5)
vector<int> conv(int _mod, int root, const vector<int> &a, const vector<int> &b) {
int s = 1, t = a.size() + b.size() - 1;
while(s < t) s *= 2;
vector<int> F(s), G(s);
for(int i = 0; i < (int)a.size(); i++) F[i] = a[i];
for(int i = 0; i < (int)b.size(); i++) G[i] = b[i];
DFT(_mod, root, F); DFT(_mod, root, G);
for(int i = 0; i < s; i++) F[i] = (ll)F[i] * G[i] % _mod;
DFT(_mod, root, F, true);
return F;
}
};
int N;
char S[SIZE];
int U[SIZE], M[SIZE], G[SIZE];
ll solve(int l, int r) {
ll res = 0;
if(r - l <= 2) return 0;
vector<int> a(r-l), b(r-l);
for(int i=l; i<r; i++) {
if (i < (l+r)/2)
a[i-l] = U[i];
else
b[i-l] = G[i];
}
auto UG = NTT::conv(mod, 5, a, b);
for(int i=0; i<(r-l); i++) {
res += (ll)UG[i*2] * M[i + l] % mod;
}
res += solve(l, (l+r)/2);
res += solve((l+r)/2, r);
return res % mod;
}
int main(){
scanf("%s", S);
N = strlen(S);
int questions = 0;
for (int i=0; i<N; i++)
questions += S[i] == '?';
ll base = power(3, questions, mod);
ll inv3 = power(3, mod - 2, mod);
for(int i=0; i<N; i++) {
if(S[i] == 'U') U[i] = base;
if(S[i] == 'M') M[i] = 1;
if(S[i] == 'G') G[i] = 1;
if(S[i] == '?') {
U[i] = base * inv3 % mod;
M[i] = G[i] = inv3;
}
}
int ans = solve(0, N);
printf("%d\n", ans);
return 0;
}
|
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2
|
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int n;
cin >> n;
int res = 0;
while (n--) {
string s;
cin >> s;
res += s == "E869120";
}
cout << res << '\n';
}
|
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $K$, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [$1, 2, ..., K$]. If there is no such sub-array, report 0.
Constraints
* $1 \leq N \leq 10^5$
* $1 \leq K \leq 10^5$
* $1 \leq a_i \leq 10^5$
Input
The input is given in the following format.
$N$ $K$
$a_1$ $a_2$ ... $a_N$
Output
Print the smallest sub-array size in a line.
Examples
Input
6 2
4 1 2 1 3 5
Output
2
Input
6 3
4 1 2 1 3 5
Output
3
Input
3 4
1 2 3
Output
0
|
#include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
int n,k;
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++) cin>>a[i];
int ans=n+1;
int x[k];
memset(x,0,sizeof(x));
int cnt=0;
int l=0;
for(int i=0;i<n;i++){
//cout<<i<<" "<<a[i]<<":"<<cnt<<endl;
a[i]--;
if(a[i]>=k) continue;
x[a[i]]++;
if(x[a[i]]==1) cnt++;
while(cnt==k){
if(a[l]>=k){
l++;
continue;
}
ans=min(ans,i-l+1);
x[a[l]]--;
if(x[a[l]]==0) cnt--;
l++;
}
}
if(ans>n) ans=0;
cout<<ans<<endl;
return 0;
}
|
Recently Chef has decided to make some changes in our beloved Codechef. As you know, each problem at Codechef has its memory and time limits. To make problems even more challenging, he decided to measure allocated memory in a different way. Now judge program will be calculating not the maximum memory usage during the execution of all test files, but all the memory ever allocated by the solution program. But as Chef is not that good in algorithms, so he asks you to write a program that will calculate total memory usage of a solution.
So, you are given N numbers M1, , ,MN representing the measurements of consumed memory (in MBs) for N test files. In other terms, it means that on i-th test file, program took Mi MBs of memory. Initially, there is no memory allocated for your program. Before running your program on each test file, if the currently allocated memory is more than memory needed for the current test file, then there will be a deallocation of the memory to fit the current program. Also, if there is less than needed memory available, then allocation of memory will happen so as to fit the current program. e.g. Let us say that our program took 10 MBs on current test file. So, assuming if there was 12 MBs memory allocated before running the program on current test file, then there will happen a deallocation of 2 MBs. Assuming if there was 8 MBs memory allocated before running the program on current test file, then there will happen a allocation of 2 MBs.
Calculate the total memory allocated for running the solution program on all the N test files. Please see third sample for more clarity.
Input
First line of input contains a single integer T denoting the number of test cases. First line of each test case contains a single integer N denoting the number of measurements. Second line of each test case contains N space separated integers, where i^th integer denotes the consumption of memory for i^th i-th test file.
Output
For each test case, print total memory allocated for running the solution program.
Constraints
1 ≤ T ≤ 10^5
1 ≤ N ≤ 10^5
1 ≤ Mi ≤ 10^9
sum of N over all test cases does not exceed 10^5
Example
Input:
3
2
1 1
5
1 2 3 4 5
3
1 3 2
Output:
1
5
3
Explanation
Example case 1. Initially, there was no memory allocated. For running first test file, there was a memory allocation of 1 MBs. There was no allocation/ deallocation for running your program on second test file.
Example case 2. On running on each test file, there was a further allocation of 1 MBs from previous one. So, there are total 5 MBs of memory allocated while running the program.
Example case 3. Initially, there was no memory allocated. For running first test file, there was a memory allocation of 1 MBs. For running second test file, there was a further memory allocation of 2 MBs to have 3 MBs of memory needed, then in the last file, there was a deallocation of 1 MB of memory so as to get 2 MBs of memory needed for running the program. So, overall, there was 1 + 2 = 3 MBs of memory ever allocated in the program. Note that we are only counting allocated memory, not allocated + unallocated.
|
t = int(raw_input())
while t:
t -= 1
raw_input()
arr = [0] + map(int, raw_input().split(' '))
o = 0
for i in range(1, len(arr)):
o += max(0, arr[i] - arr[i-1])
print o
|
For the purposes of this problem, we will assume that every page in an book is numbered sequentially, and that the first page is numbered 1.
How many digits would you need to use to number the pages of a 10 page book? Pages 1 to 9 would require 1 digit each (total 9), and page 10 would require 2 digits. This makes 11 digits. Similarly, a book of 34 pages would require 59 digits.
Can we work backwards? If you are told that a book requires 13 digits to number its pages, can you work out how many pages the book has? I hope so, because that is all you have to do for this problem. Each line in the input file represents the number of digits used in numbering a book. Your answer will be the number of pages the book has. If the number supplied cannot possibly be valid, your answer should be "Impossible!" Beware that books can be quite large, and the number of digits required for a given book can reach 2,000,000,000.
Input
Each line in the input file contains a single integer, between 1 and 2,000,000,000, representing a number of digits used in numbering the pages of a book. A single # on a line indicates the end of input.
Output
Output for each input number must be on a single line. If the input value is valid, output the number of pages in the book. Otherwise, output "Impossible!"
Example
Input:
11
13
59
60
1999999998
#
Output:
10
11
34
Impossible!
234567900
|
R = [0,9,189,2889,38889,488889,5888889,68888889,788888889]
def process(N):
for i in xrange(8,-1,-1):
if N > R[i]:
N -= R[i]
if N % (i+1): return 'Impossible!'
else: return N / (i+1) + 10**i - 1
def main():
while True:
N = raw_input()
if N == '#': break
print process(int(N))
main()
|
Jane lives in N-dimensional space. Her house is a N-dimensional hypercube, with the centre located in the origin, with each edge having length equal to 2. There is a room in every vertex of the hypercube. The room can be denoted with N it's coordinates. For any two rooms, there is a corridor between them if the square of the euclidean distance is no more than D units.
Sometimes, Jane wants to make a clean-up in her house. In order to do that, she needs to visit all the rooms. She starts with a room with the coordinates (S1, S2, ... SN) and then wants to move through all the rooms via corridors in such a way that she will visit all the rooms, and, at the same time, won't visit any room twice (she does not want to step on a floor which is not dried yet).
Please find such a route for Jane or state that it's impossible to find one.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains two space separated integers N and D denoting the number of dimensions of the space Jane lives in and the square of the maximal euclidean distance between two rooms, connected via corridor.
The second line contains N space-separated integers S1, S2, ..., SN denoting the coordinates of the room where Jane starts the cleaning.
Output
For each test case output:
if the a route exists output 2^N lines, each containing N space separated integers, denoting the coordinates of the corresponding room in the route. For every test case, the coordinates of the first room in the route should coincide with the given location. If there is more than one solution, you can print any one of them.
if such a route doesn't exist, output just -2 on the separate line.
Constraints
Example
Input:
2
2 5
-1 -1
4 3
1 -1 1 -1
Output:
-1 -1
1 -1
1 1
-1 1
-2
Explanation
Example case 1. It is easy to see that the square of the euclidean distance between any two adjacent rooms in the route will not exceed D = 5.
Example case 2. It is clearly impossible to accomplish the task.
|
def get_opposite(point, dimention):
opposite_vertex = [i for i in point]
opposite_vertex[dimention] = -point[dimention]
return opposite_vertex
def print_vertex(start_point, dimention):
if dimention == 0:
opposite_vertex = get_opposite(start_point, dimention)
print ' '.join([str(i) for i in start_point])
print ' '.join([str(i) for i in opposite_vertex])
return opposite_vertex
end_vertex = print_vertex(start_point, dimention-1)
opposite_vertex = get_opposite(end_vertex, dimention)
return print_vertex(opposite_vertex, dimention-1)
T = int(raw_input())
for t in xrange(T):
input = raw_input().split(' ')
N, D = int(input[0]), int(input[1])
l = [int(i) for i in raw_input().split(' ')]
if D < 4:
print -2
continue
print_vertex(l, N-1)
|
Mike takes part in olympiads in informatics. You think he is a rookie? Wrong! He is an experienced and well-prepared competitor! He participated in many important contests and won some of them. Now his level is rather high.
In order to keep fit, Mike decided to improve his training sessions. He downloaded N task packages. There are Ai tasks in i'th package. They are really interesting and complicated, so Mike wants to solve them all!
Unfortunately, it is going to be an important contest in a few days, so Mike can solve at most X tasks before it. Let's assume, that Mike can solve any X problems before the contest.
Do you know what makes Mike happy? Right! Successful packages! A package of tasks is successful, if Mike solved all the tasks in it.
Do you also know what makes Mike sad? Right! Failed packages! A package of tasks is failed, if Mike solved less than a half of the tasks in it.
Please, help Mike to organize his training session!
Mike wants to minimize the number of failed packages. If there are several ways of doing this, he wants to maximize the number of successful packages. Remember also that he can't solve more than X tasks before the contest.
Input
The first line contain two integers N and X.
The second line contain N positive integers, i'th integer denotes Ai. The array A is 1-indexed.
Output
The first line should contain two integers: the number of failed packages and the number of successful packages in the optimal way of solving.
Example
Input:
3 10
3 4 5
Output:
0 2
Explanation
In the test case N equals to 3, X equals to 10, A equals to {3, 4, 5}. It is optimal to solve all the problems in the first and the second packages and to solve 3 problems in the third package.
Scoring
0 ≤ X ≤ 10^15 for each test case;
1 ≤ Ai ≤ 10^9 for each test case.
Subtask 1 (10 points): 1 ≤ N ≤ 100, A1 + A2 + ... + AN ≤ X;
Subtask 2 (21 point): 1 ≤ N ≤ 15;
Subtask 3 (29 points): 1 ≤ N ≤ 1000;
Subtask 4 (25 points): 1 ≤ N ≤ 100 000;
Subtask 5 (15 points): 1 ≤ N ≤ 1 000 000.
|
def opt(par,data):
fail,total=par
success=0
data=sorted(data)
for a in data:
if(a%2==0):
half=a/2
if(total-half<0):
break
else:
total-=half
fail-=1
else:
half=a/2+1
if(total-half<0):
break
else:
total-=half
fail-=1
for a in data:
remhalf=a/2
if(total-remhalf<0):
break
else:
total-=remhalf
success+=1
return str(fail)+" "+str(success)
def process(s):
return map(int,s.split())
print opt(process(raw_input()),process(raw_input()))
|
Problem description
The mess authority of Hall 1, NIT Durgapur has decided to select a student representative. A special game is organized to select one from all the students. Everyone is sitting in the common room of Hall 1. The order in which the students will play is based on their respective CGPA.Game Description:
First student based on the priority sits on the HOT seat with his back towards a projector displaying N strings sorted lexicographically and containing names of items related to the game of cricket. Countdown starts and the participant randomly announces a string. If the string is in the list, he wins. Otherwise game continues with other students.You are given N number of strings and a string announced by Ravi. You need to answer whether Ravi won or not. NOTE: every string contains only lowercase letters.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. First line of each test case has integer N denoting the number of strings. Next N lines of each test case have N lexicographically sorted strings. Last line of each test case contains a string announced by Ravi. Length of each string won’t exceed 100.
Output
For each test case, output only line containing “yes” if Ravi wins or “no” if he doesn’t.
Constraints
1 ≤ T ≤ 1000
1 ≤ N ≤ 1000
Example
Input:
1
2
pitch
yorker
virat
Output:
no
|
for _ in range(input()):
n=input()
a=[]
while n:
n-=1
s=raw_input()
a.append(s)
#print a[0]
s=raw_input()
#print s
flag=0
for i in range(len(a)):
#print str(a[i])
if s==str(a[i]):
flag=1
break
if flag:
print 'yes'
else:
print 'no'
|
Triangle classification is an important problem in modern mathematics. Mathematicians have developed many criteria according to which a triangle can be classified. In this problem, you will be asked to classify some triangles according to their sides and angles.
According to their measure, angles may be:
Acute — an angle that is less than 90 degrees
Right — a 90-degrees angle
Obtuse — an angle that is greater than 90 degrees
According to their sides, triangles may be:
Scalene — all sides are different
Isosceles — exactly two sides are equal
According to their angles, triangles may be:
Acute — all angles are acute
Right — one angle is right
Obtuse — one angle is obtuse
Triangles with three equal sides (equilateral triangles) will not appear in the test data.
The triangles formed by three collinear points are not considered in this problem. In order to classify a triangle, you should use only the adjactives from the statement. There is no triangle which could be described in two different ways according to the classification characteristics considered above.
Input
The first line of input contains an integer SUBTASK_ID denoting the subtask id this input belongs to.
The second line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains six integers x1, y1, x2, y2, x3 and y3 denoting Cartesian coordinates of points, that form the triangle to be classified.
It is guaranteed that the points are non-collinear.
Output
For each test case, output a single line containing the classification of the given triangle.
If SUBTASK_ID equals 1, then the classification should follow the "<Side classification starting with a capital letter> triangle" format.
If SUBTASK_ID equals 2, then the classification should follow the "<Side classification starting with a capital letter> <angle classification> triangle" format.
Please, check out the samples section to better understand the format of the output.
Constraints
1 ≤ T ≤ 60
|xi|, |yi| ≤ 100
Example 1
Input:
1
2
0 0 1 1 1 2
3 0 0 4 4 7
Output:
Scalene triangle
Isosceles triangle
Example 2
Input:
2
6
0 0 4 1 1 3
0 0 1 0 1 2
0 0 1 1 1 2
0 0 2 1 1 2
3 0 0 4 4 7
0 0 2 1 4 0
Output:
Scalene acute triangle
Scalene right triangle
Scalene obtuse triangle
Isosceles acute triangle
Isosceles right triangle
Isosceles obtuse triangle
|
from math import sqrt, fabs
subid = input()
T = input()
compare = float(10**-6)
for hell in range(T):
x1,y1,x2,y2,x3,y3 = map(float, raw_input().split())
tside1 = sqrt( (x1 - x2)**2 + (y1 - y2)**2 )
tside2 = sqrt( (x2 - x3)**2 + (y2 - y3)**2 )
tside3 = sqrt( (x3 - x1)**2 + (y3 - y1)**2 )
side1 = max( tside1, tside2, tside3 )
side3 = min( tside1, tside2, tside3 )
side2 = (tside1 + tside2 + tside3) - (side1 + side3)
if fabs(side1 - side2)<compare or fabs(side2 - side3)<compare:
print "Isosceles",
else:
print "Scalene",
if subid == 2:
if (side1 - sqrt( side2**2 + side3**2 )) > compare:
print "obtuse",
elif fabs(side1 - sqrt( side2**2 + side3**2 )) < compare:
print "right",
else:
print "acute",
print "triangle"
|
There are n cities in the country of Berland. Some of them are connected by bidirectional roads in such a way that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each road has its own length. Cities are numbered from 1 to n.
The travelling time between some cities v and u is the total length of the roads on the shortest path from v to u.
The two most important cities in Berland are cities 1 and n.
The Berland Ministry of Transport decided to build a single new road to decrease the traffic between the most important cities. However, lots of people are used to the current travelling time between the most important cities, so the new road shouldn't change it too much.
The new road can only be built between such cities v and u that v ≠ u and v and u aren't already connected by some road.
They came up with m possible projects. Each project is just the length x of the new road.
Polycarp works as a head analyst at the Berland Ministry of Transport and it's his job to deal with all those m projects. For the i-th project he is required to choose some cities v and u to build the new road of length x_i between such that the travelling time between the most important cities is maximal possible.
Unfortunately, Polycarp is not a programmer and no analyst in the world is capable to process all projects using only pen and paper.
Thus, he asks you to help him to calculate the maximal possible travelling time between the most important cities for each project. Note that the choice of v and u can differ for different projects.
Input
The first line contains two integers n and m (3 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 3 ⋅ 10^5) — the number of cities and the number of projects, respectively.
Each of the next n - 1 lines contains three integers v_i, u_i and w_i (1 ≤ v_i, u_i ≤ n, 1 ≤ w_i ≤ 10^9) — the description of the i-th road. It is guaranteed that there exists exactly one path, which visits each road no more than once, between every pair of cities.
Each of the next m lines contains a single integer x_j (1 ≤ x_j ≤ 10^9) — the length of the road for the j-th project.
Output
Print m lines, the j-th line should contain a single integer — the maximal possible travelling time between the most important cities for the j-th project.
Example
Input
7 2
1 2 18
2 3 22
3 4 24
4 7 24
2 6 4
3 5 12
1
100
Output
83
88
Note
The road network from the first example:
<image>
You can build the road with length 1 between cities 5 and 6 to get 83 as the travelling time between 1 and 7 (1 → 2 → 6 → 5 → 3 → 4 → 7 = 18 + 4 + 1 + 12 + 24 + 24 = 83). Other possible pairs of cities will give answers less or equal to 83.
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e5 + 10;
int n, m;
vector<pair<long long, long long> > k[MAXN];
vector<long long> li;
long long di[MAXN];
long long subsz[MAXN];
long long shack[MAXN];
bool pa[MAXN];
long long pref[MAXN];
long long tp[MAXN], td[MAXN];
void pre(int v, int p = 0) {
if (v == n) pa[v] = true;
for (pair<long long, long long> first : k[v]) {
long long u = first.first;
if (u != p) {
pre(u, v);
if (pa[u]) pa[v] = true;
}
}
if (pa[v]) li.push_back(v);
}
void dfs(int v, int p = 0) {
subsz[v] = 1;
di[v] = 0;
for (pair<long long, long long> first : k[v]) {
long long u = first.first;
if (u != p) {
dfs(u, v);
subsz[v] += subsz[u];
if (!pa[u]) di[v] = first.second;
if (!pa[u]) shack[v] += subsz[u];
}
}
}
void cpref(int v, int p = 0, long long sum = 0) {
pref[v] = sum;
for (pair<long long, long long> first : k[v]) {
if (first.first != p && pa[first.first])
cpref(first.first, v, sum + first.second);
}
}
long long find(long long l, long long r) {
if (l == r) return 1e18;
long long mid = (l + r) / 2;
long long ret = 1e18;
ret = min(ret, find(l, mid));
ret = min(ret, find(mid + 1, r));
long long bl = 1e18;
long long br = 1e18;
for (int i = l; i <= mid; i++)
if (td[i] != 0) bl = min(bl, tp[mid] - tp[i] - td[i]);
for (int i = mid + 1; i <= r; i++)
if (td[i] != 0) br = min(br, tp[i] - tp[mid + 1] - td[i]);
ret = min(ret, bl + br + tp[mid + 1] - tp[mid]);
return ret;
}
int main() {
scanf(" %d %d", &n, &m);
for (int i = 1; i < n; i++) {
long long v, u, w;
scanf(" %lld %lld %lld", &v, &u, &w);
k[v].push_back(pair<long long, long long>(u, w));
k[u].push_back(pair<long long, long long>(v, w));
}
pre(1);
dfs(1);
long long dif = 1e18;
for (auto first : li)
if (shack[first] > 1) dif = -1;
long long cnt = 0;
reverse(li.begin(), li.end());
cpref(1);
for (auto first : li) {
++cnt;
td[cnt] = di[first];
tp[cnt] = pref[first];
}
if (dif != -1) {
for (int i = 1; i < cnt - 1; i++) dif = min(dif, tp[i + 2] - tp[i]);
for (int i = 1; i <= cnt; i++) {
if (td[i] != 0) {
if (i != 1) dif = min(dif, tp[i] - tp[i - 1] - td[i]);
if (i != cnt) dif = min(dif, tp[i + 1] - tp[i] - td[i]);
}
}
dif = min(dif, find(1, cnt));
}
for (int i = 0; i < m; i++) {
long long first;
scanf(" %lld", &first);
printf("%lld\n", min(tp[cnt], tp[cnt] - dif + first));
}
}
|
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future.
On the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on.
The director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending.
Input
The first line contains three integers n, a, and b (1 ≤ n ≤ 20, 1 ≤ a, b ≤ 100) — the number of dancers, the cost of a white suit, and the cost of a black suit.
The next line contains n numbers c_i, i-th of which denotes the color of the suit of the i-th dancer. Number 0 denotes the white color, 1 — the black color, and 2 denotes that a suit for this dancer is still to be bought.
Output
If it is not possible to form a palindrome without swapping dancers and buying new suits for those who have one, then output -1. Otherwise, output the minimal price to get the desired visual effect.
Examples
Input
5 100 1
0 1 2 1 2
Output
101
Input
3 10 12
1 2 0
Output
-1
Input
3 12 1
0 1 0
Output
0
Note
In the first sample, the cheapest way to obtain palindromic colors is to buy a black suit for the third from left dancer and a white suit for the rightmost dancer.
In the second sample, the leftmost dancer's suit already differs from the rightmost dancer's suit so there is no way to obtain the desired coloring.
In the third sample, all suits are already bought and their colors form a palindrome.
|
def go():
n, a, b = [int(i) for i in input().split(' ')]
x = [int(i) for i in input().split(' ')]
total = 0
for i in range(n // 2):
if (x[i] == 1 and x[n - 1 - i] == 0) or (x[i] == 0 and x[n - 1 - i] == 1):
return -1
elif x[i] == 2 and x[i] == x[n - 1 - i]:
total += 2 * min(a, b)
elif x[i] == 2:
if x[n - i - 1] == 1:
total += b
else:
total += a
elif x[n - i - 1] == 2:
if x[i] == 1:
total += b
else:
total += a
if n % 2 == 1 and x[n // 2] == 2:
total += min(a, b)
return total
print(go())
|
A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.
A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.
Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is 6 because all its substrings are palindromes, and the palindromic count of the string "abc" is 3 because only its substrings of length 1 are palindromes.
You are given a string s. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000) — the length of string s.
The second line contains string s that consists of exactly n lowercase characters of Latin alphabet.
Output
Print string t, which consists of the same set of characters (and each characters appears exactly the same number of times) as string s. Moreover, t should have the maximum possible value of palindromic count among all such strings strings.
If there are multiple such strings, print any of them.
Examples
Input
5
oolol
Output
ololo
Input
16
gagadbcgghhchbdf
Output
abccbaghghghgdfd
Note
In the first example, string "ololo" has 9 palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.
In the second example, the palindromic count of string "abccbaghghghgdfd" is 29.
|
#include <bits/stdc++.h>
using namespace std;
vector<int> vv1;
int lim = 1000000;
bool prime[1000000];
void sieve() {
memset(prime, true, sizeof(prime));
prime[0] = prime[1] = false;
for (int i = 2; i * i < lim; i++) {
if (prime[i]) {
for (int j = i * i; j < lim; j = j + i) {
prime[j] = false;
}
}
}
for (int i = 0; i < lim; i++)
if (prime[i]) vv1.push_back(i);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
sieve();
long long tt, cn = 0, cn1 = 0, r = 0, l = 0, h = 0;
tt = 1;
read:
while (tt--) {
vector<long long> vec2, vec1, vec, vec3, vec4, vec11;
vector<pair<long long, long long>> ve;
double x1, x2, x3, x4, y1, y2, y3, y4;
long long a, d, b, c, cn = 0, sum = 0, mx = 0, mx1 = 0, cn1 = 0;
string s;
cin >> a >> s;
sort(s.begin(), s.end());
cout << s << endl;
}
return 0;
}
|
Once Grisha found a tree (connected graph without cycles) with a root in node 1.
But this tree was not just a tree. A permutation p of integers from 0 to n - 1 is written in nodes, a number p_i is written in node i.
As Grisha likes to invent some strange and interesting problems for himself, but not always can solve them, you need to help him deal with two types of queries on this tree.
Let's define a function MEX(S), where S is a set of non-negative integers, as a smallest non-negative integer that is not included in this set.
Let l be a simple path in this tree. So let's define indices of nodes which lie on l as u_1, u_2, …, u_k.
Define V(l) as a set {p_{u_1}, p_{u_2}, … , p_{u_k}}.
Then queries are:
1. For two nodes i and j, swap p_i and p_j.
2. Find the maximum value of MEX(V(l)) in all possible l.
Input
The first line contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of nodes of a tree.
The second line contains n integers — p_1, p_2, …, p_n (0≤ p_i < n) — the permutation p, it's guaranteed that all numbers are different .
The third line contains n - 1 integers — d_2, d_3, …, d_n (1 ≤ d_i < i), where d_i is a direct ancestor of node i in a tree.
The fourth line contains a single integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries.
The following q lines contain the description of queries:
At the beginning of each of next q lines, there is a single integer t (1 or 2) — the type of a query:
1. If t = 1, the line also contains two integers i and j (1 ≤ i, j ≤ n) — the indices of nodes, where values of the permutation should be swapped.
2. If t = 2, you need to find the maximum value of MEX(V(l)) in all possible l.
Output
For each type 2 query print a single integer — the answer for this query.
Examples
Input
6
2 5 0 3 1 4
1 1 3 3 3
3
2
1 6 3
2
Output
3
2
Input
6
5 2 1 4 3 0
1 1 1 3 3
9
2
1 5 3
2
1 6 1
2
1 4 2
2
1 1 6
2
Output
3
2
4
4
2
Note
Number written in brackets is a permutation value of a node.
<image> In the first example, for the first query, optimal path is a path from node 1 to node 5. For it, set of values is \{0, 1, 2\} and MEX is 3. <image> For the third query, optimal path is a path from node 5 to node 6. For it, set of values is \{0, 1, 4\} and MEX is 2. <image> In the second example, for the first query, optimal path is a path from node 2 to node 6. For it, set of values is \{0, 1, 2, 5\} and MEX is 3. <image> For the third query, optimal path is a path from node 5 to node 6. For it, set of values is \{0, 1, 3\} and MEX is 2. <image> For the fifth query, optimal path is a path from node 5 to node 2. For it, set of values is \{0, 1, 2, 3\} and MEX is 4. <image> For the seventh query, optimal path is a path from node 5 to node 4. For it, set of values is \{0, 1, 2, 3\} and MEX is 4. <image> For the ninth query, optimal path is a path from node 6 to node 5. For it, set of values is \{0, 1, 3\} and MEX is 2.
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, tme, m = 1, q;
int a[N], pl[N], p[N], dep[N], B[N], E[N];
int lg[N * 2];
pair<int, int> MN[22][N * 2];
vector<int> son[N];
int lca(int x, int y) {
if (B[x] > B[y]) swap(x, y);
x = B[x], y = E[y];
int l = lg[y - x + 1];
return min(MN[l][x], MN[l][y - (1 << l) + 1]).second;
}
void dfs(int x) {
B[x] = E[x] = ++tme;
MN[0][tme] = make_pair(dep[x], x);
for (int i = 0; i < int(son[x].size()); i++) {
int to = son[x][i];
dep[to] = dep[x] + 1;
dfs(to);
E[x] = ++tme;
MN[0][tme] = make_pair(dep[x], x);
}
}
struct Line {
int status;
int px, py;
Line() : px(0), py(0), status(0){};
Line(int px, int py) : px(px), py(py), status(1){};
int length() const { return dep[px] + dep[py] - 2 * dep[lca(px, py)]; }
bool operator<(const Line &oth) const { return length() < oth.length(); }
bool operator>(const Line &oth) const { return oth < (*this); }
bool operator==(const Line &oth) const {
return !((*this) < oth) && !(oth < (*this));
}
Line operator+(const Line &oth) const {
if (!status) return oth;
if (!oth.status) return (*this);
if (status == 2) return (*this);
if (oth.status == 2) return oth;
Line r[7], mx, res;
mx = r[1] = (*this);
r[2] = oth;
r[3] = Line(px, oth.px);
r[4] = Line(px, oth.py);
r[5] = Line(py, oth.px);
r[6] = Line(py, oth.py);
for (int i = 1; i <= 6; i++) mx = max(mx, r[i]);
for (int i = 1; i <= 6; i++)
if (mx == r[i]) {
if (Line(mx.px, px).length() + Line(px, mx.py).length() ==
mx.length() &&
Line(mx.px, py).length() + Line(py, mx.py).length() ==
mx.length() &&
Line(mx.px, oth.px).length() + Line(oth.px, mx.py).length() ==
mx.length() &&
Line(mx.px, oth.py).length() + Line(oth.py, mx.py).length() ==
mx.length())
res = mx;
else
res.status = 2;
break;
}
return res;
}
};
int lson[N * 2], rson[N * 2];
Line val[N * 2];
void build(int pos, int x, int y) {
if (x == y) {
val[pos] = Line(pl[x], pl[x]);
return;
}
int mid = (x + y) >> 1;
lson[pos] = ++m;
rson[pos] = ++m;
build(lson[pos], x, mid);
build(rson[pos], mid + 1, y);
val[pos] = val[lson[pos]] + val[rson[pos]];
}
void modify(int pos, int x, int y, int l) {
if (x >= l && y <= l) {
val[pos] = Line(pl[l], pl[l]);
return;
}
if (x > l || y < l) return;
int mid = (x + y) >> 1;
modify(lson[pos], x, mid, l);
modify(rson[pos], mid + 1, y, l);
val[pos] = val[lson[pos]] + val[rson[pos]];
}
int query(int pos, int x, int y, Line v) {
Line nv;
if (x == y) {
nv = v + val[pos];
if (nv.status == 2) x--;
return x;
}
nv = v + val[lson[pos]];
int mid = (x + y) >> 1;
if (nv.status != 2)
return query(rson[pos], mid + 1, y, nv);
else
return query(lson[pos], x, mid, v);
}
int main() {
lg[1] = 0;
for (int i = 2; i < N * 2; i++) lg[i] = lg[i / 2] + 1;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
x++;
a[i] = x;
pl[x] = i;
}
for (int i = 2; i <= n; i++) {
scanf("%d", p + i);
son[p[i]].push_back(i);
}
dfs(1);
for (int i = 1; i <= 21; i++)
for (int j = 1; j + (1 << i) - 1 <= tme; j++)
MN[i][j] = min(MN[i - 1][j], MN[i - 1][j + (1 << (i - 1))]);
build(1, 1, n);
scanf("%d", &q);
while (q--) {
int o;
scanf("%d", &o);
if (o == 1) {
int x, y;
scanf("%d%d", &x, &y);
swap(a[x], a[y]);
pl[a[x]] = x;
pl[a[y]] = y;
modify(1, 1, n, a[x]);
modify(1, 1, n, a[y]);
} else
printf("%d\n", query(1, 1, n, Line()));
}
return 0;
}
|
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>
|
s = input()
f1 = 0; f2 = 0
for i in s:
if i=='1' and f1==0:
print(1,3); f1=1
elif i=='1' and f1==1:
print(1,1)
f1=0
elif i=='0' and f2==0:
print(3,1); f2=1
elif i=='0' and f2==1:
print(1,1); f2=0
|
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; "))" and ")((" are bracket sequences (but not regular ones), and "(a)" and "(1)+(1)" are not bracket sequences at all.
You have a number of strings; each string is a bracket sequence of length 2. So, overall you have cnt_1 strings "((", cnt_2 strings "()", cnt_3 strings ")(" and cnt_4 strings "))". You want to write all these strings in some order, one after another; after that, you will get a long bracket sequence of length 2(cnt_1 + cnt_2 + cnt_3 + cnt_4). You wonder: is it possible to choose some order of the strings you have such that you will get a regular bracket sequence? Note that you may not remove any characters or strings, and you may not add anything either.
Input
The input consists of four lines, i-th of them contains one integer cnt_i (0 ≤ cnt_i ≤ 10^9).
Output
Print one integer: 1 if it is possible to form a regular bracket sequence by choosing the correct order of the given strings, 0 otherwise.
Examples
Input
3
1
4
3
Output
1
Input
0
0
0
0
Output
1
Input
1
2
3
4
Output
0
Note
In the first example it is possible to construct a string "(())()(()((()()()())))", which is a regular bracket sequence.
In the second example it is possible to construct a string "", which is a regular bracket sequence.
|
R = lambda : map(int, raw_input().split())
a = int(raw_input())
b = int(raw_input())
c = int(raw_input())
d = int(raw_input())
if(c!=0):
if a!=0 and d!=0 and a==d: print 1
else: print 0
elif(a==d): print 1
else: print 0
|
Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...
It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of weird things, including a [trie](https://en.wikipedia.org/wiki/Trie) of all correct bracket sequences of length 2n.
The definition of correct bracket sequence is as follows:
* The empty sequence is a correct bracket sequence,
* If s is a correct bracket sequence, then (\,s ) is a correct bracket sequence,
* If s and t are a correct bracket sequence, then st is also a correct bracket sequence.
For example, the strings "(())", "()()" form a correct bracket sequence, while ")(" and "((" not.
Aki then came up with an interesting problem: What is the size of the maximum matching (the largest set of edges such that there are no two edges with a common vertex) in this trie? Since the answer can be quite large, print it modulo 10^9 + 7.
Input
The only line contains a single integer n (1 ≤ n ≤ 1000).
Output
Print exactly one integer — the size of the maximum matching in the trie. Since the answer can be quite large, print it modulo 10^9 + 7.
Examples
Input
1
Output
1
Input
2
Output
3
Input
3
Output
9
Note
The pictures below illustrate tries in the first two examples (for clarity, the round brackets are replaced with angle brackets). The maximum matching is highlighted with blue.
<image> <image>
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cplayer
*/
public class Main {
public static void main (String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DNekoAndAkisPrank solver = new DNekoAndAkisPrank();
solver.solve(1, in, out);
out.close();
}
static class DNekoAndAkisPrank {
private int mod = 1000000000 + 7;
public void solve (int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[][] dp = new int[2 * n + 5][2 * n + 5];
dp[0][0] = 1;
for (int i = 0; i < 2 * n; ++i) {
for (int j = 0; j < 2 * n; ++j) {
dp[i + 1][j + 1] += dp[i][j];
dp[i + 1][j + 1] %= mod;
if (j > 0) {
dp[i + 1][j - 1] += dp[i][j];
dp[i + 1][j - 1] %= mod;
}
}
}
long ans = 0;
for (int i = 1; i < 2 * n; i += 2) {
for (int j = 0; j <= 2 * n; ++j) {
if (i + j <= 2 * n) {
ans += dp[i][j];
ans %= mod;
}
}
}
out.println(ans);
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader (InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next () {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
public int nextInt () {
return Integer.parseInt(next());
}
}
}
|
You're given an array a of length n. You can perform the following operation on it as many times as you want:
* Pick two integers i and j (1 ≤ i,j ≤ n) such that a_i+a_j is odd, then swap a_i and a_j.
What is lexicographically the smallest array you can obtain?
An array x is [lexicographically smaller](https://en.wikipedia.org/wiki/Lexicographical_order) than an array y if there exists an index i such that x_i<y_i, and x_j=y_j for all 1 ≤ j < i. Less formally, at the first index i in which they differ, x_i<y_i
Input
The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of elements in the array a.
The second line contains n space-separated integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
The only line contains n space-separated integers, the lexicographically smallest array you can obtain.
Examples
Input
3
4 1 7
Output
1 4 7
Input
2
1 1
Output
1 1
Note
In the first example, we can swap 1 and 4 since 1+4=5, which is odd.
|
#include <bits/stdc++.h>
using namespace std;
int a[100005];
int main() {
int n;
bool odd = false;
bool even = false;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
if (a[i] % 2)
odd = true;
else
even = true;
}
if (odd && even) sort(a + 1, a + 1 + n);
for (int i = 1; i <= n; ++i) printf("%d ", a[i]);
return 0;
}
|
We are going to build a new city: the Metropolis. The city is going to be built on an infinite square grid. The finished city will consist of n skyscrapers, each occupying a different cell of the grid. At any moment during the construction, the cells that currently do not contain a skyscraper are called empty.
You are given the planned coordinates of the n skyscrapers. Your task is to find an order in which they can be built while satisfying the rules listed below.
* The building crew has only one crane, so the Metropolis has to be constructed one skyscraper at a time.
* The first skyscraper can be built anywhere on the grid.
* Each subsequent skyscraper has to share a side or a corner with at least one of the previously built skyscrapers (so that it's easier to align the new skyscraper to the grid properly).
* When building a skyscraper, there has to be a way to deliver material to the construction site from the outside of Metropolis by only moving it through empty cells that share a side. In other words, there should be a path of side-adjacent empty cells that connects the cell that will contain the skyscraper to some cell (r,c) with |r|>10^9 and/or |c|>10^9.
If a solution exists, let's denote the numbers of skyscrapers in the order in which they should be built by s_1, ..., s_n. There are two types of subtasks:
Type 1: You may produce any valid order.
Type 2: You must find the order that maximizes s_n. Among those, you must find the one that maximizes s_{n-1}. And so on. In other words, you must find the valid order of building for which the sequence (s_n,s_{n-1},...,s_1) is lexicographically largest.
Input
The first line contains a single integer n (1 ≤ n ≤ 150,000) – the number of skyscrapers.
The second line contains a single integer t (1 ≤ t ≤ 2) describing the type of the subtask as defined above.
Then, n lines follow. The i-th of these lines contains two space-separated integers r_i and c_i (|r_i|, |c_i| ≤ 10^9) denoting the coordinates of the cell containing skyscraper i.
(The skyscrapers are not numbered in any particular order. The only reason why they have numbers is that they are used in the output format.)
It is guaranteed that no two skyscrapers coincide.
Output
If it is impossible to build the skyscrapers according to the given rules, print a single line containing the string "NO".
Otherwise, print n+1 lines. The first of these lines should contain the string "YES". For each i, the i-th of the remaining n lines should contain a single integer s_i.
In subtasks with t = 1, if there are multiple valid orders, you may output any one of them.
Scoring
Subtask 1 (8 points): t = 1 and n ≤ 10
Subtask 2 (14 points): t = 1 and n ≤ 200
Subtask 3 (12 points): t = 1 and n ≤ 2,000
Subtask 4 (17 points): t = 2 and n ≤ 2,000
Subtask 5 (20 points): t = 1
Subtask 6 (10 points): t = 2, n ≤ 70,000 and |r_i|, |c_i| ≤ 900 for each i
Subtask 7 (19 points): t = 2
Examples
Input
3
2
0 0
0 1
0 2
Output
YES
1
2
3
Input
3
1
0 0
1 1
2 2
Output
YES
2
3
1
Input
2
1
0 0
0 2
Output
NO
Note
In the first example, there are three skyscrapers in a row. All of them can always be reached from outside the Metropolis, and there are four build orders which preserve connectivity:
* 1, 2, 3
* 2, 1, 3
* 2, 3, 1
* 3, 2, 1
Since t = 2, we must choose the first option.
In the second example, the only difference from the first example is that skyscraper 2 shares only corners with skyscrapers 1 and 3, the same set of orders as in the first sample is valid. Since t = 1, each of these answers is correct.
In the third example, the Metropolis is disconnected. We obviously can't build that.
|
#include <bits/stdc++.h>
using namespace std;
void vin(std::vector<int> &a) {
for (auto &x : a) cin >> x;
}
void vout(std::vector<int> &a) {
for (auto x : a) cout << x << " ";
cout << endl;
}
std::vector<set<int> > pqp, pqb;
struct UF {
std::vector<int> p;
UF(int n) {
p.resize(n);
pqb.resize(n);
pqp.resize(n);
iota(p.begin(), p.end(), 0);
}
int root(int a) {
if (a == p[a]) return a;
return (p[a] = root(p[a]));
}
bool find(int a, int b) { return root(a) == root(b); }
void connect(int a, int b) {
a = root(a);
b = root(b);
if (a == b) return;
if (pqp[a].size() < pqp[b].size()) swap(a, b);
p[b] = a;
for (auto x : pqp[b]) pqp[a].insert(x);
pqp[b].clear();
}
};
std::vector<pair<long long, long long> > nei{
make_pair(-1, 0), make_pair(-1, 1), make_pair(0, 1), make_pair(1, 1),
make_pair(1, 0), make_pair(1, -1), make_pair(0, -1), make_pair(-1, -1)};
std::vector<pair<pair<long long, long long>, pair<int, int> > > s;
int indexb(long long x, long long y) {
auto it = lower_bound(s.begin(), s.end(),
make_pair(make_pair(x, y), make_pair(-1, -1)));
if (it == s.end()) return -1;
if (it->first == make_pair(x, y) && it->second.second) return it - s.begin();
return -1;
}
int indexp(long long x, long long y) {
auto it = lower_bound(s.begin(), s.end(),
make_pair(make_pair(x, y), make_pair(-1, -1)));
if (it == s.end()) return 0;
if (it->first == make_pair(x, y) && it->second.second) return -1;
return it - s.begin();
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, tin;
cin >> n >> tin;
s.resize(n);
long long xmi = 1000000000, xma = -1000000000, ymi = 1000000000,
yma = -1000000000;
for (int i = 0; i < n; i++) {
cin >> s[i].first.first >> s[i].first.second;
s[i].second.first = i;
s[i].second.second = 1;
xmi = min(xmi, s[i].first.first);
xma = max(xma, s[i].first.first);
ymi = min(ymi, s[i].first.second);
yma = max(yma, s[i].first.second);
}
if (xma - xmi > n || yma - ymi > n) {
cout << "NO\n";
return 0;
}
sort(s.begin(), s.end());
UF buf(n);
for (int i = 0; i < n; i++) {
int j = indexb(s[i].first.first + 1, s[i].first.second);
if (j != -1) buf.connect(i, j);
j = indexb(s[i].first.first, s[i].first.second + 1);
if (j != -1) buf.connect(i, j);
j = indexb(s[i].first.first + 1, s[i].first.second + 1);
if (j != -1) buf.connect(i, j);
j = indexb(s[i].first.first + 1, s[i].first.second - 1);
if (j != -1) buf.connect(i, j);
}
for (int i = 1; i < n; i++)
if (!buf.find(0, i)) {
cout << "NO\n";
cerr << "bufno\n";
return 0;
}
cerr << "bufsi\n";
UF puf(n);
for (int i = 0; i < n; i++) {
if (i > 0 && s[i].first.first == s[i - 1].first.first) {
if (s[i].first.first == xmi &&
s[i].first.second > s[i - 1].first.second + 1)
puf.connect(i, 0);
for (int j = s[i - 1].first.second + 1; j < s[i].first.second; j++) {
int k = indexp(s[i - 1].first.first + 1, j);
if (k == -1) continue;
puf.connect(i, k);
if (s[k].first.second < j) break;
j = s[k].first.second;
}
} else {
puf.connect(i, 0);
for (int j = s[(i + n - 1) % n].first.second + 1; j <= yma; j++) {
int k = indexp(s[(i + n - 1) % n].first.first + 1, j);
if (k == -1) continue;
puf.connect(i, k);
if (s[k].first.second < j) break;
j = s[k].first.second;
}
for (int j = ymi; j < s[i].first.second; j++) {
int k = indexp(s[i].first.first + 1, j);
if (k == -1) continue;
puf.connect(i, k);
if (s[k].first.second < j) break;
j = s[k].first.second;
}
}
}
std::vector<int> ord(n, -1);
std::vector<int> is(n);
priority_queue<int> pqm;
for (int i = 0; i < n; i++) {
is[s[i].second.first] = i;
pqm.push(i);
}
int o = n - 1;
int ccfo = 0;
while (!pqm.empty()) {
int i = pqm.top();
pqm.pop();
ccfo++;
auto b = s[is[i]];
int ip = indexb(b.first.first, b.first.second);
if (ip == -1) continue;
int co = 0;
for (int j = 0; j < 8; j += 2) {
int p =
indexp(b.first.first + nei[j].first, b.first.second + nei[j].second);
if (p != -1 && puf.find(p, 0))
co = 1;
else if (p != -1)
pqp[puf.root(p)].emplace(ip);
else
pqb[indexb(b.first.first + nei[j].first,
b.first.second + nei[j].second)]
.emplace(ip);
}
if (co) {
std::vector<int> bw;
for (int j = 0; j < 8; j++) {
int x = b.first.first + nei[j].first,
y = b.first.second + nei[j].second;
int a = indexp(x, y);
if (a == -1) {
a = indexb(x, y);
pqb[a].emplace(ip);
continue;
}
x = b.first.first + nei[(j + 1) % 8].first,
y = b.first.second + nei[(j + 1) % 8].second;
if (indexb(x, y) == -1) continue;
if (j % 2) {
x = b.first.first + nei[(j + 7) % 8].first,
y = b.first.second + nei[(j + 7) % 8].second;
if (indexp(x, y) == -1) continue;
}
bw.push_back(a);
}
for (int i = 0; i < (int)bw.size(); i++)
for (int j = i + 1; j < (int)bw.size(); j++)
if (puf.find(bw[i], bw[j])) {
co = 0;
break;
}
}
int ch = 0;
if (co) {
s[is[i]].second.second = 0;
if (indexb(b.first.first - 1, b.first.second) == -1 &&
!puf.find(indexp(b.first.first - 1, b.first.second), ip)) {
ch++;
puf.connect(indexp(b.first.first - 1, b.first.second), ip);
}
if (indexb(b.first.first + 1, b.first.second) == -1 &&
!puf.find(indexp(b.first.first + 1, b.first.second), ip)) {
ch++;
puf.connect(indexp(b.first.first + 1, b.first.second), ip);
}
if (indexb(b.first.first, b.first.second - 1) == -1 &&
!puf.find(indexp(b.first.first, b.first.second - 1), ip)) {
ch++;
puf.connect(indexp(b.first.first, b.first.second - 1), ip);
}
if (indexb(b.first.first, b.first.second + 1) == -1 &&
!puf.find(indexp(b.first.first, b.first.second + 1), ip)) {
ch++;
puf.connect(indexp(b.first.first, b.first.second + 1), ip);
}
ord[i] = o--;
if (i == 69) cerr << "helloworld\n";
for (auto x : pqp[puf.root(ip)]) pqm.emplace(s[x].second.first);
pqp[puf.root(ip)].clear();
for (auto x : pqb[ip]) pqm.emplace(s[x].second.first);
pqb[ip].clear();
}
}
cerr << ccfo << "\n";
assert(o == -1);
cout << "YES\n";
std::vector<int> out(n);
for (int i = 0; i < n; i++) {
assert(ord[i] != -1);
out[ord[i]] = i + 1;
}
vout(out);
}
|
You are given a set of n vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector vi = (xi, yi) can be transformed into one of the following four vectors:
* vi1 = (xi, yi),
* vi2 = ( - xi, yi),
* vi3 = (xi, - yi),
* vi4 = ( - xi, - yi).
You should find two vectors from the set and determine which of their coordinates should be multiplied by -1 so that the absolute value of the sum of the resulting vectors was minimally possible. More formally, you should choose two vectors vi, vj (1 ≤ i, j ≤ n, i ≠ j) and two numbers k1, k2 (1 ≤ k1, k2 ≤ 4), so that the value of the expression |vik1 + vjk2| were minimum.
Input
The first line contains a single integer n (2 ≤ n ≤ 105). Then n lines contain vectors as pairs of integers "xi yi" ( - 10000 ≤ xi, yi ≤ 10000), one pair per line.
Output
Print on the first line four space-separated numbers "i k1 j k2" — the answer to the problem. If there are several variants the absolute value of whose sums is minimum, you can print any of them.
Examples
Input
5
-7 -3
9 0
-8 6
7 -8
4 -5
Output
3 2 4 2
Input
5
3 2
-4 7
-6 0
-8 4
5 1
Output
3 4 5 4
Note
A sum of two vectors v = (xv, yv) and u = (xu, yu) is vector s = v + u = (xv + xu, yv + yu).
An absolute value of vector v = (x, y) is number <image>.
In the second sample there are several valid answers, such as:
(3 1 4 2), (3 1 4 4), (3 4 4 1), (3 4 4 3), (4 1 3 2), (4 1 3 4), (4 2 3 1).
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main implements Runnable {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private Random rnd;
class Pair implements Comparable<Pair> {
final long x, y;
final int id;
Pair(long x, long y, int id) {
this.x = x;
this.y = y;
this.id = id;
}
public int compareTo(Pair o) {
long l1 = this.x * this.x + this.y * this.y;
long l2 = o.x * o.x + o.y * o.y;
if(l1 < l2) return 1;
else if(l1 > l2) return -1;
else return 0;
}
}
final int border = 100;
long res = Long.MAX_VALUE;
int ians = -1, jans = -1, k1ans = -1, k2ans = -1;
Pair[] xy;
private void check(int i, int j) {
long x = (Math.abs(xy[i].x) - Math.abs(xy[j].x));
long y = (Math.abs(xy[i].y) - Math.abs(xy[j].y));
long cur_res = x * x + y * y;
if(cur_res < res) {
res = cur_res;
ians = xy[i].id;
jans = xy[j].id;
k1ans = getK(xy[i].x, xy[i].y);
k2ans = getKrev(xy[j].x, xy[j].y);
}
}
private int getK(long x, long y) {
if(x >= 0 && y >= 0) return 1;
else if(x <= 0 && y >= 0) return 2;
else if(x >= 0 && y <= 0) return 3;
else if(x <= 0 && y <= 0) return 4;
else return -1;
}
private int getKrev(long x, long y) {
if(x >= 0 && y >= 0) return 4;
else if(x <= 0 && y >= 0) return 3;
else if(x >= 0 && y <= 0) return 2;
else if(x <= 0 && y <= 0) return 1;
else return -1;
}
public void solve() throws IOException {
int n = nextInt();
xy = new Pair[n];
for(int i = 0; i < n; i++) {
int x = nextInt(), y = nextInt();
xy[i] = new Pair(x, y, i + 1);
}
Arrays.sort(xy);
for(int i = 0; i < n; i++) {
for(int j = Math.max(0, i - border); j < Math.min(n, i + border); j++) {
if(i == j) continue;
check(i, j);
}
}
out.println(ians + " " + k1ans + " " + jans + " " + k2ans);
}
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
//in = new BufferedReader(new InputStreamReader((System.in)));
//out = new PrintWriter(System.out);
st = null;
rnd = new Random();
solve();
out.close();
} catch(IOException e) {
e.printStackTrace();
}
}
private String nextToken() throws IOException, NullPointerException {
while(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.
Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i and b_i; b_i is equal to the skill level of the i-th student (the higher, the better). Also, there are 60 known algorithms, which are numbered with integers from 0 to 59. If the i-th student knows the j-th algorithm, then the j-th bit (2^j) is set in the binary representation of a_i. Otherwise, this bit is not set.
Student x thinks that he is better than student y if and only if x knows some algorithm which y doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.
Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
Input
The first line contains one integer n (1 ≤ n ≤ 7000) — the number of students interested in the camp.
The second line contains n integers. The i-th of them is a_i (0 ≤ a_i < 2^{60}).
The third line contains n integers. The i-th of them is b_i (1 ≤ b_i ≤ 10^9).
Output
Output one integer which denotes the maximum sum of b_i over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
Examples
Input
4
3 2 3 6
2 8 5 10
Output
15
Input
3
1 2 3
1 2 3
Output
0
Input
1
0
1
Output
0
Note
In the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of b_i.
In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
|
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
made by Ray Bai
*/
import java.util.*;
import java.io.*;
public class D2
{
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
long[] A = new long[N];
long[] B = new long[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
A[i] = Long.parseLong(st.nextToken());
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
B[i] = Long.parseLong(st.nextToken());
//merge
HashMap<Long, Long> map = new HashMap<Long, Long>();
HashMap<Long, Integer> mc = new HashMap<Long, Integer>();
for(int i=0; i < N; i++)
{
if(!map.containsKey(A[i]))
{
mc.put(A[i], 0);
map.put(A[i], 0L);
}
map.put(A[i], map.get(A[i])+B[i]);
mc.put(A[i], mc.get(A[i])+1);
}
ArrayList<Boy> ls = new ArrayList<Boy>();
for(long k: map.keySet())
ls.add(new Boy(k, map.get(k), mc.get(k)));
//
long res = 0L;
ArrayList<Long> masks = new ArrayList<Long>();
for(int a=0; a < ls.size(); a++)
{
Boy boi = ls.get(a);
if(boi.count > 1)
{
res += boi.b;
masks.add(boi.a);
}
}
//addend
for(int i=0; i < ls.size(); i++)
{
if(ls.get(i).count > 1)
continue;
long mask = ls.get(i).a;
boolean flag = false;
for(long boof: masks)
if((boof^mask) == boof-mask)
flag = true;
if(flag)
res += ls.get(i).b;
}
System.out.println(res);
}
}
class Boy
{
public long a;
public long b;
public int count;
public Boy(long c, long f, int r)
{
a = c;
b = f;
count = r;
}
}
|
Recently a lot of students were enrolled in Berland State University. All students were divided into groups according to their education program. Some groups turned out to be too large to attend lessons in the same auditorium, so these groups should be divided into two subgroups. Your task is to help divide the first-year students of the computer science faculty.
There are t new groups belonging to this faculty. Students have to attend classes on three different subjects — maths, programming and P. E. All classes are held in different places according to the subject — maths classes are held in auditoriums, programming classes are held in computer labs, and P. E. classes are held in gyms.
Each group should be divided into two subgroups so that there is enough space in every auditorium, lab or gym for all students of the subgroup. For the first subgroup of the i-th group, maths classes are held in an auditorium with capacity of a_{i, 1} students; programming classes are held in a lab that accomodates up to b_{i, 1} students; and P. E. classes are held in a gym having enough place for c_{i, 1} students. Analogically, the auditorium, lab and gym for the second subgroup can accept no more than a_{i, 2}, b_{i, 2} and c_{i, 2} students, respectively.
As usual, some students skip some classes. Each student considers some number of subjects (from 0 to 3) to be useless — that means, he skips all classes on these subjects (and attends all other classes). This data is given to you as follows — the i-th group consists of:
1. d_{i, 1} students which attend all classes;
2. d_{i, 2} students which attend all classes, except for P. E.;
3. d_{i, 3} students which attend all classes, except for programming;
4. d_{i, 4} students which attend only maths classes;
5. d_{i, 5} students which attend all classes, except for maths;
6. d_{i, 6} students which attend only programming classes;
7. d_{i, 7} students which attend only P. E.
There is one more type of students — those who don't attend any classes at all (but they, obviously, don't need any place in auditoriums, labs or gyms, so the number of those students is insignificant in this problem).
Your task is to divide each group into two subgroups so that every auditorium (or lab, or gym) assigned to each subgroup has enough place for all students from this subgroup attending the corresponding classes (if it is possible). Each student of the i-th group should belong to exactly one subgroup of the i-th group; it is forbidden to move students between groups.
Input
The first line contains one integer t (1 ≤ t ≤ 300) — the number of groups.
Then the descriptions of groups follow. The description of the i-th group consists of three lines:
* the first line contains three integers a_{i, 1}, b_{i, 1} and c_{i, 1} (1 ≤ a_{i, 1}, b_{i, 1}, c_{i, 1} ≤ 3000) — the capacity of the auditorium, lab and gym assigned to the first subgroup of the i-th group, respectively;
* the second line contains three integers a_{i, 2}, b_{i, 2} and c_{i, 2} (1 ≤ a_{i, 2}, b_{i, 2}, c_{i, 2} ≤ 3000) — the capacity of the auditorium, lab and gym assigned to the second subgroup of the i-th group, respectively;
* the third line contains integers d_{i, 1}, d_{i, 2}, ..., d_{i, 7} (0 ≤ d_{i, j} ≤ 3000) — the number of students belonging to each of the seven aforementioned types in the i-th group. It is not guaranteed that the sum of these values is positive — a group can consist entirely of students that don't attend classes at all.
It is guaranteed that the total number of students in all groups is not greater than 3000.
Output
For each group, print the result of its division as follows:
* if it is impossible to divide the group, print one integer -1;
* otherwise print seven integers f_{i, 1}, f_{i, 2}, ..., f_{i, 7} (0 ≤ f_{i, j} ≤ d_{i, j}) — the number of students the first, second, ..., seventh type in the first subgroup of the i-th group (all other students will be assigned to the second subgroup). If there are multiple answers, print any of them.
Example
Input
3
9 4 13
1 10 3
1 2 3 4 5 6 7
9 4 13
1 10 3
2 1 3 4 5 6 7
1 2 3
4 5 6
0 0 0 0 0 0 0
Output
1 1 3 4 2 0 7
-1
0 0 0 0 0 0 0
|
#include <bits/stdc++.h>
using namespace std;
int rd() {
int x = 0, f = 1;
char c = getchar();
while (!isdigit(c)) {
if (c == '-') f = -1;
c = getchar();
}
while (isdigit(c)) x = (x << 3) + (x << 1) + c - '0', c = getchar();
return x * f;
}
int T, a[3], b[3], c[3];
int ans[8], flag;
vector<int> d;
bool check1(int A_1, int B_1, int C_1, int A_2, int B_2, int C_2,
vector<int> cnt) {
ans[5] = min(min(B_1, C_1), cnt[5]);
cnt[5] -= ans[5];
B_1 -= ans[5];
C_1 -= ans[5];
ans[4] = min(cnt[4], A_1);
cnt[4] -= ans[4];
A_1 -= ans[4];
ans[6] = min(cnt[6], B_1);
cnt[6] -= ans[6];
B_1 -= ans[6];
ans[7] = min(C_1, cnt[7]);
C_1 -= ans[7];
cnt[7] -= ans[7];
if (cnt[1] + cnt[2] + cnt[3] + cnt[4] > A_2) return false;
if (cnt[1] + cnt[2] + cnt[5] + cnt[6] > B_2) return false;
if (cnt[1] + cnt[3] + cnt[5] + cnt[7] > C_2) return false;
return true;
}
void check(int A_1, int B_1, int C_1, int A_2, int B_2, int C_2,
vector<int> Cnt, int num) {
if (flag) return;
int x = min(Cnt[1], min(A_1, min(B_1, C_1)));
ans[1] = x;
Cnt[1] -= x;
A_1 -= x;
B_1 -= x;
C_1 -= x;
for (int i = 0; i <= Cnt[2]; i++)
for (int j = 0; j <= Cnt[3]; j++) {
if (i + j > A_1 || i > B_1 || j > C_1) break;
ans[2] = i;
ans[3] = j;
Cnt[2] -= i;
Cnt[3] -= j;
A_1 -= i + j;
B_1 -= i;
C_1 -= j;
if (check1(A_1, B_1, C_1, A_2, B_2, C_2, Cnt)) {
flag = num;
return;
}
Cnt[2] += i;
Cnt[3] += j;
A_1 += i + j;
B_1 += i;
C_1 += j;
}
}
int main() {
T = rd();
d.resize(8);
for (int e = 1; e <= T; e++) {
flag = 0;
a[1] = rd();
b[1] = rd();
c[1] = rd();
a[2] = rd();
b[2] = rd();
c[2] = rd();
for (int i = 1; i <= 7; i++) d[i] = rd();
check(a[1], b[1], c[1], a[2], b[2], c[2], d, 1);
check(a[2], b[2], c[2], a[1], b[1], c[1], d, 2);
if (!flag)
puts("-1");
else {
for (int i = 1; i <= 7; i++)
printf("%d ", (flag == 1) ? ans[i] : d[i] - ans[i]);
puts("");
}
}
return 0;
}
|
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 10 decimal digits:
<image>
As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 1, you have to turn on 2 segments of the screen, and if you want to display 8, all 7 segments of some place to display a digit should be turned on.
You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than n segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than n segments.
Your program should be able to process t different test cases.
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 of them is represented by a separate line containing one integer n (2 ≤ n ≤ 10^5) — the maximum number of segments that can be turned on in the corresponding testcase.
It is guaranteed that the sum of n over all test cases in the input does not exceed 10^5.
Output
For each test case, print the greatest integer that can be displayed by turning on no more than n segments of the screen. Note that the answer may not fit in the standard 32-bit or 64-bit integral data type.
Example
Input
2
3
4
Output
7
11
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t, n;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
if (n % 2 != 0) {
n -= 3;
printf("7");
}
n /= 2;
while (n--) {
printf("1");
}
printf("\n");
}
return 0;
}
|
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
* All scores are integers
* 0 ≤ a_{i} ≤ m
* The average score of the class doesn't change.
You are student 1 and you would like to maximize your own score.
Find the highest possible score you can assign to yourself such that all conditions are satisfied.
Input
Each test contains multiple test cases.
The first line contains the number of test cases t (1 ≤ t ≤ 200). The description of the test cases follows.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^{3}, 1 ≤ m ≤ 10^{5}) — the number of students and the highest possible score respectively.
The second line of each testcase contains n integers a_1, a_2, ..., a_n ( 0 ≤ a_{i} ≤ m) — scores of the students.
Output
For each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._
Example
Input
2
4 10
1 2 3 4
4 5
1 2 3 4
Output
10
5
Note
In the first case, a = [1,2,3,4] , with average of 2.5. You can change array a to [10,0,0,0]. Average remains 2.5, and all conditions are satisfied.
In the second case, 0 ≤ a_{i} ≤ 5. You can change a to [5,1,1,3]. You cannot increase a_{1} further as it will violate condition 0≤ a_i≤ m.
|
for i in range(int(input())):
print(min(list(map(int, input().split()))[1], sum(list(map(int, input().split())))))
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
|
import java.io.*;
import java.util.*;
public class CF_635_Div2 {
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] intArray(int n) {
Reader r = new Reader();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = r.nextInt();
}
return arr;
}
public long[] longArray(int n) {
Reader r = new Reader();
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = r.nextInt();
}
return arr;
}
public void printArray(int arr[]) {
PrintWriter out = new PrintWriter(System.out);
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1)
out.println(arr[i]);
else
out.print(arr[i] + " ");
}
out.close();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static Reader r = new Reader();
private static void solve1() {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int a = r.nextInt();
int b = r.nextInt();
int c = r.nextInt();
int d = r.nextInt();
String ans = "" + b + " " + c + " " + c;
res.append(ans).append("\n");
}
System.out.print(res);
}
private static void solve2() {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int x = r.nextInt();
int n = r.nextInt();
int m = r.nextInt();
int first = n;
int second = m;
while ((first > 0 || second > 0)) {
if (x > 20) {
if (first > 0) {
x = ((x / 2) + 10);
first--;
} else if (second > 0) {
x -= 10;
second--;
}
} else {
if (second > 0) {
x -= 10;
second--;
} else if (first > 0) {
x = ((x / 2) + 10);
first--;
}
}
if (x <= 0) {
break;
}
}
res.append((x <= 0) ? "YES" : "NO").append("\n");
}
System.out.print(res);
}
static ArrayList<Integer> tree[] = new ArrayList[(int) 2e5 + 1];
static int vis[] = new int[(int) 2e5 + 1];
static ArrayList<Integer> happiness = new ArrayList<Integer>();
private static int DFS(int start, int depth) {
vis[start] = 1;
int noOfChild = 0;
for (Integer v : tree[start]) {
if (vis[v] == 0)
noOfChild += DFS(v, depth + 1);
}
happiness.add(depth - noOfChild);
return noOfChild + 1;
}
@SuppressWarnings("unchecked")
private static void solve3() {
int n = r.nextInt();
int k = r.nextInt();
for (int i = 0; i <= n; i++) {
tree[i] = new ArrayList<Integer>();
}
for (int i = 1; i < n; i++) {
int u = r.nextInt();
int v = r.nextInt();
tree[u].add(v);
tree[v].add(u);
}
DFS(1, 0);
Collections.sort(happiness, Collections.reverseOrder());
long happi = 0;
for (int i = 0; i < k; i++)
happi += happiness.get(i);
System.out.println(happi);
}
private static void solve4() {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
res.append(false).append("\n");
}
System.out.print(res);
}
public static void main(String[] args) throws IOException {
// solve1();
// solve2();
solve3();
// solve4();
}
}
|
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all.
After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
Input
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
Output
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
Examples
Input
5
1 2 3 4 5
Output
1 1 2 3 4
Input
5
2 3 4 5 6
Output
1 2 3 4 5
Input
3
2 2 2
Output
1 2 2
|
import java.util.*;
public class Replacement {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int a[] = new int[n];
for (int k = 0; k < n; k++) {
a[k] = cin.nextInt();
}
int max = a[0];
int index = 0;
for (int i = 1; i < n; i++) {
if (a[i] > max) {
max = a[i];
index = i;
}
}
if (a[index] != 1) {
a[index] = 1;
} else {
a[index] = 2;
}
Arrays.sort(a);
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
cin.close();
}
}
|
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
Input
The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).
Output
Print the only number — the minimum number of changes needed to get the permutation.
Examples
Input
3
3 1 2
Output
0
Input
2
2 2
Output
1
Input
5
5 3 3 3 1
Output
2
Note
The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2.
|
n = int(input())
l = list(map(int,input().split()))
cnt=0
for i in range(1,n+1):
if i not in l:
cnt+=1
print(cnt)
|
Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.
You are given three segments on the plane. They form the letter A if the following conditions hold:
* Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments.
* The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.
* The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4).
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.
Output
Output one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.
Examples
Input
3
4 4 6 0
4 1 5 2
4 0 4 4
0 0 0 6
0 6 2 -4
1 1 0 1
0 0 0 5
0 5 2 -1
1 2 0 1
Output
YES
NO
YES
|
#include <bits/stdc++.h>
using namespace std;
template <class T>
void pv(T a, T b) {
for (T i = a; i != b; ++i) cout << *i << " ";
cout << endl;
}
int in_c() {
int c;
for (; (c = getchar()) <= ' ';) {
if (!~c) throw ~0;
}
return c;
}
int in() {
int x = 0, c;
for (; (unsigned)((c = getchar()) - '0') >= 10;) {
if (c == '-') return -in();
if (!~c) throw ~0;
}
do {
x = (x << 3) + (x << 1) + (c - '0');
} while ((unsigned)((c = getchar()) - '0') < 10);
return x;
}
struct S {
long long xa, ya, xb, yb;
};
bool common(S &s, S &t) {
if (s.xa == t.xa && s.ya == t.ya) return 1;
swap(t.xa, t.xb);
swap(t.ya, t.yb);
if (s.xa == t.xa && s.ya == t.ya) return 1;
swap(s.xa, s.xb);
swap(s.ya, s.yb);
if (s.xa == t.xa && s.ya == t.ya) return 1;
swap(t.xa, t.xb);
swap(t.ya, t.yb);
if (s.xa == t.xa && s.ya == t.ya) return 1;
swap(s.xa, s.xb);
swap(s.ya, s.yb);
return 0;
}
S s[10];
int main() {
int i, j;
long long d0, d1, da, db;
for (int TC = in(); TC--;) {
for (i = 0; i < 3; ++i) {
s[i].xa = in();
s[i].ya = in();
s[i].xb = in();
s[i].yb = in();
}
for (i = 0; i < 3; ++i)
for (j = i + 1; j < 3; ++j) {
if (common(s[i], s[j])) {
swap(s[0], s[i]);
swap(s[1], s[j]);
goto found;
}
}
goto failed;
found:;
for (i = 3; i--;) {
s[i].xb -= s[0].xa;
s[i].yb -= s[0].ya;
s[i].xa -= s[0].xa;
s[i].ya -= s[0].ya;
}
if (s[0].xb * s[1].xb + s[0].yb * s[1].yb < 0) goto failed;
if (s[0].xb * s[1].yb - s[1].xb * s[0].yb == 0) goto failed;
if (s[0].xb * s[2].ya - s[2].xa * s[0].yb != 0) {
swap(s[2].xa, s[2].xb);
swap(s[2].ya, s[2].yb);
}
if (s[0].xb * s[2].ya - s[2].xa * s[0].yb != 0) goto failed;
if (s[1].xb * s[2].yb - s[2].xb * s[1].yb != 0) goto failed;
if (s[0].xb * s[2].xa + s[0].yb * s[2].ya < 0) goto failed;
if (s[1].xb * s[2].xb + s[1].yb * s[2].yb < 0) goto failed;
d0 = s[0].xb * s[0].xb + s[0].yb * s[0].yb;
d1 = s[1].xb * s[1].xb + s[1].yb * s[1].yb;
da = s[2].xa * s[2].xa + s[2].ya * s[2].ya;
db = s[2].xb * s[2].xb + s[2].yb * s[2].yb;
if (da * 25 < d0 || d0 * 16 < da * 25) goto failed;
if (db * 25 < d1 || d1 * 16 < db * 25) goto failed;
puts("YES");
continue;
failed:;
puts("NO");
}
return 0;
}
|
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely.
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
template <class T>
inline void read(T& a) {
T x = 0, s = 1;
char c = getchar();
while (!isdigit(c)) {
if (c == '-') s = -1;
c = getchar();
}
while (isdigit(c)) {
x = x * 10 + (c ^ '0');
c = getchar();
}
a = x * s;
return;
}
bool isprime[1000100];
int prime[1000100];
int n, cnt = 0;
long long sum[1000100];
void prepare() {
isprime[0] = isprime[1] = 1;
for (int i = 2; i <= maxn; i++) {
if (!isprime[i]) {
prime[++cnt] = i;
}
for (int j = 1; j <= cnt && i * prime[j] <= maxn; ++j) {
isprime[i * prime[j]] = 1;
if (i % prime[j] == 0) break;
}
}
return;
}
int main() {
prepare();
for (int i = 1; i <= maxn; i++) {
sum[i] = sum[i - 1] + (!isprime[i]);
}
int T;
read(T);
while (T--) {
int n;
read(n);
printf("%lld\n", sum[n] - sum[(int)sqrt(n)] + 1);
}
return 0;
}
|
You are given an array a of n positive integers.
You can use the following operation as many times as you like: select any integer 1 ≤ k ≤ n and do one of two things:
* decrement by one k of the first elements of the array.
* decrement by one k of the last elements of the array.
For example, if n=5 and a=[3,2,2,1,4], then you can apply one of the following operations to it (not all possible options are listed below):
* decrement from the first two elements of the array. After this operation a=[2, 1, 2, 1, 4];
* decrement from the last three elements of the array. After this operation a=[3, 2, 1, 0, 3];
* decrement from the first five elements of the array. After this operation a=[2, 1, 1, 0, 3];
Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations.
Input
The first line contains one positive integer t (1 ≤ t ≤ 30000) — the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 30000) — the number of elements in the array.
The second line of each test case contains n integers a_1 … a_n (1 ≤ a_i ≤ 10^6).
The sum of n over all test cases does not exceed 30000.
Output
For each test case, output on a separate line:
* YES, if it is possible to make all elements of the array equal to zero by applying a certain number of operations.
* NO, otherwise.
The letters in the words YES and NO can be outputed in any case.
Example
Input
4
3
1 2 1
5
11 7 9 6 8
5
1 3 1 3 1
4
5 2 1 10
Output
YES
YES
NO
YES
|
#not done by myself
t=int(input())
fflg=0
if t==3000: fflg=1
cnt=1
while t!=0:
t-=1
n=int(input())
lst=input().split(" ")
# if fflg==1 and cnt==59: print(lst)
for i in range(0,n,1):
lst[i]=int(lst[i])
flg=0
mini=1000000000000000
psum=[0 for i in range(0,n+1,1)]
for i in range(0,n-1,1):
mini=min(mini,lst[i])
if(lst[i+1]<lst[i]):
x=lst[i]-lst[i+1]
psum[0]-=x
psum[i+1]+=x
cnt+=1
for i in range(1,n+1,1):
psum[i]+=psum[i-1]
for i in range(0,n,1):
if lst[i] + psum[i] <0: flg=1
if(flg==1): print("NO")
else: print("YES")
|
You are given n sets of integers. The i-th set contains k_i integers.
Two sets are called similar if they share at least two common elements, i. e. there exist two integers x and y such that x ≠ y, and they both belong to each of the two sets.
Your task is to find two similar sets among the given ones, or report that there is no such pair of sets.
Input
The first line contains a single integer t (1 ≤ t ≤ 50000) — the number of test cases. Then t test cases follow.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) the number of given sets. The following n lines describe the sets. The i-th line starts with an integer k_i (2 ≤ k_i ≤ 10^5) — the number of integers in the i-th set. Then k_i integers a_{i,1}, a_{i,2}, ..., a_{i,k_i} (1 ≤ a_{i,j} ≤ 10^9) follow — the elements of the i-th set. It is guaranteed that all elements in each set are different.
The total number of elements in all sets in all test cases is not greater than 2⋅ 10^5.
Output
For each test case, print the answer on a single line.
If there is no pair of similar sets, print -1.
Otherwise, print two different integers — the indices of the similar sets. The sets are numbered from 1 to n in the order they are given in the input. If there are multiple answers, print any of them.
Example
Input
3
4
2 1 10
3 1 3 5
5 5 4 3 2 1
3 10 20 30
3
4 1 2 3 4
4 2 3 4 5
4 3 4 5 6
2
3 1 3 5
3 4 3 2
Output
2 3
1 2
-1
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define debug(x) cout<<#x<<" : "<<x<<'\n';
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin>>t;
while(t--) {
int n,k;
cin>>n;
vector<vector<int> > a(n+1);
map<int,int > Q;
int tot=0;
for(int i=0;i<n;i++) {
cin>>k;
a[i].resize(k);
int flag=0;
for(int j=0;j<k;j++) {
int tmp;
cin>>tmp;
if(Q[tmp]!=0) {
a[i][j] = Q[tmp];
} else {
a[i][j] = ++tot;
Q[tmp] = tot;
}
}
sort(a[i].begin(),a[i].end());
}
vector<vector<int > > f(tot+1);
for(int i=0;i<n;i++) {
for(auto it:a[i]) {
f[it].push_back(i);
}
}
int ff=0;
vector<int > pos(tot+1,-1);
vector<int > last(tot+1,-1);
for(int i=1;i<=tot;i++) { //针对每个, 所包含的每个集合都已经有一个联系
for(auto it:f[i]) {
if(a[it].size()>100) continue; //处理小集合
for(int j=0;a[it][j]<i;j++) {
if(last[a[it][j]] == i) { //是否能再建立一个联系 类似离散化?
cout<< pos[a[it][j]]+1 << " " << it+1 << "\n";
ff=1;
break;
}else {
last[a[it][j]] = i;
pos[a[it][j]] = it;
}
}
if(ff) break;
}
if(ff) break;
}
if(ff) continue;
vector<bool > vis(tot+1);
//大范围暴力
for(int i=0;i<n;i++) {
if(a[i].size()<=100) continue;
for(auto it:a[i]) vis[it]=1;
for(int j=0;j<n;j++) {
if(i==j) continue;
int num=0;
for(auto it:a[j]) {
num+=vis[it];
}
if(num>=2) {
cout<< i+1 <<" "<<j+1<<"\n";
ff=1;
break;
}
}
if(ff) break;
for(auto it:a[i]) vis[it]=0;
}
if(!ff) cout<<"-1\n";
}
}
|
You are given a string a, consisting of n characters, n is even. For each i from 1 to n a_i is one of 'A', 'B' or 'C'.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
You want to find a string b that consists of n characters such that:
* b is a regular bracket sequence;
* if for some i and j (1 ≤ i, j ≤ n) a_i=a_j, then b_i=b_j.
In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.
Your task is to determine if such a string b exists.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string a. a consists only of uppercase letters 'A', 'B' and 'C'. Let n be the length of a. It is guaranteed that n is even and 2 ≤ n ≤ 50.
Output
For each testcase print "YES" if there exists such a string b that:
* b is a regular bracket sequence;
* if for some i and j (1 ≤ i, j ≤ n) a_i=a_j, then b_i=b_j.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
4
AABBAC
CACA
BBBBAC
ABCA
Output
YES
YES
NO
NO
Note
In the first testcase one of the possible strings b is "(())()".
In the second testcase one of the possible strings b is "()()".
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll print(string s,char a, char b, char c)
{
ll pos=0;
ll n=s.size();
for(ll i=0;i<n;i++)
{
if(s[i]==a)
{
pos++;
}
else if(s[i]==b)
{
pos--;
}
else{
pos++;
}
if(pos<0)
{
return -1;
}
}
if(pos>0)
{
return -1;
}
return 1;
}
ll print1(string s,char a, char b, char c)
{
ll pos=0;
ll n=s.size();
for(ll i=0;i<n;i++)
{
if(s[i]==a)
{
pos++;
}
else if(s[i]==b)
{
pos++;
}
else{
pos--;
}
if(pos<0)
{
return -1;
}
}
if(pos>0)
{
return -1;
}
return 1;
}
ll print2(string s,char a, char b, char c)
{
ll pos=0;
ll n=s.size();
for(ll i=0;i<n;i++)
{
if(s[i]==a)
{
pos++;
}
else if(s[i]==b)
{
pos--;
}
else{
pos--;
}
if(pos<0)
{
return -1;
}
}
if(pos>0)
{
return -1;
}
return 1;
}
int main(){
ll t;
cin>>t;
while(t--)
{
string s;
cin>>ws;
cin>>s;
ll n;
n=s.size();
ll a=0,b=0,c=0;
for(ll i=0;i<n;i++)
{
if(s[i]=='A')
{
a++;
}
else if(s[i]=='B')
{
b++;
}
else
{
c++;
}
}
if((a==0 && b==0 && c!=0) || (a!=0 && b==0 && c==0) || (a==0 && b!=0 && c==0) )
{
cout<<"NO"<<"\n";
}
else {
if(s[0]=='A')
{
ll p=print(s,'A','B','C');
ll p1=print1(s,'A','B','C');
ll p2=print2(s,'A','B','C');
p1=max(p1,p2);
if(max(p,p1)==1)
{
cout<<"YES"<<"\n";
}
else{
cout<<"NO"<<"\n";
}
}
else if(s[0]=='B')
{
ll p=print(s,'B','A','C');
ll p1=print1(s,'B','A','C');
ll p2=print2(s,'B','A','C');
p1=max(p1,p2);
if(max(p,p1)==1)
{
cout<<"YES"<<"\n";
}
else{
cout<<"NO"<<"\n";
}
}
else{
ll p=print(s,'C','B','A');
ll p1=print1(s,'C','B','A');
ll p2=print2(s,'C','B','A');
p1=max(p1,p2);
if(max(p,p1)==1)
{
cout<<"YES"<<"\n";
}
else{
cout<<"NO"<<"\n";
}
}
}
}
return 0;
}
|
This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following:
* he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, …, a_r out, removing the rest of the array.
* he then cuts this range into multiple subranges.
* to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their [least common multiple (LCM)](https://en.wikipedia.org/wiki/Least_common_multiple).
Formally, he partitions the elements of a_l, a_{l + 1}, …, a_r into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for q independent ranges (l, r), tell Baby Ehab the minimum number of subarrays he needs.
Input
The first line contains 2 integers n and q (1 ≤ n,q ≤ 10^5) — the length of the array a and the number of queries.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^5) — the elements of the array a.
Each of the next q lines contains 2 integers l and r (1 ≤ l ≤ r ≤ n) — the endpoints of this query's interval.
Output
For each query, print its answer on a new line.
Example
Input
6 3
2 3 10 7 5 14
1 6
2 4
3 5
Output
3
1
2
Note
The first query asks about the whole array. You can partition it into [2], [3,10,7], and [5,14]. The first subrange has product and LCM equal to 2. The second has product and LCM equal to 210. And the third has product and LCM equal to 70. Another possible partitioning is [2,3], [10,7], and [5,14].
The second query asks about the range (2,4). Its product is equal to its LCM, so you don't need to partition it further.
The last query asks about the range (3,5). You can partition it into [10,7] and [5].
|
// Main Code at the Bottom
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
public class Main{
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(!env) {
try {
br=new BufferedReader(new FileReader("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long MOD=(long)1e9+7;
//debug
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Global variables and functions
//Main function(The main code starts from here)
public static void main (String[] args) throws java.lang.Exception {
int test=1;
//test=sc.nextInt();
while(test-->0) {
int n = sc.nextInt(), q=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) a[i]=sc.nextInt();
HashSet<Integer> set = new HashSet<>();
int l = 0, r = 0, map[]=new int[n];
Arrays.fill(map, n);
while(l<n && r<n) {
int tmp = a[r];
HashSet<Integer> cur = new HashSet<>();
boolean flag = false;
for(int i = 2;i*i<=tmp;i++) {
if(tmp%i==0) {
while(tmp%i==0) tmp/=i;
if(set.contains(i)) flag = true;
cur.add(i);
}
}
if(tmp>1) {
if(set.contains(tmp)) flag = true;
cur.add(tmp);
}
if(flag) {
map[l]=r;
tmp = a[l];
for(int i = 2;i*i<=tmp;i++) {
if(tmp%i==0) {
while(tmp%i==0) tmp/=i;
set.remove(i);
}
}
if(tmp>1) {
set.remove(tmp);
}
l++;
}
else {
for(Integer x: cur) set.add(x);
r++;
}
}
int up[][]=new int[n][19];
for(int i=0;i<n;i++) up[i][0]=map[i];
for(int j=1;j<19;j++) {
for(int i=0;i<n;i++) {
if(up[i][j-1]==n) up[i][j]=n;
else up[i][j]=up[up[i][j-1]][j-1];
}
}
while(q-->0) {
l = sc.nextInt()-1; r = sc.nextInt()-1;
int ans = 0;
for(int jump = 18;jump>=0;jump--) {
if(up[l][jump]<=r) {
ans+=(1<<jump);
l = up[l][jump];
}
}
ans++;
out.println(ans);
}
}
out.flush();
out.close();
}
}
|
This is the hard version of the problem. The only difference is that here 2≤ k≤ 100. You can make hacks only if both the versions of the problem are solved.
This is an interactive problem!
Every decimal number has a base k equivalent. The individual digits of a base k number are called k-its. Let's define the k-itwise XOR of two k-its a and b as (a + b)mod k.
The k-itwise XOR of two base k numbers is equal to the new number formed by taking the k-itwise XOR of their corresponding k-its. The k-itwise XOR of two decimal numbers a and b is denoted by a⊕_{k} b and is equal to the decimal representation of the k-itwise XOR of the base k representations of a and b. All further numbers used in the statement below are in decimal unless specified.
You have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between 0 and n-1 inclusive. So, you have decided to guess it. Luckily, you can try at most n times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was x, and you guess a different number y, then the system changes the password to a number z such that x⊕_{k} z=y. Guess the password and break into the system.
Input
The first line of input contains a single integer t (1≤ t≤ 10 000) denoting the number of test cases. t test cases follow.
The first line of each test case contains two integers n (1≤ n≤ 2⋅ 10^5) and k (2≤ k≤ 100).
It is guaranteed that the sum of n over all test cases does not exceed 2⋅ 10^5.
Interaction
For each test case, first read two integers n and k. Then you may ask up to n queries.
For each query, print a single integer y (0≤ y≤ 2⋅ 10^7). Let the current password be x. After that, read an integer r.
If x=y, you will read r=1 and the test case is solved. You must then continue solving the remaining test cases.
Else, you will read r=0. At this moment the password is changed to a number z such that x⊕_{k} z=y.
After printing a query, do not forget to output the end of line and flush the output. Otherwise, you will get the Idleness limit exceeded verdict.
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.
If you ask an invalid query or exceed n queries, you will read r=-1 and you will receive the Wrong Answer verdict. Make sure to exit immediately to avoid unexpected verdicts.
Note that the interactor is adaptive. That is, the original password is not fixed in the beginning and may depend on your queries. But it is guaranteed that at any moment there is at least one initial password such that all the answers to the queries are consistent.
Hacks:
To use hacks, use the following format of tests:
The first line should contain a single integer t (1≤ t≤ 10 000) — the number of test cases.
The first and only line of each test case should contain two integers n (1≤ n≤ 2⋅ 10^5) and k (2≤ k≤ 100) denoting the number of queries and the base respectively. The optimal original password is automatically decided by the adaptive interactor.
You must ensure that the sum of n over all test cases does not exceed 2⋅ 10^5.
Example
Input
2
5 2
0
0
1
5 3
0
0
1
Output
3
4
5
1
4
6
Note
Test Case 1:
In this case, the hidden password is 2.
The first query is 3. It is not equal to the current password. So, 0 is returned, and the password is changed to 1 since 2⊕_2 1=3.
The second query is 4. It is not equal to the current password. So, 0 is returned, and the password is changed to 5 since 1⊕_2 5=4.
The third query is 5. It is equal to the current password. So, 1 is returned, and the job is done.
Test Case 2:
In this case, the hidden password is 3.
The first query is 1. It is not equal to the current password. So, 0 is returned, and the password is changed to 7 since 3⊕_3 7=1. [3=(10)_3, 7=(21)_3, 1=(01)_3 and (10)_3⊕_3 (21)_3 = (01)_3].
The second query is 4. It is not equal to the current password. So, 0 is returned, and the password is changed to 6 since 7⊕_3 6=4. [7=(21)_3, 6=(20)_3, 4=(11)_3 and (21)_3⊕_3 (20)_3 = (11)_3].
The third query is 6. It is equal to the current password. So, 1 is returned, and the job is done.
Note that these initial passwords are taken just for the sake of explanation. In reality, the grader might behave differently because it is adaptive.
|
//#include <bits/stdc++.h>
//#define int long long int
//#define double long double
//#define endl '\n'
//#define all(c) c.begin(),c.end()
//#define mp(x,y) make_pair(x,y)
//#define eb emplace_back
//#define tr(k,st,en) for(int k = st; k <= en ; k++)
//#define trb(k,en,st) for(int k = en; k >= st ; k--)
//#define test int TN; cin>>TN; tr(T,1,TN)
//#define mxe(c) max_element(all(c))
//#define mne(c) min_element(all(c))
//using namespace std;
//
//template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
//template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }
//
//void dbg_out() { cerr << endl; }
//template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
//
//#ifdef LOCAL
//#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
//#else
//#define dbg(...)
//#endif
//
//typedef pair<int, int> pr;
//typedef vector<int> vi;
//typedef vector<vi> vvi;
//typedef vector<pr> vpr;
//
////const int mod = 1e9+7;
////const int inf = 9e18;
//
//double func(double c, double m, double p, double v) {
// if(c <= 0.0000000000001 and m <= 0.0000000000001) return 1;
// double ret = 0;
// if(c > 0.0000000000001) {
// if(c <= v + 0.00000000001) {
// double de = (c/2.0);
// ret += c * (func(0, m + de, p+de, v) + 1);
// } else {
// double de = ((v - c)/2.0);
// ret += c * (func(v, m + de, p+de, v) + 1);
// }
// }
// if(m > 0.0000000000001){
// if(m <= v + 0.00000000001) {
// double de = (m/2.0);
// ret += m * (func(c + de, 0 , p+de, v) + 1);
// } else {
// double de = ((v - m)/2.0);
// ret += m * (func(c + de, v, p+de, v) + 1);
// }
// }
// return ret;
//}
//
//int32_t main(){
// std::ios::sync_with_stdio(false);
// cin.tie(NULL); cout.tie(NULL);
//// cout<<"----START-----"<<endl;
// test{
// double a,b,c,d;
// cin>>a>>b>>c>>d;
// cout<<func(a, b, c, d)<<endl;
// }
// return 0;
//}
#include <bits/stdc++.h>
#define int long long int
#define double long double
#define all(c) c.begin(),c.end()
#define mp(x,y) make_pair(x,y)
#define eb emplace_back
#define tr(k,st,en) for(int k = st; k <= en ; k++)
#define trb(k,en,st) for(int k = en; k >= st ; k--)
#define test int TN; cin>>TN; tr(T,1,TN)
#define mxe(c) max_element(all(c))
#define mne(c) min_element(all(c))
using namespace std;
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef LOCAL
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
typedef pair<int, int> pr;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pr> vpr;
//const int mod = 1e9+7;
//const int inf = 9e18;
int k;
int sub(int a, int b) {
vector<int> t1, t2;
while(a > 0 ) {
t1.eb(a%k);
a/=k;
}
while(b > 0) {
t2.eb(b%k);
b/=k;
}
while(t2.size() < t1.size()) {
t2.eb(0);
}
while(t1.size() < t2.size()) {
t1.eb(0);
}
int ret = 0;
int x = 1;
vector<int> tm;
for(int i=0;i<t2.size();i++) {
tm.eb((t1[i] - t2[i] + k)%k);
}
for(int i=0;i<t2.size();i++) {
ret += tm[i] * x;
x *= k;
}
return ret;
}
int add(int a, int b) {
vector<int> t1, t2;
while(a > 0 ) {
t1.eb(a%k);
a/=k;
}
while(b > 0) {
t2.eb(b%k);
b/=k;
}
if(t1.size() < t2.size()) {
swap(t1, t2);
}
while(t2.size() < t1.size()) {
t2.eb(0);
}
int ret = 0;
int x = 1;
vector<int> tm;
for(int i=0;i<t2.size();i++) {
tm.eb((t2[i] + t1[i])%k);
}
for(int i=0;i<t2.size();i++) {
ret += tm[i] * x;
x *= k;
}
return ret;
}
void solve(){
int n;
cin>>n>>k;
int x=0;
tr(i,0,n-1){
int orig=i;
int toask= i%2 == 0 ? add(x, orig) : sub(x, orig);
cout<<toask<<endl;
int r;
cin>>r;
if(r==1) return;
x = sub(toask, x);
}
}
int32_t main(){
std::ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
// cout<<"----START-----"<<endl;
test{
solve();
}
return 0;
}
|
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 ≤ d ≤ 11184) — jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13
|
#include <bits/stdc++.h>
using namespace std;
bool composite[1000000];
vector<int> primes;
void sieve() {
for (int i = 2; i < 1000000; i++) {
if (composite[i]) continue;
primes.push_back(i);
for (int j = i + i; j < 1000000; j += i) {
composite[j] = true;
}
}
}
int main() {
long n;
cin >> n;
sieve();
vector<int> emirp;
for (int i = 0; i < primes.size(); i++) {
stringstream ss;
ss << primes[i];
string s = ss.str();
for (int j = 0; j < s.length() / 2; j++) {
char temp = s[j];
s[j] = s[s.length() - 1 - j];
s[s.length() - 1 - j] = temp;
}
stringstream ss2;
ss2 << s;
int x;
ss2 >> x;
if (!composite[x] && x != primes[i]) emirp.push_back(primes[i]);
}
cout << emirp[n - 1] << endl;
return 0;
}
|
Berland is very concerned with privacy, so almost all plans and blueprints are secret. However, a spy of the neighboring state managed to steal the Bertown subway scheme.
The Bertown Subway has n stations, numbered from 1 to n, and m bidirectional tunnels connecting them. All Bertown Subway consists of lines. To be more precise, there are two types of lines: circular and radial.
A radial line is a sequence of stations v1, ..., vk (k > 1), where stations vi and vi + 1 (i < k) are connected by a tunnel and no station occurs in the line more than once (vi ≠ vj for i ≠ j).
A loop line is a series of stations, v1, ..., vk (k > 2), where stations vi и vi + 1 are connected by a tunnel. In addition, stations v1 and vk are also connected by a tunnel. No station is occurs in the loop line more than once.
Note that a single station can be passed by any number of lines.
According to Berland standards, there can't be more than one tunnel between two stations and each tunnel belongs to exactly one line. Naturally, each line has at least one tunnel. Between any two stations there is the way along the subway tunnels. In addition, in terms of graph theory, a subway is a vertex cactus: if we consider the subway as a graph in which the stations are the vertexes and the edges are tunnels, then each vertex lies on no more than one simple cycle.
Unfortunately, scheme, stolen by the spy, had only the stations and the tunnels. It was impossible to determine to which line every tunnel corresponds. But to sabotage successfully, the spy needs to know what minimum and maximum number of lines may be in the Bertown subway.
Help him!
Input
The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 3·105) — the number of stations and the number of tunnels, correspondingly.
Each of the next m lines contain two integers — the numbers of stations connected by the corresponding tunnel. The stations are numbered with integers from 1 to n.
It is guaranteed that the graph that corresponds to the subway has no multiple edges or loops, it is connected and it is a vertex cactus.
Output
Print two numbers — the minimum and maximum number of lines correspondingly.
Examples
Input
3 3
1 2
2 3
3 1
Output
1 3
Input
8 8
1 2
2 3
3 4
4 5
6 4
4 7
7 2
2 8
Output
2 8
Input
6 6
1 2
2 3
2 5
5 6
3 4
3 5
Output
3 6
Note
The subway scheme with minimum possible number of lines for the second sample is:
<image>
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
vector<int> adj[maxn];
int deg[maxn];
int n, m, ret;
void init() {
scanf("%d%d", &n, &m);
int u, v;
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
if (deg[u] < 2) adj[u].push_back(v);
if (deg[v] < 2) adj[v].push_back(u);
deg[u]++;
deg[v]++;
}
}
void work() {
for (int i = 1; i <= n; i++) ret += deg[i] & 1;
ret >>= 1;
for (int i = 1; i <= n; i++)
if (deg[i] == 2) {
int x = adj[i][0], y = adj[i][1];
if (x == y) {
deg[x] = 0;
ret++;
continue;
}
adj[x][adj[x][0] != i] = y;
adj[y][adj[y][0] != i] = x;
}
}
void print() { printf("%d %d\n", ret, m); }
int main() {
init();
work();
print();
return 0;
}
|
The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 ≤ i ≤ n) region has a stable temperature of ti degrees in summer.
This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.
Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.
To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.
Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
Input
The first input line contains two integers n and m (1 ≤ n ≤ 105; 1 ≤ m ≤ 106) — the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 ≤ ti, Ti, xi, costi ≤ 106). The numbers in the lines are separated by single spaces.
Output
Print the only integer — the minimum number of roubles the organizers will have to spend to transport all schoolchildren.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
2 10
30 35 1 100
20 35 10 10
Output
120
Input
3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000
Output
200065
Note
In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
long long ans = 0;
for (int i = (0); i < (n); ++i) {
long long t, T, x, cost;
cin >> t >> T >> x >> cost;
if (t >= T) {
ans += cost + m * x;
continue;
}
long long aux1 = cost;
if (m > (T - t)) aux1 += m * x;
long long aux2 = (long long)ceil((double)(m - (T - t)) / (T - t)) + 1;
aux2 *= cost;
ans += min(aux1, aux2);
}
cout << ans << endl;
return 0;
}
|
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.
|
#include <bits/stdc++.h>
using namespace std;
int l[100100];
int main() {
int n, h;
int ans;
int id;
cin >> n >> h;
vector<pair<int, int> > a;
a.clear();
int x;
for (int i = 0; i < n; i++) {
cin >> x;
a.push_back(make_pair(x, i));
}
sort(a.begin(), a.end());
if (a.size() <= 2) {
cout << 0 << endl;
for (int i = 0; i < a.size(); i++) {
if (i) cout << " ";
cout << 1;
}
cout << endl;
} else {
ans = 1000000000;
id = 0;
ans = a[n - 1].first + a[n - 2].first - a[1].first - a[0].first;
int arr1[4];
int arr2[4];
for (int i = 1; i < a.size(); i++) {
for (int j = 0; j < 4; j++) arr1[j] = arr2[j] = -1;
arr1[0] = 1;
if (i > 1) {
arr1[1] = 2;
arr1[2] = i - 1;
arr1[3] = i;
} else {
arr1[1] = 1;
arr1[2] = 1;
arr1[3] = 1;
}
arr2[0] = 0;
if (i + 2 < a.size()) {
arr2[1] = i + 1;
arr2[2] = n - 2;
arr2[3] = n - 1;
} else if (i + 1 < a.size()) {
arr2[1] = n - 1;
arr2[2] = n - 1;
arr2[3] = n - 1;
} else {
arr2[1] = 0;
arr2[2] = 0;
arr2[3] = 0;
}
int max_ = -1;
int min_ = 1000000000;
for (int k1 = 0; k1 < 4; k1++) {
for (int k2 = 0; k2 < 4; k2++) {
if (arr1[k1] != arr1[k2]) {
max_ = max(max_, a[arr1[k1]].first + a[arr1[k2]].first);
min_ = min(min_, a[arr1[k1]].first + a[arr1[k2]].first);
}
if (arr2[k1] != arr2[k2]) {
max_ = max(max_, a[arr2[k1]].first + a[arr2[k2]].first);
min_ = min(min_, a[arr2[k1]].first + a[arr2[k2]].first);
}
max_ = max(max_, a[arr1[k1]].first + a[arr2[k2]].first + h);
min_ = min(min_, a[arr1[k1]].first + a[arr2[k2]].first + h);
}
}
if (max_ - min_ < ans) {
ans = max_ - min_;
id = i;
}
}
cout << ans << endl;
l[a[0].second] = 2;
for (int i = 1; i <= id; i++) l[a[i].second] = 1;
for (int i = id + 1; i < n; i++) l[a[i].second] = 2;
for (int i = 0; i < n; i++) {
if (i) cout << " ";
cout << l[i];
}
cout << endl;
}
return 0;
}
|
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).
* No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).
* All elements of the sequence are good integers.
Find the length of the longest good sequence.
Input
The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).
Output
Print a single integer — the length of the longest good sequence.
Examples
Input
5
2 3 4 6 9
Output
4
Input
9
1 2 3 5 6 7 8 9 10
Output
4
Note
In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long n;
cin >> n;
long long a[n];
long long divisor[100001] = {-1};
long long dp[100001] = {0};
long long max_l = 1;
for (long long i = 0; i < n; i++) {
cin >> a[i];
if (a[i] == 1) continue;
long long longest = 1;
long long root = sqrt(a[i]);
divisor[a[i]] = a[i];
for (long long j = 2; j < root + 1; j++) {
if (a[i] % j == 0) {
if (divisor[j] != (-1)) {
longest = max(longest, dp[divisor[j]] + 1);
}
if (divisor[a[i] / j] != (-1)) {
longest = max(longest, dp[divisor[a[i] / j]] + 1);
}
divisor[j] = a[i];
divisor[a[i] / j] = a[i];
}
}
dp[a[i]] = longest;
max_l = max(max_l, longest);
}
cout << max_l;
}
|
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement.
Output
In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728
|
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
int dp[11], c[11][11];
int main() {
int n, k;
cin >> n >> k;
long long ans = 1;
for (int i = 0; i < n - k; i++) ans *= n - k, ans %= mod;
dp[1] = 1;
dp[0] = 1;
c[0][0] = 1;
for (int i = 1; i < 11; i++) {
c[i][0] = 1;
for (int j = 1; j <= i; j++) c[i][j] = c[i - 1][j] + c[i - 1][j - 1];
}
for (int i = 2; i <= k - 1; i++) {
for (int j = 0; j <= i - 1; j++)
dp[i] += dp[j] * (i - j) * c[i - 1][j] * dp[i - j - 1];
}
ans *= dp[k - 1] * k;
ans %= mod;
cout << ans;
return 0;
}
|
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n). The answer to the query li, ri is the number of such integers i (li ≤ i < ri), that si = si + 1.
Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
Input
The first line contains string s of length n (2 ≤ n ≤ 105). It is guaranteed that the given string only consists of characters "." and "#".
The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≤ li < ri ≤ n).
Output
Print m integers — the answers to the queries in the order in which they are given in the input.
Examples
Input
......
4
3 4
2 3
1 6
2 6
Output
1
1
5
4
Input
#..###
5
1 3
5 6
1 5
3 6
3 4
Output
1
1
2
2
0
|
#include <bits/stdc++.h>
using namespace std;
const int INF_int = 100000000;
const long long INF_ll = 1000000000000000;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string a;
cin >> a;
int n = a.size();
int m;
cin >> m;
int b[n];
for (int i = 0; i < n; i++) {
b[i] = 0;
if (i != n - 1 && a[i] == a[i + 1]) {
b[i] = 1;
}
}
int sum[n];
sum[0] = b[0];
for (int i = 1; i < n; i++) {
sum[i] = b[i] + sum[i - 1];
}
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
x--;
y--;
if (x != 0)
cout << sum[y - 1] - sum[x - 1] << "\n";
else
cout << sum[y - 1] << "\n";
}
}
|
A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between 2 and 314! (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height i having probability 2 - i for all positive integers i. The floors of a skyscraper with height i are numbered 0 through i - 1.
To speed up transit times, a number of zip lines were installed between skyscrapers. Specifically, there is a zip line connecting the i-th floor of one skyscraper with the i-th floor of another skyscraper if and only if there are no skyscrapers between them that have an i-th floor.
Alice and Bob decide to count the number of skyscrapers.
Alice is thorough, and wants to know exactly how many skyscrapers there are. She begins at the leftmost skyscraper, with a counter at 1. She then moves to the right, one skyscraper at a time, adding 1 to her counter each time she moves. She continues until she reaches the rightmost skyscraper.
Bob is impatient, and wants to finish as fast as possible. He begins at the leftmost skyscraper, with a counter at 1. He moves from building to building using zip lines. At each stage Bob uses the highest available zip line to the right, but ignores floors with a height greater than h due to fear of heights. When Bob uses a zip line, he travels too fast to count how many skyscrapers he passed. Instead, he just adds 2i to his counter, where i is the number of the floor he's currently on. He continues until he reaches the rightmost skyscraper.
Consider the following example. There are 6 buildings, with heights 1, 4, 3, 4, 1, 2 from left to right, and h = 2. Alice begins with her counter at 1 and then adds 1 five times for a result of 6. Bob begins with his counter at 1, then he adds 1, 4, 4, and 2, in order, for a result of 12. Note that Bob ignores the highest zip line because of his fear of heights (h = 2).
<image>
Bob's counter is at the top of the image, and Alice's counter at the bottom. All zip lines are shown. Bob's path is shown by the green dashed line and Alice's by the pink dashed line. The floors of the skyscrapers are numbered, and the zip lines Bob uses are marked with the amount he adds to his counter.
When Alice and Bob reach the right-most skyscraper, they compare counters. You will be given either the value of Alice's counter or the value of Bob's counter, and must compute the expected value of the other's counter.
Input
The first line of input will be a name, either string "Alice" or "Bob". The second line of input contains two integers n and h (2 ≤ n ≤ 30000, 0 ≤ h ≤ 30). If the name is "Alice", then n represents the value of Alice's counter when she reaches the rightmost skyscraper, otherwise n represents the value of Bob's counter when he reaches the rightmost skyscraper; h represents the highest floor number Bob is willing to use.
Output
Output a single real value giving the expected value of the Alice's counter if you were given Bob's counter, or Bob's counter if you were given Alice's counter.
You answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
Examples
Input
Alice
3 1
Output
3.500000000
Input
Bob
2 30
Output
2
Input
Alice
2572 10
Output
3439.031415943
Note
In the first example, Bob's counter has a 62.5% chance of being 3, a 25% chance of being 4, and a 12.5% chance of being 5.
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = (int)3e4 + 100;
char str[maxn];
const int maxh = 31;
double expA[maxn][maxh][2];
double probA[maxn][maxh][2];
double expAS[maxn][maxh][2];
double probAS[maxn][maxh][2];
void add(double &e1, double &p1, double e2, double p2) {
if (p1 + p2 == 0) return;
e1 = (e1 * p1 + e2 * p2) / (p1 + p2);
p1 = p1 + p2;
}
double solveA(int n, int h) {
expA[0][0][0] = 1.;
probA[0][0][0] = 1.;
double ans = 0;
for (int i = 0; i < n; i++) {
for (int ph = 0; ph < h; ph++)
for (int onB = 0; onB <= 1; onB++) {
double curexp = expA[i][ph][onB];
double curp = probA[i][ph][onB];
for (int curH = 1; curH <= (onB ? ph + 1 : h); curH++) {
double probH = 1. / (double)(1 << (curH - (curH == h ? 1 : 0)));
double nprob = curp * probH;
if (curH <= ph) {
add(expA[i + 1][ph][onB], probA[i + 1][ph][onB], curexp, nprob);
} else {
add(expAS[i][curH][onB], probAS[i][curH][onB], curexp, nprob);
}
}
}
for (int ph = 1; ph <= h; ph++)
for (int onB = 0; onB <= 1; onB++) {
double curexp = expAS[i][ph][onB];
double curp = probAS[i][ph][onB];
if (i == n - 1) {
ans += curexp * curp;
}
for (int curH = 0; curH < ph; curH++) {
int nonB = onB;
if (curH < ph - 1) nonB = 1;
double nexp = curexp + (1 << curH);
add(expA[i + 1][curH][nonB], probA[i + 1][curH][nonB], nexp, curp);
}
}
}
return ans;
}
double expB[maxn][maxh][2];
double probB[maxn][maxh][2];
double expBS[maxn][maxh][2];
double probBS[maxn][maxh][2];
double solveB(int n, int h) {
probB[0][0][0] = 1;
expB[0][0][0] = 1;
double ans = 0, ansp = 0;
for (int i = 0; i < n; i++) {
for (int ph = 0; ph < h; ph++)
for (int onB = 0; onB <= 1; onB++) {
double curexp = expB[i][ph][onB];
double curp = probB[i][ph][onB];
if (ph != 0) {
double probBig = 1. / (1 << ph);
curexp += 1. / probBig - 1;
}
for (int curH = ph + 1; curH <= (onB ? ph + 1 : h); curH++) {
double probH = 1. / (double)(1 << (curH - (curH == h ? 1 : 0)));
double nprob = curp * probH;
add(expBS[i][curH][onB], probBS[i][curH][onB], curexp, nprob);
}
}
for (int ph = 1; ph <= h; ph++)
for (int onB = 0; onB <= 1; onB++) {
double curexp = expBS[i][ph][onB];
double curp = probBS[i][ph][onB];
if (i == n - 1) {
add(ans, ansp, curexp, curp);
}
for (int curH = 0; curH < ph; curH++) {
int nonB = onB;
if (curH < ph - 1) nonB = 1;
int nit = i + (1 << curH);
if (nit > n - 1) continue;
double nexp = curexp + 1;
add(expB[nit][curH][nonB], probB[nit][curH][nonB], nexp, curp);
}
}
}
return ans;
}
int main() {
scanf("%s", str);
int n, h;
scanf("%d%d", &n, &h);
h++;
double ans;
if (str[0] == 'A') {
ans = solveA(n, h);
} else {
ans = solveB(n, h);
}
printf("%.10lf\n", ans);
return 0;
}
|
Dima is a good person. In fact, he's great. But all good things come to an end...
Seryozha is going to kick Dima just few times.. For this reason he divides the room into unit squares. Now the room is a rectangle n × m consisting of unit squares.
For the beginning, Seryozha put Dima in a center of some square. Then he started to kick Dima (it is known, that he kicks Dima at least once). Each time when Dima is kicked he flyes up and moves into one of four directions (up, left, right, down). On each move Dima passes k (k > 1) unit of the length in the corresponding direction. Seryozha is really kind, so he kicks Dima in such way that Dima never meets the walls (in other words, Dima never leave the room's space). Seryozha is also dynamic character so Dima never flies above the same segment, connecting a pair of adjacent squares, twice.
Seryozha kicks Dima for a long time, but Dima is not vindictive — Dima writes. Dima marked all squares in which he was staying or above which he was flying. Thanks to kicks, Dima does not remember the k value, so he asks you to find all possible values which matches to the Dima's records.
Input
The first line contains n and m (1 ≤ n, m ≤ 103) — size of the room.
Next n lines goes, each contains m numbers aij — Dima's notes: aij = 1, if Dima was staying in the square (i, j) or was flying above it. Otherwise aij = 0.
At least one aij equals 1.
Output
In a single line in accending order print all k (k > 1), which matches the Dima's notes. If there are no such k and Dima invented this story with kicks, print -1.
Examples
Input
5 5
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
Output
2 4
Input
7 7
0 0 1 1 1 0 0
0 0 1 0 1 0 0
1 1 1 1 1 1 1
1 0 1 0 1 0 1
1 1 1 1 1 1 1
0 0 1 0 1 0 0
0 0 1 1 1 0 0
Output
2
Input
3 3
1 1 1
1 1 1
1 1 1
Output
-1
Input
4 4
1 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0
Output
3
Input
5 5
0 0 1 0 0
0 0 1 0 0
1 1 1 1 1
0 0 1 0 0
0 0 1 0 0
Output
-1
|
#include <bits/stdc++.h>
using namespace std;
int n, m, tot;
int a[1010][1010];
int s0[1010][1010], s1[1010][1010], d[1010][1010];
int readInt() {
char c;
int n = 0;
c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9') {
n = n * 10 + c - '0';
c = getchar();
}
return n;
}
int fa[1010 * 1010];
int sx, sy;
int ok(int x, int y) { return x >= 1 && x <= n && y >= 1 && y <= m; }
int find(int i) {
if (fa[i] == i)
return i;
else
return find(fa[i]);
}
int can(int k) {
int i, j, x, y, mx, my, tmp;
int dd = 0, fmx;
fmx = (sx - 1) / k, mx = (n - sx) / k, my = (m - sy) / k, dd = 0;
for (i = -fmx; i <= mx; i++)
for (j = 0; j <= my; j++) {
d[i + fmx][j] = 0;
int num = (i + fmx) * (my + 1) + j;
fa[num] = num;
}
for (i = -fmx; i <= mx; i++) {
for (j = 0; j <= my; j++) {
x = sx + i * k;
y = sy + j * k;
if (!a[x][y]) continue;
dd++;
if (ok(x + k, y) && a[x + k][y]) {
tmp = s0[x + k - 1][y] - s0[x][y];
if (tmp == k - 1) {
d[i + fmx][j]++;
d[i + 1 + fmx][j]++;
dd += k - 1;
fa[find((i + fmx) * (my + 1) + j)] =
fa[find((i + 1 + fmx) * (my + 1) + j)];
} else if (tmp > 0)
return 0;
}
if (ok(x, y + k) && a[x][y + k]) {
tmp = s1[x][y + k - 1] - s1[x][y];
if (tmp == k - 1) {
d[i + fmx][j]++;
d[i + fmx][j + 1]++;
dd += k - 1;
fa[find((i + fmx) * (my + 1) + j)] =
fa[find((i + fmx) * (my + 1) + j + 1)];
} else if (tmp > 0)
return 0;
}
}
}
if (dd != tot) return 0;
int cnt = 0, thef = find((0 + fmx) * (my + 1) + 0);
for (i = -fmx; i <= mx; i++)
for (j = 0; j <= my; j++) {
cnt += d[i + fmx][j] & 1;
}
for (i = -fmx; i <= mx; i++)
for (j = 0; j <= my; j++) {
x = sx + i * k;
y = sy + j * k;
if (!a[x][y]) continue;
if (find((i + fmx) * (my + 1) + j) != thef) return 0;
}
return cnt <= 2;
}
int main() {
int i, j, k;
while (scanf("%d %d", &n, &m) != EOF) {
tot = 0;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++) {
scanf("%d", &a[i][j]);
tot += a[i][j];
}
if ((n < 3 && m < 3) || tot == 1) {
printf("-1\n");
} else {
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++) {
s0[i][j] = s0[i - 1][j] + a[i][j];
s1[i][j] = s1[i][j - 1] + a[i][j];
}
sx = sy = 0;
for (j = 1; j <= m; j++) {
for (i = 1; i <= n; i++) {
if (a[i][j]) {
sx = i;
sy = j;
break;
}
}
if (sx) break;
}
int flag = 1;
for (k = 2; k <= min(n, m); k++) {
if (can(k)) {
if (flag)
flag = 0;
else
printf(" ");
printf("%d", k);
}
}
if (flag)
printf("-1\n");
else
printf("\n");
}
}
return 0;
}
|
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;
const int maxn = 7007;
const int maxe = 200000;
struct node {
int l, r, val;
};
vector<node> a[maxn];
int ll[maxe], rr[maxe];
set<int> mp;
int main() {
int n, m;
scanf("%d%d", &n, &m);
ll[1] = 1, rr[1] = 2;
int now = 1, cnt = 3;
ll[1] = 1;
rr[1] = 2;
for (int i = 2; i < maxe; i++) {
if ((1 << now) == i) {
now++;
ll[i] = cnt++;
} else
ll[i] = -1;
rr[i] = cnt++;
}
for (int i = 1; i <= m; i++) {
int op;
scanf("%d", &op);
if (op == 1) {
int t;
node as;
scanf("%d%d%d%d", &t, &as.l, &as.r, &as.val);
a[t].push_back(as);
} else {
int L, R;
scanf("%d%d", &L, &R);
mp.clear();
int l = R, r = R;
for (int j = L; j <= n; j++) {
for (int k = 0; k < a[j].size(); k++) {
if (a[j][k].l <= r && a[j][k].r >= l) mp.insert(a[j][k].val);
}
l = (ll[l] == -1 ? rr[l] : ll[l]);
r = rr[r];
}
printf("%d\n", mp.size());
}
}
return 0;
}
|
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
|
t = int(raw_input())
def compute(n, p):
fault = False
want = (2 * n) + p
for i in range(n):
if fault: break
for j in range(i + 1, n):
if want == 0:
fault = True
break
else:
print i + 1, j + 1
want -= 1
for x in range(t):
inp = raw_input().split()
n, p = int(inp[0]), int(inp[1])
compute(n, p)
|
Volodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour — a cycle which visits every attraction exactly once — the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.
Input
Input contains just one natural number (3 ≤ N ≤ 20) — the number of town attractions.
Output
Output should contain N rows containing N positive integer numbers each — the adjacency matrix of the prices graph (thus, j-th number in i-th row should be equal to the price of the road between the j-th and the i-th attraction). Diagonal numbers should be equal to zero. All numbers should not be greater than 1000. All prices should be positive and pairwise distinct. If there are several solutions, output any of them.
Examples
Input
3
Output
0 3 4
3 0 5
4 5 0
|
#include <bits/stdc++.h>
using namespace std;
int n, a[30][30];
const int f[] = {288, 434, 152, 375, 304, 82, 439, 195, 103, 156,
109, 458, 115, 118, 194, 447, 344, 318, 493, 256};
int main() {
scanf("%d", &n);
for (int i = 0; i < (int)(n); i++)
for (int j = 0; j < (int)(n); j++) {
a[i][j] += f[i];
a[j][i] += f[i];
}
for (int i = 0; i < (int)(n); i++) a[i][i] = 0;
for (int i = 0; i < (int)(n); i++) {
for (int j = 0; j < (int)(n); j++) {
if (j) printf(" ");
printf("%d", a[i][j]);
}
printf("\n");
}
}
|
You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.
A polyline defined by points p1, p2, p3, p4 consists of the line segments p1 p2, p2 p3, p3 p4, and its length is the sum of the lengths of the individual line segments.
Input
The only line of the input contains two integers n and m (0 ≤ n, m ≤ 1000). It is guaranteed that grid contains at least 4 different points.
Output
Print 4 lines with two integers per line separated by space — coordinates of points p1, p2, p3, p4 in order which represent the longest possible polyline.
Judge program compares your answer and jury's answer with 10 - 6 precision.
Examples
Input
1 1
Output
1 1
0 0
1 0
0 1
Input
0 10
Output
0 1
0 10
0 0
0 9
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<pair<int, int> > a;
a.push_back(make_pair(0, 0));
if (n > 0) a.push_back(make_pair(1, 0));
if (m > 0) a.push_back(make_pair(0, 1));
if (n > 0 && m > 0) a.push_back(make_pair(1, 1));
a.push_back(make_pair(n, m));
if (n > 0) a.push_back(make_pair(n - 1, m));
if (m > 0) a.push_back(make_pair(n, m - 1));
if (n > 0 && m > 0) a.push_back(make_pair(n - 1, m - 1));
a.push_back(make_pair(n, 0));
if (n > 0) a.push_back(make_pair(n - 1, 0));
if (m > 0) a.push_back(make_pair(n, 1));
if (n > 0 && m > 0) a.push_back(make_pair(n - 1, 1));
a.push_back(make_pair(0, m));
if (n > 0) a.push_back(make_pair(1, m));
if (m > 0) a.push_back(make_pair(0, m - 1));
if (n > 0 && m > 0) a.push_back(make_pair(1, m - 1));
long double d = 0;
vector<int> ans(4);
for (int i1 = 0; i1 < a.size(); i1++)
for (int i2 = 0; i2 < a.size(); i2++)
for (int i3 = 0; i3 < a.size(); i3++)
for (int i4 = 0; i4 < a.size(); i4++) {
long double dd = 0;
dd += sqrt((a[i1].first - a[i2].first) * (a[i1].first - a[i2].first) +
(a[i1].second - a[i2].second) *
(a[i1].second - a[i2].second));
dd += sqrt((a[i2].first - a[i3].first) * (a[i2].first - a[i3].first) +
(a[i2].second - a[i3].second) *
(a[i2].second - a[i3].second));
dd += sqrt((a[i3].first - a[i4].first) * (a[i3].first - a[i4].first) +
(a[i3].second - a[i4].second) *
(a[i3].second - a[i4].second));
if (dd > d && (a[i1] != a[i2]) && (a[i1] != a[i3]) &&
(a[i1] != a[i4]) && (a[i2] != a[i3]) && (a[i2] != a[i4]) &&
(a[i3] != a[i4])) {
ans[0] = i1, ans[1] = i2, ans[2] = i3, ans[3] = i4;
d = dd;
}
}
cout << a[ans[0]].first << ' ' << a[ans[0]].second << endl;
cout << a[ans[1]].first << ' ' << a[ans[1]].second << endl;
cout << a[ans[2]].first << ' ' << a[ans[2]].second << endl;
cout << a[ans[3]].first << ' ' << a[ans[3]].second << endl;
return 0;
}
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class F474 {
static final int inf = ((int) 1e9) + 100;
public static int GCD(int a, int b) {
if (b == 0)
return a;
return GCD(b, a % b);
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int n = in.nextInt();
int N = 1;
while (N < n)
N <<= 1;
int[] arr = new int[N + 1];
Arrays.fill(arr, inf);
for (int i = 1; i <= n; i++) {
arr[i] = in.nextInt();
}
SegmentTree st = new SegmentTree(arr);
int q = in.nextInt();
while (q-- > 0) {
int i = in.nextInt();
int j = in.nextInt();
Trio t = st.query(i, j);
int ans = j - i + 1;
if (t != null && t.min == t.gcd)
ans -= t.occ;
// System.out.println(t.min + " " + t.gcd + " " + t.occ);
sb.append(ans).append("\n");
}
System.out.print(sb);
}
static class Trio {
int min, gcd, occ;
Trio(int a, int b, int c) {
min = a;
gcd = b;
occ = c;
}
}
static class SegmentTree {
int N;
Trio[] sTree;
int[] arr;
SegmentTree(int[] in) {
arr = in;
N = in.length - 1;
sTree = new Trio[N << 1];
build(1, 1, N);
}
void build(int node, int b, int e) {
if (b == e) {
if (arr[b] != inf)
sTree[node] = new Trio(arr[b], arr[b], 1);
} else {
build(node << 1, b, (b + e) / 2);
build((node << 1) + 1, (b + e) / 2 + 1, e);
sTree[node] = merge(sTree[node << 1], sTree[(node << 1) + 1]);
}
}
static Trio merge(Trio t1, Trio t2) {
if (t1 == null && t2 == null)
return null;
if (t1 == null)
return new Trio(t2.min, t2.gcd, t2.occ);
if (t2 == null)
return new Trio(t1.min, t1.gcd, t1.occ);
int min = Math.min(t1.min, t2.min);
int occ = 0;
if (t1.min == min)
occ += t1.occ;
if (t2.min == min)
occ += t2.occ;
return new Trio(min, GCD(t1.gcd, t2.gcd), occ);
}
public Trio query(int i, int j) {
return query(1, 1, N, i, j);
}
public Trio query(int node, int b, int e, int i, int j) {
if (i > e || j < b)
return null;
if (b >= i && e <= j)
return sTree[node];
Trio q1 = query(node << 1, b, (b + e) / 2, i, j);
Trio q2 = query((node << 1) + 1, (b + e) / 2 + 1, e, i, j);
return merge(q1, q2);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
You are given a figure on a grid representing stairs consisting of 7 steps. The width of the stair on height i is wi squares. Formally, the figure is created by consecutively joining rectangles of size wi × i so that the wi sides lie on one straight line. Thus, for example, if all wi = 1, the figure will look like that (different colors represent different rectangles):
<image>
And if w = {5, 1, 0, 3, 0, 0, 1}, then it looks like that:
<image>
Find the number of ways to color some borders of the figure's inner squares so that no square had all four borders colored. The borders of the squares lying on the border of the figure should be considered painted. The ways that differ with the figure's rotation should be considered distinct.
Input
The single line of the input contains 7 numbers w1, w2, ..., w7 (0 ≤ wi ≤ 105). It is guaranteed that at least one of the wi's isn't equal to zero.
Output
In the single line of the output display a single number — the answer to the problem modulo 109 + 7.
Examples
Input
0 1 0 0 0 0 0
Output
1
Input
0 2 0 0 0 0 0
Output
7
Input
1 1 1 0 0 0 0
Output
9
Input
5 1 0 3 0 0 1
Output
411199181
Note
All the possible ways of painting the third sample are given below:
<image>
|
#include <bits/stdc++.h>
using namespace std;
inline long long rd() {
long long _x = 0;
int _ch = getchar(), _f = 1;
for (; !isdigit(_ch) && (_ch != '-') && (_ch != EOF); _ch = getchar())
;
if (_ch == '-') {
_f = 0;
_ch = getchar();
}
for (; isdigit(_ch); _ch = getchar()) _x = _x * 10 + _ch - '0';
return _f ? _x : -_x;
}
void write(long long _x) {
if (_x >= 10)
write(_x / 10), putchar(_x % 10 + '0');
else
putchar(_x + '0');
}
inline void wrt(long long _x, char _p) {
if (_x < 0) putchar('-'), _x = -_x;
write(_x);
if (_p) putchar(_p);
}
struct matrix {
int a[1 << 7 | 5][1 << 7 | 5], len;
matrix operator*(const matrix &B) const {
matrix ans;
memset(ans.a, 0, sizeof ans.a);
for (int i = int(0); i <= (int)(len); i++) {
for (int j = int(0); j <= (int)(len); j++) {
for (int k = int(0); k <= (int)(len); k++) {
ans.a[i][j] = (ans.a[i][j] + 1ll * a[i][k] * B.a[k][j]) % 1000000007;
}
}
}
ans.len = len;
return ans;
}
};
int calc(int A, int B, int n) {
int dp[8][2];
memset(dp, 0, sizeof dp);
dp[0][1] = 1;
for (int i = int(1); i <= (int)(n); i++) {
if ((A & (1 << (i - 1))) == 0 && (B & (1 << (i - 1))) == 0) {
dp[i][1] = dp[i - 1][0];
dp[i][0] = (dp[i - 1][0] + dp[i - 1][1]) % 1000000007;
} else {
dp[i][1] = dp[i - 1][0] + dp[i - 1][1];
dp[i][0] = dp[i - 1][0] + dp[i - 1][1];
}
}
return dp[n][1];
}
int a[8];
int dp[1 << 7 | 5], tmp[1 << 7 | 5];
matrix qpow(matrix X, int k) {
matrix ans;
memset(ans.a, 0, sizeof ans.a);
ans.len = X.len;
for (int i = int(0); i <= (int)(X.len); i++) {
ans.a[i][i] = 1;
}
for (; k; k >>= 1, X = X * X)
if (k & 1) ans = ans * X;
return ans;
}
int main() {
for (int i = int(1); i <= (int)(7); i++) a[i] = rd();
int la = 0;
dp[0] = 1;
for (int i = int(1); i <= (int)(7); i++)
if (a[i]) {
memset(tmp, 0, sizeof tmp);
matrix now;
memset(now.a, 0, sizeof now.a);
for (int A = int(0); A <= (int)((1 << i) - 1); A++) {
for (int B = int(0); B <= (int)((1 << i) - 1); B++) {
now.a[A][B] = calc(A, B, i);
}
}
now.len = (1 << i) - 1;
now = qpow(now, a[i]);
for (int j = int(0); j <= (int)((1 << i) - 1); j++) {
for (int k = int(0); k <= (int)((1 << i) - 1); k++) {
tmp[j] = (tmp[j] + 1ll * dp[k] * now.a[k][j]) % 1000000007;
}
}
memcpy(dp, tmp, sizeof dp);
la = i;
}
wrt(dp[0], '\n');
}
|
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
Input
The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.
Output
Print a single integer — the maximum length of a repost chain.
Examples
Input
5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya
Output
6
Input
6
Mike reposted Polycarp
Max reposted Polycarp
EveryOne reposted Polycarp
111 reposted Polycarp
VkCup reposted Polycarp
Codeforces reposted Polycarp
Output
2
Input
1
SoMeStRaNgEgUe reposted PoLyCaRp
Output
2
|
import java.util.*;
import java.io.*;
public class CodeForces {
static boolean g[][];
static boolean v[];
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
HashMap<String, Integer> map = new HashMap<>();
g = new boolean[n*2][n*2];
v = new boolean[n*2];
Integer x, y;
int cnt = 0;
for(int i = 0; i < n; i++){
String a = Reader.next().toLowerCase(); Reader.next();
String b = Reader.next().toLowerCase();
x = map.get(a);
if(x == null){
x = cnt++;
map.put(a, x);
}
y = map.get(b);
if(y == null){
y = cnt++;
map.put(b, y);
}
g[y][x] = true;
}
DFS(1, 0);
System.out.println(max+1);
}
static int max;
static void DFS(int cur, int counter){
if(v[cur])
return;
max = Math.max(max, counter);
for(int i = 0; i < g[cur].length; i++){
if(g[cur][i])
DFS(i, counter + 1);
}
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
public static int pars(String x) {
int num = 0;
int i = 0;
if (x.charAt(0) == '-') {
i = 1;
}
for (; i < x.length(); i++) {
num = num * 10 + (x.charAt(i) - '0');
}
if (x.charAt(0) == '-') {
return -num;
}
return num;
}
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static void init(FileReader input) {
reader = new BufferedReader(input);
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return pars(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
|
There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.
The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.
Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.
Input
The first line contains two positive space-separated integers, n and k (1 ≤ k ≤ n ≤ 2·105) — the initial number of cities in Westeros and the number of cities at which the game ends.
The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 106), which represent the population of each city in Westeros.
Output
Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.
Examples
Input
3 1
1 2 1
Output
Stannis
Input
3 1
2 2 1
Output
Daenerys
Input
6 3
5 20 12 7 14 101
Output
Stannis
Note
In the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.
In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Set;
public class C {
static int[][][][] stat;
static int game(int turn, int odd, int even, int left) {
if (left == 0) {
if (turn == 0) {
return (odd % 2 == 1) ? 1 : -1;
} else {
return (odd % 2 == 1) ? -1 : 1;
}
}
if (stat[turn][odd][even][left] != 0) {
return stat[turn][odd][even][left];
}
boolean win = false;
if (odd >= 1) {
int d = game(1-turn, odd-1, even, left-1);
if (d == -1) {
win = true;
}
}
if (even >= 1) {
int d = game(1-turn, odd, even-1, left-1);
if (d == -1) {
win = true;
}
}
stat[turn][odd][even][left] = win ? 1 : -1;
return stat[turn][odd][even][left];
}
public static void ex() {
stat = new int[2][100][100][100];
int left = 11;
for (int o = 0 ; o <= 16 ; o++) {
for (int e = 0 ; e <= 16 ; e++) {
if (o+e < left) {
System.out.print('-');
continue;
}
int g = game(0, o, e, left);
System.out.print(g == 1 ? 'W' : 'L');
}
System.out.println();
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
int odd = 0;
int even = 0;
for (int i = 0 ; i < n ; i++) {
int a = in.nextInt();
if (a % 2 == 1) {
odd++;
} else {
even++;
}
}
boolean win = true;
int turn = n - k;
if (turn % 2 == 0) {
// final turn is opponent
if (even > turn / 2) {
win = false;
} else {
win = ((odd + even) % 2) == 1;
}
} else {
if (odd <= turn / 2) {
win = false;
} else if (even > turn / 2 && odd > turn / 2) {
win = true;
} else {
win = ((odd + even) % 2) == 0;
}
}
if (n == k) {
win = (odd % 2 == 1);
} else if (k == 0) {
win = false;
}
out.println(win ? "Stannis" : "Daenerys");
out.flush();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int next() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public char nextChar() {
int c = next();
while (isSpaceChar(c))
c = next();
if ('a' <= c && c <= 'z') {
return (char)c;
}
if ('A' <= c && c <= 'Z') {
return (char)c;
}
throw new InputMismatchException();
}
public String nextToken() {
int c = next();
while (isSpaceChar(c))
c = next();
StringBuilder res = new StringBuilder();
do {
res.append((char)c);
c = next();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
|
It’s riot time on football stadium Ramacana! Raging fans have entered the field and the police find themselves in a difficult situation. The field can be represented as a square in the coordinate system defined by two diagonal vertices in (0,0) and (105, 105). The sides of that square are also considered to be inside the field, everything else is outside.
In the beginning, there are N fans on the field. For each fan we are given his speed, an integer vi as well as his integer coordinates (xi, yi). A fan with those coordinates might move and after one second he might be at any point (xi + p, yi + q) where 0 ≤ |p| + |q| ≤ vi. p, q are both integers.
Points that go outside of the square that represents the field are excluded and all others have equal probability of being the location of that specific fan after one second.
Andrej, a young and promising police officer, has sent a flying drone to take a photo of the riot from above. The drone’s camera works like this:
1. It selects three points with integer coordinates such that there is a chance of a fan appearing there after one second. They must not be collinear or the camera won’t work. It is guaranteed that not all of the initial positions of fans will be on the same line.
2. Camera focuses those points and creates a circle that passes through those three points. A photo is taken after one second (one second after the initial state).
3. Everything that is on the circle or inside it at the moment of taking the photo (one second after focusing the points) will be on the photo.
Your goal is to select those three points so that the expected number of fans seen on the photo is maximized. If there are more such selections, select those three points that give the circle with largest radius among them. If there are still more suitable selections, any one of them will be accepted. If your answer follows conditions above and radius of circle you return is smaller then the optimal one by 0.01, your output will be considered as correct.
No test will have optimal radius bigger than 1010.
Input
The first line contains the number of fans on the field, N. The next N lines contain three integers: xi ,yi, vi. They are the x-coordinate, y-coordinate and speed of fan i at the beginning of the one second interval considered in the task.
* 3 ≤ N ≤ 105
* 0 ≤ xi, yi ≤ 105
* 0 ≤ vi ≤ 1000
* All numbers are integers
Output
You need to output the three points that camera needs to select. Print them in three lines, with every line containing the x-coordinate, then y-coordinate, separated by a single space. The order of points does not matter.
Examples
Input
3
1 1 1
1 1 1
1 2 1
Output
2 2
2 1
1 0
|
#include <bits/stdc++.h>
using namespace std;
double const eps = 1e-7;
struct Points {
double x, y;
Points(double _x = 0, double _y = 0) { x = _x, y = _y; }
Points operator-(const Points &A) { return Points(x - A.x, y - A.y); }
Points operator+(const Points &A) { return Points(x + A.x, y + A.y); }
Points operator*(const double &k) { return Points(x * k, y * k); }
bool operator<(const Points &A) const {
return fabs(x - A.x) < eps ? y < A.y : x < A.x;
}
} p1, p2, p3;
inline double sqr(double x) { return x * x; }
inline double Cross(Points A, Points B) { return A.x * B.y - A.y * B.x; }
inline double Dis(Points A, Points B) {
return sqrt(sqr(A.x - B.x) + sqr(A.y - B.y));
}
inline Points Middle(Points A, Points B) {
return Points((A.x + B.x) / 2.0, (A.y + B.y) / 2.0);
}
inline Points Rev(Points A) { return Points(-A.y, A.x); }
struct Lines {
Points p, v;
Lines(Points _p = 0, Points _v = 0) { p = _p, v = _v; }
};
inline Points Inter(Lines A, Lines B) {
return A.v * (Cross(B.v, A.p - B.p) / Cross(A.v, B.v)) + A.p;
}
struct Circle {
Points o;
double r;
Circle(Points _o = 0, double _r = 0) { o = _o, r = _r; }
bool In(const Points &A) { return Dis(o, A) <= r; }
} O, ansO;
inline bool Check(Points A, Points B, Points C) {
return Cross(A - B, A - C) != 0;
}
inline Circle MakeCircle(Points A, Points B, Points C) {
Lines l1 = Lines(Middle(A, B), Rev(B - A));
Lines l2 = Lines(Middle(A, C), Rev(C - A));
Points o = Inter(l1, l2);
double r = Dis(o, A);
return Circle(o, r);
}
int const MAXN = 1e6 + 5;
vector<Points> G, Tb;
int stk1[MAXN], stk2[MAXN], top1, top2;
signed main() {
int n, Mx = 1e5;
scanf("%d", &n);
for (register int i = 1; i <= n; ++i) {
int x, y, d;
scanf("%d %d %d", &x, &y, &d);
int minx = (x - d >= 0), maxx = (x + d <= Mx);
int miny = (y - d >= 0), maxy = (y + d <= Mx);
if (minx)
G.push_back(Points(x - d, y));
else {
G.push_back(Points(0, max(0, y - d + x)));
G.push_back(Points(0, min(Mx, y + d - x)));
}
if (miny)
G.push_back(Points(x, y - d));
else {
G.push_back(Points(max(0, x - d + y), 0));
G.push_back(Points(min(Mx, x + d - y), 0));
}
if (maxx)
G.push_back(Points(x + d, y));
else {
G.push_back(Points(Mx, max(0, y - d + (Mx - x))));
G.push_back(Points(Mx, min(Mx, y + d - (Mx - x))));
}
if (maxy)
G.push_back(Points(x, y + d));
else {
G.push_back(Points(max(0, x - d + (Mx - y)), Mx));
G.push_back(Points(min(Mx, x + d - (Mx - y)), Mx));
}
}
int si = G.size();
sort(G.begin(), G.end());
for (register int i = 0; i < si; ++i) {
while (top1 > 1 && Cross(G[stk1[top1]] - G[stk1[top1 - 1]],
G[i] - G[stk1[top1 - 1]]) <= 0)
--top1;
stk1[++top1] = i;
}
for (register int i = 0; i < si; ++i) {
while (top2 > 1 && Cross(G[stk2[top2]] - G[stk2[top2 - 1]],
G[i] - G[stk2[top2 - 1]]) >= 0)
--top2;
stk2[++top2] = i;
}
for (register int i = 1; i <= top1; ++i) Tb.push_back(G[stk1[i]]);
for (register int i = top2 - 1; i > 1; --i) Tb.push_back(G[stk2[i]]);
Tb.push_back(Tb[0]);
Tb.push_back(Tb[1]);
si = Tb.size();
for (register int i = 0; i < si - 2; ++i) {
O = MakeCircle(Tb[i], Tb[i + 1], Tb[i + 2]);
if (O.r > ansO.r) ansO = O, p1 = Tb[i], p2 = Tb[i + 1], p3 = Tb[i + 2];
}
printf("%.0lf %.0lf\n", p1.x + 0.1, p1.y + 0.1);
printf("%.0lf %.0lf\n", p2.x + 0.1, p2.y + 0.1);
printf("%.0lf %.0lf\n", p3.x + 0.1, p3.y + 0.1);
return 0;
}
|
For the given sequence with n different elements find the number of increasing subsequences with k + 1 elements. It is guaranteed that the answer is not greater than 8·1018.
Input
First line contain two integer values n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 10) — the length of sequence and the number of elements in increasing subsequences.
Next n lines contains one integer ai (1 ≤ ai ≤ n) each — elements of sequence. All values ai are different.
Output
Print one integer — the answer to the problem.
Examples
Input
5 2
1
2
3
5
4
Output
7
|
import java.util.Scanner;
public class Subsequences {
public static void main(String[] args) {
Scanner fs=new Scanner(System.in);
int n=fs.nextInt(), k=fs.nextInt();
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=fs.nextInt()-1;
long[][] dp=new long[k+1][n];
BIT[] bits=new BIT[k+1];
for (int i=0; i<bits.length; i++) bits[i]=new BIT(n);
for (int i=0; i<n; i++) {
for (int kk=0; kk<=k; kk++) {
if (kk==0) {
dp[0][a[i]]=1;
}
else {
dp[kk][a[i]] = bits[kk-1].read(a[i]-1);
}
bits[kk].update(a[i], dp[kk][a[i]]);
}
}
long ans=0;
for (int end=0; end<n; end++) ans+=dp[k][end];
System.out.println(ans);
}
static class BIT {
int n;
long[] tree;
public BIT(int n) {
this.n = n;
tree = new long[n + 2];
}
long read(int i) {
i++;
long sum = 0;
while (i > 0) {
sum += tree[i];
i -= i & -i;
}
return sum;
}
void update(int i, long val) {
i++;
while (i <= n) {
tree[i] += val;
i += i & -i;
}
}
}
}
// 1 2 3 5 4
// x
|
Roger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segment is touching the red endpoint of the (i + 1)-th segment for all valid i.
Roger can move his arm in two different ways:
1. He can choose some segment and some value. This is denoted as choosing the segment number i and picking some positive l. This change happens as follows: the red endpoint of segment number i and segments from 1 to i - 1 are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments i + 1 through n are translated l units in the direction of this ray. <image> <image>
In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B gets translated.
2. He can choose a segment and rotate it. This is denoted as choosing the segment number i, and an angle a. The red endpoint of the i-th segment will stay fixed in place. The blue endpoint of that segment and segments i + 1 to n will rotate clockwise by an angle of a degrees around the red endpoint. <image> <image>
In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B get rotated around point A.
Roger will move his arm m times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.
Input
The first line of the input will contain two integers n and m (1 ≤ n, m ≤ 300 000) — the number of segments and the number of operations to perform.
Each of the next m lines contains three integers xi, yi and zi describing a move. If xi = 1, this line describes a move of type 1, where yi denotes the segment number and zi denotes the increase in the length. If xi = 2, this describes a move of type 2, where yi denotes the segment number, and zi denotes the angle in degrees. (1 ≤ xi ≤ 2, 1 ≤ yi ≤ n, 1 ≤ zi ≤ 359)
Output
Print m lines. The i-th line should contain two real values, denoting the coordinates of the blue endpoint of the last segment after applying operations 1, ..., i. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.
Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates.
Examples
Input
5 4
1 1 3
2 3 90
2 5 48
1 4 1
Output
8.0000000000 0.0000000000
5.0000000000 -3.0000000000
4.2568551745 -2.6691306064
4.2568551745 -3.6691306064
Note
The following pictures shows the state of the arm after each operation. The coordinates of point F are printed after applying each operation. For simplicity, we only show the blue endpoints of a segment (with the exception for the red endpoint of the first segment). For instance, the point labeled B is the blue endpoint for segment 1 and also the red endpoint for segment 2.
Initial state:
<image> Extend segment 1 by 3. <image> Rotate segment 3 by 90 degrees clockwise. <image> Rotate segment 5 by 48 degrees clockwise. <image> Extend segment 4 by 1. <image>
|
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#pragma GCC target( \
"sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
using namespace std;
const double PI = acos(-1.);
namespace SegmentTree {
int n;
const int _ = 2e6 + 100;
double squ(double x) { return x * x; }
struct Vector {
double x, y;
Vector() {}
Vector(double a, double b) {
x = a;
y = b;
}
double Length() { return sqrt(squ(x) + squ(y)); }
void pull(double len) {
double tmp = this->Length();
x *= (len + tmp) / tmp;
y *= (len + tmp) / tmp;
}
};
Vector operator+(const Vector& A, const Vector& B) {
return Vector(A.x + B.x, A.y + B.y);
}
struct Matrix {
double a, b, c, d;
Matrix() {
a = d = 1;
c = b = 0;
}
Matrix(double $1, double $2, double $3, double $4) {
a = $1;
b = $2;
c = $3;
d = $4;
}
Matrix(double alpha) {
double $1 = cos(alpha), $2 = sin(alpha);
a = $1;
b = -$2;
c = $2;
d = $1;
}
};
inline int sign(double x) { return x < -(1e-9) ? -1 : (x > (1e-9)); }
inline int cmp(double x, double y) { return sign(x - y); }
inline bool operator==(const Matrix& A, const Matrix& B) {
return cmp(A.a, B.a) == 0 && cmp(A.b, B.b) == 0 && cmp(A.c, B.c) == 0 &&
cmp(A.d, B.d) == 0;
}
Matrix operator*(const Matrix& A, const Matrix& B) {
Matrix ret;
ret.a = A.a * B.a + A.b * B.c;
ret.b = A.a * B.b + A.b * B.d;
ret.c = A.c * B.a + A.d * B.c;
ret.d = A.c * B.b + A.d * B.d;
return ret;
}
Vector operator*(const Matrix& A, const Vector& B) {
return Vector(A.a * B.x + A.b * B.y, A.c * B.x + A.d * B.y);
}
Vector v[_];
Matrix tag[_];
void tar(int o, Matrix V) {
tag[o] = V * tag[o];
v[o] = V * v[o];
}
void push(int o) {
if (tag[o] == tag[0]) return;
tar((o << 1), tag[o]);
tar(((o << 1) | 1), tag[o]);
tag[o] = tag[0];
}
void build(int o, int L, int R) {
if (L == R) return v[o] = Vector(1, 0), void();
int mid = (L + R) >> 1;
build((o << 1), L, mid);
build(((o << 1) | 1), mid + 1, R);
(v[o] = v[(o << 1)] + v[((o << 1) | 1)]);
}
void build(int __) {
n = __;
return build(1, 1, n);
}
void update_pull(int o, int nowl, int nowr, int p, double L) {
if (nowl == nowr) return v[o].pull(L), void();
int mid = (nowl + nowr) >> 1;
push(o);
if (p <= mid) update_pull((o << 1), nowl, mid, p, L);
if (p > mid) update_pull(((o << 1) | 1), mid + 1, nowr, p, L);
(v[o] = v[(o << 1)] + v[((o << 1) | 1)]);
}
void update_pull(int p, double L) { return update_pull(1, 1, n, p, L); }
void update_rotate(int o, int nowl, int nowr, int L, int R, Matrix x) {
if (L <= nowl && nowr <= R) return tar(o, x);
int mid = (nowl + nowr) >> 1;
push(o);
if (L <= mid) update_rotate((o << 1), nowl, mid, L, R, x);
if (R > mid) update_rotate(((o << 1) | 1), mid + 1, nowr, L, R, x);
(v[o] = v[(o << 1)] + v[((o << 1) | 1)]);
}
void update_rotate(int p, double alpha) {
alpha = 360 - alpha;
alpha = (alpha / 180.) * PI;
update_rotate(1, 1, n, p, n, Matrix(alpha));
}
Vector query() {
push(1);
return v[1];
}
} // namespace SegmentTree
using SegmentTree::build;
using SegmentTree::query;
using SegmentTree::update_pull;
using SegmentTree::update_rotate;
using SegmentTree::Vector;
int n, m;
int main() {
scanf("%d%d", &n, &m);
build(n);
while (m--) {
int opt, x;
scanf("%d%d", &opt, &x);
if (opt == 1) {
double L;
scanf("%lf", &L);
update_pull(x, L);
} else {
double alpha;
scanf("%lf", &alpha);
update_rotate(x, alpha);
}
Vector ret = query();
printf("%.5lf %.5lf\n", ret.x, ret.y);
}
return 0;
}
|
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.
He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:
Let a0, a1, ..., an denote the coefficients, so <image>. Then, a polynomial P(x) is valid if all the following conditions are satisfied:
* ai is integer for every i;
* |ai| ≤ k for every i;
* an ≠ 0.
Limak has recently got a valid polynomial P with coefficients a0, a1, a2, ..., an. He noticed that P(2) ≠ 0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.
Input
The first line contains two integers n and k (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 109) — the degree of the polynomial and the limit for absolute values of coefficients.
The second line contains n + 1 integers a0, a1, ..., an (|ai| ≤ k, an ≠ 0) — describing a valid polynomial <image>. It's guaranteed that P(2) ≠ 0.
Output
Print the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0.
Examples
Input
3 1000000000
10 -9 -3 5
Output
3
Input
3 12
10 -9 -3 5
Output
2
Input
2 20
14 -7 19
Output
0
Note
In the first sample, we are given a polynomial P(x) = 10 - 9x - 3x2 + 5x3.
Limak can change one coefficient in three ways:
1. He can set a0 = - 10. Then he would get Q(x) = - 10 - 9x - 3x2 + 5x3 and indeed Q(2) = - 10 - 18 - 12 + 40 = 0.
2. Or he can set a2 = - 8. Then Q(x) = 10 - 9x - 8x2 + 5x3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0.
3. Or he can set a1 = - 19. Then Q(x) = 10 - 19x - 3x2 + 5x3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0.
In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 109. Two first of ways listed above are still valid but in the third way we would get |a1| > k what is not allowed. Thus, the answer is 2 this time.
|
#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:256000000")
using namespace std;
const int maxN = 210000;
const int maxD = 10;
int n, k;
int a[maxN];
long long p[maxD];
long long p2[maxD][maxN];
long long x[maxD][maxN], y[maxD][maxN];
long long v[maxD][maxN];
long long w[maxD];
bool isPrime(long long n) {
for (long long i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
long long inv(long long a, long long p) {
long long x1 = 1, b1 = a;
long long x2 = 0, b2 = p;
while (b2) {
long long q = b1 / b2;
b1 -= q * b2;
x1 -= q * x2;
swap(b1, b2);
swap(x1, x2);
}
x1 %= p;
if (x1 < 0) {
x1 += p;
}
return x1;
}
int main() {
scanf("%d%d", &n, &k);
++n;
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
int m = 0;
for (long long i = 2000000000 + (rand() % 100000); m < maxD; ++i) {
if (isPrime(i)) {
p[m++] = i;
}
}
for (int i = 0; i < maxD; ++i) {
p2[i][0] = 1LL % p[i];
for (int j = 1; j < maxN; ++j) {
p2[i][j] = (2LL * p2[i][j - 1]) % p[i];
}
}
for (int i = 0; i < maxD; ++i) {
for (int j = 0; j < n; ++j) {
v[i][j] = ((long long)(a[j]) * p2[i][j]) % p[i];
}
for (int j = 0; j < n; ++j) {
x[i][j] = v[i][j];
if (j > 0) {
x[i][j] += x[i][j - 1];
x[i][j] %= p[i];
}
}
for (int j = n - 1; j >= 0; --j) {
y[i][j] = v[i][j];
if (j + 1 < n) {
y[i][j] += y[i][j + 1];
y[i][j] %= p[i];
}
}
}
long long ways = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < maxD; ++j) {
w[j] = (i > 0 ? x[j][i - 1] : 0) + (i + 1 < n ? y[j][i + 1] : 0);
w[j] %= p[j];
}
long long value = (-w[0] * inv(p2[0][i], p[0])) % p[0];
value = ((value % p[0]) + p[0]) % p[0];
if (value > (long long)(k)) {
value -= p[0];
}
if (i + 1 == n && value == 0) {
continue;
}
if (value >= (long long)(-k) && value <= (long long)(k)) {
bool isOk = true;
for (int j = 0; j < maxD; ++j) {
long long r = (w[j] + (p2[j][i] * value)) % p[j];
if (r != 0) {
isOk = false;
break;
}
}
if (isOk) {
++ways;
}
}
}
cout << ways << endl;
return 0;
}
|
The country of Reberland is the archenemy of Berland. Recently the authorities of Berland arrested a Reberlandian spy who tried to bring the leaflets intended for agitational propaganda to Berland illegally . The most leaflets contain substrings of the Absolutely Inadmissible Swearword and maybe even the whole word.
Berland legal system uses the difficult algorithm in order to determine the guilt of the spy. The main part of this algorithm is the following procedure.
All the m leaflets that are brought by the spy are numbered from 1 to m. After that it's needed to get the answer to q queries of the following kind: "In which leaflet in the segment of numbers [l, r] the substring of the Absolutely Inadmissible Swearword [pl, pr] occurs more often?".
The expert wants you to automate that procedure because this time texts of leaflets are too long. Help him!
Input
The first line contains the string s (1 ≤ |s| ≤ 5·105) — the Absolutely Inadmissible Swearword. The string s consists of only lowercase English letters.
The second line contains the only integer m (1 ≤ m ≤ 5·104) — the number of texts of leaflets for expertise.
Each of the next m lines contains the only string ti — the text of the i-th leaflet. The sum of lengths of all leaflet texts doesn't exceed 5·104. The text of the leaflets consists of only lowercase English letters.
The next line contains integer q (1 ≤ q ≤ 5·105) — the number of queries for expertise.
Finally, each of the last q lines contains four integers l, r, pl, pr (1 ≤ l ≤ r ≤ m, 1 ≤ pl ≤ pr ≤ |s|), where |s| is the length of the Absolutely Inadmissible Swearword.
Output
Print q lines. The i-th of them should contain two integers — the number of the text with the most occurences and the number of occurences of the substring [pl, pr] of the string s. If there are several text numbers print the smallest one.
Examples
Input
suffixtree
3
suffixtreesareawesome
cartesiantreeisworsethansegmenttree
nyeeheeheee
2
1 2 1 10
1 3 9 10
Output
1 1
3 4
|
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f, NIL = -1;
const int MAXS = 5e5 + 10, MAXM = 5e4 + 10, MAXQ = 5e5 + 10;
const int sam_node = (MAXS + MAXM) * 2;
struct Graph {
int to[sam_node * 2], nxt[sam_node * 2], head[sam_node], e;
void clear() {
memset(head, NIL, sizeof(head));
e = 0;
}
Graph() { clear(); }
void addedge(int f, int t) { to[e] = t, nxt[e] = head[f], head[f] = e++; }
void addtwo(int u, int v) { addedge(u, v), addedge(v, u); }
};
namespace SGT {
int NIL = 0;
int ls[MAXM * 20], rs[MAXM * 20], mx[MAXM * 20], idx[MAXM * 20], sgttail;
inline int newnode() {
ls[sgttail] = rs[sgttail] = NIL;
mx[sgttail] = 0;
return sgttail++;
}
inline void init() {
ls[NIL] = rs[NIL] = 0;
mx[NIL] = -5;
sgttail = 1;
}
inline void update(int now) {
if (mx[ls[now]] >= mx[rs[now]]) {
mx[now] = mx[ls[now]];
idx[now] = idx[ls[now]];
} else {
mx[now] = mx[rs[now]];
idx[now] = idx[rs[now]];
}
}
void insert(int l, int r, int &now, int id) {
if (now == NIL) now = newnode();
if (l == r) {
++mx[now];
idx[now] = id;
return;
}
if (id <= ((l + r) >> 1))
insert(l, ((l + r) >> 1), ls[now], id);
else
insert(((l + r) >> 1) + 1, r, rs[now], id);
update(now);
}
int merge(int l, int r, int rt1, int rt2) {
if (rt1 == NIL) return rt2;
if (rt2 == NIL) return rt1;
if (l == r) {
mx[rt1] += mx[rt2];
idx[rt1] = l;
return rt1;
}
int rl = merge(l, ((l + r) >> 1), ls[rt1], ls[rt2]),
rr = merge(((l + r) >> 1) + 1, r, rs[rt1], rs[rt2]);
ls[rt1] = rl, rs[rt1] = rr;
update(rt1);
return rt1;
}
pair<int, int> ask_max(int l, int r, int now, int st, int en) {
if (now == NIL) return make_pair(max(st, l), 0);
if (st <= l && r <= en) return make_pair(idx[now], mx[now]);
if (en <= ((l + r) >> 1)) return ask_max(l, ((l + r) >> 1), ls[now], st, en);
if (st > ((l + r) >> 1))
return ask_max(((l + r) >> 1) + 1, r, rs[now], st, en);
pair<int, int> al = ask_max(l, ((l + r) >> 1), ls[now], st, en),
ar = ask_max(((l + r) >> 1) + 1, r, rs[now], st, en);
return (al.second >= ar.second) ? al : ar;
}
} // namespace SGT
int to[sam_node][26], len[sam_node], parent[sam_node], samtail;
inline int newnode(int l) {
len[samtail] = l;
return samtail++;
}
int extend(int ch, int last) {
int p = last, now = (to[p][ch] == NIL) ? newnode(len[p] + 1) : NIL;
for (; p != NIL && to[p][ch] == NIL; p = parent[p]) to[p][ch] = now;
if (p == NIL)
parent[now] = 0;
else {
int q = to[p][ch];
if (len[q] == len[p] + 1) {
if (now == NIL)
now = q;
else
parent[now] = q;
} else {
int nq = newnode(len[p] + 1);
parent[nq] = parent[q];
memcpy(to[nq], to[q], sizeof(to[q]));
parent[q] = nq;
if (now == NIL)
now = nq;
else
parent[now] = nq;
for (; p != NIL && to[p][ch] == q; p = parent[p]) to[p][ch] = nq;
}
}
return now;
}
void init_sam() {
memset(to, NIL, sizeof(to));
len[0] = 0;
parent[0] = NIL;
samtail = 1;
}
struct Query {
int idx, l, st, en;
Query() {}
Query(int idx, int l, int st, int en) : idx(idx), l(l), st(st), en(en) {}
};
Graph tr;
char str[MAXS];
int m, q, root[sam_node];
pair<int, int> ans[MAXQ];
vector<Query> tmp[sam_node], qt[sam_node];
void get_parent() {
for (int i = 1; i < samtail; ++i) {
tr.addedge(parent[i], i);
}
}
void get_qt(int now) {
static pair<int, int> stk[sam_node];
static int stail = 0;
stk[stail++] = make_pair(len[now], now);
for (int i = 0; i < (int)tmp[now].size(); ++i) {
int idx =
lower_bound(stk, stk + stail, make_pair(tmp[now][i].l, -5))->second;
qt[idx].push_back(tmp[now][i]);
}
for (int i = tr.head[now]; i != NIL; i = tr.nxt[i]) {
get_qt(tr.to[i]);
}
--stail;
}
void get_ans(int now) {
for (int i = tr.head[now]; i != NIL; i = tr.nxt[i]) {
get_ans(tr.to[i]);
root[now] = SGT::merge(1, m, root[now], root[tr.to[i]]);
}
for (int i = 0; i < (int)qt[now].size(); ++i) {
ans[qt[now][i].idx] =
SGT::ask_max(1, m, root[now], qt[now][i].st, qt[now][i].en);
}
}
void init() {
init_sam();
memset(root, 0, sizeof(root));
SGT::init();
}
int main() {
scanf("%s", str);
init();
int len = strlen(str);
static int pos[MAXS];
int prv = 0;
for (int i = 0; i < len; ++i) {
prv = extend(str[i] - 'a', prv);
pos[i + 1] = prv;
}
scanf("%d", &m);
for (int i = 1; i <= m; ++i) {
scanf("%s", str);
int len = strlen(str), prv = 0;
for (int j = 0; j < len; ++j) {
prv = extend(str[j] - 'a', prv);
SGT::insert(1, m, root[prv], i);
}
}
get_parent();
scanf("%d", &q);
for (int i = 0, l, r, st, en; i < q; ++i) {
scanf("%d%d%d%d", &st, &en, &l, &r);
tmp[pos[r]].push_back(Query(i, r - l + 1, st, en));
}
get_qt(0);
get_ans(0);
for (int i = 0; i < q; ++i) {
printf("%d %d\n", ans[i].first, ans[i].second);
}
return 0;
}
|
The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.
Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle.
As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides). <image>
Input
The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 50). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.
Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).
Output
The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.
Example
Input
6
000000
000000
012100
024200
012100
000000
Output
Yes
Note
The lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (x1, y1), (x1, y2), (x2, y1), (x2, y2)), has a non-zero area and be contained inside of the grid (that is, 0 ≤ x1 < x2 ≤ N, 0 ≤ y1 < y2 ≤ N), and result in the levels of Zombie Contamination as reported in the input.
|
#include <bits/stdc++.h>
const int maxn = 1e2 + 10;
using namespace std;
int n, m, x[2], y[2];
char a[maxn][maxn];
bool check() {
int i, j;
for (i = 0; i <= 1; i++)
for (j = 0; j <= 1; j++)
if (a[x[i]][y[j]] != '1') return false;
for (i = x[0] + 1; i <= x[1] - 1; i++)
if (a[i][y[0]] != '2') return false;
for (i = x[0] + 1; i <= x[1] - 1; i++)
if (a[i][y[1]] != '2') return false;
for (i = y[0] + 1; i <= y[1] - 1; i++)
if (a[x[0]][i] != '2') return false;
for (i = y[0] + 1; i <= y[1] - 1; i++)
if (a[x[1]][i] != '2') return false;
for (i = x[0] + 1; i <= x[1] - 1; i++)
for (j = y[0] + 1; j <= y[1] - 1; j++)
if (a[i][j] != '4') return false;
return true;
}
int main() {
int i, j, k, t;
scanf("%d", &n);
for (i = 0; i <= n - 1; i++) scanf("%s", a[i]);
x[0] = y[0] = 0x3f3f3f3f, x[1] = y[1] = -1;
for (i = 0; i <= n - 1; i++)
for (j = 0; j <= n - 1; j++)
if (a[i][j] != '0') {
x[0] = min(x[0], i), x[1] = max(x[1], i), y[0] = min(y[0], j),
y[1] = max(y[1], j);
}
if (check())
puts("Yes");
else
puts("No");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.