input
stringlengths 29
13k
| output
stringlengths 9
73.4k
|
|---|---|
Tom is very weak at maths, his teacher gave him a simple problem of dividing two numbers but as usual Tom is having difficulty solving the problem. Can you help tom solve the problem ?
Teacher has given him 3 numbers a, b and c. The task is to divide a by b and write the answer upto c decimal places.
Input:
The first line of input contains an integer T denoting the number of test cases.
Each line of test case contains 3 numbers a, b and c as described in the question.
Output:
For each test case, output the required division of a/b upto c decimal places.
Constraints:
1 ≤ T ≤ 100,
1 ≤ a,b ≤ 100000
0 ≤ c ≤ 100000
SAMPLE INPUT
3
21 4 0
5 4 3
22 7 10
SAMPLE OUTPUT
5
1.250
3.1428571428
|
import string
import math
from decimal import *
t1 = int(raw_input())
while t1>0:
a,b,c = (raw_input().split(' '))
a = int(a)
b,c = int(b),int(c)
x=a/b
ta = a
getcontext().rounding = ROUND_DOWN
t = 0;
if x==0:
t = c +1
else:
t = c + int(math.log10(x))+1
getcontext().prec = t
a = Decimal(a)/Decimal(b)
# print a
a = str(a)
if ta%b==0:
a=a+'.'
a = a+'0'*100000
if c==0:
print a[0:t]
else:
print a[0:1+ t]
t1= t1-1
|
Most of you know that how much the sleeping barber loves sleeping, and the way he works.
For those who don't know, it isn't important for now.
Because the problem , that the sleeping barber is facing is a new one for him and because he forgot to take his coding pills, he is not able to tackle with it.
Recently, the barber learned that making a 'group' one of your regular customers increases your profits.
As too many groups are coming to his shop, he is not able to decide the order in which he should serve the customers to maximize his profit.What he knows from his intellect is that how many groups will come on that day to his shop and the size of each group.He also knows his capacity of service for the day ( how many customers he can serve on that day ). He wants to know , what is the number of groups he can serve to maximize his profit.
Now it is your task to help the barber and tell him number of groups he can serve to maximize his profit on that day.You will be provided number of days D, number of groups coming for every day G and a list of G integers denoting the size of the group.Also the maximum capacity M of the barber will be given for that day.
*Input *
The first line contains a single integer D - the number of days. The D cases follow.
First line of every case consists of a single integer G denoting number of groups and M denoting the maximum serving capacity of the barber.
Second line of every case consists of G integers denoting the size of the groups.
*Output *
In D lines print D integers - the maximum numbers groups that barber can serve.
Constraints
1 ≤ D ≤ 157
1 ≤ G ≤ 2937
1 ≤ G[i] ≤ 10^8
1 ≤ M ≤ 10^12
*Problem Setter : *Shikhar Singh
SAMPLE INPUT
2
5 5
3 2 1 4 7
5 10
5 5 2 7 4
SAMPLE OUTPUT
2
2
Explanation
Day 1 :
The barber can choose (1,2) or (1,3) or (1,4) or (2,3). In any case the maximum possible groups he can serve is 2.
Day 2 :
On of the possible optimal solution's is ( 4,5 ).In any case the maximum number of groups he can serve is 2.
|
d=int(input())
while d :
g,m=map(int,raw_input().split())
people=map(int,raw_input().split())
people.sort()
cnt=0
capacity=0
while capacity<=m and cnt<g+1:
cnt+=1
capacity+=people[cnt-1]
print cnt-1
d-=1
|
Given are integer sequences A and B of length 3N. Each of these two sequences contains three copies of each of 1, 2, \dots, N. In other words, A and B are both arrangements of (1, 1, 1, 2, 2, 2, \dots, N, N, N).
Tak can perform the following operation to the sequence A arbitrarily many times:
* Pick a value from 1, 2, \dots, N and call it x. A contains exactly three copies of x. Remove the middle element of these three. After that, append x to the beginning or the end of A.
Check if he can turn A into B. If he can, print the minimum required number of operations to achieve that.
Constraints
* 1 \leq N \leq 33
* A and B are both arrangements of (1, 1, 1, 2, 2, 2, \dots, N, N, N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_{3N}
B_1 B_2 ... B_{3N}
Output
If Tak can turn A into B, print the minimum required number of operations to achieve that. Otherwise, print -1.
Examples
Input
3
2 3 1 1 3 2 2 1 3
1 2 2 3 1 2 3 1 3
Output
4
Input
3
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
Output
0
Input
3
2 3 3 1 1 1 2 2 3
3 2 2 1 1 1 3 3 2
Output
-1
Input
8
3 6 7 5 4 8 4 1 1 3 8 7 3 8 2 4 7 5 2 2 6 5 6 1
7 5 8 1 3 6 7 5 4 8 1 3 3 8 2 4 2 6 5 6 1 4 7 2
Output
7
|
#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<utility>
#include<cassert>
#include<complex>
#include<numeric>
#include<array>
using namespace std;
//#define int long long
typedef long long ll;
typedef unsigned long long ul;
typedef unsigned int ui;
constexpr ll mod = 998244353;
const ll INF = mod * mod;
typedef pair<int, int>P;
#define stop char nyaa;cin>>nyaa;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
#define all(v) (v).begin(),(v).end()
typedef pair<ll, ll> LP;
typedef long double ld;
typedef pair<ld, ld> LDP;
const ld eps = 1e-12;
const ld pi = acosl(-1.0);
ll mod_pow(ll x, ll n, ll m = mod) {
ll res = 1;
while (n) {
if (n & 1)res = res * x % m;
x = x * x % m; n >>= 1;
}
return res;
}
struct modint {
ll n;
modint() :n(0) { ; }
modint(ll m) :n(m) {
if (n >= mod)n %= mod;
else if (n < 0)n = (n % mod + mod) % mod;
}
operator int() { return n; }
};
bool operator==(modint a, modint b) { return a.n == b.n; }
modint operator+=(modint& a, modint b) { a.n += b.n; if (a.n >= mod)a.n -= mod; return a; }
modint operator-=(modint& a, modint b) { a.n -= b.n; if (a.n < 0)a.n += mod; return a; }
modint operator*=(modint& a, modint b) { a.n = ((ll)a.n * b.n) % mod; return a; }
modint operator+(modint a, modint b) { return a += b; }
modint operator-(modint a, modint b) { return a -= b; }
modint operator*(modint a, modint b) { return a *= b; }
modint operator^(modint a, ll n) {
if (n == 0)return modint(1);
modint res = (a * a) ^ (n / 2);
if (n % 2)res = res * a;
return res;
}
ll inv(ll a, ll p) {
return (a == 1 ? 1 : (1 - p * inv(p % a, a)) / a + p);
}
modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); }
const int max_n = 1 << 21;
modint fact[max_n], factinv[max_n];
void init_f() {
fact[0] = modint(1);
for (int i = 0; i < max_n - 1; i++) {
fact[i + 1] = fact[i] * modint(i + 1);
}
factinv[max_n - 1] = modint(1) / fact[max_n - 1];
for (int i = max_n - 2; i >= 0; i--) {
factinv[i] = factinv[i + 1] * modint(i + 1);
}
}
modint comb(int a, int b) {
if (a < 0 || b < 0 || a < b)return 0;
return fact[a] * factinv[b] * factinv[a - b];
}
using bt = bitset<100>;
struct graph {
private:
int n;
vector<vector<int>> G, rG;
vector<bool> used;
vector<int> vs;
int mk;
vector<vector<int>> fG;
vector<vector<int>> ori;
vector<int> trans;
public:
graph(int sz) {
n = sz;
G.resize(n);
rG.resize(n);
used.resize(n);
fG.resize(n);
trans.resize(n, -1);
ori.resize(n);
}
void add_edge(int a, int b) {
G[a].push_back(b);
rG[b].push_back(a);
}
void dfs(int v) {
used[v] = true;
rep(i, G[v].size()) {
if (!used[G[v][i]])dfs(G[v][i]);
}
vs.push_back(v);
}
void rdfs(int v, int k) {
used[v] = true;
queue<int> q; q.push(v);
vector<int> c;
while (!q.empty()) {
int id = q.front(); q.pop();
ori[k].push_back(id);
rep(j, rG[id].size()) {
int to = rG[id][j];
if (used[to]) {
if (trans[to] >= 0)c.push_back(trans[to]);
continue;
}
used[to] = true; q.push(to);
}
}
sort(c.begin(), c.end());
int len = unique(c.begin(), c.end()) - c.begin();
rep(i, len) {
fG[c[i]].push_back(k);
}
rep(i, ori[k].size()) {
trans[ori[k][i]] = k;
}
}
void scc() {
fill(used.begin(), used.end(), false);
rep(i, n) {
if (!used[i])dfs(i);
}
fill(used.begin(), used.end(), false);
int k = 0;
per(i, (int)vs.size()) {
if (!used[vs[i]]) {
rdfs(vs[i], k); k++;
}
}
mk = k;
}
bool valid() {
rep(i, mk)if (ori[i].size() > 1)return false;
return true;
}
vector<bt> query() {
vector<bt> res(n);
per(i, mk) {
int id = ori[i][0];
res[id][id] = 1;
for (int tto : fG[i]) {
int to = ori[tto][0];
res[id] |= res[to];
}
}
return res;
}
bool valid(int sz, vector<int> banlist, vector<bool> als) {
vector<bool> used(sz);
vector<bool> exi(mk, true);
per(i, mk) {
for (int id : ori[i]) {
if (id < sz) {
if (banlist[id] & 1)exi[i] = false;
}
else {
if (banlist[id - sz] & 2)exi[i] = false;
}
if (used[id % sz])exi[i] = false;
}
for (int to : fG[i])if (!exi[to])exi[i] = false;
if (exi[i]) {
for (int id : ori[i]) {
used[id % sz] = true;
}
}
}
rep(i, als.size())if (als[i] && !used[i])return false;
return true;
}
};
int gcd(int a, int b) {
if (a > b)swap(a, b);
while (b > 0) {
int r = a % b; a = b; b = r;
}
return a;
}
int gcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
vector<int> cnt;
vector<int> loc;
void solve() {
int n; cin >> n;
vector<int> a(3 * n), b(3 * n);
rep(i, 3 * n) {
cin >> a[i]; a[i]--;
}
rep(i, 3 * n) {
cin >> b[i]; b[i]--;
}
vector<vector<int>>trans(n, vector<int>(3, -1));
vector<vector<int>> transb(n, vector<int>(3, -1));
rep(i, 3 * n) {
rep(j, 3) {
if (trans[a[i]][j] < 0) {
trans[a[i]][j] = i; break;
}
}
rep(j, 3) {
if (transb[b[i]][j] < 0) {
transb[b[i]][j] = i; break;
}
}
}
cnt.resize(n);
loc.resize(3 * n);
vector<int> lcnt(n), rcnt(n);
int ans = mod;
//[l,r]を残す
for (int l = 0; l < 3 * n; l++)for (int r = l; r < 3 * n; r++) {
fill(all(lcnt), 0);
fill(all(rcnt), 0);
rep(i, l)lcnt[b[i]]++;
Rep(i, r + 1, 3 * n) {
rcnt[b[i]]++;
}
rep(i, 3 * n)Rep(j, i, 3 * n) {
if (a[i] == b[l] && a[j] == b[r]) {
fill(all(cnt), 0);
for (int x = l; x <= r; x++) {
cnt[b[x]]++;
}
fill(all(loc), -1);
bool valid = true;
graph sc(3 * n);
rep(x, l - 1) {
sc.add_edge(x, x + 1);
}
for (int x = 3 * n - 1; x - 1 > r; x--) {
sc.add_edge(x, x - 1);
}
rep(c, n) {
if (cnt[c] == 3) {
rep(t, 3) {
loc[transb[c][t]] = trans[c][t];
}
}
else if (cnt[c] == 2) {
int id = 0;
rep(t, 3) {
if (transb[c][t] >= l && transb[c][t] <= r) {
loc[transb[c][t]] = trans[c][id];
if (id == 0)id = 2;
}
}
}
else if (cnt[c] == 1) {
if (lcnt[c] == 2) {
loc[transb[c][2]] = trans[c][2];
}
else if (rcnt[c] == 2) {
//cout << transb[c][0] << " " << trans[c][0] << "\n";
loc[transb[c][0]] = trans[c][0];
}
else {
//
}
}
else {
if (lcnt[c] == 3) {
valid = false;
}
else if (rcnt[c] == 3) {
valid = false;
}
else {
if (lcnt[c] == 1) {
sc.add_edge(transb[c][2], transb[c][0]);
//sc.add_edge(transb[c][0], transb[c][1]);
}
else {
sc.add_edge(transb[c][0], transb[c][2]);
//sc.add_edge(transb[c][2], transb[c][1]);
}
}
}
}
if (!valid)continue;
//scc
sc.scc();
if (!sc.valid())continue;
vector<bt> cp = sc.query();
graph nw(2 * n);
vector<int> banlist(n, 0);
for (int x = l; x <= r; x++) {
if (loc[x] < 0) {
int id = b[x];
int le = -mod;
if (x - 1 >= l && loc[x - 1] >= 0)le = loc[x - 1];
int ri = mod;
if (x + 1 <= r && loc[x + 1] >= 0)ri = loc[x + 1];
int al = trans[id][0];
int ar = trans[id][2];
if (x == l && al != i)banlist[id] |= 1;
if (x == r && al != j)banlist[id] |= 1;
if (x == l && ar != i)banlist[id] |= 2;
if (x == r && ar != j)banlist[id] |= 2;
if (al < le || al > ri)banlist[id] |= 1;
if (ar < le || ar > ri)banlist[id] |= 2;
if (banlist[id] == 3) {
valid = false;
}
}
}
if (!valid)continue;
if (loc[l] >= 0 && loc[l] != i)valid = false;
if (loc[r] >= 0 && loc[r] != j)valid = false;
for (int x = l; x < r; x++) {
if (loc[x] >= 0 && loc[x + 1] >= 0) {
if (loc[x] > loc[x + 1])valid = false;
}
}
//cout << "? " << l << " " << r << "\n";
if (!valid)continue;
for (int x = l; x < r; x++) {
if (loc[x] < 0 && loc[x + 1] < 0) {
int al = trans[b[x]][0];
int ar = trans[b[x]][2];
int bl = trans[b[x + 1]][0];
int br = trans[b[x + 1]][2];
if (al > br) {
valid = false;
break;
}
if (ar > br) {
banlist[b[x]] |= 2;
}
if (al > bl) {
banlist[b[x + 1]] |= 1;
}
if (ar > bl) {
nw.add_edge(b[x] + n, b[x + 1] + n);
nw.add_edge(b[x + 1], b[x]);
}
}
}
for (int x = l; x <= r; x++) {
if (loc[x] >= 0)continue;
int ale = transb[b[x]][0];
int ari = transb[b[x]][2];
if (cp[ari][ale])banlist[b[x]] |= 1;
if (cp[ale][ari])banlist[b[x]] |= 2;
for (int y = x + 1; y <= r; y++) {
if (loc[y] >= 0)continue;
int ble = transb[b[y]][0];
int bri = transb[b[y]][2];
//left,left
if (cp[ari][ble] && cp[bri][ale]) {
nw.add_edge(b[x], b[y] + n);
nw.add_edge(b[y], b[x] + n);
}
//left,right
if (cp[ari][bri] && cp[ble][ale]) {
nw.add_edge(b[x], b[y]);
nw.add_edge(b[y] + n, b[x] + n);
}
//right,left
if (cp[ale][ble] && cp[bri][ari]) {
nw.add_edge(b[x] + n, b[y] + n);
nw.add_edge(b[y], b[x]);
}
//right,right
if (cp[ale][bri] && cp[ble][ari]) {
nw.add_edge(b[x] + n, b[y]);
nw.add_edge(b[y] + n, b[x]);
}
}
}
// cout << "?! " << l << " " << r << "\n";
vector<bool> als(n);
for (int x = l; x <= r; x++)if (loc[x] < 0)als[b[x]] = true;
nw.scc();
if (!nw.valid(n, banlist, als))continue;
if (valid) {
//cout << l << " " << r << " "<<i<<" "<<j<<"\n";
ans = min(ans, l + (3 * n - 1 - r));
}
}
}
}
if (ans == mod)ans = -1;
//assert(ans >= 0);
cout << ans << "\n";
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout << fixed << setprecision(8);
//init_f();
//init();
//expr();
//int t; cin >> t; rep(i, t)
solve();
return 0;
}
|
We have a string S consisting of lowercase English letters.
If the length of S is at most K, print S without change.
If the length of S exceeds K, extract the first K characters in S, append `...` to the end of them, and print the result.
Constraints
* K is an integer between 1 and 100 (inclusive).
* S is a string consisting of lowercase English letters.
* The length of S is between 1 and 100 (inclusive).
Input
Input is given from Standard Input in the following format:
K
S
Output
Print a string as stated in Problem Statement.
Examples
Input
7
nikoandsolstice
Output
nikoand...
Input
40
ferelibenterhominesidquodvoluntcredunt
Output
ferelibenterhominesidquodvoluntcredunt
|
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
long k;
cin >> k;
cin >> s;
if (s.size() > k){
s = s.substr(0,k)+"...";
}
cout << s << endl;
}
|
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over all those ways.
Since the answer can be enormous, print it \bmod (10^9+7).
Constraints
* 1 \leq N \leq 10^5
* 1 \leq K \leq N
* |A_i| \leq 10^9
Input
Input is given from Standard Input in the following format:
N K
A_1 ... A_N
Output
Print the answer \bmod (10^9+7).
Examples
Input
4 2
1 1 3 4
Output
11
Input
6 3
10 10 10 -10 -10 -10
Output
360
Input
3 1
1 1 1
Output
0
Input
10 6
1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0
Output
999998537
|
# include <bits/stdc++.h>
using namespace std;
# define pb push_back
const int N = 100005;
# define MOD 1000000007
typedef long long i64;
int a[N];
i64 A[N];
i64 pow_mod(i64 a, i64 n, i64 mod){
i64 ret=1, tmp=a%mod;
while (n) {
if (n&1) ret=ret*tmp%MOD;
tmp=tmp*tmp%MOD;
n>>=1;
}
return ret;
}
i64 inv(i64 a, i64 mod){return pow_mod(a,mod-2,mod);}
i64 C(int x, int y) {
return A[x]*inv(A[y], MOD)%MOD*inv(A[x-y], MOD)%MOD;
}
int main ()
{
int n, k;
cin >> n >> k;
A[0] = 1;
for (int i = 1; i <= n; ++i) A[i] = A[i-1]*i%MOD;
for (int i = 1; i <= n; ++i) cin >> a[i];
sort(a + 1, a + n + 1);
i64 ans = 0;
for (int i = 1; i <= n-k+1; ++i) {
ans = (ans - a[i] * C(n-i, k-1) % MOD)%MOD;
}
for (int i = n; i >= k; --i) {
ans = (ans + a[i] * C(i-1, k-1) % MOD)%MOD;
}
cout << (ans + MOD)%MOD << endl;
return 0;
}
|
We have 3N colored balls with IDs from 1 to 3N. A string S of length 3N represents the colors of the balls. The color of Ball i is red if S_i is `R`, green if S_i is `G`, and blue if S_i is `B`. There are N red balls, N green balls, and N blue balls.
Takahashi will distribute these 3N balls to N people so that each person gets one red ball, one blue ball, and one green ball. The people want balls with IDs close to each other, so he will additionally satisfy the following condition:
* Let a_j < b_j < c_j be the IDs of the balls received by the j-th person in ascending order.
* Then, \sum_j (c_j-a_j) should be as small as possible.
Find the number of ways in which Takahashi can distribute the balls. Since the answer can be enormous, compute it modulo 998244353. We consider two ways to distribute the balls different if and only if there is a person who receives different sets of balls.
Constraints
* 1 \leq N \leq 10^5
* |S|=3N
* S consists of `R`, `G`, and `B`, and each of these characters occurs N times in S.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the number of ways in which Takahashi can distribute the balls, modulo 998244353.
Examples
Input
3
RRRGGGBBB
Output
216
Input
5
BBRGRRGRGGRBBGB
Output
960
|
//#define _GLIBCXX_DEBUG
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define P pair<ll,ll>
#define FOR(i,n,m) for(ll i=n; i<(ll)m;i++)
#define FORr(i,m,n) for(ll i=n; i>=(ll)m; i--)
#define FORm(i,m) for(auto i=m.begin();i!=m.end();i++)
#define sortAl(v) sort(v.begin(),v.end())
#define sortAlr(v) sort(v.begin(),v.end()); reverse(v.begin(),v.end())
#define cout(n) cout<<fixed<<setprecision(n)
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
ll n;
cin>>n;
string s;
cin>>s;
map<char,ll> mp;
ll MOD = 998244353;
ll ans = 1;
FOR(i,0,3*n){
vector<ll> v(3);
v[0] = mp['R'];
v[1] = mp['G'];
v[2] = mp['B'];
sortAlr(v);
if(mp[s[i]] == v[0]){
ans = ans*(n-mp[s[i]])%MOD;
}
else if(mp[s[i]] == v[1]){
ans = ans*(v[0] - v[1])%MOD;
}
else{
ans = ans*(v[1] - v[2])%MOD;
}
mp[s[i]]++;
}
cout<<ans<<endl;
}
|
In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!
There are five means of transport in this empire:
* Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.
* Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.
* Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.
* Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.
* Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.
For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).
There is a group of N people at City 1, and they all want to go to City 6.
At least how long does it take for all of them to reach there? You can ignore the time needed to transfer.
Constraints
* 1 \leq N, A, B, C, D, E \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A
B
C
D
E
Output
Print the minimum time required for all of the people to reach City 6, in minutes.
Examples
Input
5
3
2
4
3
5
Output
7
Input
10
123
123
123
123
123
Output
5
Input
10000000007
2
3
5
7
11
Output
5000000008
|
#include <bits/stdc++.h>
int main(){
using namespace std;
long N;
cin >> N;
vector<long> v(5);
for(auto& i : v)cin >> i;
cout << 5 + (N - 1) / *min_element(v.begin(), v.end()) << endl;
return 0;
}
|
There is a train going from Station A to Station B that costs X yen (the currency of Japan).
Also, there is a bus going from Station B to Station C that costs Y yen.
Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.
How much does it cost to travel from Station A to Station C if she uses this ticket?
Constraints
* 1 \leq X,Y \leq 100
* Y is an even number.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If it costs x yen to travel from Station A to Station C, print x.
Examples
Input
81 58
Output
110
Input
4 54
Output
31
|
L = list(map(int,input().split()))
print(L[0]+L[1]//2)
|
Snuke has a rooted tree with N vertices, numbered 1 through N. Vertex 1 is the root of the tree, and the parent of Vertex i ( 2\leq i \leq N ) is Vertex P_i ( P_i < i ). There is a number, 0 or 1, written on each vertex. The number written on Vertex i is V_i.
Snuke would like to arrange the vertices of this tree in a horizontal row. Here, for every vertex, there should be no ancestor of that vertex to the right of that vertex.
After arranging the vertices, let X be the sequence obtained by reading the numbers written on the vertices from left to right in the arrangement. Snuke would like to minimize the inversion number of X. Find the minimum possible inversion number of X.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq P_i < i ( 2 \leq i \leq N )
* 0 \leq V_i \leq 1 ( 1 \leq i \leq N )
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_2 P_3 ... P_N
V_1 V_2 ... V_N
Output
Print the minimum possible inversion number of X.
Examples
Input
6
1 1 2 3 3
0 1 1 0 0 0
Output
4
Input
1
0
Output
0
Input
15
1 2 3 2 5 6 2 2 9 10 1 12 13 12
1 1 1 0 1 1 0 0 1 0 0 1 1 0 0
Output
31
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fr(i,j,k) for(int i=j;i<k;i++)
#define f(n) fr(i,0,n)
#define f1(n) fr(i,1,n+1)
#define pb push_back
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
const int maxn = 200007;
int P[maxn],V[maxn],d[maxn],C[2][maxn];
struct cmp {
bool operator() (const int &a,const int &b) {
if(1LL * C[0][a] * C[1][b] != 1LL * C[0][b] * C[1][a])
return 1LL * C[0][a] * C[1][b] > 1LL * C[0][b] * C[1][a];
else return a > b;
}
};
set<int,cmp>st;
int fi(int x) {
return d[x] == x ? x : d[x] = fi(d[x]);
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 2 ; i <= n ; i++) {
cin >> P[i];
}
f1 (n) {
cin >> V[i];
}
f1 (n) {
d[i] = i;
C[V[i]][i] = 1;
}
ll ans = 0;
for (int i = 2 ; i <= n ; i++) {
st.insert(i);
}
for (int i = 1 ; i <= n - 1 ; i++) {
int v = *st.begin();
int p = fi(P[v]);
st.erase(v);
st.erase(p);
ans += 1LL * C[0][v] * C[1][p];
C[1][p] += C[1][v];
C[0][p] += C[0][v];
d[v] = p;
if (p != 1) {
st.insert(p);
}
}
cout << ans << '\n';
}
|
In some place in the Arctic Ocean, there are H rows and W columns of ice pieces floating on the sea. We regard this area as a grid, and denote the square at the i-th row and j-th column as Square (i,j). The ice piece floating in each square is either thin ice or an iceberg, and a penguin lives in one of the squares that contain thin ice. There are no ice pieces floating outside the grid.
The ice piece at Square (i,j) is represented by the character S_{i,j}. S_{i,j} is `+`, `#` or `P`, each of which means the following:
* `+`: Occupied by thin ice.
* `#`: Occupied by an iceberg.
* `P`: Occupied by thin ice. The penguin lives here.
When summer comes, unstable thin ice that is not held between some pieces of ice collapses one after another. Formally, thin ice at Square (i,j) will collapse when it does NOT satisfy either of the following conditions:
* Both Square (i-1,j) and Square (i+1,j) are occupied by an iceberg or uncollapsed thin ice.
* Both Square (i,j-1) and Square (i,j+1) are occupied by an iceberg or uncollapsed thin ice.
When a collapse happens, it may cause another. Note that icebergs do not collapse.
Now, a mischievous tourist comes here. He will do a little work so that, when summer comes, the thin ice inhabited by the penguin will collapse. He can smash an iceberg with a hammer to turn it to thin ice. At least how many icebergs does he need to smash?
Constraints
* 1 \leq H,W \leq 40
* S_{i,j} is `+`, `#` or `P`.
* S contains exactly one `P`.
Input
Input is given from Standard Input in the following format:
H W
S_{1,1}S_{1,2}...S_{1,W}
S_{2,1}S_{2,2}...S_{2,W}
:
S_{H,1}S_{H,2}...S_{H,W}
Output
Print the minimum number of icebergs that needs to be changed to thin ice in order to cause the collapse of the thin ice inhabited by the penguin when summer comes.
Examples
Input
3 3
+#+
#P#
+#+
Output
2
Input
3 3
+#+
P#
+#+
Output
2
Input
6 6
+++++
+++#++
+++++
+++P+#
+##+++
++++#+
Output
1
Input
40 40
++#+++++#+#+#+##+++++++##+#+++#++##++##
+##++++++++++#+###+##++++#+++++++++#++##
+++#+++++#++#++####+++#+#+###+++##+++#++
+++#+######++##+#+##+#+++#+++++++++#++#+
+++##+#+#++#+++#++++##+++++++++#++#+#+#+
++#+++#+#++++##+#+#+++##+#+##+#++++##++
++#+##+++#++####+#++##++#+++#+#+#++++#++
+#+###++++++##++++++#++##+#####++#++##++
+##+#+++#+#+##++#+###+######++++#+###+
+++#+++##+#####+#+#++++#+#+++++#+##++##+
+++#+##+++++++#++#++++++++++###+#++#+#+
+++##++#+++++#++++#++#+##++#+#+#++##+#
+++#+###+++++##++#+#+++####+#+++++#+++
+++#++#++#+++++++++#++###++++++++###+##+
++#+++#++++++#####++##++#+++#+++++#++++#
++#++#+##++++#####+###+++####+#+#+######
++++++##+++++##+++++#++###++#++##+++++++
+#++++##++++++#++++#+#++++#++++##+++##+#
+++++++#+#++##+##+#+++++++###+###++##+++
++++++#++###+#+#+++##+#++++++#++#+#++#+#
+##++++++#+++++#++#+#++##+++#+#+++##+#
+++#+#+##+#+##++#P#++#++++++##++#+#++##
+++#++##+##+#++++#++#++##++++++#+#+#+++
++++####+#++#####+++#+###+#++###++++#++#
+#++####++##++#+#+#+##+#+#+##++++##++#+
+###+###+#+##+++#++++++#+#++++###+#+++++
+++#+++++#+++#+++++##++++++++###++#+#+++
+#+#++#+#++++++###+#++##+#+##+##+#+#####
++++++++#+#+###+######++#++#+++++++++++
+++##+#+#++#++#++#++++++#++##+#+#++###
+#+#+#+++++++#+++++++######+##++#++##+##
++#+++#+###+#++###+++#+++#+#++++#+###+++
+#+###++#+#####+++++#+####++#++#+###+++
+#+##+#++#++##+++++++######++#++++++++++
+####+#+#+++++##+#+#++#+#++#+++##++++#+#
++##++#+#+++++##+#++++####+++++###+#+#+
+#++#++#+##+#+#++##++###+###+#+++++##+
++###+###+#+#++#++#########+++###+#+##
+++#+++#++++++++++#+#+++#++#++###+####+#
++##+###+++++++##+++++#++#++++++++++++++
Output
151
Input
1 1
P
Output
0
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
template <class T>
using V = vector<T>;
template <class T>
using VV = V<V<T>>;
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fi first
#define se second
#define rep(i, n) rep2(i, 0, n)
#define rep2(i, m, n) for (int i = m; i < (n); i++)
#define per(i, b) per2(i, 0, b)
#define per2(i, a, b) for (int i = int(b) - 1; i >= int(a); i--)
#define ALL(c) (c).begin(), (c).end()
#define SZ(x) ((int)(x).size())
constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n - 1); }
template <class T, class U>
void chmin(T& t, const U& u) {
if (t > u) t = u;
}
template <class T, class U>
void chmax(T& t, const U& u) {
if (t < u) t = u;
}
template <class T, class U>
ostream& operator<<(ostream& os, const pair<T, U>& p) {
os << "(" << p.first << "," << p.second << ")";
return os;
}
template <class T>
ostream& operator<<(ostream& os, const vector<T>& v) {
os << "{";
rep(i, v.size()) {
if (i) os << ",";
os << v[i];
}
os << "}";
return os;
}
#ifdef LOCAL
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << H;
debug_out(T...);
}
#define debug(...) \
cerr << __LINE__ << " [" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif
const int MX = 42;
const int INF = TEN(9);
int dp[MX][MX][MX][MX];
int pf[MX][MX];
int get(int a, int b, int c, int d) { //[a,b]*[c,d]
return max(0, pf[b + 1][d + 1] - pf[b + 1][c] - pf[a][d + 1] + pf[a][c]);
}
int main() {
int H, W;
cin >> H >> W;
V<string> s(H);
int pr, pc;
rep(i, H) {
cin >> s[i];
rep(j, W) {
if (s[i][j] == 'P') {
pr = i, pc = j, s[i][j] = '+';
}
pf[i + 1][j + 1] =
pf[i + 1][j] + pf[i][j + 1] - pf[i][j] + (s[i][j] == '#');
}
}
rep(i, MX) rep(j, MX) rep(k, MX) rep(l, MX) dp[i][j][k][l] = INF;
dp[0][H - 1][0][W - 1] = 0;
rep(a, H) {
for (int b = H - 1; b >= a; --b) {
rep(c, W) {
for (int d = W - 1; d >= c; --d) {
for (int e = a; e <= b; ++e) {
for (int f = c; f <= d; ++f) {
{
int nx = dp[a][b][c][d] + get(a, e, c, f) +
get(e + 1, b, f + 1, d);
if (f < d) chmin(dp[a][e][f + 1][d], nx);
if (e < b) chmin(dp[e + 1][b][c][f], nx);
}
{
int nx = dp[a][b][c][d] + get(a, e, f + 1, d) +
get(e + 1, b, c, f);
chmin(dp[a][e][c][f], nx);
if (f < d && e < b)
chmin(dp[e + 1][b][f + 1][d], nx);
}
}
}
}
}
}
}
int ans = INF;
for (int a = 0; a <= pr; ++a) {
for (int b = pr; b < H; ++b) {
for (int c = 0; c <= pc; ++c) {
for (int d = pc; d < W; ++d) {
int mini = min({get(pr, b, pc, d), get(pr, b, c, pc),
get(a, pr, c, pc), get(a, pr, pc, d)});
chmin(ans, dp[a][b][c][d] + mini);
}
}
}
}
cout << ans << endl;
return 0;
}
|
There are N turkeys. We number them from 1 through N.
M men will visit here one by one. The i-th man to visit will take the following action:
* If both turkeys x_i and y_i are alive: selects one of them with equal probability, then eats it.
* If either turkey x_i or y_i is alive (but not both): eats the alive one.
* If neither turkey x_i nor y_i is alive: does nothing.
Find the number of pairs (i,\ j) (1 ≤ i < j ≤ N) such that the following condition is held:
* The probability of both turkeys i and j being alive after all the men took actions, is greater than 0.
Constraints
* 2 ≤ N ≤ 400
* 1 ≤ M ≤ 10^5
* 1 ≤ x_i < y_i ≤ N
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_M y_M
Output
Print the number of pairs (i,\ j) (1 ≤ i < j ≤ N) such that the condition is held.
Examples
Input
3 1
1 2
Output
2
Input
4 3
1 2
3 4
2 3
Output
1
Input
3 2
1 2
1 2
Output
0
Input
10 10
8 9
2 8
4 6
4 9
7 8
2 8
1 8
3 4
3 4
2 7
Output
5
|
#include<bits/stdc++.h>
using namespace std;
const int maxN=410;
const int maxM=101000;
int n,m;
int P1[maxM],P2[maxM],Mark[maxN];
bitset<maxN> B[maxN];
int main(){
scanf("%d%d",&n,&m);for (int i=1;i<=m;i++) scanf("%d%d",&P1[i],&P2[i]);
for (int i=1;i<=n;i++){
B[i][i]=1;
for (int j=m;j>=1;j--)
if (B[i][P1[j]]&&B[i][P2[j]]){
Mark[i]=1;break;
}
else if (B[i][P1[j]]||B[i][P2[j]]) B[i][P1[j]]=B[i][P2[j]]=1;
}
int Ans=0;
for (int i=1;i<=n;i++) for (int j=i+1;j<=n;j++) if (!Mark[i]&&!Mark[j]&&!(B[i]&B[j]).any()) ++Ans;
printf("%d\n",Ans);return 0;
}
|
Joisino wants to evaluate the formula "A op B". Here, A and B are integers, and the binary operator op is either `+` or `-`. Your task is to evaluate the formula instead of her.
Constraints
* 1≦A,B≦10^9
* op is either `+` or `-`.
Input
The input is given from Standard Input in the following format:
A op B
Output
Evaluate the formula and print the result.
Examples
Input
1 + 2
Output
3
Input
5 - 7
Output
-2
|
a,b,c=input().split();print(int(a)+int(c)if b=='+'else int(a)-int(c))
|
There is a hotel with the following accommodation fee:
* X yen (the currency of Japan) per night, for the first K nights
* Y yen per night, for the (K+1)-th and subsequent nights
Tak is staying at this hotel for N consecutive nights. Find his total accommodation fee.
Constraints
* 1 \leq N, K \leq 10000
* 1 \leq Y < X \leq 10000
* N,\,K,\,X,\,Y are integers.
Input
The input is given from Standard Input in the following format:
N
K
X
Y
Output
Print Tak's total accommodation fee.
Examples
Input
5
3
10000
9000
Output
48000
Input
2
3
10000
9000
Output
20000
|
import java.util.Scanner;
class Main{
public static void main(String[] args) {
Scanner stdIn=new Scanner(System.in);
int n=stdIn.nextInt(),k=stdIn.nextInt(),x=stdIn.nextInt(),y=stdIn.nextInt(),s=0,i;
for(i=0;i<n&&i<k;i++) s+=x;
for(i=k;i<n;i++) s+=y;
System.out.print(s);
}
}
|
Write a program that extracts n different numbers from the numbers 0 to 100 and outputs the number of combinations that add up to s. Each n number is from 0 to 100, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is
1 + 2 + 3 = 6
0 + 1 + 5 = 6
0 + 2 + 4 = 6
There are three ways.
Input
Given multiple datasets. For each dataset, n (1 ≤ n ≤ 9) and s (0 ≤ s ≤ 1000) are given on one line, separated by a space. When both n and s are 0, it is the end of the input.
The number of datasets does not exceed 50.
Output
For each dataset, output the number of combinations in which the sum of n integers is s on one line.
No input is given with more than 1010 combinations.
Example
Input
3 6
3 1
0 0
Output
3
0
|
#include <iostream>
using namespace std;
long long dp[102][11][1002];
int main(){
int N,S;
while(cin>>N>>S&&(N!=0)){
for(int i=101;i>=0;i--){
for(int j=0;j<=N;j++){
for(int k=0;k<=S;k++){
long long res=0;
if(i==101)res=(j==0&&k==0);
else{
res+=dp[i+1][j][k];
if(j-1>=0&&k-i>=0)res+=dp[i+1][j-1][k-i];
}
dp[i][j][k]=res;
}
}
}
cout<<dp[0][N][S]<<endl;
}
return 0;
}
|
Ataru Oafoot of Aizu Gakuen University High School decided to play with a slot machine.
When you insert a medal on this machine, three reels will start spinning and each reel will stop automatically. In a normal game (normal game), 3 medals are inserted, and when the symbols are aligned, the following medals are obtained according to the symbols.
<image>
A special service will be started depending on how the patterns are aligned. A big bonus starts when you have 3 of 7 symbols, and you can play 5 bonus games. Also, when you have 3 BAR symbols, the regular bonus will start and you can play 3 bonus games.
If you have 3 star symbols, the free game will start and you will not be able to get medals, but you can start the next game without inserting medals.
During the bonus game, if you insert 2 medals per game, you will automatically get 3 grape patterns and 15 medals.
Oafoot started playing on the machine with 100 medals. After playing for a while, it ended in a normal game. How many medals did you have left?
Create a program that inputs play information and outputs the number of medals left at hand. The play information is given as the number of big bonuses b, the number of regular bonuses r, the number of grapes aligned during a normal game g, the number of cherries aligned c, the number of stars aligned s, and the total number of games t.
Note that t includes the number of bonus games. Also, medals will not disappear in the middle of the game.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a zero line. Each dataset is given in the following format:
b r g c s t
b, r, g, c, and s are integers greater than or equal to 0 and less than 200, and t is an integer less than or equal to 1000.
The number of datasets does not exceed 120.
Output
For each input dataset, the number of medals remaining at hand is output on one line.
Example
Input
3 2 30 3 26 226
9 0 18 3 20 118
5 5 12 2 15 203
7 4 19 2 22 197
7 4 24 4 17 209
0 0 0 0 0 0
Output
127
793
414
629
617
|
import java.io.*;
class Main
{
public static void main(String args[])throws IOException
{
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str=input.readLine();
String str_ary[]=str.split(" ");
if(str_ary[0].equals("0") && str_ary[1].equals("0") && str_ary[2].equals("0") && str_ary[3].equals("0") &&str_ary[4].equals("0")&& str_ary[5].equals("0"))break;
int x[]=new int[6];
for(int i=0;i<6;i++)
{
x[i]=Integer.parseInt(str_ary[i]);
}
int score=15*(x[0]+x[1])+15*(x[0]*5+x[1]*3)+7*x[2]+2*x[3]+100-3*(x[5]-x[4]-(x[0]*5+x[1]*3))-2*(x[0]*5+x[1]*3);
System.out.println(score);
}
}
}
|
Mr. Kobou found a bundle of old paper when he was cleaning his family home. On each paper, two series of numbers are written. Strange as it appeared to him, Mr. Kobou further went through the storehouse and found out a note his ancestor left. According to it, the bundle of paper is a treasure map, in which the two sequences of numbers seem to give a clue to the whereabouts of the treasure the ancestor buried.
Mr. Kobou’s ancestor divided the area where he buried his treasure in a reticular pattern and used only some of the grid sections. The two series of numbers indicate the locations: the $i$-th member of the first series indicates the number of locations in the $i$-th column (form left) of the grid sections where a part of the treasure is buried, and the $j$-th member of the second indicates the same information regarding the $j$-th row from the top. No more than one piece of treasure is buried in one grid section. An example of a 5 × 4 case is shown below. If the pieces of treasure are buried in the grid sections noted as "#" the two series of numbers become "0,2,2,1,1" and "1,1,1,3".
| 0| 2| 2| 1| 1
---|---|---|---|---|---
1| | | #| |
1| | #| | |
1| | | | | #
3| | #| #| #|
Mr. Kobou’s ancestor seems to be a very careful person. He slipped some pieces of paper with completely irrelevant information into the bundle. For example, a set of number series "3,2,3,0,0" and "4,2,0,0,2" does not match any combination of 5 × 5 matrixes. So, Mr. Kobou has first to exclude these pieces of garbage information.
Given the set of information written on the pieces of paper, make a program to judge if the information is relevant.
Input
The input is given in the following format.
$W$ $H$
$a_1$ $a_2$ $...$ $a_W$
$b_1$ $b_2$ $...$ $b_H$
The first line provides the number of horizontal partitions $W$ ($1 \leq W \leq 1000$) and vertical partitions $H$ ($1 \leq H \leq 1000$). The second line provides the $i$-th member of the first number series $a_i$ ($0 \leq a_i \leq H$) written on the paper, and the third line the $j$-th member of the second series $b_j$ ($0 \leq b_j \leq W$).
Output
Output "1" if the information written on the paper is relevant, or "0" otherwise.
Examples
Input
5 4
0 2 2 1 1
1 1 1 3
Output
1
Input
5 5
3 2 3 0 0
4 2 0 0 2
Output
0
|
#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
int a[2000],b[2000];
int main(){
int w,h;cin>>w>>h;
priority_queue<int>que;
rep(i,w){
scanf("%d",&a[i]);
if(a[i])que.push(a[i]);
}
rep(i,h){
scanf("%d",&b[i]);
vector<int>v;
rep(j,b[i]){
if(que.empty()){
puts("0");return 0;
}
int p=que.top();que.pop();
p--;
if(p)v.push_back(p);
}
for(int i:v)que.push(i);
}
if(!que.empty())puts("0");
else puts("1");
}
|
Emacs is a text editor which is widely used by many programmers.
The advantage of Emacs is that we can move a cursor without arrow keys and the mice. For example, the cursor can be moved right, left, down, and up by pushing f, b, n, p with the Control Key respectively. In addition, cut-and-paste can be performed without the mouse.
Your task is to write a program which simulates key operations in the Emacs-like editor. The program should read a text and print the corresponding edited text.
The text consists of several lines and each line consists of zero or more alphabets and space characters. A line, which does not have any character, is a blank line.
The editor has a cursor which can point out a character or the end-of-line in the corresponding line. The cursor can also point out the end-of-line in a blank line.
In addition, the editor has a buffer which can hold either a string (a sequence of characters) or a linefeed.
The editor accepts the following set of commands (If the corresponding line is a blank line, the word "the first character" should be "the end-of-line"):
* a
Move the cursor to the first character of the current line.
* e
Move the cursor to the end-of-line of the current line.
* p
Move the cursor to the first character of the next upper line, if it exists.
If there is no line above the current line, move the cursor to the first character of the current line.
* n
Move the cursor to the first character of the next lower line, if it exists.
If there is no line below the current line, move the cursor to the first character of the current line.
* f
Move the cursor by one character to the right, unless the cursor points out the end-of-line.
If the cursor points out the end-of-line and there is a line below the current line, move the cursor to the first character of the next lower line. Otherwise, do nothing.
* b
Move the cursor by one character to the left, unless the cursor points out the first character.
If the cursor points out the first character and there is a line above the current line, move the cursor to the end-of-line of the next upper line. Otherwise, do nothing.
* d
If the cursor points out a character, delete the character (Characters and end-of-line next to the deleted character are shifted to the left).
If the cursor points out the end-of-line and there is a line below, the next lower line is appended to the end-of-line of the current line (Lines below the current line are shifted to the upper).
Otherwise, do nothing.
* k
If the cursor points out the end-of-line and there is a line below the current line, perform the command d mentioned above, and record a linefeed on the buffer.
If the cursor does not point out the end-of-line, cut characters between the cursor (inclusive) and the end-of-line, and record them on the buffer. After this operation, the cursor indicates the end-of-line of the current line.
* y
If the buffer is empty, do nothing.
If the buffer is holding a linefeed, insert the linefeed at the cursor. The cursor moves to the first character of the new line.
If the buffer is holding characters, insert the characters at the cursor. The cursor moves to the character or end-of-line which is originally pointed by the cursor.
The cursor position just after reading the text is the beginning of the first line, and the initial buffer is empty.
Constraints
* The number of lines in the text given as input ≤ 10
* The number of characters in a line given as input ≤ 20
* The number of commands ≤ 300
* The maximum possible number of lines in the text during operations ≤ 100
* The maximum possible number of characters in a line during operations ≤ 1000
Input
The input consists of only one data-set which includes two parts. The first part gives a text consisting of several lines. The end of the text is indicated by a line (without quotes):
"END_OF_TEXT"
This line should not be included in the text.
Next part gives a series of commands. Each command is given in a line. The end of the commands is indicated by a character '-'.
Output
For the input text, print the text edited by the commands.
Example
Input
hyo
ni
END_OF_TEXT
f
d
f
f
k
p
p
e
y
a
k
y
y
n
y
-
Output
honihoni
honi
|
#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
const ld eps = 1e-9;
//// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\b.txt"
int main() {
vector<string>emacs;
while (1) {
string st;
getline(cin, st);
if (st == "END_OF_TEXT") {
break;
}
else {
emacs.push_back(st);
}
}
int x = 0, y = 0;
vector<string>buf;
while (1) {
char c; cin >> c;
switch (c) {
case 'a':
x = 0;
break;
case 'e':
x = emacs[y].size();
break;
case 'p':
if (y) {
y--;
}
x = 0;
break;
case 'n':
if (y != emacs.size() - 1) {
y++;
}
x = 0;
break;
case 'f':
if (x != emacs[y].size())x++;
else {
if (y != emacs.size() - 1) {
y++;
x = 0;
}
}
break;
case 'b':
if (x)x--;
else {
if (y) {
y--;
x = emacs[y].size();
}
}
break;
case 'd':
if (x != emacs[y].size()) {
emacs[y].erase(emacs[y].begin() + x);
}
else {
if (y != emacs.size() - 1) {
emacs[y].insert(emacs[y].end(), emacs[y + 1].begin(), emacs[y + 1].end());
emacs.erase(emacs.begin() + y + 1);
}
}
break;
case 'k':
if (x == emacs[y].size()) {
if (y != emacs.size() - 1) {
emacs[y].insert(emacs[y].end(), emacs[y + 1].begin(), emacs[y + 1].end());
emacs.erase(emacs.begin() + y + 1);
buf = vector<string>(1);
}
}
else {
buf = vector<string>(1, emacs[y].substr(x));
emacs[y].erase(emacs[y].begin() + x, emacs[y].end());
}
break;
case 'y':
if (buf.empty()) {
}
else {
if (buf[0] == "") {
string rest = emacs[y].substr(x);
emacs[y].erase(emacs[y].begin() + x, emacs[y].end());
emacs.insert(emacs.begin() + y+1, rest);
y++;
x = 0;
}
else {
emacs[y].insert(emacs[y].begin() + x, buf[0].begin(), buf[0].end());
x += buf[0].size();
}
}
break;
}
if (c=='-')break;/*
for (auto s : emacs) {
cout << s << endl;
}
cout << "x: " << x << endl << "y: " << y << endl;*/
}
for (auto s : emacs) {
cout << s << endl;
}
return 0;
}
|
There are many blue cards and red cards on the table. For each card, an integer number greater than 1 is printed on its face. The same number may be printed on several cards.
A blue card and a red card can be paired when both of the numbers printed on them have a common divisor greater than 1. There may be more than one red card that can be paired with one blue card. Also, there may be more than one blue card that can be paired with one red card. When a blue card and a red card are chosen and paired, these two cards are removed from the whole cards on the table.
<image>
Figure E-1: Four blue cards and three red cards
For example, in Figure E-1, there are four blue cards and three red cards. Numbers 2, 6, 6 and 15 are printed on the faces of the four blue cards, and 2, 3 and 35 are printed on those of the three red cards. Here, you can make pairs of blue cards and red cards as follows. First, the blue card with number 2 on it and the red card with 2 are paired and removed. Second, one of the two blue cards with 6 and the red card with 3 are paired and removed. Finally, the blue card with 15 and the red card with 35 are paired and removed. Thus the number of removed pairs is three.
Note that the total number of the pairs depends on the way of choosing cards to be paired. The blue card with 15 and the red card with 3 might be paired and removed at the beginning. In this case, there are only one more pair that can be removed and the total number of the removed pairs is two.
Your job is to find the largest number of pairs that can be removed from the given set of cards on the table.
Input
The input is a sequence of datasets. The number of the datasets is less than or equal to 100. Each dataset is formatted as follows.
> m n
> b1 ... bk ... bm
> r1 ... rk ... rn
>
The integers m and n are the number of blue cards and that of red cards, respectively. You may assume 1 ≤ m ≤ 500 and 1≤ n ≤ 500. bk (1 ≤ k ≤ m) and rk (1 ≤ k ≤ n) are numbers printed on the blue cards and the red cards respectively, that are integers greater than or equal to 2 and less than 10000000 (=107). The input integers are separated by a space or a newline. Each of bm and rn is followed by a newline. There are no other characters in the dataset.
The end of the input is indicated by a line containing two zeros separated by a space.
Output
For each dataset, output a line containing an integer that indicates the maximum of the number of the pairs.
Sample Input
4 3
2 6 6 15
2 3 5
2 3
4 9
8 16 32
4 2
4 9 11 13
5 7
5 5
2 3 5 1001 1001
7 11 13 30 30
10 10
2 3 5 7 9 11 13 15 17 29
4 6 10 14 18 22 26 30 34 38
20 20
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
100 100
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
117 755 835 683 52 369 302 424 513 870
75 874 299 228 140 361 30 342 750 819
761 123 804 325 952 405 578 517 49 457
932 941 988 767 624 41 912 702 241 426
351 92 300 648 318 216 785 347 556 535
166 318 434 746 419 386 928 996 680 975
231 390 916 220 933 319 37 846 797 54
272 924 145 348 350 239 563 135 362 119
446 305 213 879 51 631 43 755 405 499
509 412 887 203 408 821 298 443 445 96
274 715 796 417 839 147 654 402 280 17
298 725 98 287 382 923 694 201 679 99
699 188 288 364 389 694 185 464 138 406
558 188 897 354 603 737 277 35 139 556
826 213 59 922 499 217 846 193 416 525
69 115 489 355 256 654 49 439 118 961
0 0
Output for the Sample Input
3
1
0
4
9
18
85
Example
Input
4 3
2 6 6 15
2 3 5
2 3
4 9
8 16 32
4 2
4 9 11 13
5 7
5 5
2 3 5 1001 1001
7 11 13 30 30
10 10
2 3 5 7 9 11 13 15 17 29
4 6 10 14 18 22 26 30 34 38
20 20
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
100 100
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
117 755 835 683 52 369 302 424 513 870
75 874 299 228 140 361 30 342 750 819
761 123 804 325 952 405 578 517 49 457
932 941 988 767 624 41 912 702 241 426
351 92 300 648 318 216 785 347 556 535
166 318 434 746 419 386 928 996 680 975
231 390 916 220 933 319 37 846 797 54
272 924 145 348 350 239 563 135 362 119
446 305 213 879 51 631 43 755 405 499
509 412 887 203 408 821 298 443 445 96
274 715 796 417 839 147 654 402 280 17
298 725 98 287 382 923 694 201 679 99
699 188 288 364 389 694 185 464 138 406
558 188 897 354 603 737 277 35 139 556
826 213 59 922 499 217 846 193 416 525
69 115 489 355 256 654 49 439 118 961
0 0
Output
3
1
0
4
9
18
85
|
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <string>
#define SIZE 1002
#define INF 10000005
using namespace std;
typedef long long int ll;
typedef pair <int,int> P;
ll K;
struct edge{int to,cap,rev;};
vector<edge> G[SIZE];
bool used[SIZE];
//グラフ追加: from -> to (cap)
void add_edge(int from, int to, int cap){
G[from].push_back((edge){to,cap,(int)G[to].size()});
G[to].push_back((edge){from,0,(int)G[from].size()-1});
}
//パスを一本見つける
int dfs(int v, int t, int f){
if(v==t)return f;
used[v] = true;
for(int i=0;i<G[v].size();i++){
edge &e = G[v][i];
if(!used[e.to] && e.cap>0){
int d = dfs(e.to,t,min(f,e.cap));
if(d>0){ //v -> G[v][i].toにd流す
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s,int t){
int flow = 0;
for(;;){
memset(used,0,sizeof(used));
int f = dfs(s,t,INF);
if(f==0)return flow;
flow += f;
}
}
int gcd(int a,int b){ //a>=b
if(b==0)return a;
return gcd(b,a%b);
}
bool imain()
{
int m,n;
int B[500];
int R[500];
scanf("%d %d",&m,&n);
if(m==0&&n==0)return false;
for(int i=0;i<m;i++){
scanf("%d",&B[i]);
add_edge(1000,i,1);
}
for(int i=0;i<n;i++){
scanf("%d",&R[i]);
add_edge(i+500,1001,1);
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(gcd(B[i],R[j])!=1){
add_edge(i,500+j,1);
}
}
}
int ans = max_flow(1000,1001);
printf("%d\n",ans);
for(int i=0;i<m;i++)G[i].clear();
for(int i=0;i<n;i++)G[i+500].clear();
G[1000].clear();
G[1001].clear();
return true;
}
int main(){
while(imain());
return 0;
}
|
The earth is under an attack of a deadly virus. Luckily, prompt actions of the Ministry of Health against this emergency successfully confined the spread of the infection within a square grid of areas. Recently, public health specialists found an interesting pattern with regard to the transition of infected areas. At each step in time, every area in the grid changes its infection state according to infection states of its directly (horizontally, vertically, and diagonally) adjacent areas.
* An infected area continues to be infected if it has two or three adjacent infected areas.
* An uninfected area becomes infected if it has exactly three adjacent infected areas.
* An area becomes free of the virus, otherwise.
Your mission is to fight against the virus and disinfect all the areas. The Ministry of Health lets an anti-virus vehicle prototype under your command. The functionality of the vehicle is summarized as follows.
* At the beginning of each time step, you move the vehicle to one of the eight adjacent areas. The vehicle is not allowed to move to an infected area (to protect its operators from the virus). It is not allowed to stay in the same area.
* Following vehicle motion, all the areas, except for the area where the vehicle is in, change their infection states according to the transition rules described above.
Special functionality of the vehicle protects its area from virus infection even if the area is adjacent to exactly three infected areas. Unfortunately, this virus-protection capability of the vehicle does not last. Once the vehicle leaves the area, depending on the infection states of the adjacent areas, the area can be infected.
The area where the vehicle is in, which is uninfected, has the same effect to its adjacent areas as an infected area as far as the transition rules are concerned.
The following series of figures illustrate a sample scenario that successfully achieves the goal.
Initially, your vehicle denoted by @ is found at (1, 5) in a 5 × 5-grid of areas, and you see some infected areas which are denoted by #'s.
<image>
Firstly, at the beginning of time step 1, you move your vehicle diagonally to the southwest, that is, to the area (2, 4). Note that this vehicle motion was possible because this area was not infected at the start of time step 1.
Following this vehicle motion, infection state of each area changes according to the transition rules. The column "1-end" of the figure illustrates the result of such changes at the end of time step 1. Note that the area (3, 3) becomes infected because there were two adjacent infected areas and the vehicle was also in an adjacent area, three areas in total.
In time step 2, you move your vehicle to the west and position it at (2, 3).
Then infection states of other areas change. Note that even if your vehicle had exactly three infected adjacent areas (west, southwest, and south), the area that is being visited by the vehicle is not infected. The result of such changes at the end of time step 2 is as depicted in "2-end".
Finally, in time step 3, you move your vehicle to the east. After the change of the infection states, you see that all the areas have become virus free! This completely disinfected situation is the goal. In the scenario we have seen, you have successfully disinfected all the areas in three time steps by commanding the vehicle to move (1) southwest, (2) west, and (3) east.
Your mission is to find the length of the shortest sequence(s) of vehicle motion commands that can successfully disinfect all the areas.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing a single zero. Each dataset is formatted as follows.
n
a11 a12 ... a1n
a21 a22 ... a2n
...
an1 an2 ... ann
Here, n is the size of the grid. That means that the grid is comprised of n × n areas. You may assume 1 ≤ n ≤ 5. The rest of the dataset consists of n lines of n letters. Each letter aij specifies the state of the area at the beginning: '#' for infection, '.' for free of virus, and '@' for the initial location of the vehicle. The only character that can appear in a line is '#', '.', or '@'. Among n × n areas, there exists exactly one area which has '@'.
Output
For each dataset, output the minimum number of time steps that is required to disinfect all the areas. If there exists no motion command sequence that leads to complete disinfection, output -1. The output should not contain any other extra character.
Examples
Input
3
...
.@.
...
3
.##
.#.
@##
3
##.
#..
@..
5
....@
##...
#....
...#.
##.##
5
#...#
...#.
#....
...##
..@..
5
#....
.....
.....
.....
..@..
5
#..#.
#.#.#
.#.#.
....#
.#@##
5
..##.
..#..
#....
#....
.#@..
0
Output
0
10
-1
3
2
1
6
4
Input
3
...
.@.
...
3
.##
.#.
@##
3
.
..
@..
5
....@
...
....
...#.
.##
5
...#
...#.
....
...##
..@..
5
....
.....
.....
.....
..@..
5
..#.
.#.#
.#.#.
....#
.#@##
5
..##.
..#..
....
....
.#@..
0
Output
0
10
-1
3
2
1
6
4
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int N;
while(cin >> N, N) {
string S;
for(int i = 0; i < N; i++) {
string T;
cin >> T;
S += T;
}
queue< string > que;
map< string, int > v;
que.emplace(S);
v[S] = 0;
bool flag = false;
while(!que.empty()) {
string p = que.front();
int cost = v[p];
que.pop();
if(count(begin(p), end(p), '#') == 0) {
cout << cost << endl;
flag = true;
break;
}
auto pos = p.find('@');
int x = pos % N, y = pos / N;
for(int i = -1; i <= 1; i++) {
for(int j = -1; j <= 1; j++) {
if(i == 0 && j == 0) continue;
int nx = x + i, ny = y + j;
if(nx < 0 || ny < 0 || nx >= N || ny >= N) continue;
if(p[nx + ny * N] == '#') continue;
swap(p[nx + ny * N], p[pos]);
string T = p;
for(int k = 0; k < N; k++) {
for(int l = 0; l < N; l++) {
int ret = 0;
for(int m = -1; m <= 1; m++) {
for(int n = -1; n <= 1; n++) {
if(m == 0 && n == 0) continue;
int vx = k + m, vy = l + n;
if(vx < 0 || vy < 0 || vx >= N || vy >= N) continue;
ret += p[vx + vy * N] != '.';
}
}
if(p[k + l * N] == '#') T[k + l * N] = ret == 2 || ret == 3 ? '#' : '.';
else if(p[k + l * N] == '.') T[k + l * N] = ret == 3 ? '#' : '.';
}
}
if(!v.count(T)) {
v[T] = cost + 1;
que.emplace(T);
}
swap(p[nx + ny * N], p[pos]);
}
}
}
if(!flag) cout << -1 << endl;
}
}
|
Problem
Rolling Block is a game in which a rectangular parallelepiped metal body is rotated and moved, and dropped into a hole in the goal.
The condition to clear this game is to drop the metal body to the goal.
image0
About blocks
From (1) in the figure below, the block is a 1 × 1 × L rectangular parallelepiped. The block can move while rotating in either the north, south, east, or west direction. However, the block cannot move beyond the stage.
From (2) in the figure below, when the block is tilted sideways, it moves while rotating in this way with respect to the moving direction.
From (3) in the figure below, when the block is upright, it moves while rotating in this way with respect to the moving direction.
For (2) and (3), the gray block is the block before movement and the white block is the block after movement.
The black arrow indicates that the block has moved in that direction. Also, the white arrow indicates that the block rotated in that direction as it moved. Dotted lines are drawn on the blocks, which are drawn to make the rotation easier to understand. (Such a dotted line is not written on the blocks actually handled in the game)
image1
The figure below is a diagram to supplement the rotation of the block. Suppose there is a block like a dice where the sum of the faces is 7. The figure below shows the changes in the numbers on the top surface when this block is moved while rotating in four directions, north, south, east, and west, for the upright block and the collapsed block. (Such numbers are not written on the blocks actually handled in the game.)
image2
About the stage
Stages are given in an H × W two-dimensional grid (1 ≤ H, W ≤ 25). Each two-dimensional grid consists of the following types of cells.
* "." Floor
Blocks can sit on the floor.
* "#" wall
It is impossible to proceed to the wall, and it is not possible to move such that a part of the block rides on the wall.
* Initial position of "S" block
Only one character is given for the block. In the initial state, there is only an upright state.
* "G" goal point
Only one goal will appear during the stage.
Also, it is only possible to reach the goal when the block is upright.
* Special walls and switches
Alphabet lowercase special wall
Uppercase alphabet Switch for special walls
The special wall cannot progress when it appears, and it is not possible to move a part of the block so that it rides on the special wall. When the block rotates and stands upright and there is a switch beneath the block, that switch is pressed.
When the switch is pressed, it disappears when a special wall of the same alphabet appears, and conversely it appears when it disappears.
It is assumed that all special walls have appeared immediately after the start of the stage.
There are a maximum of 5 types of special walls and switches that appear on one stage.
The alphabet for the switch is {'A','B','C','D','E'}.
The alphabet for special walls is {'a','b','c','d','e'}.
The number of switches and special walls is H x W or less.
A switch with the same alphabet as the special wall does not always appear on the stage.
Also, a special wall with the same alphabet as the switch does not always appear on the stage.
* "^" Trap
Do not ride the rectangular parallelepiped upright on the trap square.
Given the stage information and the initial position of the metal body, find the shortest effort to solve this puzzle. Output -1 if no solution exists.
Constraints
The input satisfies the following conditions.
* 1 ≤ H, W ≤ 25
* 1 <L <10
* Cell is Cell = {'A','B','C','D','E','S','G','a','b','c','d', It consists of'e','^','#','.'}.
Input
H W L
Cell1-1 ... Cell1-W
..
..
..
CellH-1 ... CellH-W
First, H, W, L are given.
The vertical length, horizontal length, and block length of the stage are shown, respectively.
Next, an H × W two-dimensional grid is given. This represents stage information.
Output
Given the stage information and the initial position of the metal body, find the shortest effort to solve this puzzle.
Output -1 if no solution exists.
Examples
Input
5 5 2
#####
#S.G#
#...#
#...#
#####
Output
4
Input
5 5 2
S.G#
...#
...#
Output
4
Input
3 12 2
S..A..a..G#
Output
6
Input
3 12 2
S...A.a..G#
Output
-1
Input
7 13 3
S....#.....#
.....#.....#
.....#.....#
...........#
..........G#
Output
8
Input
3 12 2
S^^.^^.^^G#
Output
6
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
typedef pair<int,int> P;
struct data{
int y,x;
int bit;
int s;
data(){
}
data(int yy,int xx,int bb,int ss){
x=xx;
y=yy;
bit=bb;
s=ss;
}
};
int h,w,L;
bool wall[32][25][25];
bool trap[25][25];
int swi[25][25];
P st,g;
int dp[25][25][32][3];
bool pus[6];
queue<data> que;
bool isok(int y,int x,int bit,int s){
if(y<0 || y>=h || x<0 || x>=w)return false;
if(s==0){
if(trap[y][x])return false;
if(wall[bit][y][x])return false;
}
if(s==1){
for(int i=0;i<L;i++){
if(x+i>=w)return false;
if(wall[bit][y][x+i])return false;
}
}
if(s==2){
for(int i=0;i<L;i++){
if(y+i>=h)return false;
if(wall[bit][y+i][x])return false;
}
}
return true;
}
int upd(int y,int x,int bit,int s){
memset(pus,false,sizeof(pus));
if(s==0){
pus[swi[y][x]]=true;
}
for(int i=0;i<5;i++){
if(pus[i+1]){
bit^=(1<<i);
}
}
return bit;
}
int check(int y,int x,int bit,int s){
if(!isok(y,x,bit,s))return -1;
int nbit=upd(y,x,bit,s);
if(!isok(y,x,nbit,s))return -1;
return nbit;
}
void trys(int y,int x,int bit,int s,int val){
int nbit=check(y,x,bit,s);
if(nbit>=0 && dp[y][x][nbit][s]==-1){
dp[y][x][nbit][s]=val+1;
que.push(data(y,x,nbit,s));
}
}
int bfs(){
memset(dp,-1,sizeof(dp));
que.push(data(st.first,st.second,31,0));
dp[st.first][st.second][31][0]=0;
while(que.size()){
data d=que.front();
que.pop();
if(d.x==g.second && d.y==g.first && d.s==0)return dp[d.y][d.x][d.bit][d.s];
int val=dp[d.y][d.x][d.bit][d.s];
if(d.s==0){
trys(d.y,d.x-L,d.bit,1,val);
trys(d.y,d.x+1,d.bit,1,val);
trys(d.y-L,d.x,d.bit,2,val);
trys(d.y+1,d.x,d.bit,2,val);
}
if(d.s==1){
trys(d.y,d.x-1,d.bit,0,val);
trys(d.y,d.x+L,d.bit,0,val);
trys(d.y-1,d.x,d.bit,1,val);
trys(d.y+1,d.x,d.bit,1,val);
}
if(d.s==2){
trys(d.y-1,d.x,d.bit,0,val);
trys(d.y+L,d.x,d.bit,0,val);
trys(d.y,d.x-1,d.bit,2,val);
trys(d.y,d.x+1,d.bit,2,val);
}
}
return -1;
}
int main(){
scanf("%d%d%d",&h,&w,&L);
for(int i=0;i<h;i++){
string str;
cin >> str;
for(int j=0;j<w;j++){
if(str[j]=='S'){
st=P(i,j);
}
if(str[j]=='G'){
g=P(i,j);
}
if(str[j]>='a' && str[j]<='e'){
int v=(str[j]-'a');
for(int k=0;k<32;k++){
if(k>>v & 1){
wall[k][i][j]=true;
}
}
}
if(str[j]>='A' && str[j]<='E'){
swi[i][j]=(str[j]-'A')+1;
}
if(str[j]=='^'){
trap[i][j]=true;
}
if(str[j]=='#'){
for(int k=0;k<32;k++){
wall[k][i][j]=true;
}
}
}
}
printf("%d\n",bfs());
return 0;
}
|
Princess, a Cryptanalyst
Decryption of the princess
English text is not available in this practice contest.
A brave princess in a poor country's tomboy got an old document written in Japanese, a town she went out in stealth. The princess can speak Japanese, so I immediately read this old document. Then I found something amazing. This ancient document showed the whereabouts of the ancient treasure. However, the location of the treasure was encrypted, making it difficult to understand. So the princess ordered you, your servant, to help you break the code.
You conducted a day and night survey to help the princess. As a result, it was found that a character string called Shortest Secret String (SSS) plays an important role in cryptanalysis. Here, SSS is a character string that contains all N words as a substring and has the minimum length.
Your job is to find the SSS out of N words.
Input
Inputs are given in multiple datasets. The first line of the dataset is given the number of words N (1 ≤ N ≤ 10) contained in the dataset. Words are given in the following N lines. After the last dataset, a line containing only 0 is given.
It should be noted that the words given by input consist only of lowercase letters and are guaranteed to be at most 10 in length.
Output
Output the SSS on one line for each dataset. If there are more than one, output the smallest one in lexicographic order.
Sample Input
Four
apple
length
things
thin
2
icp
cpc
3
zeta
eta
alphabet
2
until until
till
0
Output for the Sample Input
applengthings
icpc
zetalphabet
untill
Example
Input
4
apple
length
things
thin
2
icp
cpc
3
zeta
eta
alphabet
2
until
till
0
Output
applengthings
icpc
zetalphabet
untill
|
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) repi(i,0,n)
#define repi(i,a,b) for(int i=(int)(a);i < (int)(b);++i)
template<class T1, class T2> ostream& operator << (ostream &s, pair<T1,T2> P)
{ return s << '<' << P.first << ", " << P.second << '>'; }
template<class T> ostream& operator << (ostream &s, vector<T> P)
{ for (int i = 0; i < P.size(); ++i) { if (i > 0) { s << " "; } s << P[i]; } return s; }
template<class T> ostream& operator << (ostream &s, vector<vector<T> > P)
{ for (int i = 0; i < P.size(); ++i) { s << endl << P[i]; } return s << endl; }
template<class Key,class Value> ostream& operator << (ostream &s, map<Key,Value> M)
{ for ( auto itr = begin(M); itr != end(M); ++itr) { s << itr->first << ":" << itr->second; } return s;}
void print(const std::vector<int>& v)
{
std::for_each(v.begin(), v.end(), [](int x) {
std::cout << x << " ";
});
std::cout << std::endl;
}
bool is_sub(string s1,string s2) {
int s1_size = s1.size();
int s2_size = s2.size();
if (s1_size > s2_size) {
rep(i,s1_size-s2_size + 1) {
bool flg = true;
rep(j,s2_size) {
if (s1[i+j] != s2[j]) {
flg = false;
break;
}
}
if (flg) return true;
}
return false;
}
else {
rep(i,s2_size-s1_size + 1) {
bool flg = true;
rep(j,s1_size) {
if (s2[i+j] != s1[j]) {
flg = false;
break;
}
}
if (flg) return true;
}
return false;
}
}
int main() {
while (true) {
int n = 0;
cin >> n;
if (n == 0) {
break;
}
long init = 0;
vector<string> S(n);
rep(i,n) cin >> S[i];
rep(i,n-1) {
repi(j,i+1,n) {
// cout << is_sub(S[i],S[j]) << " " << i << " " << j << endl;
if( is_sub(S[i],S[j]) ) {
if (S[i].size() > S[j].size()) init |= (1 << j);
else init |= (1 << i);
}
}
}
vector<int> v;
rep(i,n) {
if (!((init >> i) & 1)) v.push_back(i);
}
//cout << v << endl;
// cout << v << endl;
// suffix,prefix計算
vector<vector<string>> preffix(n),suffix(n);
rep(i,n) {
if (((init >> i) & 1)) continue;
preffix[i] = vector<string>(S[i].size()+1,"");
suffix[i] = vector<string>(S[i].size()+1,"");
rep(j, S[i].size()) {
repi(k,j+1,S[i].size()+1) {
preffix[i][k] += S[i][j];
suffix[i][k] = S[i][S[i].size()-1-j] + suffix[i][k];
}
}
}
int string_num = v.size();
string ans = "77";
do {
string cur = S[v[0]];
rep(i, string_num-1) {
int s_size = min(S[v[i]].size(),S[v[i+1]].size());
rep(j,s_size) {
//cout << suffix[v[i]][s_size-1-j] << " " << preffix[v[i+1]][s_size-1-j] << endl;;
if (suffix[v[i]][s_size-1-j] == preffix[v[i+1]][s_size-1-j]) {
//cout << cur << " " << suffix[v[i+1]][S[v[i+1]].size()-j] << endl;
int match = s_size - 1 - j;
cur += suffix[v[i+1]][S[v[i+1]].size()-match];
break;
}
}
}
if (ans == "77" || ans.size() > cur.size() || ( ans.size() == cur.size() && ans > cur)) ans = cur;
} while (next_permutation(v.begin(), v.end()));
cout << ans << endl;
}
}
|
We understand that reading English is a great pain to many of you. So we’ll keep this problem statememt simple. Write a program that reports the point equally distant from a set of lines given as the input. In case of no solutions or multiple solutions, your program should report as such.
Input
The input consists of multiple datasets. Each dataset is given in the following format:
n
x1,1 y1,1 x1,2 y1,2
x2,1 y2,1 x2,2 y2,2
...
xn,1 yn,1 xn,2 yn,2
n is the number of lines (1 ≤ n ≤ 100); (xi,1, yi,1) and (xi,2, yi,2) denote the different points the i-th line passes through. The lines do not coincide each other. The coordinates are all integers between -10000 and 10000.
The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed.
Output
For each dataset, print a line as follows. If there is exactly one point equally distant from all the given lines, print the x- and y-coordinates in this order with a single space between them. If there is more than one such point, just print "Many" (without quotes). If there is none, just print "None" (without quotes).
The coordinates may be printed with any number of digits after the decimal point, but should be accurate to 10-4.
Example
Input
2
-35 -35 100 100
-49 49 2000 -2000
4
0 0 0 3
0 0 3 0
0 3 3 3
3 0 3 3
4
0 3 -4 6
3 0 6 -4
2 3 6 6
-1 2 -4 6
0
Output
Many
1.5000 1.5000
1.000 1.000
|
#include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
//#define EPS 0.000000001
using namespace std;
#define EPS 0.000001
struct Point{
Point(double arg_x,double arg_y){
x = arg_x;
y = arg_y;
}
Point(){
x = y = 0.0;
}
Point operator + (Point p){ return Point(x+p.x,y+p.y); }
Point operator - (Point p){ return Point(x-p.x,y-p.y);}
Point operator * (double a){ return Point(a*x,a*y); }
Point operator / (double a){ return Point(x/a,y/a); }
double abs(){ return sqrt(norm()); }
double norm(){ return x*x + y*y; }
bool operator<(const Point &p) const{
return x != p.x? x < p.x: y < p.y;
}
bool operator == (const Point &p) const{
return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS;
}
double x,y;
};
struct Line{
Point p[2];
Line(Point p1,Point p2){
p[0] = p1;
p[1] = p2;
}
Line(){
}
};
typedef Point Vector;
int N;
Point point[3];
vector<Line> LINE;
double slope[3];
//交点を求める関数
Point calc_Cross_Point(double x1,double x2,double x3,double x4,double y1,double y2,double y3,double y4){
Point ret;
ret.x = ((x2-x1)*(y3*(x4-x3)+x3*(y3-y4))-(x4-x3)*(y1*(x2-x1)+x1*(y1-y2)))/((y2-y1)*(x4-x3)-(y4-y3)*(x2-x1));
if(x1 != x2){
ret.y = ((y2-y1)*ret.x+y1*(x2-x1)+x1*(y1-y2))/(x2-x1);
}else{
ret.y = ((y4-y3)*ret.x+y3*(x4-x3)+x3*(y3-y4))/(x4-x3);
}
return ret;
}
//インタフェース関数
Point calc_Cross_Point(Point a,Point b,Point c,Point d){
return calc_Cross_Point(a.x,b.x,c.x,d.x,a.y,b.y,c.y,d.y);
}
Point calc_Cross_Point(Line A,Line B){
return calc_Cross_Point(A.p[0],A.p[1],B.p[0],B.p[1]);
}
double calc_slope(Line A){
if(fabs(A.p[0].x-A.p[1].x) < EPS){
return DBL_MAX;
}else if(fabs(A.p[0].y-A.p[1].y) < EPS){
return 0;
}else{
return (A.p[0].y-A.p[1].y)/(A.p[0].x-A.p[1].x);
}
}
//★★直線の交差判定★★
bool is_Cross(Line A,Line B){
return fabs(calc_slope(A)-calc_slope(B)) > EPS;
}
double norm(Vector a){
return a.x*a.x+a.y*a.y;
}
double abs(Vector a){
return sqrt(norm(a));
}
double cross(Vector a,Vector b){
return a.x*b.y-a.y*b.x;
}
double dot(Vector a,Vector b){
return a.x*b.x + a.y*b.y;
}
double calc_dist1(Line line,Point point){
return abs(cross(line.p[1]-line.p[0],point-line.p[0]))/abs(line.p[1]-line.p[0]);
}
vector<Line> calc_Equal_Line(Line A,Line B){
vector<Line> ret;
if(is_Cross(A,B)){
Point cross_point = calc_Cross_Point(A,B);
Vector dir_A = A.p[1]-A.p[0];
Vector dir_B = B.p[1]-B.p[0];
dir_A = dir_A/abs(dir_A);
dir_B = dir_B/abs(dir_B);
ret.push_back(Line(cross_point,cross_point+dir_A+dir_B));
ret.push_back(Line(cross_point,cross_point+dir_A-dir_B));
}else{
ret.push_back(Line((A.p[0]+B.p[0])/2,(A.p[0]+B.p[0])/2+(A.p[1]-A.p[0])));
}
return ret;
}
void func(){
LINE.clear();
for(int i = 0; i < N; i++){
Point A,B;
scanf("%lf %lf %lf %lf",&A.x,&A.y,&B.x,&B.y);
if(A.x > B.x){
swap(A,B);
}
LINE.push_back(Line(A,B));
}
if(N <= 2){
printf("Many\n");
return;
}
vector<Line> LINE_01 = calc_Equal_Line(LINE[0],LINE[1]);
vector<Line> LINE_02 = calc_Equal_Line(LINE[0],LINE[2]);
vector<Point> CANDIDATE,ANS;
for(int i = 0; i < LINE_01.size(); i++){
for(int k = 0; k < LINE_02.size(); k++){
if(!is_Cross(LINE_01[i],LINE_02[k]))continue;
CANDIDATE.push_back(calc_Cross_Point(LINE_01[i],LINE_02[k]));
}
}
sort(CANDIDATE.begin(),CANDIDATE.end());
CANDIDATE.erase(unique(CANDIDATE.begin(),CANDIDATE.end()),CANDIDATE.end());
int count = 0;
for(int i = 0; i < CANDIDATE.size(); i++){
double base_dist = calc_dist1(LINE[0],CANDIDATE[i]);
bool FLG = true;
for(int k = 1; k < N; k++){
if(fabs(base_dist-calc_dist1(LINE[k],CANDIDATE[i])) > EPS){
FLG = false;
break;
}
}
if(FLG){
count++;
ANS.push_back(CANDIDATE[i]);
}
}
if(count == 0){
printf("None\n");
}else if(count >= 2){
printf("Many\n");
}else{
printf("%.10lf %.10lf\n",ANS[0].x,ANS[0].y);
}
}
int main(){
while(true){
scanf("%d",&N);
if(N == 0)break;
func();
}
return 0;
}
|
The 15th month of 2119. A spellbook was written by the court magician Sengemon Lugene. This magic book "In Magiray" was an innovative book in that it systematized "double magic", which is deeply related to the basis of the magic law of this world, as a technique that anyone can learn. First, let's take a look at a summary of the contents of this book.
【element】
Every object in the world is composed of tiny elements such as "spring", "wind", "feather", "flower", "sand", "light", and so on. There are many types of elements, and by signing a contract with an element, humans can activate double magic using the type of element with which they have a contract.
[Double magic]
Double magic, as the name implies, is magic that superimposes two elements and releases them. The main element is called the "main attribute" and the other is called the "sub-attribute". For example, if the primary attribute is "light" and the secondary attribute is "flower", the double magic is written as (light, flower). (Light, flower) and (flower, light) are different double magics. Moreover, the primary attribute and the sub-attribute may be the same.
【keyword】
Each element can have a one-to-one correspondence with a short "keyword" such as "spring → huda", "wind → loar", "feather → sheza", and "flower → leide". A keyword is an epoch-making concept that makes it possible to easily activate double magic simply by chanting a few consecutive keyword strings by symbolizing the nature of the element in short words.
【incantation】
A spell is a sequence of one or more keywords, such as "huda, leide, loar, sheza". By casting the spell intended by the caster, you can activate the corresponding double spell. Specifically, double magic is activated with the element corresponding to the first keyword of the spell as the main attribute and the element corresponding to the last keyword as the sub attribute. In the example of the spell I mentioned earlier, the double magic that is activated is (fountain, feather). If the spell consists of only one keyword, both the primary attribute and the sub-attribute are the elements corresponding to that keyword.
[Compatibility between elements]
I have already mentioned that the spell "huda, leide, loar, sheza" activates the double magic of (fountain, feather). However, at first glance, if you want to use (fountain, feather), it seems that you can just use "huda / sheza" without having to cast a long spell. But in reality, that is not possible. This is because "huda" and "sheza" are not compatible, and if you cast a spell in which these two are next to each other, a repulsive action will occur and the elements will cancel each other out. On the other hand, "fountain (huda)" and "flower (leide)", "flower (leide)" and "wind (loar)", "wind (loar)" and "feather (sheza)" are all good. Because of their compatibility, spells such as "huda, leide, loar, sheza" and "loar, leide, huda" do not offset elements.
[Spell logic]
Those who want to use double magic should define in advance which keyword is the "upper word" and which keyword is the "lower word" for each pair of compatible elements. There must be. When A is defined as the upper word and B is defined as the lower word for the keywords "A" and "B" of two compatible elements, it is written as A> B. When A> B, A cannot be placed immediately after B in a spell. In other words, if "A1, A2, A3 ... Ak" is the correct spell, it must be A1> A2, A2> A3, ..., Ak-1> Ak. By the way, even if A> B and B> C, it does not have to be A> C.
In this way, each surgeon defines the upper and lower words to his or her own taste, which is called "construction of spell logic". This is a device to clarify the flow of elements and increase the success probability of the target double magic by intentionally restricting the syntax of the spell. However, the price is that building spell logic can result in double spells that can't be cast no matter how you cast the spell (although you can use it no matter what spell logic you build. It has been proven that there is no double magic that cannot be done). Given these circumstances, what kind of spell logic to build is a thorny issue that has plagued many magicians both now and in the past.
Uto, an apprentice magician boy living in a small town, has signed contracts with all the elements and is about to perform a ritual to build his spell logic tomorrow. Ute simply thought that spell logic that could cast as many types of double magic as possible was good spell logic.
As a super-first-class electrician (super programmer in modern Japan), how many types of double magic can you use if you can successfully build spell logic from your friend Ute? I was consulted to know. This is a difficult problem that humans around the world have challenged, but no one could solve. If you can solve it, your name will be handed down all over the world in the future.
Input
N M
s1
s2
..
..
..
sN
p1 q1 p2 q2.
..
..
pM M
On the first line of input, the integer N and the integer M are written separated by blanks. This means that there are a total of N types of elements and a total of M pairs of compatible elements.
One character string is written in the following N lines. The character string si written on the 1 + i line indicates that the keyword corresponding to the i-th element is si.
On the following M line, two strings are written separated by blanks. The character strings pi and qi written on the 1 + N + i lines indicate that the element corresponding to the keyword pi and the pair of elements corresponding to the keyword qi are compatible. Conversely, pairs of elements that do not appear here are not compatible.
These data satisfy the following conditions.
* 2 ≤ N ≤ 100
* 1 ≤ M ≤ 4,950
* si is a string of 1 to 15 characters consisting of only uppercase or lowercase letters of the alphabet.
* i ≠ j ⇒ si ≠ sj
* pi ≤ qi
* i ≤ j ⇒ (pi, qi) ≠ (pj, qj) and (pi, qi) ≠ (qj, pj)
* There is no double magic that cannot be activated by constructing any spell logic.
Output
Output the maximum number of double magic types available when you build spell logic.
Examples
Input
4 3
huda
leide
loar
sheza
huda leide
leide loar
loar sheza
Output
10
Input
3 3
torn
siole
dimi
torn siole
torn dimi
siole dimi
Output
9
Input
9 10
riris
soa
elah
clar
arma
memori
neoles
qhaon
clue
clar riris
riris memori
riris neoles
soa clar
soa memori
neoles elah
elah qhaon
neoles qhaon
clue riris
arma elah
Output
54
|
#include<cstdio>
#include<iostream>
#include<string>
#include<map>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;
const int inf=1e8;
template<class T> void chMax(T &a,T b){
a=max(a,b);
}
map<string,int> elements;
int m,head[110],to[10100],nxt[10100];
int pre[110];
int comp[110];
int num_comp=0;
int c=0;
int N,M;
void init_edge();
void add_edge(int u,int v);
void init_edge(){
for(int i=0;i<N;i++) head[i]=-1;
}
void add_edge(int u,int v){
nxt[m]=head[u];to[m]=v;head[u]=m;m++;
nxt[m]=head[v];to[m]=u;head[v]=m;m++;
}
void visit(int v,int p,stack<int> &roots,stack<int> &s){
pre[v]=c++;
s.push(v);
roots.push(v);
for(int e=head[v];e!=-1;e=nxt[e]){
int u=to[e];
if(u==p) continue;
else if(pre[u]==-1){
visit(u,v,roots,s);
}else{
while(pre[roots.top()]>pre[u]){
roots.pop();
}
}
}
if(v==roots.top()){
while(true){
int w=s.top();
s.pop();
comp[w]=num_comp;
if(w==v) break;
}
num_comp++;
roots.pop();
}
}
void bridge(){
for(int i=0;i<N;i++) pre[i]=-1;
stack<int> roots,s;
for(int v=0;v<N;v++){
if(pre[v]==-1){
visit(v,-1,roots,s);
}
}
}
vector<int> G[110];
int weight[110];
int par[110];
int dp[2][110][110];
int res[110][110][110];
int sz[110];
int V;
void get_tree(){
for(int v=0;v<N;v++){
for(int e=head[v];e!=-1;e=nxt[e]){
int u=to[e];
int nv=comp[v],nu=comp[u];
if(nv==nu) continue;
G[nv].push_back(nu);
}
}
V=num_comp;
for(int i=0;i<N;i++) weight[i]=0;
for(int v=0;v<N;v++){
weight[comp[v]]++;
}
}
void solve(int v,int p){
sz[v]=weight[v];
for(int i=0;i<G[v].size();i++){
int u=G[v][i];
if(u==p) continue;
solve(u,v);
sz[v]+=sz[u];
}
for(int i=0;i<=sz[v];i++) for(int j=0;j<=sz[v];j++){
res[v][i][j]=-inf;
}
if(sz[v]==weight[v]){
res[v][sz[v]][sz[v]]=0;
return;
}
for(int i=0;i<=sz[v];i++) for(int j=0;j<=sz[v];j++){
for(int t=0;t<2;t++) dp[t][i][j]=-inf;
}
dp[0][0][0]=0;
int t=0;
// int ad=0;
for(int id=0;id<G[v].size();id++){
int u=G[v][id];
if(u==p) continue;
// ad+=weight[v]*weight[u];
for(int i=0;i<=sz[v];i++) for(int j=0;j<=sz[v];j++){
dp[t^1][i][j]=-inf;
}
for(int i=0;i<=sz[v]-weight[v]-sz[u];i++) for(int j=0;j<=sz[v]-weight[v]-sz[u];j++){
for(int k=0;k<=sz[u];k++) for(int l=0;l<=sz[u];l++){
if(res[u][k][l]<0) continue;
chMax(dp[t^1][i+k][j],dp[t][i][j]+res[u][k][l]+k*j+k*weight[v]);
chMax(dp[t^1][i][j+l],dp[t][i][j]+res[u][k][l]+i*l+l*weight[v]);
}
}
t^=1;
}
for(int i=0;i<=sz[v];i++) for(int j=0;j<=sz[v];j++){
res[v][i][j]=-inf;
}
for(int i=0;i<=sz[v]-weight[v];i++) for(int j=0;j<=sz[v]-weight[v];j++){
if(dp[t][i][j]>=0) res[v][i+weight[v]][j+weight[v]]=dp[t][i][j];
}
}
int main(){
cin>>N>>M;
for(int i=0;i<N;i++){
string str;
cin>>str;
elements[str]=i;
}
init_edge();
for(int i=0;i<M;i++){
string str1,str2;
cin>>str1>>str2;
int u=elements[str1];
int v=elements[str2];
add_edge(u,v);
}
bridge();
get_tree();
/* for(int i=0;i<V;i++){
printf("weight[%d]=%d\n",i,weight[i]);
}*/
/* for(int i=0;i<V;i++){
printf("%d- ",i);
for(int j=0;j<G[i].size();j++){
printf("%d ",G[i][j]);
}
printf("\n");
}*/
solve(0,-1);
int ans=0;
for(int i=0;i<V;i++){
ans+=weight[i]*weight[i];
}
int Ma=-1;
for(int i=0;i<=N;i++) for(int j=0;j<=N;j++){
chMax(Ma,res[0][i][j]);
}
printf("%d\n",ans+Ma);
return 0;
}
|
Sliding GCD
Problem Statement
For the set S of natural numbers, let f (S) be the number of elements in the set \\ {GCD (T) | T ⊆ S, T is not empty \\}.
Here, GCD (T) is the greatest integer that divides all the numbers contained in T.
In particular, note that GCD (\\ {a \\}) = a when T consists of only one integer a.
Find f (\\ {i, i + 1, ..., i + W --1 \\}) for i = 1, 2, ..., N --W + 1.
Constraints
* 1 ≤ W ≤ N ≤ 10 ^ 5
Input
Input follows the following format. All given numbers are integers.
N W
Output
The value of f (\\ {i, i + 1, ..., i + W-1 \\}) when i = 1, 2, ..., N-W + 1 is separated by a space. Print on a line.
Examples
Input
10 2
Output
2 3 3 3 3 3 3 3 3
Input
30 7
Output
7 8 9 10 10 11 11 11 11 12 11 12 10 12 12 11 10 12 12 12 10 11 11 13
|
#include <cstdio>
using namespace std;
int ans;
bool f[100001];
void check(int k, int t, int u){
if((t <= k && k <= u) || ((t + k - 1) / k < u / k)){
if(!f[k]){
f[k] = true;
++ans;
}
}
else if(f[k]){
f[k] = false;
--ans;
}
}
int main(){
int n, w;
scanf("%d%d", &n, &w);
for(int i = 1; i <= w; ++i){
f[i] = true;
}
ans = w;
for(int i = 1; i <= n - w + 1; ++i){
printf("%d%c", ans, i == n - w + 1 ? '\n' : ' ');
for(int j = 1; j * j <= i; ++j){
if(i % j == 0){
check(j, i + 1, i + w);
check(i / j, i + 1, i + w);
}
}
for(int j = 1; j * j <= i + w; ++j){
if((i + w) % j == 0){
check(j, i + 1, i + w);
check((i + w) / j, i + 1, i + w);
}
}
}
}
|
Problem statement
A programming contest will be held in the Russian Federation. The contest has N questions and has M participants. Question i has a score a_i, and it is known that participant j's ability is b_j. For problem i and participant j, participant j can always solve problem i if a_i ≤ b_j and only then. The score of a participant through the contest is the sum of the scores of the problems that the person was able to solve. Participant j also sets a target score c_j for this contest.
Determine if each participant can score more than the target score.
input
The input is given in the following format.
N
a_ {0} a_ {1} a_ {2}… a_ {N−1}
M
b_ {0} b_ {1} b_ {2}… b_ {M−1}
c_ {0} c_ {1} c_ {2}… c_ {M−1}
Constraint
* All inputs are integers
* 1 \ ≤ N \ ≤ 300 \,000
* 1 \ ≤ M \ ≤ 300 \,000
* 0 \ ≤ a_ {i} \ ≤ 1 \, 000 \,000
* 0 \ ≤ b_ {i} \ ≤ 1 \, 000 \,000
* 0 \ ≤ c_ {i} \ ≤ ∑a_k
output
Print the answer on line M. On the i-line, output `Yes` if the participant i-1 can get more points than the target score, and` No` if not.
sample
Sample input 1
6
1 2 1 3 4 5
7
1 3 4 5 3 1 0
2 4 5 3 4 5 3
Sample output 1
Yes
Yes
Yes
Yes
Yes
No
No
The points obtained by each participant are as follows.
* Participant 0: 1 + 1 = 2
* Participant 1: 1 + 2 + 1 + 3 = 7
* Participant 2: 1 + 2 + 1 + 3 + 4 = 11
* Participant 3: 1 + 2 + 1 + 3 + 4 + 5 = 16
* Participant 4: 1 + 2 + 1 + 3 = 7
* Participant 5: 1 + 1 = 2
* Participants 6: 0
Sample input 2
8
1 1 2 3 3 4 6 100
Four
1 3 4 99
1 10 15 120
Sample output 2
Yes
Yes
No
No
Example
Input
6
1 2 1 3 4 5
7
1 3 4 5 3 1 0
2 4 5 3 4 5 3
Output
Yes
Yes
Yes
Yes
Yes
No
No
|
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <functional>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <deque>
#include <ctime>
using namespace std;
#define rep(i,n) REP(i,0,n)
#define REP(i,s,e) for(int i=(s); i<(int)(e); i++)
#define pb push_back
#define mp make_pair
#define all(r) r.begin(),r.end()
#define fi first
#define se second
#define println(X) cout<<X<<endl;
#define DBG(X) cout<<#X<<" : "<<X<<endl;
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 = 1e9;
const ll MOD = 1e9 + 7;
double EPS = 1e-3;
int dx[]={-1,0,1,0};
int dy[]={0,-1,0,1};
int main(){
int n, m;
cin>>n;
vl a(n);
rep(i, n) cin>>a[i];
cin>>m;
vl b(m), c (m);
rep(i, m) cin>>b[i];
rep(i, m) cin>>c[i];
sort(all(a));
vl s(n+1);
rep(i, n) s[i+1] = s[i]+a[i];
for(int i = 0; i < m; i++){
auto it = upper_bound(all(a), b[i]) - a.begin();
//cout<<s[it]<<" ";
if(s[it] >= c[i]) printf("Yes\n");
else printf("No\n");
}
}
|
D: Sunburn-Suntan-
story
Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. Cute like an angel. Aizu Nyan is planning to participate in this summer festival, so I made a schedule for the band to go to listen to. I'm worried about sunburn here. All live performances are held outdoors, but Aizu Nyan has a constitution that makes it easy to get sunburned, so if you are exposed to too much ultraviolet rays outdoors for a long time, you will get sunburned immediately. I plan to avoid UV rays as much as possible by evacuating indoors while there is no live performance, but during the live performance, it will inevitably hit the sun. Therefore, Aizu Nyan thought about taking measures against ultraviolet rays by applying sunscreen.
problem
If you apply sunscreen, you can get the effect for T minutes from the time you apply it. Sunscreen can only be applied once, so I want to use it effectively. Aizu Nyan is outdoors from the start time to the end time of the live, and is indoors at other times. You'll be given a live schedule that Aizu Nyan will listen to, so find the maximum amount of time you can get the sunscreen effect while you're outdoors.
Input format
The input can be given in the following format.
T
N
s_1 t_1
...
s_N t_N
The first line is given an integer T that represents the time it takes to get the sunscreen effect. The second line is given an integer N that represents the number of live concerts Aizu Nyan listens to. The following N lines are given the integer s_i, which represents the start time of the live that Aizu Nyan listens to thi, and the integer t_i, which represents the end time, separated by spaces.
Constraint
* 1 ≤ T ≤ 10 ^ {15}
* 1 ≤ N ≤ 10 ^ 5
* 0 ≤ s_i <t_i ≤ 10 ^ {15} (1 ≤ i ≤ N)
* The start time of the (i + 1) th live is the same as or later than the end time of the i-th live. That is, t_i ≤ s_ {i + 1} (1 ≤ i <N)
output
Print one line for the maximum amount of time you can get the sunscreen effect while you're outdoors.
Input example 1
20
1
0 10
Output example 1
Ten
Input example 2
20
1
0 100
Output example 2
20
Input example 3
9
3
1 5
9 11
13 20
Output example 3
7
Input example 4
twenty five
Five
9 12
15 20
21 25
28 40
45 60
Output example 4
twenty one
Example
Input
20
1
0 10
Output
10
|
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define INF (1e9+1)
//#define INF (1LL<<59)
int main(){
ll t;
int n;
cin>>t>>n;
vector<ll> v;
rep(i,n){
ll a,b;
cin>>a>>b;
v.pb(a), v.pb(b);
}
int left = 0, right = 0;// (0,0)
ll tmp = 0, ans = 0;
while(left<=right){
while( right+1<2*n && v[right+1] - v[left] <= t ){
if((right+1)%2==1)tmp += v[right+1]-v[right];
right++;
}
if(right%2==0)ans = max(ans,tmp+t-(v[right]-v[left]));
else ans = max(ans,tmp);
if(left%2==0)tmp -= v[left+1] - v[left];
left++;
}
cout<<ans<<endl;
}
|
problem
There is a mysterious device $ M $, and if you put Tanuki and Fox in this device, one animal will come out from the device (hereinafter, Tanuki will be $ T $ and Fox will be $ F $).
$ M (x, y) $ represents an animal that came out by putting animals in the device $ M $ in the order of $ x, y $.
As a result of various trials, the following was found.
$ M (T, T) = T $
$ M (T, F) = F $
$ M (F, T) = T $
$ M (F, F) = T $
You put the animals in a row $ P_1, P_2, ..., P_N $ into the device as follows.
$ M (.... M (M (P_1, P_2), P_3) ...., P_N) $
Answer the last animal that appears.
output
Output the last animal character $ T $ or $ F $, and also a newline at the end.
Example
Input
3
F T T
Output
T
|
#include<bits/stdc++.h>
#define INF 1e9
#define llINF 1e18
#define MOD 1000000007
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define ll long long
#define ull unsigned long long
#define vi vector<ll>
#define vvi vector<vi>
#define BITLE(n) (1LL<<(n))
#define BITCNT(n) (__builtin_popcountll(n))
#define SUBS(s,f,t) ((s).substr((f)-1,(t)-(f)+1))
#define ALL(a) (a).begin(),(a).end()
using namespace std;
struct Grid{ll x,y,t;};
struct Edge{ll to,cost;};
struct Graph{vector<vector<Edge>>E;int V;
const ll Inf = llINF;const int MAX_V=201010;vector<ll>d;
Graph(int n):E(n){d.resize(MAX_V);E.resize(n);V=n;}
void init(){for(int i=0;i<MAX_V;i++)d[i]=Inf;}
void add_edge(ll from,ll to,ll cost){E[from].pb({to,cost});}
};
bool change(bool now,bool input){
return (!now)||input;
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
ll n;cin>>n;
bool now=true;
for(int i=0;i<n;i++){
char c;cin>>c;
if(c=='T')now=change(now,true);
else now=change(now,false);
}
cout<<(now?'T':'F')<<endl;
return 0;
}
|
A: Find the difference
problem
Given rectangular boards A and B with N squares vertically and M squares horizontally. For each board, each square is painted white or black.
The color of the square in the i-th row and j-th column of the board X is written as C (i, j, X).
Count how many pairs of integers (i, j) meet the following conditions:
* 1 \ leq i \ leq N
* 1 \ leq j \ leq M
* C (i, j, A) \ neq C (i, j, B)
Input format
N M
A_1_1
...
A_N
B_1_1
...
B_N
When the jth character of A_i (1 \ leq i \ leq N) is `#`, C (i, j, A) is black, and when it is `.`, C (i, j, A) is white. Represents that. The same is true for B.
Constraint
* 1 \ leq N, M \ leq 2,000
* | A_i | = | B_i | = M
* A_i and B_i are strings consisting only of `#` and `.`
Output format
Print the answer on one line.
Input example 1
twenty three
.. #
..
.##
..
Output example 1
2
Input example 2
7 28
............................
... # ..... ### ... #### .... ### ..
.. #. # ... # ... # ... # ... # .... # ... #.
. # ... # ... # ...... #### ... # .....
. ##### .. # ... # .. # ...... # ... #.
. # ... # ... ### ... # ....... ### ..
............................
............................
.. ### .... ### ..... ## .... ### ..
. # ... # ... # ... # ... #. # ... # ... #.
...##...#...# ..... # .... ####.
.. # ..... # ... # ..... # ....... #.
. ##### ... ### .... #### ... ### ..
............................
Output example 2
40
Example
Input
2 3
..#
##.
.##
#..
Output
2
|
/* -*- coding: utf-8 -*-
*
* 3107.cc: Spot The Difference
*/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
using namespace std;
/* constant */
const int MAX_H = 2000;
const int MAX_W = 2000;
/* typedef */
/* global variables */
char a[MAX_H][MAX_W + 4], b[MAX_H][MAX_W + 4];
/* subroutines */
/* main */
int main() {
int h, w;
scanf("%d%d", &h, &w);
for (int y = 0; y < h; y++) scanf("%s", a[y]);
for (int y = 0; y < h; y++) scanf("%s", b[y]);
int c = 0;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
if (a[y][x] != b[y][x]) c++;
printf("%d\n", c);
return 0;
}
|
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
|
#include <iostream>
#include <algorithm>
using namespace std;
#define INF 1e8
int main(){
int V,E;
cin>>V>>E;
int G[V][V];
fill(G[0],G[V],INF);
int ans=0;
int deg[V];
fill(deg,deg+V,0);//?¬???°
for(int i=0;i<E;i++){
int s,t,d;
cin>>s>>t>>d;
G[s][t]=G[t][s]=min(G[s][t],d);
ans+=d;
deg[s]++;deg[t]++;
}
unsigned int M=0;
for(int i=0;i<V;i++){
if(deg[i]%2) M|=(1<<i);
}
for(int i=0;i<V;i++)G[i][i]=0;
for(int k=0;k<V;k++){
for(int i=0;i<V;i++){
for(int j=0;j<V;j++){
G[i][j]=min(G[i][j],G[i][k]+G[k][j]);
}
}
}
int dp[1<<V];
fill(dp,dp+(1<<V),INF);
dp[0]=0;
for(unsigned int S=0;S<(1<<V);S++){
if(__builtin_popcount(S)%2)continue;
for(int i=0;i<V;i++){
if(!((1<<i)&S))continue;
for(int j=i+1;j<V;j++){
if(!((1<<j)&S))continue;
unsigned int s = ((1<<i)|(1<<j))^S;
dp[S]=min(dp[S],dp[s]+G[i][j]);
}
}
}
ans+=dp[M];
cout<<ans<<endl;
}
|
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
|
from functools import reduce
import math
n = int(input())
def lcm_base(x, y):
return (x * y) // math.gcd(x, y)
def lcm_list(numbers):
return reduce(lcm_base, numbers, 1)
numlis = [int(a) for a in input().split()]
print(lcm_list(numlis))
|
Akhil comes across a string S of length N. He started wondering about the smallest lexicographical subsequence of string S of length K.
A subsequence of a string is formed by deleting some characters (possibly none) from it's original string.
A string A is said to be lexicographically smaller than the string B of the same length if at the first position where A and B differ, A contains a letter which appears earlier in the dictionary than the corresponding letter in B.
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 will contain string S
Second line of each test case will contain an integer K.
Output
For each test case, output a single line containing the lexicographically smallest subsequence of S of length K.
Constraints
1 ≤ T ≤ 5
1 ≤ K ≤ N
S consists of lowercase English alphabet characters, i.e. from 'a' to 'z'.
Example
Input:
2
abdc
3
bacb
2
Output:
abc
ab
Explanation
Example case 1. "abc" is the smallest lexicographical subsequence out of ["abd", "bdc", "abc", "adc"].
Example case 2. "ab" is the smallest lexicographical subsequence of length 2.
|
import heapq
def solve(s, k):
res = []
start_index = -1
end_index = len(s) - k
#choose the staring window
h = [(y, x) for x, y in enumerate(s[:end_index])]
heapq.heapify(h)
for _ in range(k):
# enlarge the window by increamenting one (character, pos_of_haracter) from right
heapq.heappush(h, (s[end_index], end_index))
end_index += 1
# get the min from s[start_index : end_index] by using heappop (O(logN))
while True:
val, ind = heapq.heappop(h)
if ind > start_index: break
# save the min, shorten the window
res.append(val)
start_index = ind
return ''.join(res)
def astring():
T = int(raw_input())
for t in range(T):
s = raw_input()
k = int(raw_input())
print solve(s,k)
if __name__ == "__main__":
astring()
|
Churu is taking the course called “Introduction to Data Structures”. Yesterday, he learned how to use a stack to check is a given parentheses expression is balanced or not. He finds it intriguing, and more importantly, he was given an assignment. The professor gave him a string S containing characters “(” and “)”, and asked him numerous queries of the form (x, y), i.e., if the substring S[x, y] represents a balanced parentheses expression or not. Here, S[x, y] refers to the substring of S from index x to y (both inclusive), assuming 0-based indexing. Diligently working through his assignment, our ace student Churu finds that all the queries given by the professor represented balanced substrings. Later, Churu lost his original string but he has all the queries.
Churu wants to restore his original string. As there can be many valid strings, print any one among them.
Input
First line of input contains an integer T denoting the number of test cases.
First line of each of test case contains two space-separated integers: N, K representing the length of the string and number of queries asked by professor, respectively.
Each of the next K lines contains a space-separated pair of integers: x and y, denoting a query.
Output
Print T lines, with the i^th one containing the solution string for the i^th test case.
Constraints
Subtask #1: 20 points
1 ≤ T ≤ 5, 2 ≤ N ≤ 16, 1 ≤ K ≤ 20, x ≤ y
Subtask #2: 80 points
1 ≤ T ≤ 5, 2 ≤ N ≤ 2000, 1 ≤ K ≤ 30, x ≤ y
Input:
2
4 1
0 3
4 2
0 3
1 2
Output:
()()
(())
Explanation
For the first sample case, "(())" are "()()" are two possible outputs. Printing anyone will do.
|
t=input()
while t>0:
t-=1
n,k=map(int,raw_input().split())
li=['0']*n
flag=0
while k>0:
k-=1
a,b=map(int,raw_input().split())
for i in range(a,b+1,2):
li[i]="("
li[i+1]=")"
for i in range(n):
if li[i]=='0' and flag==0:
li[i]="("
flag=1
elif li[i]=="0" and flag==1:
li[i]=")"
flag=0
print "".join(li)
|
You're given an integer N. Write a program to calculate the sum of all the digits of N.
Input
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.
Output
Calculate the sum of digits of N.
Constraints
1 ≤ T ≤ 1000
1 ≤ N ≤ 100000
Example
Input
3
12345
31203
2123
Output
15
9
8
|
t=int(raw_input())
while(t>0):
n=[]
a=raw_input()
n=list(a)
n=map(int,list(n))
print sum(n)
t-=1
|
Little Elephant from the Zoo of Lviv hates exams. Since Little Elephant lives in Ukraine, he is going to take exams called 'ZNO'. Help him.
There will be n tickets on the table. Each ticket has a number written on it. The i-th ticket can be numbered Ai with probability Pi percent and with probability 100-Pi percent it can be numbered Bi. It can not have any other number. A numbering of tickets on the table is correct if and only if all tickets have distinct ticket numbers.
Help Little Elephant find the probability that the numbering will be correct.
Input
The first line of the input contains a single integer T - the number of test cases. T test cases follow. The first line of each test case contains a single integer n - the number of tickets on the table. n lines will follow. Each of these lines contains three integers: Pi, Ai and Bi.
Output
Output T lines, each containing a single real number - answer for the corresponding test case. Rounding errors less than 10^-6 will be ignored.
Constraints
1 <= T <= 10
1 <= n <= 50
1 <= Ai, Bi <= 16
0 <= Pi <= 100
Example
Input:
2
2
50 1 2
50 2 1
3
100 1 3
47 2 1
74 3 2
Output:
0.500000000
0.347800000
|
#! /usr/bin/env python
# -* - coding: UTF-8 -* -
rounds = int(raw_input())
A,B,P = [],[],[]
def main():
for _ in range(rounds):
tickets = int(raw_input())
global A, B, P
A,B,P = [],[],[]
for _ in range(tickets):
p, a, b = raw_input().split(" ")
P.append(int(p))
A.append(int(a))
B.append(int(b))
# compute probability of lossing game
# width-first traverse
stack = []
result = 0
stack.insert(0, (0, 1.0, 0))
while(len(stack) > 0):
bits, prob, i = stack.pop()
if i == tickets:
result += prob
continue
for b, p in wins(bits, i):
stack.insert(0, (b, prob * p, i + 1))
print result
def wins(bits, i):
if i >= len(A):
return
p1, p2 = 0, 0
if not (bits & 1 << A[i]):
yield bits | 1 << A[i], P[i] / 100.0
if not (bits & 1 << B[i]):
yield bits | 1 << B[i], (100 - P[i]) / 100.0
if __name__ == '__main__':
main()
|
Given two vessels, one of which can accommodate a liters of water and the other which can accommodate b liters of water, determine the number of steps required to obtain exactly c liters of water in one of the vessels.
At the beginning both vessels are empty. The following operations are counted as 'steps':
emptying a vessel,
filling a vessel,
pouring water from one vessel to the other, without spilling, until one of the vessels is either full or empty.
Input
An integer t, 1 ≤ t ≤ 100, denoting the number of test cases, followed by t sets of input data, each consisting of three positive integers a (the number of liters the first container can hold), b (the number of liters the second container can hold), and c (the final amount of liters of water one vessel should contain), not larger than 40000, given in separate lines.
Output
For each set of input data, output the minimum number of steps required to obtain c liters, or -1 if this is impossible.
Example
Sample input:
2
5
2
3
2
3
4
Sample output:
2
-1
|
def gcd(a, b):
while b:
a, b = b, a%b
return a
def solve(a,b,c):
if c==0:return 0
if c==a or c==b:return 1
if a>b:a,b=b,a
if c>b:return -1
if c==b-a:return 2
d=gcd(a,b)
if d!=1:
if c%d:return -1
a/=d;b/=d;c/=d;
q=b/a
rk=0
r=a
while True:
if c==r:return rk
rk+=2
if c==b-r:return rk
x=r;y=b-r
for k in range(1,q+2):
x+=a
y=b-x
rk+=2
if y<0:
r=-y
break
if c==x or c==y:return rk
t=int(raw_input())
for _ in range(t):
a=int(raw_input())
b=int(raw_input())
c=int(raw_input())
print solve(a,b,c)
|
Problem description.
A matrix of dimension mxn containing only 0's and 1's as it elements is given.Determine the maximum possible sub-square matrix containing only 1's as its elements
Input
Input description.
The first line of input contains an integer T,denoting the number of test cases
First line of each test case contains two space separated integers m,n denoting dimensions of matrix as mXn.
Next m lines contains n space separated integers(0's and 1's) .
Output
Output description.
For every test case , output the max possible sub-square matrix dimension.
Constraints
1 ≤ T ≤10^5
1 ≤ m,n ≤ 100
Example
Input:
3
3 3
1 0 0
0 1 0
0 0 1
3 3
0 0 0
0 0 0
0 0 0
4 5
1 0 0 0 0
1 0 1 1 0
0 1 1 1 1
0 1 0 0 0
Output:
1
0
2
Explanation
Example case 3.
|
t = int(raw_input())
for x in range(t):
inputs = raw_input()
inputs = inputs.split(" ")
m = int(inputs[0])
n = int(inputs[1])
city_array = []
for x in range(m):
temp = raw_input()
temp = temp.split(" ")
city_array.append(temp)
for x in range(m):
for y in range(n):
if city_array[x][y] == '1':
city_array[x][y] = 1
else:
city_array[x][y] = 0
for x in range(1,m):
for y in range(1,n):
if city_array[x][y] == 1:
city_array[x][y] = min(city_array[x-1][y],city_array[x][y-1],city_array[x-1][y-1]) + 1
else:
city_array[x][y] = 0
max_length = 0
for x in range(m):
for y in range(n):
if city_array[x][y] > max_length:
max_length = city_array[x][y]
print(max_length)
|
After a long day, Alice and Bob decided to play a little game. The game board consists of n cells in a straight line, numbered from 1 to n, where each cell contains a number a_i between 1 and n. Furthermore, no two cells contain the same number.
A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell i to cell j only if the following two conditions are satisfied:
* the number in the new cell j must be strictly larger than the number in the old cell i (i.e. a_j > a_i), and
* the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. |i-j|mod a_i = 0).
Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of numbers.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Furthermore, there are no pair of indices i ≠ j such that a_i = a_j.
Output
Print s — a string of n characters, where the i-th character represents the outcome of the game if the token is initially placed in the cell i. If Alice wins, then s_i has to be equal to "A"; otherwise, s_i has to be equal to "B".
Examples
Input
8
3 6 5 4 2 7 1 8
Output
BAAAABAB
Input
15
3 11 2 5 10 9 7 13 15 8 4 12 6 1 14
Output
ABAAAABBBAABAAB
Note
In the first sample, if Bob puts the token on the number (not position):
* 1: Alice can move to any number. She can win by picking 7, from which Bob has no move.
* 2: Alice can move to 3 and 5. Upon moving to 5, Bob can win by moving to 8. If she chooses 3 instead, she wins, as Bob has only a move to 4, from which Alice can move to 8.
* 3: Alice can only move to 4, after which Bob wins by moving to 8.
* 4, 5, or 6: Alice wins by moving to 8.
* 7, 8: Alice has no move, and hence she loses immediately.
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int n=fs.nextInt();
int[] board=fs.readArray(n);
Space[] spaces=new Space[n];
for (int i=0; i<n; i++) spaces[i]=new Space(board[i], i);
Arrays.sort(spaces);
boolean[] losingSpaces=new boolean[n];
for (int i=n-1; i>=0; i--) {
Space cur=spaces[i];
boolean canHitLose=false;
for (int dx=0; dx<=n; dx+=spaces[i].value) {
int newPos=cur.pos+dx;
if (newPos<0||newPos>=n) continue;
if (board[newPos]>cur.value && losingSpaces[newPos]) {
canHitLose=true;
}
}
for (int dx=0; dx<=n; dx+=spaces[i].value) {
int newPos=cur.pos-dx;
if (newPos<0||newPos>=n) continue;
if (board[newPos]>cur.value && losingSpaces[newPos]) {
canHitLose=true;
}
}
losingSpaces[cur.pos]=!canHitLose;
}
for (int i=0; i<n; i++) {
System.out.print(losingSpaces[i]?"B":"A");
}
System.out.println();
}
static class Space implements Comparable<Space>{
int value, pos;
public Space(int value, int pos) {
this.value=value;
this.pos=pos;
}
public int compareTo(Space o) {
return Integer.compare(value, o.value);
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) {
a[i]=nextInt();
}
return a;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.
During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
Input
The first line contains a single integer n (2 ≤ n ≤ 100) — the number of stops Arkady saw.
The next n lines describe the stops. Each of them starts with a single integer r (1 ≤ r ≤ 100) — the number of tram lines that stop there. r distinct integers follow, each one between 1 and 100, inclusive, — the line numbers. They can be in arbitrary order.
It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
Output
Print all tram lines that Arkady could be in, in arbitrary order.
Examples
Input
3
3 1 4 6
2 1 4
5 10 5 6 4 1
Output
1 4
Input
5
1 1
10 10 9 8 7 100 5 4 3 99 1
5 1 2 3 4 5
5 4 1 3 2 5
4 10 1 5 3
Output
1
Note
Consider the first example. Arkady woke up three times. The first time he saw a stop with lines 1, 4, 6. The second time he saw a stop with lines 1, 4. The third time he saw a stop with lines 10, 5, 6, 4 and 1. He can be in a tram of one of two lines: 1 or 4.
|
import java.util.*;
public class determine_line{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
ArrayList<Integer> ans = new ArrayList<Integer>();
ArrayList<ArrayList<Integer> > list = new ArrayList<ArrayList<Integer> >();
for(int i = 0; i < n; ++i){
ArrayList<Integer> li = new ArrayList<>();
int t = s.nextInt();
for(int j = 0; j < t; ++j){
li.add(s.nextInt());
}
list.add(li);
}
for(int i = 0; i < list.get(0).size(); ++i){
boolean pos = true;
for(int j = 1; j < n; ++j){
if(!list.get(j).contains(list.get(0).get(i))){
pos = false;
break;
}
}
if(pos){
System.out.print(list.get(0).get(i) + " ");
}
}
// System.out.println(ans);
}
}
|
You have a set of n weights. You know that their masses are a_1, a_2, ..., a_n grams, but you don't know which of them has which mass. You can't distinguish the weights.
However, your friend does know the mass of each weight. You can ask your friend to give you exactly k weights with the total mass m (both parameters k and m are chosen by you), and your friend will point to any valid subset of weights, if it is possible.
You are allowed to make this query only once. Find the maximum possible number of weights you can reveal after this query.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of weights.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100) — the masses of the weights.
Output
Print the maximum number of weights you can learn the masses for after making a single query.
Examples
Input
4
1 4 2 2
Output
2
Input
6
1 2 4 4 4 9
Output
2
Note
In the first example we can ask for a subset of two weights with total mass being equal to 4, and the only option is to get \{2, 2\}.
Another way to obtain the same result is to ask for a subset of two weights with the total mass of 5 and get \{1, 4\}. It is easy to see that the two remaining weights have mass of 2 grams each.
In the second example we can ask for a subset of two weights with total mass being 8, and the only answer is \{4, 4\}. We can prove it is not possible to learn masses for three weights in one query, but we won't put the proof here.
|
import java.io.*;
import java.util.*;
public class Main {
private void solve() throws Exception {
n = nextInt();
HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++) {
int a = nextInt();
countMap.put(a, countMap.getOrDefault(a, 0)+1);
}
a = countMap.keySet().toArray(new Integer[0]);
int m = a.length;
count = new int[m];
int max = 0;
for(int i = 0; i < m; i++) {
count[i] = countMap.get(a[i]);
max = Math.max(max, a[i]*count[i]);
}
if(m <= 2) {
out.println(n);
return;
}
memo = new Integer[m][n][max+1];
int res = 0;
for(int i = 0; i < m; i++) {
for(int t = 0; t <= count[i]; t++) {
if(doit(m-1,t, t*a[i]) == 1) res = Math.max(res, t);
}
}
out.println(res);
}
int n;
Integer[] a;
int[] count;
Integer[][][] memo;
int doit(int i, int k, int m) {
if(i < 0 && k == 0 && m == 0) return 1;
else if(i < 0) return 0;
else if(m < 0) return 0;
else if(k < 0) return 0;
else if(memo[i][k][m] == null) {
int res = 0;
for(int t = 0; t <= count[i] && t*a[i] <= m; t++) {
res += doit(i-1,k-t,m-t*a[i]);
if(res > 1) {
res = 2;
break;
}
}
memo[i][k][m] = res;
}
return memo[i][k][m];
}
public static void main(String[] args) {
new Main().run();
// new Thread(null, new Runnable() {
// public void run() {
// new Main().run();
// }
// }, "1", 1 << 27).start();
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tokenizer;
public void run() {
try {
long start = System.nanoTime();
in = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
System.err.println((System.nanoTime()-start)/1E9);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
/* try {
in = new BufferedReader(new FileReader("B-large-practice (1).in"));
tokenizer = null;
out = new PrintWriter(new File("output.txt"));
long start = System.nanoTime();
solve();
in.close();
out.close();
System.err.println((System.nanoTime()-start)/1E9);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}*/
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextLine() throws IOException {
return new String(in.readLine());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
}
|
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with vertices at integer points.
In order to draw a segment, Sofia proceeds as follows. If she wants to draw a vertical segment with the coordinates of the ends (x, y) and (x, y+1). Then Sofia looks if there is already a drawn segment with the coordinates of the ends (x', y) and (x', y+1) for some x'. If such a segment exists, then Sofia quickly draws a new segment, using the old one as a guideline. If there is no such segment, then Sofia has to take a ruler and measure a new segment for a long time. Same thing happens when Sofia wants to draw a horizontal segment, but only now she checks for the existence of a segment with the same coordinates x, x+1 and the differing coordinate y.
For example, if Sofia needs to draw one square, she will have to draw two segments using a ruler:
<image>
After that, she can draw the remaining two segments, using the first two as a guide:
<image>
If Sofia needs to draw two squares, she will have to draw three segments using a ruler:
<image>
After that, she can draw the remaining four segments, using the first three as a guide:
<image>
Sofia is in a hurry, so she wants to minimize the number of segments that she will have to draw with a ruler without a guide. Help her find this minimum number.
Input
The only line of input contains a single integer n (1 ≤ n ≤ 10^{9}), the number of squares that Sofia wants to draw.
Output
Print single integer, the minimum number of segments that Sofia will have to draw with a ruler without a guide in order to draw n squares in the manner described above.
Examples
Input
1
Output
2
Input
2
Output
3
Input
4
Output
4
|
#include <bits/stdc++.h>
using namespace std;
int n, ans = 1e9 + 5;
int main(void) {
cin >> n;
for (int i = 1; i * i <= n; i++) {
int j = (n % i == 0 ? n / i : n / i + 1);
ans = ((ans) < (i + j) ? (ans) : (i + j));
}
cout << ans << endl;
return 0;
}
|
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 ≥ x
* a1 + a2 + ... + an ≤ y
Input
The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106).
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11
|
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, x, y, i, ans;
while (cin >> n >> x >> y) {
if (y < n) {
cout << -1 << endl;
continue;
}
if (y - n + 1 > 1000000)
ans = 1000000;
else
ans = y - n + 1;
if ((n - 1) + ans * ans >= x) {
for (i = 1; i < n; i++) cout << 1 << endl;
cout << y - n + 1 << endl;
} else
cout << -1 << endl;
}
}
|
You are given a rooted tree with n nodes, labeled from 1 to n. The tree is rooted at node 1. The parent of the i-th node is p_i. A leaf is node with no children. For a given set of leaves L, let f(L) denote the smallest connected subgraph that contains all leaves L.
You would like to partition the leaves such that for any two different sets x, y of the partition, f(x) and f(y) are disjoint.
Count the number of ways to partition the leaves, modulo 998244353. Two ways are different if there are two leaves such that they are in the same set in one way but in different sets in the other.
Input
The first line contains an integer n (2 ≤ n ≤ 200 000) — the number of nodes in the tree.
The next line contains n-1 integers p_2, p_3, …, p_n (1 ≤ p_i < i).
Output
Print a single integer, the number of ways to partition the leaves, modulo 998244353.
Examples
Input
5
1 1 1 1
Output
12
Input
10
1 2 3 4 5 6 7 8 9
Output
1
Note
In the first example, the leaf nodes are 2,3,4,5. The ways to partition the leaves are in the following image <image>
In the second example, the only leaf is node 10 so there is only one partition. Note that node 1 is not a leaf.
|
#include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
vector<int> v[200010];
int d[200010], d1[200010];
int rid_put(int a, int b) {
int sol = 1;
for (long long i = 1; i <= b; i <<= 1) {
if (b & i) sol = (1LL * sol * a) % mod;
a = (1LL * a * a) % mod;
}
return sol;
}
void dfs(int nod) {
int p = 1, p1 = 1;
for (int i = 0; i < v[nod].size(); i++) {
int vec = v[nod][i];
dfs(vec);
p = (1LL * p * d[vec]) % mod;
p1 = (1LL * p1 * ((d[vec] + d1[vec]) % mod)) % mod;
}
int s = 0;
for (int i = 0; i < v[nod].size(); i++) {
int vec = v[nod][i];
int a = (1LL * p * rid_put(d[vec], mod - 2)) % mod;
a = (1LL * a * d1[vec]) % mod;
s = (s + a) % mod;
}
if (v[nod].size() == 0) {
d[nod] = d1[nod] = 1;
return;
}
d[nod] = (p1 - s + mod) % mod;
d1[nod] = (p1 - p + mod) % mod;
}
int main() {
int n, x;
scanf("%d", &n);
for (int i = 2; i <= n; i++) {
scanf("%d", &x);
v[x].push_back(i);
}
dfs(1);
printf("%d", d[1]);
return 0;
}
|
You are given an array a_1, a_2, ..., a_n. All a_i are pairwise distinct.
Let's define function f(l, r) as follows:
* let's define array b_1, b_2, ..., b_{r - l + 1}, where b_i = a_{l - 1 + i};
* sort array b in increasing order;
* result of the function f(l, r) is ∑_{i = 1}^{r - l + 1}{b_i ⋅ i}.
Calculate \left(∑_{1 ≤ l ≤ r ≤ n}{f(l, r)}\right) mod (10^9+7), i.e. total sum of f for all subsegments of a modulo 10^9+7.
Input
The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of array a.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9, a_i ≠ a_j for i ≠ j) — array a.
Output
Print one integer — the total sum of f for all subsegments of a modulo 10^9+7
Examples
Input
4
5 2 4 7
Output
167
Input
3
123456789 214365879 987654321
Output
582491518
Note
Description of the first example:
* f(1, 1) = 5 ⋅ 1 = 5;
* f(1, 2) = 2 ⋅ 1 + 5 ⋅ 2 = 12;
* f(1, 3) = 2 ⋅ 1 + 4 ⋅ 2 + 5 ⋅ 3 = 25;
* f(1, 4) = 2 ⋅ 1 + 4 ⋅ 2 + 5 ⋅ 3 + 7 ⋅ 4 = 53;
* f(2, 2) = 2 ⋅ 1 = 2;
* f(2, 3) = 2 ⋅ 1 + 4 ⋅ 2 = 10;
* f(2, 4) = 2 ⋅ 1 + 4 ⋅ 2 + 7 ⋅ 3 = 31;
* f(3, 3) = 4 ⋅ 1 = 4;
* f(3, 4) = 4 ⋅ 1 + 7 ⋅ 2 = 18;
* f(4, 4) = 7 ⋅ 1 = 7;
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
const ld pi = acos(0) * 2;
template <typename T>
inline void read(T &x) {
char c;
bool nega = 0;
while ((!isdigit(c = getchar())) && (c != '-'))
;
if (c == '-') {
nega = 1;
c = getchar();
}
x = c - 48;
while (isdigit(c = getchar())) x = x * 10 + c - 48;
if (nega) x = -x;
}
template <typename T>
inline void writep(T x) {
if (x > 9) writep(x / 10);
putchar(x % 10 + 48);
}
template <typename T>
inline void write(T x) {
if (x < 0) {
putchar('-');
x = -x;
}
writep(x);
}
template <typename T>
inline void writeln(T x) {
write(x);
putchar('\n');
}
const ll base = 1000000007;
int n;
ll x[500002];
ll add(ll a, ll b) {
a += b;
while (a >= base) a -= base;
return a;
}
class segment_tree {
public:
using pointer = segment_tree *;
int l, r, m;
pointer left, right;
ll a, b;
segment_tree(int l, int r) {
this->l = l;
this->r = r;
m = (l + r) / 2;
if (l != r) {
left = new segment_tree(l, m);
right = new segment_tree(m + 1, r);
a = b = 0;
} else {
a = b = 0;
}
}
void down() {
left->a = add(left->a, a);
left->b = add(left->b, b);
right->a = add(right->a, a);
right->b = add(right->b, b);
a = b = 0;
}
pair<ll, ll> get(int u) {
if (l == r)
return make_pair(a, b);
else {
down();
if (m >= u)
return left->get(u);
else
return right->get(u);
}
}
void update(int u, int v, ll aa, ll bb) {
if (l > v || r < u) return;
if (u <= l && v >= r) {
a = add(a, aa);
b = add(b, bb);
} else {
down();
left->update(u, v, aa, bb);
right->update(u, v, aa, bb);
}
}
};
segment_tree::pointer tree;
vector<int> order;
int main() {
read(n);
x[0] = 1e18;
for (int i = (1); i <= (n); i++) read(x[i]);
tree = new segment_tree(1, n);
for (int i = (1); i <= (n); i++) order.push_back(i);
sort(order.begin(), order.end(), [](int a, int b) { return x[a] > x[b]; });
for (int u : order) {
auto res = tree->get(u);
tree->update(u, u, base - res.first, base - res.second);
tree->update(u, n, base - u, ((ll)(n + 1)) * u);
if (u > 1) tree->update(1, u - 1, n - u + 1, 0);
}
ll ans = 0;
for (int i = (1); i <= (n); i++) {
auto res = tree->get(i);
ll cnt = (res.first * i + res.second) % base;
ans = (ans + cnt * x[i]) % base;
}
if (ans < 0) ans += base;
writeln(ans);
}
|
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks.
Determine whether the Cossack can reward all participants, giving each of them at least one pen and at least one notebook.
Input
The first line contains three integers n, m, and k (1 ≤ n, m, k ≤ 100) — the number of participants, the number of pens, and the number of notebooks respectively.
Output
Print "Yes" if it possible to reward all the participants. Otherwise, print "No".
You can print each letter in any case (upper or lower).
Examples
Input
5 8 6
Output
Yes
Input
3 9 3
Output
Yes
Input
8 5 20
Output
No
Note
In the first example, there are 5 participants. The Cossack has 8 pens and 6 notebooks. Therefore, he has enough pens and notebooks.
In the second example, there are 3 participants. The Cossack has 9 pens and 3 notebooks. He has more than enough pens but only the minimum needed number of notebooks.
In the third example, there are 8 participants but only 5 pens. Since the Cossack does not have enough pens, the answer is "No".
|
def solve(n, m, k):
if min(m,k) >= n:
return "Yes"
else:
return "No"
def main():
n, m, k = list(map(int, input().split()))
print(solve(n, m, k))
if __name__ == '__main__':
main()
|
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied:
For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more than by 1.
For example, choose n = 3. On the left you can see an example of a valid arrangement: 1 + 4 + 5 = 10, 4 + 5 + 2 = 11, 5 + 2 + 3 = 10, 2 + 3 + 6 = 11, 3 + 6 + 1 = 10, 6 + 1 + 4 = 11, any two numbers differ by at most 1. On the right you can see an invalid arrangement: for example, 5 + 1 + 6 = 12, and 3 + 2 + 4 = 9, 9 and 12 differ more than by 1.
<image>
Input
The first and the only line contain one integer n (1 ≤ n ≤ 10^5).
Output
If there is no solution, output "NO" in the first line.
If there is a solution, output "YES" in the first line. In the second line output 2n numbers — numbers from 1 to 2n in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.
Examples
Input
3
Output
YES
1 4 5 2 3 6
Input
4
Output
NO
Note
Example from the statement is shown for the first example.
It can be proved that there is no solution in the second example.
|
n = int(input())
if n%2 == 0:
print("NO")
exit(0)
arr = []
for i in range(1, n+1):
if i%2 == 1:
arr.append(2*i-1)
else:
arr.append(2*i)
for i in range(n):
if arr[i] % 2 == 1:
arr.append(arr[i]+1)
else:
arr.append(arr[i]-1)
print("YES")
print(*arr)
|
Alice and Bob play a game. Initially they have a string s_1, s_2, ..., s_n, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select a substing of length a, and Bob must select a substring of length b. It is guaranteed that a > b.
For example, if s = ...X.. and a = 3, b = 2, then after Alice's move string can turn only into XXXX... And if it's Bob's turn and the string s = ...X.., then after Bob's move the string can turn into XX.X.., .XXX.. or ...XXX.
Whoever is unable to make a move, loses. You have to determine who wins if they both play optimally.
You have to answer q independent queries.
Input
The first line contains one integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
The first line of each query contains two integers a and b (1 ≤ b < a ≤ 3 ⋅ 10^5).
The second line of each query contains the string s (1 ≤ |s| ≤ 3 ⋅ 10^5), consisting of only characters . and X.
It is guaranteed that sum of all |s| over all queries not exceed 3 ⋅ 10^5.
Output
For each test case print YES if Alice can win and NO otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
Example
Input
3
3 2
XX......XX...X
4 2
X...X.X..X
5 3
.......X..X
Output
YES
NO
YES
Note
In the first query Alice can select substring s_3 ... s_5. After that s turns into XXXXX...XX...X. After that, no matter what move Bob makes, Alice can make the move (this will be her second move), but Bob can't make his second move.
In the second query Alice can not win because she cannot even make one move.
In the third query Alice can choose substring s_2 ... s_6. After that s turns into .XXXXX.X..X, and Bob can't make a move after that.
|
#include <bits/stdc++.h>
using namespace std;
bool solve(int a, int b, char str[]) {
vector<int> arr;
int curr = 0;
for (int i = 0; str[i] != 0; i++) {
if (str[i] == '.')
curr++;
else if (str[i] == 'X' && curr != 0) {
arr.push_back(curr);
curr = 0;
}
}
if (curr != 0) arr.push_back(curr);
int crit = 0, non_crit = 0, crit_len;
for (int i = 0; i < arr.size(); i++) {
int s = arr[i];
if ((s >= b && s < a) || ((s - a) % 2 == 0 && (s - a) / 2 >= 2 * b) ||
((s - a) % 2 == 1 && (s - a + 1) / 2 >= 2 * b)) {
return false;
}
if (s >= 2 * b) {
crit++;
crit_len = s;
} else if (s >= a)
non_crit++;
}
if (crit > 1) {
return false;
}
if (crit == 0) {
return (non_crit % 2 == 1);
}
for (int i = 0; i <= crit_len - a; i++) {
int j = crit_len - a - i;
if (!(i >= b && i < a) && !(j >= b && j < a) && !(i >= 2 * b) &&
!(j >= 2 * b) && ((non_crit + (i >= a) + (j >= a)) % 2 == 0))
return true;
}
return false;
}
int main() {
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int a, b;
char str[300005];
cin >> a >> b >> str;
cout << (solve(a, b, str) ? "YES" : "NO") << endl;
}
}
|
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.
The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point (0, 0). While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to OX or OY axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.
Alexey wants to make a polyline in such a way that its end is as far as possible from (0, 0). Please help him to grow the tree this way.
Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000) — the number of sticks Alexey got as a present.
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10 000) — the lengths of the sticks.
Output
Print one integer — the square of the largest possible distance from (0, 0) to the tree end.
Examples
Input
3
1 2 3
Output
26
Input
4
1 1 2 2
Output
20
Note
The following pictures show optimal trees for example tests. The squared distance in the first example equals 5 ⋅ 5 + 1 ⋅ 1 = 26, and in the second example 4 ⋅ 4 + 2 ⋅ 2 = 20.
<image> <image>
|
#include <bits/stdc++.h>
using namespace std;
int a[100001];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
sort(a, a + n);
unsigned long long sum1 = 0, ans, sum2 = 0;
for (int i = n - 1; i >= (n / 2); i--) {
sum1 += a[i];
}
for (int i = 0; i < (n / 2); i++) {
sum2 += a[i];
}
ans = sum1 * sum1 + sum2 * sum2;
printf("%llu", ans);
return 0;
}
|
Let G be a simple graph. Let W be a non-empty subset of vertices. Then W is almost-k-uniform if for each pair of distinct vertices u,v ∈ W the distance between u and v is either k or k+1.
You are given a tree on n vertices. For each i between 1 and n, find the maximum size of an almost-i-uniform set.
Input
The first line contains a single integer n (2 ≤ n ≤ 5 ⋅ 10^5) – the number of vertices of the tree.
Then n-1 lines follows, the i-th of which consisting of two space separated integers u_i, v_i (1 ≤ u_i, v_i ≤ n) meaning that there is an edge between vertices u_i and v_i.
It is guaranteed that the given graph is tree.
Output
Output a single line containing n space separated integers a_i, where a_i is the maximum size of an almost-i-uniform set.
Examples
Input
5
1 2
1 3
1 4
4 5
Output
4 3 2 1 1
Input
6
1 2
1 3
1 4
4 5
4 6
Output
4 4 2 1 1 1
Note
Consider the first example.
* The only maximum almost-1-uniform set is \{1, 2, 3, 4\}.
* One of the maximum almost-2-uniform sets is or \{2, 3, 5\}, another one is \{2, 3, 4\}.
* A maximum almost-3-uniform set is any pair of vertices on distance 3.
* Any single vertex is an almost-k-uniform set for k ≥ 1.
In the second sample there is an almost-2-uniform set of size 4, and that is \{2, 3, 5, 6\}.
|
#include <bits/stdc++.h>
using namespace std;
const long long N = 5e5 + 9;
vector<long long> adj[N], vec[N];
long long h[N], up[N], ans[N];
pair<long long, long long> edge[N];
vector<pair<long long, long long> > a[N], b;
void DFS1(long long u, long long par) {
h[u] = 1;
for (long long v : adj[u])
if (v != par) {
DFS1(v, u);
h[u] = max(h[u], h[v] + 1);
vec[u].push_back(h[v]);
}
}
void DFS2(long long u, long long par) {
multiset<long long> s;
for (long long v : adj[u])
if (v != par) s.insert(-h[v]);
for (long long v : adj[u])
if (v != par) {
s.erase(s.find(-h[v]));
up[v] = up[u] + 1;
if (!s.empty()) up[v] = max(up[v], -(*s.begin()) + 1);
vec[v].push_back(up[v]);
s.insert(-h[v]);
}
for (long long v : adj[u])
if (v != par) DFS2(v, u);
}
void DFS3(long long u, long long par) {
for (long long v : adj[u])
if (v != par) {
long long iu = 0, iv = 0;
while (iu < a[u].size() && iv < a[v].size()) {
if (a[u][iu].first < a[v][iv].first)
b.push_back(a[u][iu++]);
else if (a[u][iu].first > a[v][iv].first)
b.push_back(a[v][iv++]);
else if (a[u][iu].first == a[v][iv].first)
b.push_back({a[v][iv].first, a[v][iv++].second + a[u][iu++].second});
}
while (iv < a[v].size()) b.push_back(a[v][iv++]);
while (iu < a[u].size()) b.push_back(a[u][iu++]);
for (long long i = 0; i < b.size(); i++) {
if (b[i].first == up[v]) b[i].second--;
if (b[i].first == h[v]) b[i].second--;
}
long long num = 0;
while (b.size()) {
ans[b.back().first * 2] =
max(ans[b.back().first * 2], (num += b.back().second));
b.pop_back();
}
DFS3(v, u);
}
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
long long n;
cin >> n;
for (long long i = 1; i < n; i++) {
long long u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
fill(ans, ans + N, 1);
DFS1(1, 0);
DFS2(1, 0);
for (long long i = 1; i <= n; i++) {
sort(vec[i].begin(), vec[i].end());
for (long long j = 0; j < vec[i].size() - 1; j++)
if (vec[i][j] != vec[i][j + 1])
ans[vec[i][j] * 2 + 1] =
max(ans[vec[i][j] * 2 + 1], (long long)vec[i].size() - j);
for (long long j = 0; j < vec[i].size(); j++)
ans[vec[i][j] * 2 - 1] =
max(ans[vec[i][j] * 2 - 1], (long long)vec[i].size() - j),
ans[vec[i][j] * 2] = max(
ans[vec[i][j] * 2], (long long)vec[i].size() - j);
for (long long j = 0, k = 0; max(j, k) < vec[i].size(); j = k) {
while (k < vec[i].size() && vec[i][j] == vec[i][k]) k++;
a[i].push_back({vec[i][j], k - j});
}
}
DFS3(1, 0);
for (long long i = n; i > 0; i--) ans[i] = max(ans[i], ans[i + 2]);
for (long long i = 1; i <= n; i++)
ans[1] = max(ans[1], (long long)adj[i].size() + 1);
for (long long i = 1; i <= n; i++) cout << ans[i] << " ";
return 0;
}
|
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results.
Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days optimizing the program, he will make the program run in \left⌈ (d)/(x + 1) \right⌉ days (\left⌈ a \right⌉ is the ceiling function: \left⌈ 2.4 \right⌉ = 3, \left⌈ 2 \right⌉ = 2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x + \left⌈ (d)/(x + 1) \right⌉.
Will Adilbek be able to provide the generated results in no more than n days?
Input
The first line contains a single integer T (1 ≤ T ≤ 50) — the number of test cases.
The next T lines contain test cases – one per line. Each line contains two integers n and d (1 ≤ n ≤ 10^9, 1 ≤ d ≤ 10^9) — the number of days before the deadline and the number of days the program runs.
Output
Print T answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in n days or NO (case insensitive) otherwise.
Example
Input
3
1 1
4 5
5 11
Output
YES
YES
NO
Note
In the first test case, Adilbek decides not to optimize the program at all, since d ≤ n.
In the second test case, Adilbek can spend 1 day optimizing the program and it will run \left⌈ 5/2 \right⌉ = 3 days. In total, he will spend 4 days and will fit in the limit.
In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 2 days, it'll still work \left⌈ (11)/(2+1) \right⌉ = 4 days.
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
double n, d;
cin >> n >> d;
if (n >= d) {
cout << "YES" << endl;
continue;
}
double x = 1, f = 0;
double y;
for (int i = 0; i < d; i++) {
y = double(d / (x + 1));
y = ceil(y);
if ((x + y) <= n) {
cout << "YES" << endl;
f = 1;
break;
}
x++;
if (x >= n) {
break;
}
}
if (f == 1) {
continue;
} else
cout << "NO" << endl;
}
}
|
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
|
value = input()
print(int(value, 16)%2)
|
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
Each test case is given in two lines.
The first line contains two integers a_1 and b_1 (1 ≤ a_1, b_1 ≤ 100) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
The second line contains two integers a_2 and b_2 (1 ≤ a_2, b_2 ≤ 100) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
Output
Print t answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).
Example
Input
3
2 3
3 1
3 2
1 3
3 3
1 3
Output
Yes
Yes
No
|
import java.util.*;
import java.math.*;
public class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int a1 = sc.nextInt();
int b1 = sc.nextInt();
int a2 = sc.nextInt();
int b2 = sc.nextInt();
if(Math.max(a1, b1)==Math.max(a2, b2) &&
(Math.min(a1, b1) + Math.min(a2, b2)) == Math.max(a1, b1)) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
}
|
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!
You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k.
Let's define:
* A_{i,j} as the integer in the i-th row and the j-th column.
* R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n).
* C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n).
* In other words, R_i are row sums and C_j are column sums of the grid A.
* For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X).
Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases.
For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2).
It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5.
Output
For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied.
After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}.
If there are multiple answers you can print any.
Example
Input
4
2 2
3 8
1 0
4 16
Output
0
10
01
2
111
111
101
0
0
0
1111
1111
1111
1111
Note
In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A).
In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A).
|
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#######################################
t=int(input())
for i in range(t):
n,k=map(int,input().split())
a=k//n
b=k%n
l=[[0 for j in range(n)] for p in range(n)]
x=0
c=n-b
if k!=0:
for j in range(n):
if c>0:
for p in range(x,x+a):
l[j][p%n]=1
c-=1
else:
for p in range(x,x+a+1):
l[j][p%n]=1
x+=1
x%=n
if k%n:
ans=2
else:
ans=0
else:
ans=0
print(ans)
for j in l:
print(*j,sep='')
|
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
|
#! /usr/bin/python3
n, d, m = [int(inp) for inp in input().split()]
aArr = sorted([int(inp) for inp in input().split()], reverse = True)
i = sum([j > m for j in aArr])
aU = aArr[:i]
aL = aArr[i:]
aUS = aU
for i in range(1, len(aU)):
aUS[i] += aUS[i - 1]
aUS = [0] + aUS
aLS = aL
for i in range(1, len(aL)):
aLS[i] += aLS[i - 1]
aLS = [0] + aLS
fromU = min(1 + (n - 1)//(d + 1), len(aU))
maxFun = aUS[0] + aLS[-1]
for j in range(1, fromU + 1):
newFun = aUS[j] + aLS[min(max(0, n - 1 - (j - 1)*(d + 1)), len(aL))]
if newFun > maxFun:
maxFun = newFun
print(maxFun)
|
You are given four integers n, m, l and r.
Let's name a tuple (x_1, y_1, x_2, y_2) as good if:
1. 1 ≤ x_1 < x_2 ≤ n;
2. 1 ≤ y_2 < y_1 ≤ m;
3. x_1 ⋅ y_1 = x_2 ⋅ y_2;
4. l ≤ x_1 ⋅ y_1 ≤ r.
Find any good tuple for each x_1 from 1 to n inclusive.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5).
The second line contains two integers l and r (1 ≤ l ≤ r ≤ nm).
Output
For each x_1 from 1 to n inclusive:
* if there are no such four integers, print -1;
* otherwise, print four integers x_1, y_1, x_2 and y_2. If there are multiple answers, print any of them.
Examples
Input
8 20
91 100
Output
-1
-1
-1
-1
-1
6 16 8 12
-1
-1
Input
4 5
1 10
Output
1 2 2 1
2 3 3 2
-1
-1
Input
5 12
16 60
Output
-1
2 9 3 6
3 8 4 6
4 5 5 4
-1
|
#include <bits/stdc++.h>
constexpr int N = 2e5;
std::vector<int> divisors[N + 1];
int cnt[N + 1];
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n, m;
std::cin >> n >> m;
int64_t l, r;
std::cin >> l >> r;
--l;
for (int i = 1; i <= N; ++i)
for (int j = i; j <= N; j += i) divisors[j].push_back(i);
std::set<int> s;
for (int x1 = 1, L = m, R = m; x1 <= n; ++x1) {
int64_t ly = l / x1;
int64_t ry = std::min<int64_t>(m, r / x1);
if (ly >= ry) {
std::cout << -1 << "\n";
continue;
}
while (L > ly) {
for (auto c : divisors[L]) {
if (cnt[c] == 0) s.insert(c);
++cnt[c];
}
--L;
}
while (R > ry) {
for (auto c : divisors[R]) {
--cnt[c];
if (cnt[c] == 0) s.erase(c);
}
--R;
}
bool ok = false;
for (auto b : divisors[x1]) {
int a = x1 / b;
auto it = s.upper_bound(b);
if (it != s.end() && *it <= n / a) {
int c = *it;
int d = R / c;
std::cout << a * b << " " << c * d << " " << a * c << " " << b * d
<< "\n";
ok = true;
break;
}
}
if (!ok) std::cout << -1 << "\n";
}
return 0;
}
|
In this problem MEX of a certain array is the smallest positive integer not contained in this array.
Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today.
You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers.
An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself.
Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays!
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array.
Output
Print a single integer — the MEX of MEXes of all subarrays.
Examples
Input
3
1 3 2
Output
3
Input
5
1 4 3 1 2
Output
6
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5, S = 355;
int n, a[N], cnt[N], B, bel[N], cntb, L[N], R[N], mar[S][N];
vector<int> p[N];
pair<int, int> rg[N];
bool check(int l, int r, int mex) {
if (!mex) return true;
if (mex > n + 1) return false;
for (int i = 1; i < bel[mex]; i++)
if (mar[i][r] < l) return false;
for (int i = L[bel[mex]], x; i <= mex; i++) {
x = upper_bound(p[i].begin(), p[i].end(), r) - p[i].begin() - 1;
if (p[i][x] < l) return false;
}
return true;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]), p[a[i]].push_back(i);
for (int i = 1; i <= n; i++) p[i].push_back(0), p[i].push_back(n + 1);
for (int i = 1; i <= n; i++) sort(p[i].begin(), p[i].end());
B = sqrt(n);
for (int i = 1; i <= n + 1; i++) bel[i] = (i - 1) / B + 1;
cntb = bel[n];
for (int i = 1; i <= cntb; i++) L[i] = (i - 1) * B + 1, R[i] = min(i * B, n);
for (int k = 1, sl, sr; k <= cntb; k++) {
sl = L[k];
sr = R[k];
for (int j = sl; j <= sr; j++) cnt[j] = 0;
int now = 0;
for (int j = 1, pos = 1; j <= n; j++) {
if (a[j] >= sl && a[j] <= sr) {
if (!cnt[a[j]]) now++;
cnt[a[j]]++;
}
while (now == sr - sl + 1 &&
(a[pos] < sl || a[pos] > sr || cnt[a[pos]] > 1)) {
if (a[pos] >= sl && a[pos] <= sr) cnt[a[pos]]--;
pos++;
}
if (now == sr - sl + 1)
mar[k][j] = pos;
else
mar[k][j] = -1;
}
}
for (int mex = 1, lst, len; mex <= n + 1; mex++) {
len = lst = 0;
for (auto x : p[mex]) {
if (!x) {
lst = x;
continue;
}
if (lst + 1 < x) rg[++len] = pair<int, int>(lst + 1, x - 1);
lst = x;
}
if (lst + 1 <= n) rg[++len] = pair<int, int>(lst + 1, n);
bool fl = false;
for (int i = 1; i <= len; i++)
if (check(rg[i].first, rg[i].second, mex - 1)) {
fl = true;
break;
}
if (!fl) {
printf("%d\n", mex);
return 0;
}
}
printf("%d\n", n + 2);
return 0;
}
|
Ron is a happy owner of a permutation a of length n.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
<image>
Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data.
As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged.
You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100).
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation.
The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places.
It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5).
Output
For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}.
Example
Input
4
4 3
4 3 2 1
1 0.3
3 1
4 0.6
5 3
4 2 1 3 5
3 0.8
4 0.6
5 0.3
6 5
1 3 2 4 5 6
4 0.9
5 0.3
2 0.4
6 0.7
3 0.5
4 2
1 2 3 4
2 0.5
4 0.1
Output
0.600000
0.720000
0.989500
1.000000
Note
Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment.
|
from sys import stdin
from functools import reduce
from operator import mul
rints = lambda: [int(x) for x in stdin.readline().split()]
rfloats = lambda: [float(x) for x in stdin.readline().split()]
rfloat_2d = lambda n: [rfloats() for _ in range(n)]
out = []
for _ in range(int(input())):
n, m = rints()
a, qur, mem = rints(), rfloat_2d(m), [0] * n
mi, ma, all = n + 1, 0, []
if sorted(a) == a:
out.append('1')
continue
for i in range(n - 1, -1, -1):
mem[i] = 1
if a[i] != i + 1:
break
for r, p in qur:
if mem[int(r) - 1]:
all.append(1 - p)
try:
out.append('%.6f' % (1 - reduce(mul, all)))
except:
out.append('0.000000')
print('\n'.join(out))
|
You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median.
A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1.
Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
Output
Output one integer m — the maximum median you can get.
Examples
Input
5 3
1 2 3 2 1
Output
2
Input
4 2
1 2 3 4
Output
3
Note
In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too.
In the second example median([3..4]) = 3.
|
import java.io.*;
import java.util.*;
public class CF {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
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;
}
}
public static void main(String[] args) {
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {
System.err.println("Error");
}
FastReader fs = new FastReader();
int t = 1;
int ans = 0;
while(t-- > 0) {
int n = fs.nextInt();
int k = fs.nextInt();
int[] a = new int[n+2];
for(int i=1; i<=n; i++) {
a[i] = fs.nextInt();
}
int l = 1, h = n;
while(l <= h) {
int m = (l+h)/2;
int f = 0;
int[] temp = new int[n+2];
int[] prefix = new int[n+2];
for(int i=1; i<n+1; i++) {
if(a[i] >= m) temp[i] = 1;
else temp[i] = -1;
}
for(int i=1; i<=n; i++) {
prefix[i] += prefix[i-1] + temp[i];
}
int min = Integer.MAX_VALUE;
for(int i=k; i<=n; i++) {
min = Math.min(min, prefix[i-k]);
if(prefix[i] - min > 0) {
f = 1;
}
}
if(f == 1) {
ans = m;
l = m+1;
} else h = m-1;
}
System.out.println(ans);
}
}
}
|
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000).
Output
On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3.
In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6.
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vii;
typedef vector<vi> vvi;
typedef vector<pll> vll;
typedef vector<vl> vvl;
#define fori(i, n) for (int i = 0; i < n; i++)
#define ford(i, n) for (int i = n - 1; i >= 0; i--)
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define repd(i, a, b) for (int i = a; i >= b; i--)
#define trav(x, a) for (auto &x : a)
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define eb emplace_back
#define endl '\n'
#define sz(a) (int)(a).size()
#define fi first
#define se second
clock_t time_p = clock();
void time_taken()
{
time_p = clock() - time_p;
cerr << "Time Taken : " << (float)(time_p) / CLOCKS_PER_SEC << "\n";
}
const ll mod = 1e9 + 7;
const ll INF = 1e18;
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr);
int n, d;
cin >> n >> d;
vi a(n);
fori(i, n) cin >> a[i];
vector<vector<ld>> dp(n + 1, vector<ld>(10, -1));
vvi prv(n + 1, vi(10));
vvi taken(n + 1, vi(10));
dp[0][1] = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 10; j++)
{
if (dp[i][j] == -1)
continue;
int to = (j * a[i]) % 10;
ld maybe = dp[i][j] + log2l(a[i]);
if (maybe > dp[i + 1][to])
{
dp[i + 1][to] = maybe;
taken[i + 1][to] = 1;
prv[i + 1][to] = j;
}
to = j;
maybe = dp[i][j];
if (maybe > dp[i + 1][to])
{
dp[i + 1][to] = maybe;
taken[i + 1][to] = 0;
prv[i + 1][to] = j;
}
}
}
if (dp[n][d] == -1)
{
cout << "-1" << endl;
return 0;
}
int i = n, j = d;
vi ans;
while (i)
{
if (taken[i][j])
{
ans.pb(a[i - 1]);
}
j = prv[i][j];
i--;
}
if(sz(ans) == 0){
cout << -1 << endl;
return 0;
}
cout << sz(ans) << endl;
for (int x : ans)
{
cout << x << ' ';
}
cout << endl;
time_taken();
return 0;
}
|
Omkar and Akmar are playing a game on a circular board with n (2 ≤ n ≤ 10^6) cells. The cells are numbered from 1 to n so that for each i (1 ≤ i ≤ n-1) cell i is adjacent to cell i+1 and cell 1 is adjacent to cell n. Initially, each cell is empty.
Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter.
A player loses when it is their turn and there are no more valid moves.
Output the number of possible distinct games where both players play optimally modulo 10^9+7. Note that we only consider games where some player has lost and there are no more valid moves.
Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different.
A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move.
Input
The only line will contain an integer n (2 ≤ n ≤ 10^6) — the number of cells on the board.
Output
Output a single integer — the number of possible distinct games where both players play optimally modulo 10^9+7.
Examples
Input
2
Output
4
Input
69420
Output
629909355
Input
42069
Output
675837193
Note
For the first sample case, the first player has 4 possible moves. No matter what the first player plays, the second player only has 1 possible move, so there are 4 possible games.
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
const ll lp = 1e9+7;
const int msize = 1e6+7;
//! ll power
ll powmod(int a, int x){ //a^x
if (x == 0) return 1;
if (x % 2 == 0){
ll temp = powmod(a,x/2);
return (temp*temp) % lp;
}else{
ll temp = powmod(a,x/2);
return ((temp*temp) % lp * a) % lp;
}
}
ll lpinv(int a){ //inverse of a under the prime
return powmod(a,lp-2);
}
//! ll ncr offset
ll ncroffset(int n, int r, int n0, int r0, int prev){
ll ans = prev;
if (r == 0 || n == r) return 1;
//*numerator
if (n > n0){
for (int i=n0+1; i<=n; ++i){
ans = (ans*i) % lp;
}
}else if (n < n0){
for (int i=n0; i>n; --i){
ans = (ans*lpinv(i)) % lp;
}
}
//*denominator1
if (r > r0){
for (int i=r0+1; i<=r; ++i){
ans = (ans*lpinv(i)) % lp;
}
}else if (r < r0){
for (int i=r0; i>r; --i){
ans = (ans*i) % lp;
}
}
//*denominator2
r = n-r;
r0 = n0-r0;
if (r > r0){
for (int i=r0+1; i<=r; ++i){
ans = (ans*lpinv(i)) % lp;
}
}else if (r < r0){
for (int i=r0; i>r; --i){
ans = (ans*i) % lp;
}
}
return ans;
}
vector<ll> facarr(msize,0);
void facpre(){
facarr[0] = 1;
for (int i=1; i<msize; ++i){
facarr[i] = (facarr[i-1]*i) % lp;
}
return;
}
int m,n,k,cnt,idx,len,temp,test_cnt;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
facpre();
//cout << ncr(8,5) << endl;
//cout << fac(10) << endl;
//cout << ncroffset(8,5,7,6,7) << endl;
//cout << lpinv(2) << endl;
cin >> cnt;
int twocnt = cnt/2, onecnt = cnt % 2;
if ((twocnt + onecnt) % 2){
twocnt--;
onecnt+=2;
}
ll ans = 0;
int n0,r0,v0;
n0 = r0 = v0 = 1;
while(twocnt >= 0){
v0 = ncroffset(twocnt+onecnt, twocnt,n0,r0,v0);
n0 = twocnt+onecnt;
r0 = twocnt;
ll part = (v0*facarr[twocnt+onecnt]) % lp;
//cout << part << " " << twocnt << " " << onecnt << '\n';
ans = (ans+part) % lp;
twocnt-=2;
onecnt+=4;
}
twocnt = cnt/2-1; onecnt = cnt % 2;
if ((twocnt + onecnt) % 2 == 0){
twocnt--;
onecnt+=2;
}
n0 = r0 = v0 = 1;
while(twocnt >= 0){
v0 = ncroffset(twocnt+onecnt, twocnt,n0,r0,v0);
n0 = twocnt+onecnt;
r0 = twocnt;
ll part = (v0*facarr[twocnt+onecnt+1]) % lp;
//cout << part << " " << twocnt << " " << onecnt << '\n';
ans = (ans+part) % lp;
twocnt-=2;
onecnt+=4;
}
ans = (ans*2) % lp;
cout << ans << endl;
return 0;
}
|
The best programmers of Embezzland compete to develop a part of the project called "e-Government" — the system of automated statistic collecting and press analysis.
We know that any of the k citizens can become a member of the Embezzland government. The citizens' surnames are a1, a2, ..., ak. All surnames are different. Initially all k citizens from this list are members of the government. The system should support the following options:
* Include citizen ai to the government.
* Exclude citizen ai from the government.
* Given a newspaper article text, calculate how politicized it is. To do this, for every active government member the system counts the number of times his surname occurs in the text as a substring. All occurrences are taken into consideration, including the intersecting ones. The degree of politicization of a text is defined as the sum of these values for all active government members.
Implement this system.
Input
The first line contains space-separated integers n and k (1 ≤ n, k ≤ 105) — the number of queries to the system and the number of potential government members.
Next k lines contain the surnames a1, a2, ..., ak, one per line. All surnames are pairwise different.
Next n lines contain queries to the system, one per line. Each query consists of a character that determines an operation and the operation argument, written consecutively without a space.
Operation "include in the government" corresponds to the character "+", operation "exclude" corresponds to "-". An argument of those operations is an integer between 1 and k — the index of the citizen involved in the operation. Any citizen can be included and excluded from the government an arbitrary number of times in any order. Including in the government a citizen who is already there or excluding the citizen who isn't there changes nothing.
The operation "calculate politicization" corresponds to character "?". Its argument is a text.
All strings — surnames and texts — are non-empty sequences of lowercase Latin letters. The total length of all surnames doesn't exceed 106, the total length of all texts doesn't exceed 106.
Output
For any "calculate politicization" operation print on a separate line the degree of the politicization of the given text. Print nothing for other operations.
Examples
Input
7 3
a
aa
ab
?aaab
-2
?aaab
-3
?aaab
+2
?aabbaa
Output
6
4
3
6
|
#include <bits/stdc++.h>
using namespace std;
const int MaxN = 1000005;
struct node {
node* fail;
node* next[26];
int lo, hi;
vector<node*> link;
node() {
fail = NULL;
for (int i = 0; i < 26; i++) next[i] = NULL;
}
};
int T, n;
char text[MaxN];
node* root = new node();
queue<node*> Q;
int fenwick[10 * MaxN], gtime;
bool erased[MaxN];
node* ptr[MaxN];
void insert(char* patt, int index) {
node* current = root;
for (int j = 0; patt[j]; j++) {
if (current->next[patt[j] - 'a'] == NULL)
current->next[patt[j] - 'a'] = new node();
current = current->next[patt[j] - 'a'];
}
ptr[index] = current;
}
void ahoC() {
root->fail = root;
for (int i = 0; i < 26; i++)
if (root->next[i] != NULL) {
root->next[i]->fail = root;
Q.push(root->next[i]);
root->link.push_back(root->next[i]);
} else
root->next[i] = root;
while (!Q.empty()) {
node* state = Q.front();
Q.pop();
for (int i = 0; i < 26; i++)
if (state->next[i] != NULL) {
node* r = state->fail;
while (r->next[i] == NULL) r = r->fail;
state->next[i]->fail = r->next[i];
r->next[i]->link.push_back(state->next[i]);
Q.push(state->next[i]);
}
}
}
void dfs(node* u) {
u->lo = ++gtime;
for (int i = u->link.size() - 1; i >= 0; i--) dfs(u->link[i]);
u->hi = ++gtime;
}
void add(int k, int val) {
for (int i = k; i <= gtime; i += (i & -i)) fenwick[i] += val;
}
int query(node* u) {
int ret = 0;
for (int i = u->lo; i > 0; i -= (i & -i)) ret = ret + fenwick[i];
return ret;
}
void update(int index, int val) {
if (erased[index] && val == -1) return;
if (!erased[index] && val == +1) return;
add(ptr[index]->lo, val);
add(ptr[index]->hi, -val);
erased[index] = !erased[index];
}
int main() {
scanf("%d%d", &T, &n);
for (int i = 0; i < n; i++) {
scanf("%s", text);
insert(text, i);
}
ahoC();
dfs(root);
for (int i = 0; i < n; i++) {
erased[i] = true;
update(i, +1);
}
while (T--) {
scanf("%s", text);
if (text[0] == '+' || text[0] == '-') {
int index;
sscanf(text + 1, "%d", &index);
update(index - 1, (text[0] == '+') ? +1 : -1);
} else {
long long answer = 0;
node* current = root;
for (int i = 1; text[i]; i++) {
while (current->next[text[i] - 'a'] == NULL) current = current->fail;
current = current->next[text[i] - 'a'];
answer += query(current);
}
printf("%I64d\n", answer);
}
}
return 0;
}
|
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.
<image>
Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.
Input
The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Output
Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).
Examples
Input
1
Output
3
Input
2
Output
10
Note
The first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.
|
n=int(input())
e=10**9+7
print(1if n==0else(pow(2,n-1,e)+pow(2,n*2-1,e))%e)
# Made By Mostafa_Khaled
|
The Smart Beaver from ABBYY has come up with a new developing game for children. The Beaver thinks that this game will help children to understand programming better.
The main object of the game is finite rooted trees, each of their edges contains some lowercase English letter. Vertices on any tree are always numbered sequentially from 1 to m, where m is the number of vertices in the tree. Before describing the actual game, let's introduce some definitions.
We'll assume that the sequence of vertices with numbers v1, v2, ..., vk (k ≥ 1) is a forward path, if for any integer i from 1 to k - 1 vertex vi is a direct ancestor of vertex vi + 1. If we sequentially write out all letters from the the edges of the given path from v1 to vk, we get some string (k = 1 gives us an empty string). We'll say that such string corresponds to forward path v1, v2, ..., vk.
We'll assume that the sequence of tree vertices with numbers v1, v2, ..., vk (k ≥ 1) is a backward path if for any integer i from 1 to k - 1 vertex vi is the direct descendant of vertex vi + 1. If we sequentially write out all the letters from the edges of the given path from v1 to vk, we get some string (k = 1 gives us an empty string). We'll say that such string corresponds to backward path v1, v2, ..., vk.
Now let's describe the game that the Smart Beaver from ABBYY has come up with. The game uses two rooted trees, each of which initially consists of one vertex with number 1. The player is given some sequence of operations. Each operation is characterized by three values (t, v, c) where:
* t is the number of the tree on which the operation is executed (1 or 2);
* v is the vertex index in this tree (it is guaranteed that the tree contains a vertex with this index);
* c is a lowercase English letter.
The actual operation is as follows: vertex v of tree t gets a new descendant with number m + 1 (where m is the current number of vertices in tree t), and there should be letter c put on the new edge from vertex v to vertex m + 1.
We'll say that an ordered group of three integers (i, j, q) is a good combination if:
* 1 ≤ i ≤ m1, where m1 is the number of vertices in the first tree;
* 1 ≤ j, q ≤ m2, where m2 is the number of vertices in the second tree;
* there exists a forward path v1, v2, ..., vk such that v1 = j and vk = q in the second tree;
* the string that corresponds to the forward path in the second tree from vertex j to vertex q equals the string that corresponds to the backward path in the first tree from vertex i to vertex 1 (note that both paths are determined uniquely).
Your task is to calculate the number of existing good combinations after each operation on the trees.
Input
The first line contains integer n — the number of operations on the trees. Next n lines specify the operations in the order of their execution. Each line has form "t v c", where t is the number of the tree, v is the vertex index in this tree, and c is a lowercase English letter.
To get the full points for the first group of tests it is sufficient to solve the problem with 1 ≤ n ≤ 700.
To get the full points for the second group of tests it is sufficient to solve the problem with 1 ≤ n ≤ 7000.
To get the full points for the third group of tests it is sufficient to solve the problem with 1 ≤ n ≤ 100000.
Output
Print exactly n lines, each containing one integer — the number of existing good combinations after the corresponding operation from the input.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5
1 1 a
2 1 a
1 2 b
2 1 b
2 3 a
Output
1
3
3
4
7
Note
After the first operation the only good combination was (1, 1, 1). After the second operation new good combinations appeared, (2, 1, 2) and (1, 2, 2). The third operation didn't bring any good combinations. The fourth operation added good combination (1, 3, 3). Finally, the fifth operation resulted in as much as three new good combinations — (1, 4, 4), (2, 3, 4) and (3, 1, 4).
|
#include <bits/stdc++.h>
using namespace std;
class fenv_tree {
static int f(int x) { return x & -x; }
vector<int> tr;
public:
void add(int x, int v) {
assert(0 <= x && x + 1 < ((int)(tr).size()));
for (x++; x < ((int)(tr).size()); x += f(x)) tr[x] += v;
}
int get(int x) {
assert(-1 <= x && x + 1 < ((int)(tr).size()));
int res = 0;
for (x++; x > 0; x -= f(x)) res += tr[x];
return res;
}
fenv_tree(int n = 0) : tr(n + 1) {}
};
const unsigned long long P = 29;
const int K = 17;
const int MAXN = 1e5 + 1e3;
unsigned long long PPOW[MAXN + 1];
struct _node;
struct Up {
_node *x;
unsigned long long h, hrev;
Up() : x(0), h(0), hrev(0) {}
Up(_node *x, unsigned long long h, unsigned long long hrev)
: x(x), h(h), hrev(hrev) {}
};
typedef struct _node {
_node *ne[26];
int cnt;
Up ups[K];
unsigned long long sumhrev;
int depth;
_node() : cnt(0), sumhrev(0), depth(0) { memset(ne, 0, sizeof ne); }
pair<int, int> eulerIds;
int sufpos;
} * node;
bool cmp(node v1, node v2) {
if (v1 == v2) return false;
assert(v1 && v2);
for (int i = K - 1; i >= 0; i--)
if (v1->ups[i].h == v2->ups[i].h) {
v1 = v1->ups[i].x;
v2 = v2->ups[i].x;
assert(v1);
assert(v2);
}
assert(v1->ups[0].h != v2->ups[0].h);
return v1->ups[0].h < v2->ups[0].h;
}
unsigned long long gethr(node base, int step, int len) {
step = base->depth - step - len;
assert(step >= 0);
for (int i = K - 1; i >= 0; i--)
if (step >= (1 << i)) {
base = base->ups[i].x;
step -= 1 << i;
assert(base);
}
unsigned long long res = 0;
for (int i = K - 1; i >= 0; i--)
if (len >= (1 << i)) {
res = res * PPOW[1 << i] + base->ups[i].hrev;
base = base->ups[i].x;
len -= 1 << i;
}
return res;
}
bool cmp2(node v1, node v2) {
int clen = 0;
for (int i = K - 1; i >= 0; i--) {
if (((clen + (1 << i)) <= v2->depth) &&
v1->ups[i].h == gethr(v2, clen, (1 << i))) {
v1 = v1->ups[i].x;
clen += 1 << i;
assert(v1);
}
}
if (clen >= v2->depth) return false;
assert(v1->ups[0].h != gethr(v2, clen, 1));
return v1->ups[0].h < gethr(v2, clen, 1);
}
bool cmp3(node v1, node v2) {
int clen = 0;
for (int i = K - 1; i >= 0; i--) {
if (((clen + (1 << i)) <= v2->depth) &&
v1->ups[i].h == gethr(v2, clen, (1 << i))) {
v1 = v1->ups[i].x;
clen += 1 << i;
assert(v1);
}
}
if (clen >= v2->depth) return true;
assert(v1->ups[0].h != gethr(v2, clen, 1));
return v1->ups[0].h < gethr(v2, clen, 1);
}
class Tree {
vector<node> ns;
public:
Tree() : ns(1, new _node()) { ns[0]->cnt++; }
node add(int v, char c) {
assert(0 <= v && v < ((int)(ns).size()));
assert('a' <= c && c <= 'z');
node vv = ns[v];
node x = vv->ne[c - 'a'];
if (!x) {
x = vv->ne[c - 'a'] = new _node();
x->depth = vv->depth + 1;
x->sumhrev = vv->sumhrev * P + c;
x->ups[0] = Up(vv, c, c);
for (int i = 1; i < K; i++) {
Up a = x->ups[i - 1];
Up b;
if (a.x) b = a.x->ups[i - 1];
x->ups[i] = Up(b.x, a.h * PPOW[1 << (i - 1)] + b.h,
b.hrev * PPOW[1 << (i - 1)] + a.hrev);
}
}
ns.push_back(x);
return x;
}
private:
map<unsigned long long, node> hnodes;
int ctim;
void dfs(node v) {
if (!v) return;
assert(!hnodes.count(v->sumhrev));
hnodes[v->sumhrev] = v;
v->eulerIds.first = ctim++;
for (int i = 0; i < 26; i++) dfs(v->ne[i]);
v->eulerIds.second = ctim++;
}
fenv_tree euler;
vector<node> sufarr;
vector<int> sufpos;
fenv_tree sufsum;
public:
void precalc() {
ctim = 0;
hnodes.clear();
dfs(ns[0]);
euler = fenv_tree(ctim);
assert(ns[0]->cnt == 1);
sufarr = ns;
sort(sufarr.begin(), sufarr.end(), cmp);
for (int i = 0; i < ((int)(sufarr).size()); i++) {
sufarr[i]->sufpos = i;
}
sufsum = fenv_tree(((int)(sufarr).size()));
addCnt(ns[0]);
}
void addCnt(node v) {
euler.add(v->eulerIds.first, 1);
euler.add(v->eulerIds.second, -1);
sufsum.add(v->sufpos, 1);
}
int getParSum(node v) { return euler.get(v->eulerIds.first); }
node getHashRev(unsigned long long h) { return hnodes[h]; }
node getV(int x) { return ns[x]; }
int getSufStartWith(node t2) {
int a =
lower_bound(sufarr.begin(), sufarr.end(), t2, cmp2) - sufarr.begin();
int b =
lower_bound(sufarr.begin(), sufarr.end(), t2, cmp3) - sufarr.begin();
assert(0 <= a && a <= b && b <= ((int)(sufarr).size()));
return sufsum.get(b - 1) - sufsum.get(a - 1);
}
};
struct Op {
int t, v;
char c;
};
int main() {
PPOW[0] = 1;
for (int i = 1; i <= MAXN; i++) PPOW[i] = PPOW[i - 1] * P;
int n;
while (scanf("%d", &n) >= 1) {
Tree t1, t2;
long long ans = 1;
vector<Op> ops(n);
for (int step = 0; step < n; step++) {
Op &o = ops[step];
scanf("%d%d %c", &o.t, &o.v, &o.c), o.v--;
if (o.t == 1) {
t1.add(o.v, o.c);
} else {
t2.add(o.v, o.c);
}
}
t1.precalc();
t2.precalc();
int m1 = 0, m2 = 0;
for (int step = 0; step < n; step++) {
Op &o = ops[step];
if (o.t == 1) {
node x = t1.getV(++m1);
t1.addCnt(x);
ans += t2.getSufStartWith(x);
} else if (o.t == 2) {
node x = t2.getV(++m2);
t2.addCnt(x);
node y = x;
unsigned long long ch = 0;
for (int i = K - 1; i >= 0; i--) {
unsigned long long h = ch * PPOW[1 << i] + y->ups[i].h;
if (t1.getHashRev(h)) {
ch = h;
y = y->ups[i].x;
}
}
ans += t1.getParSum(t1.getHashRev(ch));
}
printf("%I64d\n", ans);
}
}
return 0;
}
|
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.
This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.
Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.
Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.
It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.
Help Vasya to recover the initial set of cards with numbers.
Input
The single line contains three space-separated integers: n (2 ≤ n ≤ 100) — the initial number of cards on the table, d (|d| ≤ 104) — the number on the card that was left on the table after all the magical actions, and l (1 ≤ l ≤ 100) — the limits for the initial integers.
Output
If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.
Examples
Input
3 3 2
Output
2 1 2
Input
5 -4 3
Output
-1
Input
5 -4 4
Output
2 4 1 4 1
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class VasyaMagic {
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] ns = bf.readLine().split(" ");
int n,d,l;
n = Integer.parseInt(ns[0]);
d = Integer.parseInt(ns[1]);
l = Integer.parseInt(ns[2]);
int a,b;
if(n%2==0){
b = n/2;
a = b;
}
else{
b = n/2;
a = b+1;
}
int x = 0,y = 0;
int sumPos = 0,sumNeg = 0;
for(int i = a;i<=a*l;i++)
for(int j = b;j<=b*l;j++){
if(i-j==d){
x = i;
y = j;
for(int k = 0;k<n;k++){
if(k%2==0){
System.out.print(((x-sumPos)/a)+" ");
sumPos += (x-sumPos)/a;
a--;
}
else{
System.out.print(((y-sumNeg)/b)+" ");
sumNeg += (y-sumNeg)/b;
b--;
}
}
return;
}
}
System.out.println(-1);
}
}
|
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter.
|
n,m,k=map(int,input().split(" "))
li=list(map(int,input().split(" ",n)[:n]))
li.sort(reverse=True)
fl=0
a,s=0,0
if m<=k:
print(0)
else:
while fl==0 and a<n:
s+=li[a]
a+=1
if a!=1:
s-=1
if s+k-1>=m and a!=0:
fl=1
break
if fl!=1:
print(-1)
else:
print(a)
|
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α.
<image>
Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.
Input
The first line contains three integers w, h, α (1 ≤ w, h ≤ 106; 0 ≤ α ≤ 180). Angle α is given in degrees.
Output
In a single line print a real number — the area of the region which belongs to both given rectangles.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.
Examples
Input
1 1 45
Output
0.828427125
Input
6 4 30
Output
19.668384925
Note
The second sample has been drawn on the picture above.
|
import math
def solve(a1, b1, c1, a2, b2, c2):
return (c1 * b2 - c2 * b1) / (a1 * b2 - a2 * b1), (c1 * a2 - c2 * a1) / (b1 * a2 - b2 * a1)
if __name__ == '__main__':
w, h, a = [int(x) for x in raw_input().split()]
w, h = max(w, h), min(w, h)
a = min(a, 180 - a) / 180.0 * math.pi
if a < 2.0 * math.atan2(h, w):
x, y = solve(1 + math.cos(a), math.sin(a), w, math.sin(a), 1 + math.cos(a), h)
res = w * h - (x * x + y * y) * math.cos(a) * math.sin(a)
else:
res = w * h - (w - h / math.sin(a)) * h
print(res)
|
Yaroslav likes algorithms. We'll describe one of his favorite algorithms.
1. The algorithm receives a string as the input. We denote this input string as a.
2. The algorithm consists of some number of command. Сommand number i looks either as si >> wi, or as si <> wi, where si and wi are some possibly empty strings of length at most 7, consisting of digits and characters "?".
3. At each iteration, the algorithm looks for a command with the minimum index i, such that si occurs in a as a substring. If this command is not found the algorithm terminates.
4. Let's denote the number of the found command as k. In string a the first occurrence of the string sk is replaced by string wk. If the found command at that had form sk >> wk, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates.
5. The value of string a after algorithm termination is considered to be the output of the algorithm.
Yaroslav has a set of n positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.
Help Yaroslav.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the set. The next n lines contains one positive integer each. All the given numbers are less than 1025.
Output
Print the algorithm which can individually increase each number of the set. In the i-th line print the command number i without spaces.
Your algorithm will be launched for each of these numbers. The answer will be considered correct if:
* Each line will a correct algorithm command (see the description in the problem statement).
* The number of commands should not exceed 50.
* The algorithm will increase each of the given numbers by one.
* To get a respond, the algorithm will perform no more than 200 iterations for each number.
Examples
Input
2
10
79
Output
10<>11
79<>80
|
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
int n;
cin >> n;
for (int i = 0; i < n; i++) getline(cin, s);
for (int i = 0; i < 10; i++) cout << "??" << i << ">>" << i << "??" << endl;
cout << "??>>?" << endl;
for (int i = 0; i < 9; i++) cout << i << "?<>" << i + 1 << "\n";
cout << "9?>>?0\n?<>1\n>>??\n";
}
|
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.
Ways (1, 2) and (2, 1) should be regarded as different.
Input
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
Output
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
Examples
Input
5 10
10 20 50 60 65
Output
6
Input
5 1
55 30 29 31 55
Output
6
|
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int [] h = new int [n];
for(int i=0 ; i<n ; i++)
h[i] = in.nextInt();
Arrays.sort(h);
int cnt=0;
for(int i=0 ; i<n ; i++)
for(int j=0 ; j<n ; j++)
if(Math.abs(h[j] - h[i]) <= d && j != i)
cnt++;
System.out.println(cnt);
}
}
//730453
|
Emperor Palpatine loves owls very much. The emperor has some blueprints with the new Death Star, the blueprints contain n distinct segments and m distinct circles. We will consider the segments indexed from 1 to n in some way and the circles — indexed from 1 to m in some way.
Palpatine defines an owl as a set of a pair of distinct circles (i, j) (i < j) and one segment k, such that:
1. circles i and j are symmetrical relatively to the straight line containing segment k;
2. circles i and j don't have any common points;
3. circles i and j have the same radius;
4. segment k intersects the segment that connects the centers of circles i and j.
Help Palpatine, count the number of distinct owls on the picture.
Input
The first line contains two integers — n and m (1 ≤ n ≤ 3·105, 2 ≤ m ≤ 1500).
The next n lines contain four integers each, x1, y1, x2, y2 — the coordinates of the two endpoints of the segment. It's guaranteed that each segment has positive length.
The next m lines contain three integers each, xi, yi, ri — the coordinates of the center and the radius of the i-th circle. All coordinates are integers of at most 104 in their absolute value. The radius is a positive integer of at most 104.
It is guaranteed that all segments and all circles are dictinct.
Output
Print a single number — the answer to the problem.
Please, do not use the %lld specifier to output 64-bit integers is С++. It is preferred to use the cout stream or the %I64d specifier.
Examples
Input
1 2
3 2 3 -2
0 0 2
6 0 2
Output
1
Input
3 2
0 0 0 1
0 -1 0 1
0 -1 0 0
2 0 1
-2 0 1
Output
3
Input
1 2
-1 0 1 0
-100 0 1
100 0 1
Output
0
Note
Here's an owl from the first sample. The owl is sitting and waiting for you to count it.
<image>
|
#include <bits/stdc++.h>
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("O3")
#pragma GCC optimize("fast-math")
using namespace std;
const long long INF = 2e9;
const long long INFll = 2e18;
const long long BASE1 = 179;
const long long BASE2 = 653;
const long long MOD = 1e9 + 7;
const long long MAXN = 1e5 + 10;
const long double PI = 3.1415926535;
const long double EPS = 1e-10;
struct line {
long long A, B, C;
line(long long A, long long B, long long C) : A(A), B(B), C(C){};
};
struct event {
long long t;
long double x;
event() {
t = -1;
x = -1;
}
event(long long t, long double x) : t(t), x(x){};
};
long long gcd(long long a, long long b) {
while (b != 0) {
a = a % b;
swap(a, b);
}
return a;
}
pair<pair<long long, long long>, long long> normal(long long A, long long B,
long long C) {
if (A < 0)
A *= -1, B *= -1, C *= -1;
else if (A == 0 && B < 0)
A *= -1, B *= -1, C *= -1;
long long g = gcd(abs(A), gcd(abs(B), abs(C)));
A /= g, B /= g, C /= g;
return make_pair(make_pair(A, B), C);
}
bool cmp(event& a, event& b) { return a.x < b.x || a.x == b.x && a.t < b.t; }
void solve() {
long long n, m;
cin >> n >> m;
map<pair<pair<long long, long long>, long long>, vector<event>> dop;
for (long long i = 0; i < (n); i++) {
long long x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
long long A = y2 - y1, B = x1 - x2, C = -A * x1 - B * y1;
pair<pair<long long, long long>, long long> l = normal(A, B, C);
if (dop.find(l) == dop.end())
dop[l] = {event(-1, min(x1, x2)), event(1, max(x1, x2))};
else {
dop[l].emplace_back(event(-1, min(x1, x2)));
dop[l].emplace_back(event(1, max(x1, x2)));
}
}
vector<long long> x(m), y(m), r(m);
for (long long i = 0; i < (m); i++) cin >> x[i] >> y[i] >> r[i];
long long dcnt = 0;
for (long long i = 0; i < (m); i++) {
for (long long j = 0; j < (i); j++) {
if (r[i] != r[j]) continue;
long long d =
((x[i] - x[j]) * (x[i] - x[j])) + ((y[i] - y[j]) * (y[i] - y[j]));
if (d <= 4 * ((r[i]) * (r[i]))) continue;
long long xm = x[i] + x[j], ym = y[i] + y[j];
long long A1 = y[j] - y[i], B1 = x[i] - x[j];
long long A = 2 * B1, B = -2 * A1, C = -B1 * xm + A1 * ym;
pair<pair<long long, long long>, long long> l = normal(A, B, C);
if (dop.find(l) == dop.end()) {
continue;
} else {
dop[l].emplace_back(event(0, xm / (long double)2));
dcnt++;
}
}
}
long long res = 0;
for (auto [line, v] : dop) {
sort(v.begin(), v.end(), cmp);
long long bal = 0;
for (event e : v) {
if (e.t == -1)
bal++;
else if (e.t == 1)
bal--;
else {
0;
res += bal;
}
}
}
cout << res << "\n";
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cout << fixed << setprecision(15);
long long t = 1;
while (t--) solve();
return 0;
}
|
Inna, Dima and Sereja are in one room together. It's cold outside, so Sereja suggested to play a board game called "Babies".
The babies playing board is an infinite plane containing n blue babies and m red ones. Each baby is a segment that grows in time. At time moment t the blue baby (x, y) is a blue segment with ends at points (x - t, y + t), (x + t, y - t). Similarly, at time t the red baby (x, y) is a red segment with ends at points (x + t, y + t), (x - t, y - t) of the plane. Initially, at time t = 0 all babies are points on the plane.
The goal of the game is to find the first integer moment of time when the plane contains a rectangle of a non-zero area which sides are fully covered by some babies. A side may be covered by multiple babies. More formally, each point of each side of the rectangle should be covered by at least one baby of any color. At that, you must assume that the babies are closed segments, that is, they contain their endpoints.
You are given the positions of all babies — help Inna and Dima to find the required moment of time.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 2000).
Next n lines contain the coordinates of the blue babies. The i-th line contains integers xi, yi — a baby's coordinates. Next m lines contain the coordinates of m red babies in the similar form.
All coordinates of the input don't exceed 106 in their absolute value. Note that all babies stand in distinct points.
Output
In the single line print a single integer — the answer to the problem.
If the rectangle never appears on the plane, print "Poor Sereja!" without the quotes.
Examples
Input
2 2
2 2
5 5
3 7
5 1
Output
3
Input
3 2
2 2
3 2
6 2
4 2
5 2
Output
1
|
#include <bits/stdc++.h>
using namespace std;
template <class P, class Q>
void mmin(P &a, const Q &b) {
if (b < a) a = b;
}
template <class P, class Q>
void mmax(P &a, const Q &b) {
if (b > a) a = b;
}
template <class P>
P GCD(P a, P b) {
if (a < b) swap(a, b);
P c;
while (b) {
c = a % b;
a = b;
b = c;
}
return a;
}
const int MAXn = 2000;
int n, m;
pair<int, int> a[MAXn], b[MAXn];
vector<pair<int, pair<int, int> > > vc1, vc2;
bool mark[MAXn][MAXn];
bool cmp(const pair<int, int> &a, const pair<int, int> &b) {
return a.second != b.second ? a.second < b.second : a.first < b.first;
}
inline bool coincide(const pair<int, pair<int, int> > &a,
const pair<int, pair<int, int> > &b) {
return b.second.first <= a.first && a.first <= b.second.second &&
a.second.first <= b.first && b.first <= a.second.second;
}
inline bool check(int x) {
vc1.clear();
vc2.clear();
for (int i = 0; i < (n); ++i) fill_n(mark[i], n, 0);
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && a[j].first == a[i].first &&
a[j - 1].second + 2 * x >= a[j].second - 2 * x)
++j;
vc1.push_back(make_pair(
a[i].first, make_pair(a[i].second - 2 * x, a[j - 1].second + 2 * x)));
i = j;
}
for (int i = 0; i < m;) {
int j = i + 1;
while (j < m && b[j].second == b[i].second &&
b[j - 1].first + 2 * x >= b[j].first - 2 * x)
++j;
vc2.push_back(make_pair(
b[i].second, make_pair(b[i].first - 2 * x, b[j - 1].first + 2 * x)));
i = j;
}
for (int j = 0; j < ((int)(vc2).size()); ++j) {
vector<int> vc;
for (int i = 0; i < ((int)(vc1).size()); ++i)
if (coincide(vc1[i], vc2[j])) {
vc.push_back(i);
}
for (int i = 0; i < ((int)(vc).size()); ++i)
for (int j = (i + 1); j < ((int)(vc).size()); ++j)
if (mark[vc[i]][vc[j]])
return true;
else
mark[vc[i]][vc[j]] = 1;
}
return false;
}
inline int BS() {
int s = -1, e = 2e6;
if (!check(e)) return -1;
while (s + 1 < e) {
int mid = s + e >> 1;
if (check(mid))
e = mid;
else
s = mid;
}
return e;
}
int main() {
ios_base::sync_with_stdio(false);
cin >> n >> m;
for (int i = 0; i < (n); ++i) {
int x, y;
cin >> x >> y;
a[i] = pair<int, int>(x + y, x - y);
}
for (int i = 0; i < (m); ++i) {
int x, y;
cin >> x >> y;
b[i] = pair<int, int>(x + y, x - y);
}
sort(a, a + n);
sort(b, b + m, cmp);
int ans = BS();
if (ans == -1)
cout << "Poor Sereja!" << endl;
else
cout << ans << endl;
return 0;
}
|
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.
The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!
Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.
Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.
In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
Input
The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri).
Output
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
Examples
Input
2
5 2 3
6 4 5
Output
Yes
No
Note
You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n, l, r;
scanf("%d%d%d", &n, &l, &r);
if (n < l)
cout << "No" << endl;
else if ((n >= l && n <= r) || (n / l * r >= n) || (r >= 2 * l - 1))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
|
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address (vasya@gmail.com).
It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots.
You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result.
Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at.
Input
The first line contains the email address description. It is guaranteed that that is a proper email address with all the dots replaced by dot an the at signs replaced by at. The line is not empty and its length does not exceed 100 symbols.
Output
Print the shortest email address, from which the given line could be made by the described above replacements. If there are several solutions to that problem, print the lexicographically minimal one (the lexicographical comparison of the lines are implemented with an operator < in modern programming languages).
In the ASCII table the symbols go in this order: . @ ab...z
Examples
Input
vasyaatgmaildotcom
Output
vasya@gmail.com
Input
dotdotdotatdotdotat
Output
dot..@..at
Input
aatt
Output
a@t
|
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int sl = s.length();
string ans = "";
ans += s[0];
bool at = false;
for (int i = 1; i < sl; i++) {
if (at == false && (sl - i) > 2 && s.substr(i, 2) == "at")
ans += '@', at = true, i++;
else if ((sl - i) > 3 && s.substr(i, 3) == "dot")
ans += ".", i += 2;
else
ans += s[i];
}
cout << ans << "\n";
return 0;
}
|
DZY has a sequence a, consisting of n integers.
We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.
Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.
You only need to output the length of the subsegment you find.
Input
The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Output
In a single line print the answer to the problem — the maximum length of the required subsegment.
Examples
Input
6
7 2 3 1 5 6
Output
5
Note
You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
|
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split())
def msi(): return map(str,input().split())
def li(): return list(mi())
n=ii()
a=li()
pre,suf = [1]*n,[1]*n
for i in range(1,n):
if a[i]>a[i-1]:
pre[i]+=pre[i-1]
for i in range(n-2,-1,-1):
if a[i]<a[i+1]:
suf[i]+=suf[i+1]
ans=max(pre)
if ans<n:
ans+=1
for i in range(1,n-1):
if a[i+1]>a[i-1]+1:
ans=max(ans,pre[i-1]+suf[i+1]+1)
print(ans)
|
Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied:
* If number x belongs to set A, then number a - x must also belong to set A.
* If number x belongs to set B, then number b - x must also belong to set B.
Help Little X divide the numbers into two sets or determine that it's impossible.
Input
The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≤ pi ≤ 109).
Output
If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B.
If it's impossible, print "NO" (without the quotes).
Examples
Input
4 5 9
2 3 4 5
Output
YES
0 0 1 1
Input
3 3 4
1 2 4
Output
NO
Note
It's OK if all the numbers are in the same set, and the other one is empty.
|
#include <bits/stdc++.h>
using namespace std;
const int N = int(1e5) + 10;
const int K = int(2e6) + 10;
const long long MOD = int(1e9) + 7;
const int INF = int(1e9) + 5;
const long long INF64 = 1e18;
map<int, int> mp, ans;
int p[N], q[N];
vector<int> f, s, t;
void solve() {
int n, a, b;
cin >> n >> a >> b;
for (int i = 1; i <= n; i++) {
cin >> p[i];
q[i] = p[i];
mp[p[i]]++;
}
sort(p + 1, p + 1 + n);
int flag = 0;
for (int i = 1; i <= n; i++) {
bool ok = true;
if (!mp[p[i]]) continue;
int x = p[i];
if (mp[a - x] == 0 && mp[b - x] == 0) {
ok = false;
} else if (mp[b - x] == 0) {
mp[x] = 0;
mp[a - x] = 0;
ans[x] = 0;
ans[a - x] = 0;
} else if (mp[a - x] == 0) {
mp[x] = 0;
mp[b - x] = 0;
ans[x] = 1;
ans[b - x] = 1;
} else {
int y1 = a - x;
int y2 = b - x;
int t1 = a - (b - x);
int t2 = b - (a - x);
if (mp[t1] > 0) {
mp[x] = 0;
mp[a - x] = 0;
mp[b - x] = 0;
mp[t1] = 0;
ans[x] = ans[a - x] = ans[b - x] = ans[t1] = 0;
} else if (mp[t2] > 0) {
mp[x] = 0;
mp[a - x] = 0;
mp[b - x] = 0;
mp[t2] = 0;
ans[x] = ans[a - x] = ans[b - x] = ans[t2] = 1;
} else {
ok = false;
}
}
if (!ok) {
cout << "NO" << '\n';
return;
}
}
cout << "YES" << '\n';
for (int i = 1; i <= n; i++) cout << ans[q[i]] << " ";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
t = 1;
while (t--) {
solve();
}
return 0;
}
|
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
|
import math
from collections import deque
class Empty(Exception):
pass
class _DoublyLinkedBase:
"""A base class providing a doubly linked list representation."""
#-------------------------- nested _Node class --------------------------
# nested _Node class
class _Node:
"""Lightweight, nonpublic class for storing a doubly linked node."""
__slots__ = '_element', '_prev', '_next' # streamline memory
def __init__(self, element, prev, next): # initialize node's fields
self._element = element # user's element
self._prev = prev # previous node reference
self._next = next # next node reference
#-------------------------- list constructor --------------------------
def __init__(self):
"""Create an empty list."""
self._header = self._Node(None, None, None)
self._trailer = self._Node(None, None, None)
self._header._next = self._trailer # trailer is after header
self._trailer._prev = self._header # header is before trailer
self._size = 0 # number of elements
#-------------------------- public accessors --------------------------
def __len__(self):
"""Return the number of elements in the list."""
return self._size
def is_empty(self):
"""Return True if list is empty."""
return self._size == 0
#-------------------------- nonpublic utilities --------------------------
def _insert_between(self, e, predecessor, successor):
"""Add element e between two existing nodes and return new node."""
newest = self._Node(e, predecessor, successor) # linked to neighbors
predecessor._next = newest
successor._prev = newest
self._size += 1
return newest
def _delete_node(self, node):
"""Delete nonsentinel node from the list and return its element."""
predecessor = node._prev
successor = node._next
predecessor._next = successor
successor._prev = predecessor
self._size -= 1
element = node._element # record deleted element
node._prev = node._next = node._element = None # deprecate node
return element # return deleted element
class LinkedDeque(_DoublyLinkedBase): # note the use of inheritance
"""Double-ended queue implementation based on a doubly linked list."""
def first(self):
"""Return (but do not remove) the element at the front of the deque.
Raise Empty exception if the deque is empty.
"""
if self.is_empty():
raise Empty("Deque is empty")
return self._header._next._element # real item just after header
def last(self):
"""Return (but do not remove) the element at the back of the deque.
Raise Empty exception if the deque is empty.
"""
if self.is_empty():
raise Empty("Deque is empty")
return self._trailer._prev._element # real item just before trailer
def insert_first(self, e):
"""Add an element to the front of the deque."""
self._insert_between(e, self._header, self._header._next) # after header
def insert_last(self, e):
"""Add an element to the back of the deque."""
self._insert_between(e, self._trailer._prev, self._trailer) # before trailer
def delete_first(self):
"""Remove and return the element from the front of the deque.
Raise Empty exception if the deque is empty.
"""
if self.is_empty():
raise Empty("Deque is empty")
return self._delete_node(self._header._next) # use inherited method
def delete_last(self):
"""Remove and return the element from the back of the deque.
Raise Empty exception if the deque is empty.
"""
if self.is_empty():
raise Empty("Deque is empty")
return self._delete_node(self._trailer._prev) # use inherited method
class PositionalList(_DoublyLinkedBase):
"""A sequential container of elements allowing positional access."""
#-------------------------- nested Position class --------------------------
class Position:
"""An abstraction representing the location of a single element.
Note that two position instaces may represent the same inherent
location in the list. Therefore, users should always rely on
syntax 'p == q' rather than 'p is q' when testing equivalence of
positions.
"""
def __init__(self, container, node):
"""Constructor should not be invoked by user."""
self._container = container
self._node = node
def element(self):
"""Return the element stored at this Position."""
return self._node._element
def __eq__(self, other):
"""Return True if other is a Position representing the same location."""
return type(other) is type(self) and other._node is self._node
def __ne__(self, other):
"""Return True if other does not represent the same location."""
return not (self == other) # opposite of __eq__
#------------------------------- utility methods -------------------------------
def _validate(self, p):
"""Return position's node, or raise appropriate error if invalid."""
if not isinstance(p, self.Position):
raise TypeError('p must be proper Position type')
if p._container is not self:
raise ValueError('p does not belong to this container')
if p._node._next is None: # convention for deprecated nodes
raise ValueError('p is no longer valid')
return p._node
def _make_position(self, node):
"""Return Position instance for given node (or None if sentinel)."""
if node is self._header or node is self._trailer:
return None # boundary violation
else:
return self.Position(self, node) # legitimate position
#------------------------------- accessors -------------------------------
def first(self):
"""Return the first Position in the list (or None if list is empty)."""
return self._make_position(self._header._next)
def last(self):
"""Return the last Position in the list (or None if list is empty)."""
return self._make_position(self._trailer._prev)
def before(self, p):
"""Return the Position just before Position p (or None if p is first)."""
node = self._validate(p)
return self._make_position(node._prev)
def after(self, p):
"""Return the Position just after Position p (or None if p is last)."""
node = self._validate(p)
return self._make_position(node._next)
def __iter__(self):
"""Generate a forward iteration of the elements of the list."""
cursor = self.first()
while cursor is not None:
yield cursor.element()
cursor = self.after(cursor)
#------------------------------- mutators -------------------------------
# override inherited version to return Position, rather than Node
def _insert_between(self, e, predecessor, successor):
"""Add element between existing nodes and return new Position."""
node = super()._insert_between(e, predecessor, successor)
return self._make_position(node)
def add_first(self, e):
"""Insert element e at the front of the list and return new Position."""
return self._insert_between(e, self._header, self._header._next)
def add_last(self, e):
"""Insert element e at the back of the list and return new Position."""
return self._insert_between(e, self._trailer._prev, self._trailer)
def add_before(self, p, e):
"""Insert element e into list before Position p and return new Position."""
original = self._validate(p)
return self._insert_between(e, original._prev, original)
def add_after(self, p, e):
"""Insert element e into list after Position p and return new Position."""
original = self._validate(p)
return self._insert_between(e, original, original._next)
def delete(self, p):
"""Remove and return the element at Position p."""
original = self._validate(p)
return self._delete_node(original) # inherited method returns element
def replace(self, p, e):
"""Replace the element at Position p with e.
Return the element formerly at Position p.
"""
original = self._validate(p)
old_value = original._element # temporarily store old element
original._element = e # replace with new element
return old_value # return the old element value
L1=LinkedDeque()
L2=LinkedDeque()
dic={}
dic2={}
n=int(input())
for i in range(n):
a,b=(int(i) for i in input().split())
dic[a]=b
dic2[b]=a
forw=0
while (forw in dic) :
L1.insert_last(dic[forw])
t=dic[forw]
dic.pop(forw)
forw=t
if L1.last()==0 :
L1.delete_last()
if n%2==0 :
backw=0
while (backw in dic2) :
L2.insert_first(dic2[backw])
t=dic2[backw]
dic2.pop(backw)
backw=t
else:
tk,tv=0,0
for (k, v) in dic.items():
tk=k
tv=v
forw=tk
while (forw in dic) :
L2.insert_last(dic[forw])
t=dic[forw]
dic.pop(forw)
forw=t
backw=tv
while (backw in dic2) :
L2.insert_first(dic2[backw])
t=dic2[backw]
dic2.pop(backw)
backw=t
outList=[]
while L1.is_empty()==False :
outList.append(str(L2.first()))
outList.append(str(L1.first()))
L1.delete_first()
L2.delete_first()
if L2.is_empty()==False :
outList.append(str(L2.first()))
pass
print(" ".join(outList))
|
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane.
Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).
Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.
The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.
Input
The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun.
Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.
Output
Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.
Examples
Input
4 0 0
1 1
2 2
2 0
-1 -1
Output
2
Input
2 1 2
1 1
1 0
Output
1
Note
Explanation to the first and second samples from the statement, respectively:
<image>
|
n, x0, y0 = map(int, input().split())
slopes = {} # key: (num, den), val: count
for i in range(n):
x, y = map(int, input().split())
num = y - y0
den = x - x0
# print(num, den)
if den == 0 and "inf" in slopes:
slopes["inf"] += 1
elif den == 0:
slopes["inf"] = 1
else:
found = False
for s in slopes:
# print(isinstance(s, tuple))
if isinstance(s, tuple) and num * s[1] == den * s[0]:
slopes[s] += 1
found = True
if found == False:
slopes[(num, den)] = 1
print(slopes.__len__())
|
You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.
The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.
Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r, c).
You are staying in the cell (r1, c1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r2, c2) since the exit to the next level is there. Can you do this?
Input
The first line contains two integers, n and m (1 ≤ n, m ≤ 500) — the number of rows and columns in the cave description.
Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice).
The next line contains two integers, r1 and c1 (1 ≤ r1 ≤ n, 1 ≤ c1 ≤ m) — your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r1, c1), that is, the ice on the starting cell is initially cracked.
The next line contains two integers r2 and c2 (1 ≤ r2 ≤ n, 1 ≤ c2 ≤ m) — the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.
Output
If you can reach the destination, print 'YES', otherwise print 'NO'.
Examples
Input
4 6
X...XX
...XX.
.X..X.
......
1 6
2 2
Output
YES
Input
5 4
.X..
...X
X.X.
....
.XX.
5 3
1 1
Output
NO
Input
4 7
..X.XX.
.XX..X.
X...X..
X......
2 2
1 6
Output
YES
Note
In the first sample test one possible path is:
<image>
After the first visit of cell (2, 2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended.
|
#include <bits/stdc++.h>
using namespace std;
int target, n, m;
bool same_x(int i, int j) { return ceil(i / (double)m) == ceil(j / (double)m); }
bool same_y(int i, int j) {
return i - (ceil(i / (double)m) - 1) * m == j - (ceil(j / (double)m) - 1) * m;
}
bool edge_exists(int i, int j) {
return ((abs(i - j) == 1 && (same_x(i, j) || same_y(i, j))) ||
(abs(i - j) == m && (same_x(i, j) || same_y(i, j))));
}
void dfs(int vertex, bool visited[]) {
int x = ceil(vertex / (double)m);
int y = vertex - (x - 1) * m;
visited[vertex] = true;
if (edge_exists(vertex, target)) {
visited[target] = true;
return;
}
vector<int> v = {vertex - 1, vertex + 1, vertex - m, vertex + m};
for (auto i : v) {
if (i >= 1 && i <= n * m && (same_x(vertex, i) || same_y(vertex, i))) {
if (!visited[i] && !visited[target]) dfs(i, visited);
if (visited[target]) break;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
char c;
extern int n, m;
int counter = 0, start_x, start_y, end_x, end_y;
cin >> n >> m;
bool visited[n * m + 1];
memset(visited, false, sizeof(visited));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> c, visited[++counter] = (c == 'X') ? true : false;
for (int i = 1, x, y; i <= n * m; i++) {
x = ceil(i / (double)m);
y = i - (x - 1) * m;
}
cin >> start_x >> start_y >> end_x >> end_y;
target = (end_x - 1) * m + end_y;
visited[(start_x - 1) * m + start_y] = false;
bool again = false;
if (visited[target]) again = true, visited[target] = false;
dfs((start_x - 1) * m + start_y, visited);
if (again && visited[target]) cout << "YES" << endl, exit(0);
if (visited[target] == true) {
visited[target] = false;
vector<int> v = {target - 1, target + 1, target - m, target + m};
for (auto i : v) {
if (i >= 1 && i <= n * m && (same_x(target, i) || same_y(target, i)))
if (visited[i] == false) visited[target] = true;
}
if (visited[target] == true)
cout << "YES" << endl;
else
cout << "NO" << endl;
} else
cout << "NO" << endl;
return 0;
}
|
One Khanate had a lot of roads and very little wood. Riding along the roads was inconvenient, because the roads did not have road signs indicating the direction to important cities.
The Han decided that it's time to fix the issue, and ordered to put signs on every road. The Minister of Transport has to do that, but he has only k signs. Help the minister to solve his problem, otherwise the poor guy can lose not only his position, but also his head.
More formally, every road in the Khanate is a line on the Oxy plane, given by an equation of the form Ax + By + C = 0 (A and B are not equal to 0 at the same time). You are required to determine whether you can put signs in at most k points so that each road had at least one sign installed.
Input
The input starts with two positive integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 5)
Next n lines contain three integers each, Ai, Bi, Ci, the coefficients of the equation that determines the road (|Ai|, |Bi|, |Ci| ≤ 105, Ai2 + Bi2 ≠ 0).
It is guaranteed that no two roads coincide.
Output
If there is no solution, print "NO" in the single line (without the quotes).
Otherwise, print in the first line "YES" (without the quotes).
In the second line print a single number m (m ≤ k) — the number of used signs. In the next m lines print the descriptions of their locations.
Description of a location of one sign is two integers v, u. If u and v are two distinct integers between 1 and n, we assume that sign is at the point of intersection of roads number v and u. If u = - 1, and v is an integer between 1 and n, then the sign is on the road number v in the point not lying on any other road. In any other case the description of a sign will be assumed invalid and your answer will be considered incorrect. In case if v = u, or if v and u are the numbers of two non-intersecting roads, your answer will also be considered incorrect.
The roads are numbered starting from 1 in the order in which they follow in the input.
Examples
Input
3 1
1 0 0
0 -1 0
7 -93 0
Output
YES
1
1 2
Input
3 1
1 0 0
0 1 0
1 1 3
Output
NO
Input
2 3
3 4 5
5 6 7
Output
YES
2
1 -1
2 -1
Note
Note that you do not have to minimize m, but it shouldn't be more than k.
In the first test all three roads intersect at point (0,0).
In the second test all three roads form a triangle and there is no way to place one sign so that it would stand on all three roads at once.
|
#include <bits/stdc++.h>
using namespace std;
struct line {
long long a;
long long b;
long long c;
int id;
};
vector<pair<int, int> > ans;
const long double eps = 1e-12;
bool do_inter(const line &l, const line &r) { return (l.a * r.b != r.a * l.b); }
bool on(const line &l, const pair<long double, long double> &pt) {
return fabs(l.a * pt.first + l.b * pt.second - l.c) < eps;
}
pair<long double, long double> intersect(const line &l, const line &r) {
long double y = (long double)(l.c * r.a - r.c * l.a) /
(long double)(l.b * r.a - l.a * r.b);
long double x = (long double)(l.c * r.b - r.c * l.b) /
(long double)(l.a * r.b - r.a * l.b);
assert(on(l, make_pair(x, y)));
assert(on(r, make_pair(x, y)));
return make_pair(x, y);
}
bool work(vector<line> &v, int k) {
if ((int)v.size() == 0 && k >= 0) return true;
if ((int)v.size() > 0 && k == 0) return false;
if ((int)v.size() <= k) {
for (int i = 0; i < (int)v.size(); i++)
ans.push_back(make_pair(v[i].id, -1));
return true;
}
if ((int)v.size() >= k * k + 1) {
int actual = k * k + 1;
int mi = -1, mj = -1;
for (int i = 0; i < actual && mi == -1; i++)
for (int j = i + 1; j < actual; j++)
if (do_inter(v[i], v[j])) {
auto vs = intersect(v[i], v[j]);
int cnt = 0;
for (int s = 0; s < actual; s++) cnt += on(v[s], vs);
if (cnt >= k + 1) {
mi = i;
mj = j;
break;
}
}
if (mi == -1) return false;
auto vs = intersect(v[mi], v[mj]);
vector<line> nline;
for (int i = 0; i < (int)v.size(); i++)
if (!on(v[i], vs)) nline.push_back(v[i]);
ans.push_back(make_pair(v[mi].id, v[mj].id));
bool cres = work(nline, k - 1);
if (!cres) ans.pop_back();
return cres;
}
assert((int)v.size() > k);
for (int i = 0; i < k; i++)
for (int j = i + 1; j < k; j++)
if (do_inter(v[i], v[j])) {
auto vs = intersect(v[i], v[j]);
vector<line> nline;
for (int s = 0; s < (int)v.size(); s++)
if (!on(v[s], vs)) nline.push_back(v[s]);
ans.push_back(make_pair(v[i].id, v[j].id));
bool cres = work(nline, k - 1);
if (!cres)
ans.pop_back();
else
return true;
}
return false;
}
void solve(int n) {
int k;
cin >> k;
vector<line> all(n);
for (int i = 0; i < n; i++) {
int a, b, c;
scanf(" %d %d %d", &a, &b, &c);
all[i].a = a, all[i].b = b, all[i].c = c;
all[i].id = i + 1;
}
ans.clear();
bool ok = work(all, k);
if (!ok)
puts("NO");
else {
puts("YES");
printf("%d\n", (int)ans.size());
for (auto pt : ans) printf("%d %d\n", pt.first, pt.second);
}
}
int main() {
int n;
while (cin >> n) solve(n);
}
|
In Berland a money reform is being prepared. New coins are being introduced. After long economic calculations was decided that the most expensive coin should possess the denomination of exactly n Berland dollars. Also the following restriction has been introduced for comfort: the denomination of each coin should be divisible by the denomination of any cheaper coin. It is known that among all the possible variants the variant with the largest number of new coins will be chosen. Find this variant. Print in the order of decreasing of the coins' denominations.
Input
The first and only line contains an integer n (1 ≤ n ≤ 106) which represents the denomination of the most expensive coin.
Output
Print the denominations of all the coins in the order of decreasing. The number of coins must be the largest possible (with the given denomination n of the most expensive coin). Also, the denomination of every coin must be divisible by the denomination of any cheaper coin. Naturally, the denominations of all the coins should be different. If there are several solutins to that problem, print any of them.
Examples
Input
10
Output
10 5 1
Input
4
Output
4 2 1
Input
3
Output
3 1
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
cin >> a;
for (int i = a; i > 0; i--) {
if (a % i == 0) {
a = i;
cout << a << " ";
}
}
return 0;
}
|
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!
One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.
Limak assumes three things:
* Years are listed in the strictly increasing order;
* Every year is a positive integer number;
* There are no leading zeros.
Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits.
The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.
Output
Print the number of ways to correctly split the given sequence modulo 109 + 7.
Examples
Input
6
123434
Output
8
Input
8
20152016
Output
4
Note
In the first sample there are 8 ways to split the sequence:
* "123434" = "123434" (maybe the given sequence is just one big number)
* "123434" = "1" + "23434"
* "123434" = "12" + "3434"
* "123434" = "123" + "434"
* "123434" = "1" + "23" + "434"
* "123434" = "1" + "2" + "3434"
* "123434" = "1" + "2" + "3" + "434"
* "123434" = "1" + "2" + "3" + "4" + "34"
Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.
In the second sample there are 4 ways:
* "20152016" = "20152016"
* "20152016" = "20" + "152016"
* "20152016" = "201" + "52016"
* "20152016" = "2015" + "2016"
|
import java.util.Scanner;
/**
* Created by d40a on 01.01.16.
*/
public class Main {
static final int mod = (int)(1e9) + 7;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
reader.nextLine();
char[] s = reader.next().toCharArray();
int nxt[][] = new int[n + 1][n + 1];
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
if (s[i] == s[j])
nxt[i][j] = nxt[i + 1][j + 1] + 1;
else
nxt[i][j] = 0;
}
}
long dp[][] = new long[n + 1][n + 1];
if (s[0] != '0') {
for (int b = 1; b <= n; b++)
dp[1][b] = 1;
}
for (int a = 2; a <= n; a++) {
long sum = 0;
for (int b = a; b <= n; b++) {
if (s[a - 1] == '0')
{
dp[a][b] = 0;
continue;
}
int len = b - a + 1;
boolean added = false;
if (a - len > 0) {
int d = a - 1;
int c = a - len;
int l = nxt[a - 1][c - 1];
if (l < len && s[a - 1 + l] > s[c - 1 + l]) {
sum = add(sum, dp[c][d]);
added = true;
}
}
dp[a][b] = sum;
if (a - len > 0 && !added)
sum = add(sum, dp[a - len][a - 1]);
}
}
// for (int i = 1; i <= n; i++) {
// for (int j = 1; j <= n; j++) {
// System.out.print(dp[i][j]);
// }
// System.out.println();
// }
long res = 0;
for (int i = 1; i <= n; i++) {
res = add(res, dp[i][n]);
}
System.out.println(res);
}
static long add(long res, long x) {
long md = (long)(1e9) + 7;
res += x;
if (res >= md) res -= md;
return res;
}
}
|
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.
We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ..., xr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n.
<image>
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the length of the arrays.
The second line contains n integers ai (0 ≤ ai ≤ 109).
The third line contains n integers bi (0 ≤ bi ≤ 109).
Output
Print a single integer — the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n.
Examples
Input
5
1 2 4 3 2
2 3 3 12 1
Output
22
Input
10
13 2 7 11 8 4 9 8 5 1
5 7 18 9 2 3 0 11 8 6
Output
46
Note
Bitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation.
In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5.
In the second sample, the maximum value is obtained for l = 1 and r = 9.
|
#include <bits/stdc++.h>
using namespace std;
vector<int> a, b;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a.push_back(x);
}
for (int i = 0; i < n; i++) {
int x;
cin >> x;
b.push_back(x);
}
int ret = 0;
for (int i = 0; i < n; i++) {
int aa = a[i];
int bb = b[i];
ret = max(aa + bb, ret);
for (int j = i + 1; j < n; j++) {
aa = aa | a[j];
bb = bb | b[j];
ret = max(aa + bb, ret);
}
}
cout << ret << endl;
return 0;
}
|
As you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the name of the house the student should enter.
At that the Hat is believed to base its considerations on the student's personal qualities: it sends the brave and noble ones to Gryffindor, the smart and shrewd ones — to Ravenclaw, the persistent and honest ones — to Hufflepuff and the clever and cunning ones — to Slytherin. However, a first year student Hermione Granger got very concerned about the forthcoming sorting. She studied all the literature on the Sorting Hat and came to the conclusion that it is much simpler than that. If the relatives of the student have already studied at Hogwarts, the hat puts the student to the same house, where his family used to study. In controversial situations, when the relatives studied in different houses or when they were all Muggles like Hermione's parents, then the Hat sorts the student to the house, to which the least number of first years has been sent at that moment. If there are several such houses, the choice is given to the student himself. Then the student can choose any of the houses, to which the least number of first years has been sent so far.
Hermione has already asked the students that are on the list before her about their relatives. Now she and her new friends Harry Potter and Ron Weasley want to find out into what house the Hat will put Hermione.
Input
The first input line contains an integer n (1 ≤ n ≤ 10000). It is the number of students who are in the list before Hermione. The next line contains n symbols. If all the relatives of a student used to study in the same house, then the i-th character in the string coincides with the first letter of the name of this house. Otherwise, the i-th symbol is equal to "?".
Output
Print all the possible houses where Hermione can be sent. The names of the houses should be printed in the alphabetical order, one per line.
Examples
Input
11
G????SS???H
Output
Gryffindor
Ravenclaw
Input
2
H?
Output
Gryffindor
Ravenclaw
Slytherin
Note
Consider the second example. There are only two students before Hermione. The first student is sent to Hufflepuff. The second disciple is given the choice between the houses where the least number of students has been sent, i.e. Gryffindor, Slytherin and Ravenclaw. If he chooses Gryffindor, Hermione is forced to choose between Ravenclaw and Slytherin, if he chooses Ravenclaw, Hermione will choose between Gryffindor and Slytherin, if he chooses Slytherin, Hermione will choose between Gryffindor and Ravenclaw. In the end, the following situation is possible (it depends on the choice of the second student and Hermione). Hermione will end up 1) in Gryffindor, 2) in Ravenclaw, 3) in Slytherin. Note that, despite the fact that in neither case Hermione will be given a choice between all the three options, they are all possible and they should all be printed in the answer. Hermione will not, under any circumstances, end up in Hufflepuff.
|
import java.util.*;
import java.math.*;
import static java.lang.Character.isDigit;
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Character.isDigit;
public class Main{
static void debug(Object...os){
System.err.println(deepToString(os));
}
void run(){
n=nextInt();
cs=next().toCharArray();
int res=solve();
for(int i=0;i<4;i++){
if((res>>i&1)==1){
System.out.println(SS[i]);
}
}
}
int n;
char[] cs;
String[] SS={"Gryffindor","Hufflepuff","Ravenclaw","Slytherin"};
String S="GHRS";
class Array{
int[] is;
Array(int[] is){
this.is=is;
}
public int hashCode(){
return Arrays.hashCode(is);
}
public boolean equals(Object obj){
Array other=(Array)obj;
if(!Arrays.equals(is,other.is)) return false;
return true;
}
}
int solve(){
Array init=new Array(new int[4]);
HashSet<Array>[] sets=new HashSet[2];
for(int i=0;i<2;i++)
sets[i]=new HashSet<Array>();
sets[0].add(init);
for(int i=0;i<n;i++){
int cur=i%2,nxt=(i+1)%2;
sets[nxt].clear();
for(Array a:sets[cur]){
if(cs[i]=='?'){
int min=Integer.MAX_VALUE;
for(int j=0;j<4;j++)
min=min(min,a.is[j]);
for(int j=0;j<4;j++)
if(a.is[j]==min){
int[] is=a.is.clone();
is[j]++;
sets[nxt].add(new Array(is));
}
}else {
int[] is = a.is.clone();
is[S.indexOf(cs[i])]++;
sets[nxt].add(new Array(is));
}
}
}
int res=0;
for(Array a:sets[n%2]){
int min=Integer.MAX_VALUE;
for(int j=0;j<4;j++)
min=min(min,a.is[j]);
for(int j=0;j<4;j++)
if(a.is[j]==min){
res|=1<<j;
}
}
return res;
}
int nextInt(){
try{
int c=System.in.read();
if(c==-1) return c;
while(c!='-'&&(c<'0'||'9'<c)){
c=System.in.read();
if(c==-1) return c;
}
if(c=='-') return -nextInt();
int res=0;
do{
res*=10;
res+=c-'0';
c=System.in.read();
}while('0'<=c&&c<='9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c=System.in.read();
if(c==-1) return -1;
while(c!='-'&&(c<'0'||'9'<c)){
c=System.in.read();
if(c==-1) return -1;
}
if(c=='-') return -nextLong();
long res=0;
do{
res*=10;
res+=c-'0';
c=System.in.read();
}while('0'<=c&&c<='9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res=new StringBuilder("");
int c=System.in.read();
while(Character.isWhitespace(c))
c=System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res=new StringBuilder("");
int c=System.in.read();
while(c=='\r'||c=='\n')
c=System.in.read();
do{
res.append((char)c);
c=System.in.read();
}while(c!='\r'&&c!='\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new Main().run();
}
}
|
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.
Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink.
The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop.
The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink.
Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
Output
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
Example
Input
5
3 10 8 6 11
4
1
10
3
11
Output
0
4
1
5
Note
On the first day, Vasiliy won't be able to buy a drink in any of the shops.
On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.
On the third day, Vasiliy can buy a drink only in the shop number 1.
Finally, on the last day Vasiliy can buy a drink in any shop.
|
def binary(t,s):
fir=0
last=len(t)-1
mid=0
while(fir<=last):
mid=(fir+last)//2
if t[mid]>s:
last=mid-1
else:
fir=mid+1
return last+1
n=int(input())
t=list(map(int,input().split()))
m=int(input())
p=0
t.sort()
for i in range(m):
s=int(input())
print(binary(t,s))
|
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.
Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").
Galya has already made k shots, all of them were misses.
Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.
It is guaranteed that there is at least one valid ships placement.
Input
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made.
The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
Output
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.
In the second line print the cells Galya should shoot at.
Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left.
If there are multiple answers, you can print any of them.
Examples
Input
5 1 2 1
00100
Output
2
4 2
Input
13 3 2 3
1000000010001
Output
2
7 11
Note
There is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
|
#include <bits/stdc++.h>
using namespace std;
void scanint(long long int &x);
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int n, a, b, k;
cin >> n >> a >> b >> k;
long long int i = 0;
string s;
cin >> s;
long long int pre = -1;
long long int total = 0;
for (i = 0; i < n; i++) {
if (s[i] - '0') {
total += (i - pre - 1) / b;
pre = i;
}
}
total += (n - pre - 1) / b;
cout << total - a + 1 << endl;
long long int m = 0;
for (i = 0; i < n && total >= a; i++) {
if (s[i] - '0' == 0) {
m++;
if (m == b) cout << i + 1 << " ", m = 0, total--;
} else {
m = 0;
}
}
return 0;
}
void scanint(long long int &x) {
register int c = getchar();
x = 0;
int neg = 0;
for (; ((c < 48 || c > 57) && c != '-'); c = getchar())
;
if (c == '-') {
neg = 1;
c = getchar();
}
for (; c > 47 && c < 58; c = getchar()) {
x = (x << 1) + (x << 3) + c - 48;
}
if (neg) x = -x;
}
|
You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally:
1. Pick a random segment (continuous subsequence) from l to r. All <image> segments are equiprobable.
2. Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1, p2, ..., pk. All k! permutation are equiprobable.
3. This permutation is applied to elements of the chosen segment, i.e. permutation a1, a2, ..., al - 1, al, al + 1, ..., ar - 1, ar, ar + 1, ..., an is transformed to a1, a2, ..., al - 1, al - 1 + p1, al - 1 + p2, ..., al - 1 + pk - 1, al - 1 + pk, ar + 1, ..., an.
Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and ai > aj. Find the expected number of inversions after we apply exactly one operation mentioned above.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the length of the permutation.
The second line contains n distinct integers from 1 to n — elements of the permutation.
Output
Print one real value — the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 9.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Example
Input
3
2 3 1
Output
1.916666666666666666666666666667
|
#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
template <class T, class U>
inline void Max(T &a, U b) {
if (a < b) a = b;
}
template <class T, class U>
inline void Min(T &a, U b) {
if (a > b) a = b;
}
inline void add(int &a, int b) {
a += b;
while (a >= 1000000007) a -= 1000000007;
}
int pow(int a, int b) {
int ans = 1;
while (b) {
if (b & 1) ans = ans * (long long)a % 1000000007;
a = (long long)a * a % 1000000007;
b >>= 1;
}
return ans;
}
long long f[1000010];
int h[1000010];
void upd(int first, int v) {
while (first < 1000010) f[first] += v, h[first]++, first += first & -first;
}
pair<long long, long long> query(int first) {
long long ans = 0, res = 0;
while (first > 0) ans += f[first], res += h[first], first -= first & -first;
return {ans, res};
}
int a[1000010];
int main() {
int T, i, j, k, ca = 0, m = 0, n, K = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
long long p1, p2, sum = 0;
double tot = 1LL * n * (n + 1) / 2, ans = 0;
for (int i = 0; i < n; i++) {
if (i) {
pair<long long, long long> res = query(a[i]);
p2 = res.first, K = res.second;
p1 = sum - p2;
K = i - K;
ans += K + (p2 - p1) / tot * (n - i) / 2;
}
upd(a[i], i + 1);
sum += i + 1;
}
printf("%.9lf\n", ans);
return 0;
}
|
You are given n integers a1, a2, ..., an. Denote this list of integers as T.
Let f(L) be a function that takes in a non-empty list of integers L.
The function will output another integer as follows:
* First, all integers in L are padded with leading zeros so they are all the same length as the maximum length number in L.
* We will construct a string where the i-th character is the minimum of the i-th character in padded input numbers.
* The output is the number representing the string interpreted in base 10.
For example f(10, 9) = 0, f(123, 321) = 121, f(530, 932, 81) = 30.
Define the function
<image> Here, <image> denotes a subsequence.
In other words, G(x) is the sum of squares of sum of elements of nonempty subsequences of T that evaluate to x when plugged into f modulo 1 000 000 007, then multiplied by x. The last multiplication is not modded.
You would like to compute G(0), G(1), ..., G(999 999). To reduce the output size, print the value <image>, where <image> denotes the bitwise XOR operator.
Input
The first line contains the integer n (1 ≤ n ≤ 1 000 000) — the size of list T.
The next line contains n space-separated integers, a1, a2, ..., an (0 ≤ ai ≤ 999 999) — the elements of the list.
Output
Output a single integer, the answer to the problem.
Examples
Input
3
123 321 555
Output
292711924
Input
1
999999
Output
997992010006992
Input
10
1 1 1 1 1 1 1 1 1 1
Output
28160
Note
For the first sample, the nonzero values of G are G(121) = 144 611 577, G(123) = 58 401 999, G(321) = 279 403 857, G(555) = 170 953 875. The bitwise XOR of these numbers is equal to 292 711 924.
For example, <image>, since the subsequences [123] and [123, 555] evaluate to 123 when plugged into f.
For the second sample, we have <image>
For the last sample, we have <image>, where <image> is the binomial coefficient.
|
#include <bits/stdc++.h>
using namespace std;
const int maxn(1e6 + 5);
const int mod(1e9 + 7);
inline void Inc(int &x, int y) { x = x + y >= mod ? x + y - mod : x + y; }
inline int Add(int x, int y) { return x + y >= mod ? x + y - mod : x + y; }
inline void Dec(int &x, int y) { x = x - y < 0 ? x - y + mod : x - y; }
inline int Sub(int x, int y) { return x - y < 0 ? x - y + mod : x - y; }
int n, val[maxn], mx, cnt[maxn], val1[maxn], val2[maxn], pw[maxn];
int pw10[10] = {1, 10, 100, 1000, 10000, 100000, 1000000};
long long ans;
int main() {
int i, j, s, nxt;
scanf("%d", &n);
for (i = 1; i <= n; ++i) scanf("%d", &val[i]), mx = max(mx, val[i]);
for (pw[0] = i = 1; i <= n; ++i) pw[i] = Add(pw[i - 1], pw[i - 1]);
for (i = 1; i <= n; ++i)
Inc(val1[val[i]], val[i]), ++cnt[val[i]],
Inc(val2[val[i]], (long long)val[i] * val[i] % mod);
for (j = 1; j <= 6; ++j)
for (i = mx; ~i; --i) {
if (i / pw10[j - 1] % 10 == 9) continue;
nxt = i + pw10[j - 1];
Inc(val1[i], val1[nxt]), Inc(val2[i], val2[nxt]), Inc(cnt[i], cnt[nxt]);
}
for (i = 0; i <= mx; ++i)
if (cnt[i]) {
val1[i] = (long long)val1[i] * val1[i] % mod;
Dec(val1[i], val2[i]);
if (cnt[i] > 1)
val1[i] = (long long)val1[i] * pw[cnt[i] - 2] % mod;
else
val1[i] = 0;
val2[i] = (long long)val2[i] * pw[cnt[i] - 1] % mod;
Inc(val1[i], val2[i]);
}
for (j = 1; j <= 6; ++j)
for (i = 0; i <= mx; ++i) {
if (i / pw10[j - 1] % 10 == 9) continue;
nxt = i + pw10[j - 1], Dec(val1[i], val1[nxt]);
}
for (i = 0; i <= mx; ++i) ans ^= (long long)val1[i] * i;
printf("%lld\n", ans);
return 0;
}
|
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int v[N], lson[N], rson[N], used[N], l[N], r[N];
set<int> s;
void dfs(int x) {
if (~lson[x]) {
l[lson[x]] = l[x];
r[lson[x]] = min(r[x], v[x]);
dfs(lson[x]);
}
if (~rson[x]) {
l[rson[x]] = max(l[x], v[x]);
r[rson[x]] = r[x];
dfs(rson[x]);
}
}
int main() {
int n, root, ans;
scanf("%d", &n);
memset(used, 0, sizeof(used));
for (int i = 1; i <= n; i++) {
scanf("%d %d %d", &v[i], &lson[i], &rson[i]);
if (~lson[i]) used[lson[i]] = 1;
if (~rson[i]) used[rson[i]] = 1;
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
root = i;
break;
}
}
l[root] = 0;
r[root] = 1e9;
dfs(root);
ans = 0;
for (int i = 1; i <= n; i++) {
if (v[i] >= l[i] && v[i] <= r[i]) s.insert(v[i]);
}
for (int i = 1; i <= n; i++) {
if (!s.count(v[i])) ans++;
}
printf("%d\n", ans);
return 0;
}
|
You are given a set of integer numbers, initially it is empty. You should perform n queries.
There are three different types of queries:
* 1 l r — Add all missing numbers from the interval [l, r]
* 2 l r — Remove all present numbers from the interval [l, r]
* 3 l r — Invert the interval [l, r] — add all missing and remove all present numbers from the interval [l, r]
After each query you should output MEX of the set — the smallest positive (MEX ≥ 1) integer number which is not presented in the set.
Input
The first line contains one integer number n (1 ≤ n ≤ 105).
Next n lines contain three integer numbers t, l, r (1 ≤ t ≤ 3, 1 ≤ l ≤ r ≤ 1018) — type of the query, left and right bounds.
Output
Print MEX of the set after each query.
Examples
Input
3
1 3 4
3 1 6
2 1 3
Output
1
3
1
Input
4
1 1 3
3 5 6
2 4 4
3 1 6
Output
4
4
4
1
Note
Here are contents of the set after each query in the first example:
1. {3, 4} — the interval [3, 4] is added
2. {1, 2, 5, 6} — numbers {3, 4} from the interval [1, 6] got deleted and all the others are added
3. {5, 6} — numbers {1, 2} got deleted
|
#include <bits/stdc++.h>
using namespace std;
int seg[2 * (1 << 18)], segFlip[2 * (1 << 18)], l[2 * (1 << 18)],
r[2 * (1 << 18)], up[2 * (1 << 18)];
void init() {
for (int i = (1 << 18); i < 2 * (1 << 18); i++) {
l[i] = r[i] = i - (1 << 18);
seg[i] = 1000000000, segFlip[i] = i - (1 << 18);
}
for (int i = (1 << 18) - 1; i > 0; i--) {
l[i] = l[2 * i], r[i] = r[2 * i + 1];
seg[i] = 1000000000, segFlip[i] = l[i];
}
}
void push(int i) {
if (up[i]) {
if (up[i] == 1) {
seg[i] = l[i], segFlip[i] = 1000000000;
if (i < (1 << 18)) up[2 * i] = up[2 * i + 1] = 1;
} else if (up[i] == 2) {
seg[i] = 1000000000, segFlip[i] = l[i];
if (i < (1 << 18)) up[2 * i] = up[2 * i + 1] = 2;
} else {
swap(seg[i], segFlip[i]);
if (i < (1 << 18))
up[2 * i] = 3 - up[2 * i], up[2 * i + 1] = 3 - up[2 * i + 1];
}
up[i] = 0;
}
}
int low, high;
void update(int i, int v) {
push(i);
if ((l[i] > high) || (r[i] < low)) return;
if ((l[i] >= low) && (r[i] <= high)) {
up[i] = v;
push(i);
return;
}
update(2 * i, v);
update(2 * i + 1, v);
seg[i] = min(seg[2 * i], seg[2 * i + 1]);
segFlip[i] = min(segFlip[2 * i], segFlip[2 * i + 1]);
}
long long tp[100000], ql[100000], qr[100000];
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int Q;
cin >> Q;
vector<long long> lst;
for (int i = 0; i < Q; i++) {
cin >> tp[i] >> ql[i] >> qr[i];
lst.push_back(ql[i]);
lst.push_back(qr[i] + 1);
}
lst.push_back(1);
sort(lst.begin(), lst.end());
lst.resize(distance(lst.begin(), unique(lst.begin(), lst.end())));
init();
for (int i = 0; i < Q; i++) {
ql[i] = lower_bound(lst.begin(), lst.end(), ql[i]) - lst.begin();
qr[i] = lower_bound(lst.begin(), lst.end(), qr[i] + 1) - lst.begin();
low = ql[i], high = qr[i] - 1;
update(1, tp[i]);
cout << lst[segFlip[1]] << '\n';
}
}
|
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.
Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.
Every element of the sequence must appear in exactly one subsequence.
Input
The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence.
The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
Output
In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements.
In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence.
Indices could be printed in any order. Every index from 1 to n must appear in output exactly once.
If there are several possible answers, print any of them.
Examples
Input
6
3 2 1 6 5 4
Output
4
2 1 3
1 2
2 4 6
1 5
Input
6
83 -75 -49 11 37 62
Output
1
6 1 2 3 4 5 6
Note
In the first sample output:
After sorting the first subsequence we will get sequence 1 2 3 6 5 4.
Sorting the second subsequence changes nothing.
After sorting the third subsequence we will get sequence 1 2 3 4 5 6.
Sorting the last subsequence changes nothing.
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution1 {
public static void main(String[] args)
{
int n = i(),c=0;
TreeMap<Integer,Integer> tm = new TreeMap();
TreeMap<Integer,Integer> ts = new TreeMap();
int ar[] = new int[n];
StringBuilder ans = new StringBuilder();
ArrayList<Integer> aa = new ArrayList();
for(int i=0;i<n;i++) {ar[i]=i(); tm.put(ar[i],i);}
for(int i : tm.keySet()) ts.put(i,c++);
// System.out.print(tm+" "+ts);
int ct=0;
while(!tm.isEmpty())
{
ct++;
int val=0;
for(int i : tm.keySet()){val=i;break;}
while(tm.containsKey(val))
{
int in = tm.get(val);
aa.add(in);
tm.remove(val);
val = ar[ts.get(val)];
}
ans.append(aa.size()+" ");
for(int i : aa)
ans.append((i+1)+" ");
ans.append("\n");
aa.clear();
}
System.out.print(ct+"\n"+ans);
}
static Scanner sc = new Scanner(System.in);
static int i(){
return sc.nextInt();
}
}
|
Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug.
Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers:
* 1 li ri vi — for each x such that li ≤ x ≤ ri ax ≥ vi;
* 2 li ri vi — for each x such that li ≤ x ≤ ri ax ≤ vi.
Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows:
<image>, where cnt(i) is the number of occurences of i in the array.
Help Ivan to determine minimum possible cost of the array that corresponds to the facts!
Input
The first line contains two integer numbers n and q (1 ≤ n ≤ 50, 0 ≤ q ≤ 100).
Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n, 1 ≤ vi ≤ n, ti denotes the type of the fact).
Output
If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array.
Examples
Input
3 0
Output
3
Input
3 1
1 1 3 2
Output
5
Input
3 2
1 1 3 2
2 1 3 2
Output
9
Input
3 2
1 1 3 2
2 1 3 1
Output
-1
|
#include <bits/stdc++.h>
using namespace std;
bool print = 0;
struct Edge {
Edge() { x = y = c = f = w = 0; }
Edge(long long _x, long long _y, long long _c, long long _f, long long _w)
: x(_x), y(_y), c(_c), f(_f), w(_w) {}
long long x, y, c, f, w;
};
struct MinCostMaxFlow {
int n, m, idm = 0, s, t;
int totCost, totFlow, oo = int(1e9);
vector<Edge> EdgeList;
vector<int> dist;
vector<vector<int>> adj;
vector<int> trace;
MinCostMaxFlow() { n = 0; }
MinCostMaxFlow(int n) {
this->n = n;
adj.assign(n + 5, vector<int>(0, 0));
EdgeList.clear();
dist = vector<int>(n + 5);
trace = vector<int>(n + 5);
}
void addEdge(int u, int v, int c, int w) {
adj[u].push_back(EdgeList.size());
EdgeList.push_back(Edge(u, v, c, 0, w));
adj[v].push_back(EdgeList.size());
EdgeList.push_back(Edge(v, u, 0, 0, -w));
}
bool FordBellman(int s, int t) {
for (int i = 1; i <= n; ++i) dist[i] = oo, trace[i] = -1;
vector<bool> inq = vector<bool>(n + 5, false);
queue<int> q;
q.push(s);
inq[s] = true;
dist[s] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
inq[u] = false;
for (int id : adj[u])
if (EdgeList[id].c > EdgeList[id].f) {
int v = EdgeList[id].y;
Edge e = EdgeList[id];
int co = 0;
if (e.w == 1) co = (e.f + 1) * (e.f + 1) - (e.f) * (e.f);
if (co != 0)
if (print)
cerr << "Cost from " << e.x << " to " << e.y << " is " << co
<< " " << e.f + 1 << endl;
if (dist[v] > dist[u] + co) {
dist[v] = dist[u] + co;
trace[v] = id;
if (!inq[v]) {
q.push(v);
inq[v] = true;
}
}
}
}
return (dist[t] < oo);
}
void solve() {
totFlow = totCost = 0;
while (FordBellman(s, t)) {
long long delta = oo;
if (print) cerr << "Found path from s to t : ";
for (int u = t; u != s; u = EdgeList[trace[u]].x) {
if (print) cerr << u << " <- ";
delta = min(delta, EdgeList[trace[u]].c - EdgeList[trace[u]].f);
}
if (print) cerr << s << " with the cost " << dist[t] << endl;
for (int u = t; u != s; u = EdgeList[trace[u]].x) {
EdgeList[trace[u]].f += delta;
EdgeList[trace[u] ^ 1].f -= delta;
}
totCost += dist[t];
totFlow += delta;
}
}
};
const int N = 55, oo = 1e8 + 7;
int n, q, lwb[N], upb[N];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> q;
for (int i = 1; i <= n; ++i) upb[i] = n, lwb[i] = 1;
for (int i = 1; i <= q; ++i) {
int t, l, r, v;
cin >> t >> l >> r >> v;
if (t == 1) {
for (int j = l; j <= r; j++) lwb[j] = max(lwb[j], v);
} else {
for (int j = l; j <= r; ++j) upb[j] = min(upb[j], v);
}
}
for (int i = 1; i <= n; ++i)
if (print) cerr << "Upb[" << i << "] : " << upb[i] << endl;
for (int i = 1; i <= n; ++i)
if (lwb[i] > upb[i]) {
cout << -1;
return 0;
}
MinCostMaxFlow mcmf = MinCostMaxFlow(2 * n + 2);
mcmf.s = 2 * n + 1;
mcmf.t = mcmf.s + 1;
for (int i = 1; i <= n; ++i) {
mcmf.addEdge(n + i, mcmf.t, oo, 1);
mcmf.addEdge(mcmf.s, i, 1, 0);
for (int j = lwb[i]; j <= upb[i]; j++) {
mcmf.addEdge(i, n + j, 1, 0);
}
}
mcmf.solve();
if (mcmf.totFlow < n) {
cout << -1;
if (print) cerr << mcmf.totFlow << endl;
return 0;
} else
cout << mcmf.totCost << endl;
return 0;
}
|
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code:
int fast_max(int n, int a[]) {
int ans = 0;
int offset = 0;
for (int i = 0; i < n; ++i)
if (ans < a[i]) {
ans = a[i];
offset = 0;
} else {
offset = offset + 1;
if (offset == k)
return ans;
}
return ans;
}
That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer.
Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109 + 7.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 106), separated by a space — the length of the permutations and the parameter k.
Output
Output the answer to the problem modulo 109 + 7.
Examples
Input
5 2
Output
22
Input
5 3
Output
6
Input
6 3
Output
84
Note
Permutations from second example:
[4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5].
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const long long MOD = 1e9 + 7;
long long d[N], psum[N], fact[N], ifact[N], n, k, ans, tmp;
long long bigExp(long long a, long long b) {
long long res = 1;
while (b) {
if (b & 1) res = (res * a) % MOD;
a = (a * a) % MOD;
b >>= 1;
}
return res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
fact[0] = 1;
for (int i = 1; i <= n; i++) fact[i] = (fact[i - 1] * i) % MOD;
ifact[n] = bigExp(fact[n], MOD - 2);
for (int i = n - 1; i >= 0; i--) ifact[i] = (ifact[i + 1] * (i + 1)) % MOD;
assert(bigExp(fact[25], MOD - 2) == ifact[25]);
for (int i = k + 1; i <= n; i++) {
d[i] = ((i - k - 1) + (psum[i - 1] - psum[i - k - 1] + MOD)) % MOD;
d[i] = (d[i] * fact[i - 2]) % MOD;
psum[i] = (psum[i - 1] + d[i] * ifact[i - 1]) % MOD;
}
for (int i = 1; i <= n; i++) {
tmp = (d[i] * fact[n - 1]) % MOD;
tmp = (tmp * ifact[i - 1]) % MOD;
ans = (ans + tmp) % MOD;
}
cout << ans << "\n";
return 0;
}
|
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough.
Right now there are A yellow and B blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.
Input
The first line features two integers A and B (0 ≤ A, B ≤ 109), denoting the number of yellow and blue crystals respectively at Grisha's disposal.
The next line contains three integers x, y and z (0 ≤ x, y, z ≤ 109) — the respective amounts of yellow, green and blue balls to be obtained.
Output
Print a single integer — the minimum number of crystals that Grisha should acquire in addition.
Examples
Input
4 3
2 1 1
Output
2
Input
3 9
1 1 3
Output
1
Input
12345678 87654321
43043751 1000000000 53798715
Output
2147483648
Note
In the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue.
|
y,b=input().split(' ')
ay,ag,ab=input().split(' ')
y=int(y)
b=int(b)
ay=int(ay)
ag=int(ag)
ab=int(ab)
b=b-(ab*3)
y=y-(ay*2)
b=b-ag
y=y-ag
br=0
if(y<0):
br=br-y
if(b<0):
br=br-b
print(br)
|
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a1, a2, ..., an, and Banban's have brightness b1, b2, ..., bm respectively.
Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.
Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.
You are asked to find the brightness of the chosen pair if both of them choose optimally.
Input
The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50).
The second line contains n space-separated integers a1, a2, ..., an.
The third line contains m space-separated integers b1, b2, ..., bm.
All the integers range from - 109 to 109.
Output
Print a single integer — the brightness of the chosen pair.
Examples
Input
2 2
20 18
2 14
Output
252
Input
5 3
-1 0 1 2 3
-1 0 1
Output
2
Note
In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.
In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself.
|
n, m = [int(x) for x in input().split()]
lstT = [int(x) for x in input().split()]
lstB = [int(x) for x in input().split()]
z=-9999999999999999999999999999
T=0
B=0
for i in range(n):
for j in range(m):
if z<lstT[i]*lstB[j]:
T=i
B=j
z=lstT[i]*lstB[j]
lol = -99999999999999999999
for i in range(n):
for j in range(m):
if T!=i:
lol = max(lol, lstT[i]*lstB[j])
print(lol)
|
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it.
Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ d
Pikachu was finally left with X subsequences.
However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018.
Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1.
Input
The only line of input consists of two space separated integers X and d (1 ≤ X, d ≤ 109).
Output
Output should consist of two lines.
First line should contain a single integer n (1 ≤ n ≤ 10 000)— the number of integers in the final array.
Second line should consist of n space separated integers — a1, a2, ... , an (1 ≤ ai < 1018).
If there is no answer, print a single integer -1. If there are multiple answers, print any of them.
Examples
Input
10 5
Output
6
5 50 7 15 6 100
Input
4 2
Output
4
10 100 1000 10000
Note
In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid.
Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
|
#include <bits/stdc++.h>
using namespace std;
int x, d, i;
vector<long long> v;
long long temp = 1;
long long po(int power) {
long long ans = 1;
for (int j = 0; j < power; j++) ans *= 2;
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin >> x >> d;
while (x > 0) {
if (x == 1) {
v.push_back(temp);
break;
}
int ln = floor(log2(x));
x -= (po(ln) - 1);
for (i = 0; i < ln; i++) v.push_back(temp);
temp += d;
}
cout << v.size() << "\n";
cout << v[0];
for (i = 1; i < v.size(); i++) cout << " " << v[i];
return 0;
}
|
You are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Count the number of connected components in that graph.
Input
In the first line of input there are two integers n and m (0 ≤ n ≤ 22, 1 ≤ m ≤ 2^{n}).
In the second line there are m integers a_1, a_2, …, a_m (0 ≤ a_{i} < 2^{n}) — the elements of the set. All a_{i} are distinct.
Output
Print the number of connected components.
Examples
Input
2 3
1 2 3
Output
2
Input
5 5
5 19 10 20 12
Output
2
Note
Graph from first sample:
<image>
Graph from second sample:
<image>
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000005;
using namespace std;
bool vis[5000000];
bool have[5000000];
int a[5000000];
int N, M, MASK;
void dfs(int u) {
vis[u] = 1;
if (!vis[u ^ MASK] && have[u]) dfs(u ^ MASK);
for (int i = 0; i < N; i++) {
if (u & (1 << i)) {
if (!vis[u ^ (1 << i)]) dfs(u ^ (1 << i));
}
}
}
int main() {
scanf("%d%d", &N, &M);
MASK = (1 << N) - 1;
for (int i = 0; i < M; i++) {
scanf("%d", &a[i]);
have[a[i]] = 1;
}
int cnt = 0;
for (int i = 0; i < M; i++) {
if (!vis[a[i]]) {
cnt++;
dfs(a[i]);
}
}
cout << cnt << endl;
return 0;
}
|
Alook was composing magical spells for his mage master. The mage was good at spellcasting but since spell design requires intricate mathematics, this task was given to Alook who had the gift of numbers.
The power contained in a spell is a function of its lexicographical structure, which is why Alook wants to extensively test spells of difference lexicographical structures.
Spells are composed of 2 types of lexemes : long and short; a short lexeme is one phoneme long while a long lexeme is two phonemes long. A third special type of lexeme of length 2 phonemes can be used only at the beginning of a spell.
Additionally, each phoneme can be uttered in two ways :in a 'high' or a 'low' note.
There are still, however only 2 types of lexemes and not 6 as lexemes are characterized only on the basis of their length and not their constituent phonemes. Phonemes are spoken while lexemes are written. Lexemes enforce a substructure on phonemes, but phonemes do not enforce any structure on lexemes.
Every day, Alook writes down spells of all possible lexicographical structures, upto n phonemes in length. His master utters all possible phonetic variations of every written spell to service his oral fixation. Given n, you have to tell how many phonetically different spells the mage casts.
Read about lexeme here : Lexeme
Read abour phoneme here : Phoneme
[Input]
First line contains and integer t denoting number of test cases.
Each test consists of single line containing integer n denoting length.
[Output]
For each test case output single line denoting ans.
NOTE: As ans can be large output the ans by taking mod with 10^9 + 7.
[Constraints]
1 ≤ t ≤ 100
1 ≤ n ≤ 1000000000
SAMPLE INPUT
2
1
2
SAMPLE OUTPUT
2
14
Explanation
for n=1
No. of lexicographically different spells of length 1 : 1 {S}
No. of phonetic variations : 2 {H,L} where H denotes High and L denotes Low
Therefore total no.of different spells = 1*2 = 2
|
def matmult(a,b,c,M):
#/multiply matrix a and b. put result in c
for i in xrange(2):
for j in xrange(2):
c[i][j]=0
for k in xrange(2):
c[i][j]+=(a[i][k]*b[k][j])
c[i][j]=c[i][j]%M
def matpow(Z,n,ans,M):
#find ( Z^n )% M and return result in ans
temp=[[0,0],[0,0]]
#assign ans= the identity matrix
ans[0][0]=1
ans[1][0]=0
ans[0][1]=0
ans[1][1]=1
while(n>0):
if(n&1):
matmult(ans,Z,temp,M)
for i in xrange(2):
for j in xrange(2):
ans[i][j]=temp[i][j]
matmult(Z,Z,temp,M)
for i in xrange(2):
for j in xrange(2):
Z[i][j]=temp[i][j]
n=n/2
def findFibonacci(n,M):
fib=0
ini = [0,2,12]
if(n>2):
n+=2
Z=[[2,4],[1,0]]
result=[[0,0],[0,0]]
#modify matrix a[][] for other recurrence relations
matpow(Z,n-2,result,M)
#fib2=((result[0][0]*ini[2])%M + (result[0][1]*ini[1])%M)%M
#fib1=((result[1][0]*ini[2])%M + (result[1][1]*ini[1])%M)%M
#final multiplication of Z^(n-2) with the initial terms of the series
fib2 = result[0][0]*ini[2] + result[0][1]*ini[1]
fib1 = result[1][0]*ini[2] + result[1][1]*ini[1]
x = 400000003
fib = (((fib2-fib1-ini[2]+ini[1])%M)*x)%M
else:
fib=ini[n]+ini[n-1]
return fib%M
def findFibonacci2(n,M):
fib=0
ini = [0,2,12]
if(n>2):
#n+=2
Z=[[2,4],[1,0]]
result=[[0,0],[0,0]]
#modify matrix a[][] for other recurrence relations
matpow(Z,n-2,result,M)
fib=((result[0][0]*ini[2])%M + (result[0][1]*ini[1])%M)%M
#fib1=((result[1][0]*ini[2])%M + (result[1][1]*ini[1])%M)%M
#final multiplication of Z^(n-2) with the initial terms of the series
#fib = ((fib2-fib1-ini[2]+ini[1])%M)5/
else:
fib=ini[n]
return fib
def main():
M = 1000000007
for _ in xrange(int(raw_input())):
n=int(raw_input())
#ans =0
#for i in xrange(1,n+1):
# ans = (ans + findFibonacci2(i,M))%M
print findFibonacci(n,M)
main()
|
You are given a collection of words, say as in a dictionary.
You can represent it in the following compressed form:
The first word will be followed by a sequence of pair of a integer (x) and a word.
The number in the pair is the position till which the previous word's characters are included in the new word
and the tail is the remaining trailing word which is the different than the previous word.
Example:
Suppose successive words in our dictionary are:
color
comma
commatose
dot
Then we can compress it in the following way:
color
2 mma (to denote that first two characters are same as that of 'color' and remaining string is 'mma')
5 tose (to denote that the first five characters are same as that of 'comma' and remaining string is 'tose')
0 dot (to denote that zero characters are same as that of 'commatose' and the remaining string is 'dot')
INPUT :
First line contains the integer 'N' denoting the number of words in the dictionary.
Second line would contain the first word.
It will be followed by 'N-1' lines each containing an integer (x) and a trailing string.
Note: The input is designed such that the integer (x) will always be ≤ size of previous word formed.
OUTPUT :
Output a single string that is the last resulting word of the given dictionary.
Constraints
1 ≤ N ≤ 1000
1 ≤ Length of all string that will appear in input file ≤50
SAMPLE INPUT
4
zebra
3 u
2 nith
1 iggurat
SAMPLE OUTPUT
ziggurat
Explanation
The dictionary actually is:
zebra
zebu (3 first characters are common with zebra)
zenith (2 first characters are common with zebu)
zggurat (1 first character is common with zenith)
|
N=input(); Q=raw_input();
for _ in xrange(N-1):
n,s=raw_input().split(); m=int(n);
temp=Q[:m]; temp+=s; Q=temp;
print Q
|
Bosky often helps his younger brother Nitin with his home work and also clears his doubts.
Today, Nitin learned about proper fractions. He went a step forward and tried to represent the same proper fraction in its decimal form, but runs into problems. He now seeks help from his brother Bosky.
Nitin is a very sincere learner, thus he wants his brother to help him but doesn't want him to completely solve the problem. He goes to his brother Bosky and asks him to help him wherever he gets stuck while representing the proper fraction in decimal expansion by telling the next digit in the decimal expansion.
Though Bosky is a bit busy today with his school project, he doesn't want to disappoint his brother. He is familiar with your brilliant programming skills and asks you to create a program to help his brother, which can output R th digit in the decimal expansion for a given proper fraction \frac{N}{D}.
Input:
Input will contain a number T denoting the number of test cases.
Then T test cases follow, each one consisting 3 integers N D R
where N and D are numerator and denominator respectively.
Output
For each test case, output a single integer representing R th digit from the left in the decimal expansion.
NOTE: The number is a proper fraction, hence the counting will always start after the decimal place. For eg. fraction \frac{1}{2} can be written as 0.5 so its first digit is 5 and all the digits after 5 are 0.
Constraints
1 ≤ T ≤ 100
1 ≤ N ≤ D ≤ 1000000
1 ≤ R ≤ 1000000
SAMPLE INPUT
4
1 2 1
1 2 2
1 2 20
1234 12345 123
SAMPLE OUTPUT
5
0
0
7
Explanation
Case 1 : 1\; 2\; 1
\frac{1}{2} = 0.5 and 1st digit is 5.
Case 2 and 3:
\frac{1}{2} = 0.50000000000000000000
All digits after 5 are 0, hence the output is 0 and 0.
Case 4: Same logic!
|
def nth_digit(a,b,c):
r=a
digit=0
for _ in xrange(c):
if r==0:
return 0
digit=(r*10)/b
r=(r*10)%b
return digit
for _ in xrange(input()):
temp=map(int,raw_input().split())
a,b,c=temp[0],temp[1],temp[2]
print nth_digit(a,b,c)
|
Andrew is very fond of Maths.He has N boxes with him,in each box there is some value which represents the Strength of the Box.The ith box has strength A[i].
He wants to calculate the Overall Power of the all N Boxes.
Overall Power here means Sum of Absolute Difference of the strengths of the boxes(between each pair of boxes) multiplied by the Maximum strength among N boxes.
Since the Overall Power could be a very large number,output the number modulus 10^9+7(1000000007).
Input
First line of the input contains the number of test cases T. It is followed by T test cases.
Each test case has 2 lines. First line contains the number of boxes N. It is followed by a line containing N elements where ith element is the strength of Andrew's ith box.
Output
For each test case, output a single number, which is the Overall Power for that testcase.
Constraints
1 ≤ T ≤ 10
2 ≤ N ≤ 10^5
0 ≤ A[i] ≤ 10^9
SAMPLE INPUT
2
2
1 2
5
4 5 3 1 2
SAMPLE OUTPUT
2
100
Explanation
For 1st test case sum of absolute difference between strength is 1.So Overall Power would be 2.
For 2nd test case sum of absolute difference between each pair of boxes is 20.So Overall Power is 100.
|
t = input()
while (t > 0):
n = input()
a = []
i = 0
line = raw_input().split(' ')
while(i < n) :
a.append(int(line[i]))
i = i+1
a.sort(reverse=True)
x = n-1
temp = 0
for i in range(0,n):
temp += x*a[i]
x -= 2
print (temp*a[0])%1000000007
t = t-1
|
After obtaining a lot of gold from capturing different kingdoms, King Kala buys a large area of land. N trees are planted on the land, numbered from 1 to N. Each tree i, has coordinates as Xi, Yi. King Kala has two sons who, as their father, are selfish. To divide the land between two sons, King Kala draws a partition line on the land which is given by three coefficients of the line equation A, B and C. Now, Prince Parmar, being the elder son got a chance to pick any one side. But he wants the side of the partition which contains the maximum number of trees. How many trees can he get?
Input
The first line contains the number of test cases T. In each test case, the first line contains N. The next line contains three space separated integers A, B and C. The next N lines contain Xi, Yi which are the co-ordinates of N trees.
Output
For each test case, print the maximum number of trees which are completely on one side of the partition line.
Constraints
1 ≤ T ≤10
1 ≤ N ≤ 10^5
-100 ≤ A,B ≤ 100
-10^5 ≤ C, Xi, Yi ≤ 10^5
SAMPLE INPUT
1
4
1 -1 0
2 1
1 3
4 2
3 3
SAMPLE OUTPUT
2
|
t=input()
count=0
count1=0
while (t):
n=input()
d=map(int,raw_input().strip().split(' '))
a=d[0]
b=d[1]
c=d[2]
for i in range (n):
x,y=raw_input().strip().split(' ')
x,y=[int(x),int(y)]
w=a*x+b*y+c
if(w>0):
count=count+1
elif(w==0):
count1=count1+1
if(n-count1-count>count):
print n-count1-count
else:
print count
count=0
count1=0
t=t-1
|
You have been given a String S consisting of uppercase and lowercase English alphabets. You need to change the case of each alphabet in this String. That is, all the uppercase letters should be converted to lowercase and all the lowercase letters should be converted to uppercase. You need to then print the resultant String to output.
Input Format
The first and only line of input contains the String S
Output Format
Print the resultant String on a single line.
Constraints
1 ≤ |S| ≤ 100 where |S| denotes the length of string S.
SAMPLE INPUT
abcdE
SAMPLE OUTPUT
ABCDe
|
a=raw_input()
res=[]
for i in a:
if ord(i)>=65 and ord(i)<=90:
res.append(chr(ord(i)+32))
else:
res.append(chr(ord(i)-32))
print "".join(res)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.