contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
sequencelengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
/*CPPCode*/
using namespace std;
#define ll long long
#define mod 1000000007
#define vi vector<int>
#define vvi vector<vector<int>>
#define vc vector<char>
#define vs vector<string>
#define vpi vector<pair<int,int>>
#define pi pair<int,int>
#define ff first
#define ss second
#define int long long int
#define endl "\n"
#define uii unordered_map<int,int>
#define rep(i,s,l) for(int i=s;i<l;i++)
#define all(x) begin(x), end(x)
void input(vi &v){rep(i,0,v.size())cin>>v[i];}
#define maxn 10007
int fact[maxn], ifact[maxn];
int mpow(int a,int b) {
int res = 1;
while(b) {
if(b&1) res *= a, res %= mod;
a *= a;
a %= mod;
b >>= 1;
}
return res;
}
void pre() {
fact[0] = fact[1] = ifact[0] = ifact[1] = 1;
for(int i = 2; i < maxn; i++) fact[i] = fact[i - 1]*i, fact[i] %= mod;
for(int i = 2; i < maxn; i++) ifact[i] = ifact[i - 1]*mpow(i, mod - 2), ifact[i] %= mod;
}
int comb(int a,int b) {
if(b == 0) return 1LL;
int ans = fact[a];
ans *= ifact[b];
ans %= mod;
ans *= ifact[a - b];
ans %= mod;
return ans;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin>>n;
uii m;
int ans=0;
rep(i,0,n){
int x;
cin>>x;
m[x-i]+=x;
ans=max(m[x-i],ans);
}
cout<<ans<<endl;
return 0;
}
| cpp |
1322 | E | E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5
1 2 1 2 1
OutputCopy2
1 1 1 1 1
InputCopy6
1 3 2 5 4 6
OutputCopy1
1 2 3 4 5 6
InputCopy6
1 1 2 2 1 1
OutputCopy0
1 1 2 2 1 1
NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00. | [
"data structures"
] | #include<bits/stdc++.h>
#define eb emplace_back
#define ep emplace
static const int N = 500005;
int n, m, res;
int a[N], b[N], d[N], ans[N];
std::vector<int> c[N];
std::set<int> s1, s2;
void insert(int x) {
if (x > 1 && !d[x - 1]) s1.erase(x - 1); else s1.insert(x - 1);
if (x < n && !d[x + 1]) s1.erase(x); else s1.insert(x);
d[x] = 1;
}
void change(int l, int r, int x) {
auto it = s2.lower_bound(l);
while (it != s2.end() && *it <= r) {
ans[*it] = x;
s2.erase(it);
it = s2.lower_bound(l);
}
}
void update(int x, int y) {
auto it = s1.lower_bound(x);
int r = (*it), l = (*--it) + 1;
res = std::max(res, (r - l) / 2);
int mid = (l + r) >> 1;
if (d[l]) change(l, mid, y);
if (d[r]) change(mid + 1, r, y);
}
signed main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%d", a + i);
for (int i = 1; i <= n; ++i) b[i] = a[i];
std::sort(b + 1, b + n + 1);
m = std::unique(b + 1, b + n + 1) - b - 1;
for (int i = 1; i <= n; ++i) a[i] = std::lower_bound(b + 1, b + m + 1, a[i]) - b;
for (int i = 1; i <= n; ++i) c[a[i]].eb(i);
for (int i = 0; i <= n; ++i) s1.ep(i);
for (int i = 1; i <= n; ++i) s2.ep(i);
for (int i = 1; i <= m; ++i) {
for (int j : c[i]) insert(j);
for (int j : c[i]) {
update(j, i);
if (j > 1) update(j - 1, i);
if (j < n) update(j + 1, i);
}
}
printf("%d\n", res);
for (int i = 1; i <= n; ++i) printf("%d ", b[ans[i]]);
return 0;
} | cpp |
1288 | E | E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] | [
"data structures"
] | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
//#include<boost/algorithm/string.hpp>
//pragmas
#pragma GCC optimize("O3")
//types
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define ll long long int
#define ull unsigned long long int
#define vec vector<long long int>
#define pall pair<long long int, long long int>
#define vecpair vector<pair<long long int,long long int>>
#define vecvec(a, i, j) vector<vector<long long int>> a (i, vec (j, 0))
#define vecvecvec(a, i, j, k) vector<vector<vector<long long int>>> dp (i + 1, vector<vector<long long int>>(j + 1, vector<long long int>(k + 1, 0)))
using namespace std;
using namespace __gnu_pbds;
//random stuff
#define all(a) a.begin(),a.end()
#define read(a) for (auto &x : a) cin >> x
#define endl "\n"
#define pb push_back
#define print(a) for(auto x : a) cout << x << " "; cout << endl
#define sz(x) x.size()
#define F first
#define S second
#define sp " "
const ll INF = 9223372036854775807, mod = 1e9 + 7;
int inf = 0x3f3f3f3f;
typedef tree<long long int, null_type, less<long long int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
#define safe_map unordered_map<long long, int, custom_hash>
//debug
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#define reach cerr<<"reached"<<endl
#else
#define debug(x...)
#define reach
#endif
/*---------------------------------------------------------------------------------------------------------------------------*/
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3
ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b
ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}
bool revsort(ll a, ll b) {return a > b;}
void swap(int &x, int &y) {int temp = x; x = y; y = temp;}
ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}
void google(int t) {cout << "Case #" << t << ": ";}
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (ll j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
ll mod_add(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mod_mul(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll mod_sub(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mod_div(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m
ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))
void precision(int a) {cout << setprecision(a) << fixed;}
ll ceil_div(ll x, ll y){return (x + y - 1) / y;}
unsigned long long power(unsigned long long x,ll y, ll p){unsigned long long res = 1;x = x % p; while (y > 0){if (y & 1)res = (res * x) % p;y = y >> 1;x = (x * x) % p;}return res;}
unsigned long long modInverse(unsigned long long n,int p){return power(n, p - 2, p);}
ll nCr(ll n,ll r, ll p){if (n < r)return 0;if (r == 0)return 1;unsigned long long fac[n + 1];fac[0] = 1;for (int i = 1; i <= n; i++)fac[i] = (fac[i - 1] * i) % p;return (fac[n] * modInverse(fac[r], p) % p* modInverse(fac[n - r], p) % p)% p;}
ll accumulate(const vec &nums){ll sum = 0; for(auto x : nums) sum += x; return sum;}
ll tmax(ll a, ll b, ll c = 0, ll d = -INF, ll e = -INF, ll f = -INF){return max(a, max(b, max(c, max(d, max(e, f)))));}
int log2_floor(unsigned long long i) {return i ? __builtin_clzll(1) - __builtin_clzll(i) : -1;}
string bin(ll n){return bitset<32>(n).to_string();}
/*--------------------------------------------------------------------------------------------------------------------------*/
const ll MAXN = 3 * 1e5 + 1;
int n, m, ai;
vector<int> q, mn(MAXN, inf), mx(MAXN, -inf), ans;
vector<bool> ms(MAXN, false);
vector<pair<int, int>> queries;
vector<vector<int>> ind(MAXN);
bool compare(pair<pair<int, int>, int>& a, pair<pair<int, int>, int>& b){
return a.F.S < b.F.S;
}
void update(int index, vector<int>& bit, int value){
for(; index < sz(bit); index += (index & (-index))){
bit[index] += value;
}
}
int query(int index, vector<int>& bit){
int sum = 0;
for(; index > 0; index -= (index & (-index))){
sum += bit[index];
}
return sum;
}
vector<int> distinctQueries(int n, int q, vector<int>& arr, vector<pair<int, int>>& queries){
map<int, int> compreSion;
int prev = 0;
for(auto &i : arr){
if(compreSion.find(i) == compreSion.end()){
compreSion[i] = prev;
prev++;
}
i = compreSion[i];
}
vector<int> lastIndex(sz(compreSion), -1);
vector<pair<pair<int, int>, int>> tempQueries(q);
for(int i = 0; i < q; i++){
tempQueries[i].F.F = queries[i].F + 1;
tempQueries[i].F.S = queries[i].S + 1;
tempQueries[i].S = i;
}
vector<int> ans(q);
sort(all(tempQueries), compare);
int num = 0;
vector<int> bit(n + 1);
for(int i = 0; i < n; i++){
if(lastIndex[arr[i]] != -1){
update(lastIndex[arr[i]] + 1, bit, -1);
}
lastIndex[arr[i]] = i;
update(i + 1, bit, 1);
while(num < q && tempQueries[num].F.S == i + 1){
int index = tempQueries[num].S;
ans[index] = query(i + 1, bit) - query(tempQueries[num].F.F - 1, bit);
num++;
}
}
return ans;
}
//code starts
int main()
{
fastio();
cin >> n >> m;
for(int i = n; i >= 1; i --) q.pb(i), mn[i] = i, mx[i] = i;
for(int i = 1; i <= m; i ++) cin >> ai, q.pb(ai), mn[ai] = 1;
reverse(all(q));
for(int i = 0; i < n; i ++) ind[i].pb(0);
for(int i = 0; i < n + m; i ++) ind[q[i]].pb(i);
for(int i = 1; i <= n; i++) for(ll j = 0; j < ind[i].size() - 1; j ++) queries.pb({ind[i][j], ind[i][j + 1]});
ans = distinctQueries(n + m, queries.size(), q, queries);
for(int i = 1, qa = 0; i <= n; i ++)
{
for(int j = 0; j < ind[i].size() - 1; j ++, qa ++)
mx[i] = max(mx[i], ans[qa]);
cout << mn[i] << sp << mx[i] << endl;
}
}
// There is an idea of a Patrick Bateman. Some kind of abstraction.
// But there is no real me. Only an entity. Something illusory.
// And though I can hide my cold gaze, and you can shake my hand and
// feel flesh gripping yours, and maybe you can even sense our lifestyles
// are probably comparable, I simply am not there. | cpp |
13 | C | C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1 | [
"dp",
"sortings"
] | // Problem: Sequence
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF13C
// Memory Limit: 62 MB
// Time Limit: 1000 ms
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
using ll = long long;
const int MAX = 5E3 + 7;
ll n;
ll a[MAX], b[MAX];
ll S[MAX] = {1 << 30};
int main() {
cin >> n;
for (int i = 1; i<= n; i++) cin >> a[i], b[i] = a[i];
sort(b + 1, b + n + 1);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
S[j] += abs(a[i] - b[j]);
if (j > 1)
S[j] = min(S[j], S[j - 1]);
}
}
cout << S[n] << endl;
return 0;
}
| cpp |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
#include <iostream>
using namespace std;
#include <stack>
#include <vector>
#include <set>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
typedef long long int ll;
#define MAX 100001
#include <map>
const int MOD = 1e9 + 7;
const ll MaxVal = 2e18;
string PI = "314159265358979323846264338327";
map<ll, ll> freq;
vector<ll> power2;
vector<ll> pf;
vector<bool> prime(1000001, true);
int x[9] = {1, 1, 1, -1, -1, -1, 0, 0, 0};
int y[9] = {-1, 1, 0, -1, 1, 0, -1, 1, 0};
void solve(){
int n; cin >> n;
vector<int> v(n);
set<int> s;
for (int& x: v){
cin >> x;
s.insert(x);
}
cout << s.size() << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// for (ll q = 1;q<=MaxVal; q*=2){
// power2.push_back(q);
// }
// pf.resize(power2.size());
// pf[0] = power2[0];
// for (int i=1; i<power2.size(); i++) pf[i] = pf[i - 1] + power2[i];
int t;
// t = 1;
cin >> t;
while (t--) solve();
}
| cpp |
1316 | F | F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212. | [
"data structures",
"divide and conquer",
"probabilities"
] | ///Moba8ta gya mn el 2alb
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,fma")
#include "bits/stdc++.h"
using namespace std;
#define pb push_back
#define F first
#define S second
#define f(i, a, b) for (int i = a; i < b; i++)
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define sz(x) (int)(x).size()
#define mp(x, y) make_pair(x, y)
#define popCnt(x) (__builtin_popcountll(x))
#define int ll
using ll = long long;
using ull = unsigned long long;
using uint = uint32_t;
using ii = pair<int, int>;
const int N = 1e5 + 5, A = 12, LG = 18, MOD = 1e9 + 7, INV = (MOD + 1) / 2;
const long double PI = acos(-1);
const long double EPS = 1e-9;
const int INF = 1e18;
string DIC = "UDRLX";
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, 1, -1};
struct Nd
{
int cnt;
ll sumL, sumR, ans;
} t[1 << 21];
vector<ii> ord;
int n, q, p[300005], cur[300005];
int pwr[300005];
void update(int node, int s, int e, int index, int val)
{
if (s == e)
{
t[node].cnt = val;
t[node].ans = 0;
t[node].sumL = t[node].sumR = val * ord[index].F * INV % MOD;
return;
}
int md = (s + e) >> 1;
if (index <= md)
update(node << 1, s, md, index, val);
else
update(node << 1 | 1, md + 1, e, index, val);
t[node].cnt = t[node << 1].cnt + t[node << 1 | 1].cnt;
t[node].ans = (t[node << 1].ans + t[node << 1 | 1].ans + t[node << 1].sumL * t[node << 1 | 1].sumR) % MOD;
t[node].sumL = (t[node << 1 | 1].sumL + t[node << 1].sumL * pwr[t[node << 1 | 1].cnt]) % MOD;
t[node].sumR = (t[node << 1].sumR + t[node << 1 | 1].sumR * pwr[t[node << 1].cnt]) % MOD;
}
int qrI[300005], qrX[300005];
int getIndex(ii p)
{
return lower_bound(all(ord), p) - begin(ord);
}
void doWork()
{
cin >> n;
pwr[0] = 1;
for (int i = 1; i <= n; i++)
{
pwr[i] = pwr[i - 1] * INV % MOD;
cin >> p[i];
ord.push_back(mp(p[i], i));
cur[i] = i;
}
cin >> q;
for (int i = 1; i <= q; i++)
{
cin >> qrI[i] >> qrX[i];
ord.push_back(mp(qrX[i], n + i));
}
sort(all(ord));
for (int i = 1; i <= n; i++)
{
int index = getIndex(mp(p[i], i));
update(1, 0, ord.size() - 1, index, 1);
}
cout << t[1].ans << endl;
for (int i = 1; i <= q; i++)
{
int prvIndex = getIndex(mp(p[qrI[i]], cur[qrI[i]]));
update(1, 0, ord.size() - 1, prvIndex, 0);
p[qrI[i]] = qrX[i];
cur[qrI[i]] = n + i;
int index = getIndex(mp(p[qrI[i]], cur[qrI[i]]));
update(1, 0, ord.size() - 1, index, +1);
cout << t[1].ans << endl;
}
}
int32_t main()
{
#ifdef ONLINE_JUDGE
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif // ONLINE_JUDGE
int t = 1;
// cin >> t;
while (t--)
{
doWork();
}
return 0;
} | cpp |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | /*
"THE STONE THAT THE BUILDERS REJECTED HAS BECOME THE CORNERSTONE.
THIS IS THE LORD'S DOING , THIS IS MARVELOUS IN OUR EYES ." (118 :22-23 ) ❤
Dear online judge:
I have not failed. I've just found 10,000 ways that won't work.
_Thomas A. Edison
"لكن بالنسبة لكَ كُن قويًا ولا تستسلم لأنَّ عملَك سيُكافأ"
*/
#include <bits/stdc++.h>
#include <iostream>
#include <chrono>
#include <vector>
#include <set>
#include <map>
#include<math.h>
#include <stack>
#include <cmath>
#include <unordered_map>
#include <algorithm>
#include <iomanip>
#include <bitset>
#include <utility>
#include <string>
#include <cctype>
#include <iomanip>
#include <numeric> // for NTH
#define bye return;
#define endl '\n'
#define ll long long
#define li long int
#define lli long long int
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define Number_of_leading_zeroes_l(num) __builtin_clz(num)
#define Number_of_leading_zeroes_ll(num) __builtin_clzll(num)
#define Number_of_trailing_zeroes_ll(num) __builtin_ctz(num)
#define pop_count_int(num) __builtin_popcount(num)
#define pop_count_l(num) __builtin_popcountl(num)
#define pop_count_ll(num) __builtin_popcountll(num)
#define ison(num, bit) (num & (1 << bit))
#define setoffif(num, bit) (num ^= (1 << bit)) // iff (num &(1<<bit))
#define setoff(num, bit) (num &= ~(1 << bit))
#define seton(num, bit) (num |= (1 << bit))
#define flipbit(num, bit) (num ^= (1 << bit))
#define LSB(num) (num & (-num))
#define indx_of_MSB(n) _lg(n) // zero based from right
#define Num_of_Digits(n) ((ll)log10(n) + 1)
#define ceill(n, m) (((n) / (m)) + (((n) % (m) ) ? 1 : 0))
#define lastOne(x) (__builtin_clzll(x))
#define fixed(n) fixed << setprecision(n)
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define Time cerr << "Time Taken: " << (float)clock() / CLOCKS_PER_SEC << " Secs" << "\n";
#define Pi 3.14159265358979323846264
#define INF_LL 0x3f3f3f3f3f3f3f3f
#define INF_INT 0x3f3f3f3f
#define sin(a) sin((a)*PI/180)
#define cos(a) cos((a)*PI/180)
#define yes cout << "YES" << endl;
#define no cout << "NO" << endl;
#define M 64 //the size of the bitset must be a constant number. You can't read n and then declare bitset<n>
#define bitset(n) bitset<M>(n) // zero based , indexing beginning from the right not left
// #define ordered_set tree<pair<int, int>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update>
// #define ordered_map tree<int, int, less<>, rb_tree_tag, tree_order_statistics_int_update>
ll sgn(ll x){ if(x > 0) return 1; if(x < 0) return -1; return 0;}
ll mod = 1e9 + 7;
ll mul(ll a, ll b) { return ((a % mod) * (b % mod)) % mod; }
ll add(ll a, ll b) { return ((a % mod) + (b % mod)) % mod; }
ll sub(ll a, ll b) { return ((a % mod) - (b % mod) + mod) % mod; }
const ll llmin = -1e18 ;
const ll llmax = 1e18 ;
const int imin = -1e9 ;
const int imax = 1e9 ;
const int N = 2e5 ;
using namespace std;
void AC() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); // or cin.tie(NULL)
cout.tie(nullptr); // or cout.tie(0)
}
void file_set(){ //string& file_name
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// freopen((file_name+".in").c_str(), "r", stdin);
// freopen((file_name+".out").c_str(), "w", stdout);
}
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b)
{
return (a.second < b.second);
}
// THOSE WHO CAN'T REMEMBER THE PAST'RE CONDEMNED TO REPEAT IT (USE DP -_-) - George Santayana
// PUSH HARDER THAN YESTERDAY IF YOU WANT A DIFFERENT TOMORROW !
//YOU DON'T HAVE TO BE A GENIUS , YOU NEED TO BE DETERMINED .
const ll MAX = 1e5+2;
ll vis[MAX];
// n = ~(int)0; // test for possible overflow
ll MSB(ll x ){
ll k = Number_of_leading_zeroes_ll(x);
return (63-k) ;
}
void LELLO(){
ll n , a , b , k ; cin >> n >> a >> b >> k ;
vector<ll> vc(n) , ans(n);
for (int i = 0; i < n; i++)
{
cin >> vc[i];
}
// NOTE : (r/a) == ((r+a-1 )/ a) == ((r-1 / a )+1)
// to make (r/a -1) == (r-1 / a )+1) - 1 == (r-1 / a )
for (int i = 0; i < n; i++)
{
vc[i] %=(a+b);
if(vc[i] == 0 ) vc[i] = (a+b);
ans[i] = (vc[i] - 1) / a ;
}
sort(all(ans)) ;
ll co(0);
for (int i = 0; i < n; i++)
{
if(ans[i] <= k){
k -=ans[i];
co++;
}
}
cout<< co <<endl;
}
void driver(ll t=1)
{
while (t--) LELLO();
Time
}
signed main()
{
AC();
// file_set();
// ll test ; cin >> test ;
driver();
} | cpp |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define sz(a) ((int) (a).size())
#define L(i, j, k) for(int i = (j); i <= (k); ++i)
#define R(i, j, k) for(int i = (j); i >= (k); --i)
#define endl '\n'
#define pb push_back
#define all(x) (x).begin(),(x).end()
typedef long long ll;
const int N=2e5;
ll gcd (ll a, ll b) {
if (b == 0)
return a;
else
return gcd (b, a % b);
}
void solve(){
ll a;
cin>>a;
string s;
cin>>s;
bool t=0;
for(int i=0;i<s.size();i++){
if(s[i]!='9') t=1;
}
cout<<a*(s.size()-ll(t))<<"\n";
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t;
cin>>t;
while(t--){
solve();
}
}
| cpp |
1299 | A | A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer. | [
"brute force",
"greedy",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define lb long double
#define pb push_back
#define f first
#define s second
const int mod=1e9+7;
const int mod1=998244353;
void burn ()
{
int n,p;
cin >> n;
while(n--)
cin>>p;
return;
}
void reveal ()
{
int n,p;
string val;
cin>>n;
cout<<n<<endl;
while(n--)
{ cin>>p;
cout<<p<<" ";}
cout << '\n';
return;
}
int fact[200001];
void solve()
{
ll n,i,j,x,p,y,k,m;
cin>>n;
vector<ll>arr(n);
for(i=0;i<n;i++)
cin>>arr[i];
sort(arr.begin(),arr.end(),greater<int>());
vector<pair<ll,ll>>v;
int pref[n],suff[n];
pref[0]=suff[n-1]=INT_MAX;
for(i=1;i<n;i++)
pref[i]=pref[i-1]&(~arr[i-1]);
for(i=n-2;i>=0;i--)
suff[i]=suff[i+1]&(~arr[i+1]);
int ans=INT_MIN,pos=-1,tmp;
for(i=0;i<n;i++){
tmp=pref[i]&arr[i]&suff[i];
if(tmp>ans){
ans=tmp;
pos=i;
}
}
vector<ll>arr1;
cout<<arr[pos]<<" ";
for(i=0;i<n;i++){
if(i!=pos)
arr1.push_back(arr[i]);}
sort(arr1.begin(),arr1.end());
for(i=0;i<n-1;i++)
cout<<arr1[i]<<" ";
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int t=1;
//cin >> t;
// fact[0]=1;
// for(int i=1;i<200001;i++)
// {
// fact[i]=((fact[i-1]%mod)*((i)%mod))%mod;
// }
// if (t == 10000)
// {
// for (int i = 0; i < 368; i++)
// burn ();
// reveal ();
// return 0;
// }
while (t--){
solve();
}
} | cpp |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | #include<bits/stdc++.h>
#include <iostream>
#include <cmath>
#include <set>
#include <map>
#include <cctype>
#include <algorithm>
#include <cstdlib>
#include <string.h>
#include <string>
#include <sstream>
using namespace std;
//#define int long long int
#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define F first
#define S second
typedef long long int ll;
const int N = 1e7+7;
const int mod=1e9+7;
//cout<<fixed<<setprecision(10);
/*void subarray(){
int n,ans;
ll t;
cin>>n>>t;
int a[n+5],s[n+5]={0};
for(int i=1; i<=n; ++i)
{
cin>>a[i];
s[i]=s[i-1]+a[i];
}
for(int i=1; i<=n; ++i)
{
if(a[i]>t)continue;
int l=i,r=n;
while(l<r)
{
int mid=(l+r)>>1;
mid++;
if(s[mid]-s[i-1]<=t)l=mid;
else r=mid-1;
}
ans=max(ans,l-i+1);
}
cout<<ans;
}
*/
/*void E2()
{
int n,m,k;
cin>>n>>m>>k;
vector<int>v;
ll ans=0;
for(int i=0; i<n; i++)
{
int x;
cin>>x;
v.push_back(x);
}
sort(v.begin(),v.end());
for(int i=0; i<n; i++)
{
auto idx=upper_bound(v.begin(),v.end(),v[i]+k)-v.begin();
idx-=1;
if(idx-i+1>=m)
ans=(ans%MOD+ncr(idx-i,m-1)%MOD)%MOD;
}
cout<<ans<<'\n';
}*/
ll power(ll a,ll b)
{
if(b==0)
{
return 1;
}
ll s= power(a,b/2);
return(b&1 ?a*s*s:s*s);
}
ll gcd(ll a,ll b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
const int D = 1e5 + 5;
int prime[D];
void Sieve()
{
for (int i = 2; i < D; ++i)
{
if (!prime[i])
{
for (int j = i + i; j <= D; j += i)
{
prime[j]=1;
}
}
}
}
ll fact[1000006],inv[1000006];
ll mul(ll a,ll b)
{
return (a%mod * b%mod)%mod;
}
ll npr(ll n, ll r)
{
return mul(fact[n],inv[n-r]);
}
ll ncr(ll n, ll r)
{
return mul(fact[n],mul(inv[n-r],inv[r]));
}
ll fast_power(ll base,ll exp)
{
if(exp==0)
return 1;
ll ans = fast_power(base,exp/2);
ans = mul(ans,ans);
if(exp%2!=0)
ans = mul(ans,base);
return ans;
}
void calcFacAndInv(ll n)
{
fact[0] = inv[0] = 1;
for(ll i=1; i<=n; i++)
{
fact[i] = (i*fact[i-1])%mod;
inv[i] = fast_power(fact[i],mod-2);
}
}
ll prime_factorize(ll n)
{
// O(sqrt(N))
for(ll i=2; i*i<=n; i++)
{
while(n%(i*i)==0)
{
n/=i;
}
}
return n;
}
bool isSquare(ll n)
{
double sqn=sqrt(n);
if(sqn==int(sqn))
{
return 1;
}
else
{
return 0;
}
}
void work1()
{
ll n;
cin>>n;
ll ans=0;
for(ll i=2; i<n; i++)
{
ll k=n;
while(k)
{
ans+=(k%i);
k/=i;
// debug(res);
}
}
ll x =n-2;
ll G =gcd(ans,x);
cout<<ans/G<<"/"<<x/G;
}
int main()
{
FIO
int t=1;
//calcFacAndInv(100005);
//cin>>t;
while(t--)
work1();
}
| cpp |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
| [
"math"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define ld long double
#define el "\n"
#define matrix vector<vector<int>>
#define pt complex<ld>
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ordered_multiset tree<ll, null_type,less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update>
using namespace __gnu_pbds;
using namespace std;
const ll N = 2e5 + 7, LOG = 20;
const ld pi = acos(-1);
const ll mod = 1e9 + 7;
int dx[] = {0, -1, 0, 1, -1, 1, -1, 1};
int dy[] = {-1, 0, 1, 0, 1, -1, -1, 1};
ll n, m, k, x, y;
ll hp[N];
void dowork() {
cin >> k >> n;
ll sum = 0;
for (int i = 1; i <= n; i++) {
cin >> hp[i];
sum += hp[i];
if (sum + k <= 0) {
cout << i << el;
return;
}
}
if (sum >= 0) {
cout << -1 << el;
return;
}
ll ans = 2e18;
ll cur = 0, all = abs(sum);
sum = 0;
for (int i = 1; i <= n; i++) {
sum += hp[i];
cur = k + sum;
cur = ((cur + all - 1) / all) * n;
cur += i;
ans = min(ans, cur);
}
cout << ans << el;
}
int main() {
fast
//freopen("cowland.in", "r", stdin);
//freopen("cowland.out", "w", stdout);
int t = 1;
//cin >> t;
for (int i = 1; i <= t; i++) {
dowork();
}
} | cpp |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | #pragma GCC target ("avx2")
#pragma GCC optimize ("O3")
#pragma GCC optimize ("unroll-loops")
#include<bits/stdc++.h>
using namespace std;
// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// int rnd(int x, int y) {return (rng() % (y-x +1)) + x;};
#define ll long long
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define lb lower_bound
#define ub upper_bound
#define ins insert
#define ull unsigned long long
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ff first
#define ss second
#define fio ios::sync_with_stdio(0) , cin.tie(0) , cout.tie(0);
#define nl "\n"
#define sz(a) (int)(a).size()
#define all(a) (a).begin(),(a).end()
#define fl(a,x) memset(a,x,sizeof(a));
#define pt(a,x) cout << get<x>(a) << " " ;
#define mt make_tuple
#define vec vector
#define mxe max_element
#define mne min_element
#define present(c, x) (c.find(x) != c.end())
#define printall(a) for(auto i : a) cout << i << " " ; cout << nl ;
#define int long long
typedef vector<int> vii;
typedef vector<ll> vll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<pii> vpi;
typedef vector<pll> vpl;
typedef vector<vii> vvi;
typedef vector<vll> vvl;
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
ll lcm(ll a,ll b){
ll g =__gcd(a,b);
return (a*b/g);
}
const int mod = (int) 1e9 + 7 ;
const int MOD = (int) 998244353 ;
const ll INF = (ll) 1e18;
int power(int a, int n) {
if(n == 0) return 1;
int p = power(a, n/2) ;
p = p * p % mod ;
return n & 1 ? p * a % mod : p;
}
void ANON7MOUS(){
int n; cin >> n;
vii a(n), pfx(n), sfx(n);
rep(i,0,n) cin >> a[i];
pfx[0] = a[0];
sfx.back() = a.back();
for(int i = 1; i < n; ++i) pfx[i] = pfx[i - 1] + a[i];
for(int i = n - 2; i >= 0; --i) sfx[i] = sfx[i + 1] + a[i];
bool ok1 = 0, ok2 = 0;
for(auto i : pfx){
if(i <= 0){
ok1 = 1;
break;
}
}
for(auto i : sfx){
if(i <= 0){
ok2 = 1;
break;
}
}
if(ok1 || ok2) cout << "NO" << endl;
else cout << "YES" << endl;
}
int32_t main(){
fio;
ll tc = 1; cin >> tc; while(tc--)
ANON7MOUS();
// cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
return 0;
} | cpp |
13 | C | C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1 | [
"dp",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
#define endl "\n"
typedef long long ll;
int main()
{
ll n,ans=0,arr[5005];
priority_queue<ll> pq;
cin >> n;
for(ll i=1;i<=n;i++)
{
cin >> arr[i];
if(!pq.empty()&&pq.top()>arr[i])
{
ans=ans+pq.top()-arr[i];
pq.pop();
pq.push(arr[i]);
}
pq.push(arr[i]);
}
cout << ans << endl;
return 0;
}
| cpp |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define YES cout << "YES" << endl
#define NO cout << "NO" << endl
#define all(_) _.begin(), _.end()
#define rall(_) _.rbegin(), _.rend()
#define sz(_) (int)_.size()
#define fs first
#define se second
#define Odd(_x) ((_x) & 1)
using i64 = long long;
using ll = long long;
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int inf = 1e9 + 10;
const ll mod = 1e9 + 7;
void solve() {
int n, m;
cin >> n >> m;
vector a(n, vector<int>(m ));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> a[i][j];
a[i][j]--;
}
}
int ans = 0;
for (int i = 0; i < m; i++) {
vector<int> cnt(n);
for (int j = 0; j < n; j++) {
if (a[j][i] % m == i && a[j][i] < n * m) {
++cnt[(j - a[j][i] / m + n) % n];
}
}
int res = n;
for (int i = 0; i < n; i++) {
res = min(res, n - cnt[i] + i);
}
ans += res;
}
cout << ans << "\n";
}
//#define MULTI_INPUT
int main() {
#ifndef ONLINE_JUDGE
freopen(R"(D:\source files\source file2\input.txt)", "r", stdin);
freopen(R"(D:\source files\source file2\output.txt)", "w", stdout);
#endif
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout << fixed << setprecision(20);
#ifdef MULTI_INPUT
int T;
cin >> T;
while (T--) {
solve();
}
#else
solve();
#endif
return 0;
} | cpp |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD 1000000007
#define MOD1 998244353
#define ln "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define vi vector<int>
#define vlli vector<ll>
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
/******************************************/
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ll countDivisors(ll n){ll cnt = 0;for (ll i = 1; i <= sqrt(n); i++) {if (n % i == 0) {if (n / i == i)cnt++;else cnt = cnt + 2;}}return cnt;}
ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b
ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}
bool revsort(ll a, ll b) {return a > b;}
ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}
void google(int t) {cout << "Case #" << t << ": ";}
vector<ll> primeFactors(ll n){vector<ll>ret;while (n % 2 == 0){ret.pb(2);n = n/2;}for (ll i = 3; i <= sqrt(n); i = i + 2){while (n % i == 0){ret.pb(i);n = n/i;}}if (n > 2){ret.pb(n);}return ret;}
vector<ll> prime(ll n) {ll*arr = new ll[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (ll j = (ll(i) * ll(i)); j <= n; j += i)arr[j] = 1;} return vect;}
vector<ll>divisor(ll n){vector<ll>res;for (ll i=1; i<=sqrt(n); i++){if (n%i == 0){if (n/i == i)res.pb(i);else{res.pb(i);res.pb(n/i);} }}return res;}
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
ll countnumber(ll n){ll cnt=0;while(n>0){cnt++;n/=10;}return cnt;}
ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll getupper(ll k){ll x = 8*k+1;ll sqr = sqrt(x);if((sqr*sqr)==x){sqr--;return(sqr/2);}sqr--;return (sqr/2)+1;}
ll get2upper(ll n,ll rem){ll a = (2*n)+1;ll s = ((4*n*n)+(4*n)+1)-(8*rem);ll sqr = sqrt(s);if((sqr*sqr)==s){return ((a-sqr)/2)-1;}sqr++;return ((a-sqr)/2);}
ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m
ll modPower(ll x,ll y){ll res = 1;x = x % MOD;if (x == 0)return 0;while (y > 0) {if (y & 1)res = (res * x) % MOD;y = y / 2;x = (x * x) % MOD;}return res;}
ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))
ll modFact(ll n){ll result = 1;for (ll i = 1; i <= n; i++)result = (result * i) % MOD;return result;}
ll power(ll x,ll y){ll res=1;while(y>0){if(y&1)res = res * x;y = y >> 1;x = x * x;}return res;}
ll negMOD(ll x){x=-x;ll s = x/MOD;if(x%MOD)s++;return (MOD*s)-x;}
ll maxll(ll a,ll b) {if(a>b) return a; return b;}
ll minll(ll a,ll b) {if(a<b) return a; return b;}
void precision(ll a) {cout << setprecision(a) << fixed;}
ll msb(ll n){ ll res=0; while(n/2!=0){ n/=2; res++;} return res;}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("Error.txt", "w", stderr);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n,k;cin>>n>>k;
vector<string> v(n);
for(int i=0;i<n;i++) cin>>v[i];
set<string> st;
for(int i=0;i<n;i++) st.insert(v[i]);
ll ans=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
string temp;
for(int m=0;m<k;m++){
if(v[i][m]==v[j][m]) temp.pb(v[i][m]);
else if((v[i][m]=='S' and v[j][m]=='T') or (v[j][m]=='S' and v[i][m]=='T')) temp.pb('E');
else if((v[i][m]=='E' and v[j][m]=='S') or (v[j][m]=='E' and v[i][m]=='S')) temp.pb('T');
else if((v[i][m]=='E' and v[j][m]=='T') or (v[j][m]=='E' and v[i][m]=='T')) temp.pb('S');
}
if(st.find(temp)!=st.end()){
ans++;
// st.erase(v[i]);
// st.erase(temp);
// st.erase(v[j]);
}
}
}
cout<<ans/3;
return 0;
}
| cpp |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;cin>>t;
while(t--){
int n;cin>>n;
vector<int>v(2*n);
for(int i=0;i<(2*n);i++){
cin>>v[i];
}
sort(v.begin(),v.end());
cout<<(v[n]-v[n-1])<<"\n";
}
return 0;
} | cpp |
1316 | F | F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212. | [
"data structures",
"divide and conquer",
"probabilities"
] | #include <bits/stdc++.h>
using namespace std;
// clang-format off
namespace { enum operand_type_enum : uint32_t { RAW = 0, COMPOSED = 1 << 1, REQUIRE_PARAM = 1 << 2, }; template <class T> concept has_operand_type = requires() { { T::operand_type } -> convertible_to<uint32_t>; }; template <class T> class operand_type { public: inline static constexpr uint32_t value() { if constexpr (has_operand_type<T>) return T::operand_type; else return operand_type_enum::RAW; } }; template <class T> constexpr uint32_t operand_type_v = operand_type<decay_t<T>>::value();
template <class T> concept is_raw = ((operand_type_v<T> & RAW) == RAW); template <class T> concept is_composed = ((operand_type_v<T> & COMPOSED) == COMPOSED); template <class T> concept require_param = ((operand_type_v<T> & REQUIRE_PARAM) == REQUIRE_PARAM); template <class T> concept require_no_param = !require_param<T>; template <class left_t, class right_t> class composed_operation_t { public: inline static constexpr uint32_t operand_type = COMPOSED | operand_type_v<right_t> | operand_type_v<left_t>;
left_t left; right_t right; }; template <class left_t, class right_t> requires(is_composed<left_t> && (!is_composed<right_t>)) auto operator|(left_t&& left, right_t&& right) { return left.left | (left.right | right); } template <class left_t, class right_t> requires(is_raw<left_t>&& require_param<right_t>) auto operator|(left_t&& left, right_t&& right) { return composed_operation_t<left_t, right_t>(left, right); } namespace array_binding_details { template <typename T> class array_binding_t_full { public:
inline static constexpr uint32_t operand_type = RAW; T* array; int l, r; T* begin() { return array + l; } T* end() { return array + r + 1; } void resize(const size_t sz) { r = l + sz - 1; } }; class array_binding_t_l_r { public: inline static constexpr uint32_t operand_type = RAW; template <typename T> friend array_binding_t_full<T> operator|(T* array, const array_binding_t_l_r& binding) { return array_binding_t_full<T>{array, binding.l, binding.r}; } int l, r; }; class array_binding_t_l { public:
inline static constexpr uint32_t operand_type = REQUIRE_PARAM; array_binding_t_l_r operator|(const int r) const { return array_binding_t_l_r{l, r}; } int l; }; class array_binding_t_empty { public: inline static constexpr uint32_t operand_type = REQUIRE_PARAM; array_binding_t_l operator|(const int l) const { return array_binding_t_l{l}; } }; static_assert(has_operand_type<array_binding_t_empty>); static_assert(require_param<array_binding_t_empty>); } enum general_operation_t { REVERSE, };
enum comparable_operation_t { SORT, UNIQUE, PREFIX_MIN, PREFIX_MAX, }; enum integer_operation_t { PREFIX_AND, PREFIX_OR, PREFIX_XOR, }; enum number_operation_t { PREFIX_SUM, PREFIX_PROD, }; enum single_input_operation_t { NEXT_INPUT, }; enum array_input_operation_t { ARRAY_INPUT, INDEX_1, }; enum array_output_operation_t { OUTPUT_1LINE, OUTPUT_1_PER_LINE, }; template <typename container_t> auto operator|(container_t&& a, const general_operation_t& op) { switch (op) {
case REVERSE: reverse(a.begin(), a.end()); break; default: assert(false); }; return a; } template <typename container_t> auto operator|(container_t&& a, const comparable_operation_t& op) { switch (op) { case SORT: { sort(a.begin(), a.end()); break; }; case UNIQUE: { sort(a.begin(), a.end()); a.resize(unique(a.begin(), a.end()) - a.begin()); break; } case PREFIX_MIN: { auto begin = a.begin(); ++begin; while (begin < a.end()) { (*begin) = min(*begin, *(begin - 1)); begin++; } break; } case PREFIX_MAX: {
auto begin = a.begin(); ++begin; while (begin < a.end()) { (*begin) = max(*begin, *(begin - 1)); begin++; } break; } default: assert(false); } return a; } template <typename container_t> auto operator|(container_t&& a, const number_operation_t& op) { switch (op) { case PREFIX_SUM: { for (size_t i = 1; i < a.size(); i++) a[i] += a[i - 1]; break; } case PREFIX_PROD: { for (size_t i = 1; i < a.size(); i++) a[i] *= a[i - 1]; break; } default: assert(false); } return a; } template <typename container_t>
auto operator|(container_t&& a, const integer_operation_t& op) { switch (op) { case PREFIX_AND: { for (size_t i = 1; i < a.size(); i++) a[i] &= a[i - 1]; break; } case PREFIX_OR: { for (size_t i = 1; i < a.size(); i++) a[i] |= a[i - 1]; break; } case PREFIX_XOR: { for (size_t i = 1; i < a.size(); i++) a[i] ^= a[i - 1]; break; } default: break; } return a; } template <typename container_t> auto operator|(container_t&& a, const array_input_operation_t& op) { switch (op) { case ARRAY_INPUT: {
for (auto&& x : a) cin >> x; break; } default: assert(0); } return a; } template <typename container_t> auto operator|(container_t&& a, const array_output_operation_t& op) { switch (op) { case OUTPUT_1LINE: { for (auto&& x : a) cout << x << ' '; cout << '\n'; break; } case OUTPUT_1_PER_LINE: { for (auto&& x : a) cout << x << '\n'; cout << '\n'; break; } default: assert(0); } return a; } constexpr array_binding_details::array_binding_t_empty ARRAY; }
// clang-format on
// #define MULTI_TEST
// #define SKIP_ASSERT
#ifdef SKIP_ASSERT
#define assert(x) (x)
#endif
constexpr int base = 1e9 + 7;
constexpr int half = (base + 1) / 2;
// calculate sum (a[i] * a[j] * 1/2 ^(number of item from i to j))
// = sum
// left->weight + right->weight +
class segment_tree_t {
public:
segment_tree_t *left, *right;
int64_t i_weight, j_weight; // weight when this element is i, weight when this element is j
int64_t i_weight_stack, j_weight_stack; // 2
int64_t sum; // actual answer
int l, r, m;
segment_tree_t(const int& l, const int& r)
: l(l), r(r), m((l + r) / 2), i_weight(0), j_weight(0), i_weight_stack(1), j_weight_stack(1), sum(0) {
if (l != r) {
left = new segment_tree_t(l, m);
right = new segment_tree_t(m + 1, r);
}
}
void up() {
(i_weight = left->i_weight + right->i_weight * left->i_weight_stack) %= base;
(i_weight_stack = left->i_weight_stack * right->i_weight_stack) %= base;
(j_weight = left->j_weight + right->j_weight * left->j_weight_stack) %= base;
(j_weight_stack = left->j_weight_stack * right->j_weight_stack) %= base;
(sum = left->sum + right->sum + left->i_weight * ((right->j_weight * left->j_weight_stack) % base)) %= base;
}
void update(const int& u, const int64_t& n_weight, const int64_t& n_i_weight_stack, const int64_t& n_j_weight_stack) {
if (l == r) {
sum = 0;
i_weight_stack = n_i_weight_stack;
j_weight_stack = n_j_weight_stack;
i_weight = n_weight;
j_weight = (n_weight * n_j_weight_stack) % base;
} else {
if (m >= u) left->update(u, n_weight, n_i_weight_stack, n_j_weight_stack);
else right->update(u, n_weight, n_i_weight_stack, n_j_weight_stack);
up();
}
}
};
segment_tree_t* tree;
int n, q;
class query_t {
public:
int id, u, x, pos;
} p[600001];
int last[300001];
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
p[i].id = i;
p[i].u = i;
cin >> p[i].x;
}
cin >> q;
for (int i = n + 1; i <= n + q; i++) {
p[i].id = i;
cin >> p[i].u >> p[i].x;
}
sort(p + 1, p + n + q + 1, [](const auto& A, const auto& B) { return A.x < B.x; });
for (int i = 1; i <= n + q; i++) p[i].pos = i;
sort(p + 1, p + n + q + 1, [](const auto& A, const auto& B) { return A.id < B.id; });
tree = new segment_tree_t(1, n + q);
for (int i = 1; i <= n + q; i++) {
auto&& [id, u, x, pos] = p[i];
if (last[u]) {
auto&& [p_id, p_u, p_x, p_pos] = p[last[u]];
tree->update(p_pos, 0, 1, 1);
}
last[u] = i;
tree->update(pos, x, 2, half);
if (i >= n) cout << tree->sum << '\n';
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
#ifdef MULTI_TEST
cin >> t;
#endif
while (t--) solve();
} | cpp |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long int
int bs(int k, int x)
{
int l = 0, h;
int p = 1;
for (int i = 1; i < 60; i++)
{
if (p * k < 0)
break;
h = i;
p = p * k;
}
int ans = -1;
while (l <= h)
{
int mid = (l + h) / 2;
int key = 1;
for (int i = 1; i <= mid; i++)
{
key = key * k;
}
if (key <= x)
{
ans = mid;
l = mid + 1;
}
else
h = mid - 1;
}
return ans;
}
void solve()
{
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
map<int, int> mp;
for (int i = 0; i < n; i++)
{
while (a[i] > 0)
{
int x = bs(k, a[i]);
if (x == -1)
{
cout << "NO";
return;
}
mp[x]++;
if (mp[x] > 1)
{
cout << "NO";
return;
}
int p = 1;
//cout<<x<<" hehe\n";
for (int j = 1; j <= x; j++)
p = p * k;
a[i] -= p;
}
}
cout << "YES";
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
cin >> t;
while (t--)
{
solve();
cout << "\n";
}
return 0;
} | cpp |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <bits/stdc++.h>
using namespace std;
int main()
{
float n;
cin>>n;
float s=0.00000000000;
for(float i=1;i<=n;i++){
s+=(1/i);
}
cout<<s<<endl;
return 0;
}
| cpp |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | /**
* Author: Richw818
* Created: 01.25.2023 23:09:49
**/
#include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
string dir = "ULDR";
int n; cin >> n;
vector<vector<int>> x(n, vector<int>(n)), y(n, vector<int>(n));
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cin >> x[i][j] >> y[i][j];
if(x[i][j] != -1) x[i][j]--, y[i][j]--;
}
}
vector<string> grid(n, string(n, '.'));
auto dfs = [&](int r, int c, int d, int sr, int sc, auto&& dfs) -> void {
if(r < 0 || r >= n || c < 0 || c >= n || grid[r][c] != '.' || x[r][c] != sr || y[r][c] != sc) return;
grid[r][c] = (r == sr && c == sc ? 'X' : dir[d]);
for(int i = 0; i < 4; i++){
dfs(r + dx[i], c + dy[i], i, sr, sc, dfs);
}
};
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(x[i][j] == i && y[i][j] == j) dfs(i, j, -1, i, j, dfs);
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(x[i][j] != -1 && grid[i][j] == '.'){
cout << "INVALID\n";
return 0;
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(x[i][j] == -1){
for(int d = 0; d < 4; d++){
int nx = i + dx[d], ny = j + dy[d];
if(nx >= 0 && nx < n && ny >= 0 && ny < n && x[nx][ny] == -1) grid[i][j] = dir[d ^ 2];
}
if(grid[i][j] == '.'){
cout << "INVALID\n";
return 0;
}
}
}
}
cout << "VALID\n";
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++) cout << grid[i][j];
cout << '\n';
}
return 0;
} | cpp |
1299 | E | E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2
| [
"interactive",
"math"
] | #include<bits/stdc++.h>
#define vi std::vector<int>
#define N 805
int n;
vi V[N<<2];
int a[N<<2];
inline int qry1(int i,int l,int r,int x,int y){
printf("? %d ",(r-l+1)<<1);
for(int j=l;j<=r;j++) if(j!=i)
printf("%d %d ",V[j][0],V[j][1]);
printf("%d %d\n",x,y),fflush(stdout);
int res;
scanf("%d",&res);
return res;
}
int ans[N];
inline int qry2(int x,int y){
printf("? %d ",n-1-(std::min(x,n-1-x)<<1));
for(int i=1;i<=n;i++) if(i!=y&&(ans[i]==-1||ans[i]==x||ans[i]==n-1-x))
printf("%d ",i);
puts(""),fflush(stdout);
int res;
scanf("%d",&res);
return res;
}
inline void sch(int x){
int u=1,t=x;
while(~a[u])
u=u<<1|(a[u]^(t&1)),t>>=1;
for(auto i:V[u]) if(qry2(x,i)){
ans[i]=x;
while(V[u].size()>1){
a[u]=0,u=u<<1|(a[u]^(t&1)),t>>=1;
if(std::find(V[u].begin(),V[u].end(),i)==V[u].end())
a[u>>1]=1,u^=1;
}
break;
}
}
int main(){
scanf("%d",&n);
V[1].resize(n),std::iota(V[1].begin(),V[1].end(),1);
int l=1,r=1;
while(1){
bool flg=0;
for(int i=l;i<=r;i++)
flg|=V[i].size()>2;
if(!flg){
for(int i=l;i<=r;i++) if(V[i].size()==2)
V[i<<1].emplace_back(V[i][0]),V[i<<1|1].emplace_back(V[i][1]);
break;
}
for(int i=l;i<=r;i++){
int x=V[i].back();
vi &A=V[i<<1],&B=V[i<<1|1];
for(auto y:V[i]) if(y!=x)
(qry1(i,l,r,x,y)?A:B).emplace_back(y);
if(A.size()!=B.size())
(A.size()<B.size()?A:B).emplace_back(x);
else
(qry1(i,l,r,A[0],B[0])?B:A).emplace_back(x);
}
l=l<<1,r=r<<1|1;
}
memset(a,-1,sizeof(a)),memset(ans,-1,sizeof(ans));
for(int i=0;i<n/2;i++)
sch(i),sch(n-1-i);
if(ans[1]>=n/2)
for(int i=1;i<=n;i++)
ans[i]=n-1-ans[i];
printf("! ");
for(int i=1;i<=n;i++)
printf("%d ",ans[i]+1);
puts(""),fflush(stdout);
} | cpp |
1284 | F | F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4
1 2
2 3
4 3
1 3
2 4
1 4
OutputCopy3
3 2 4 2
2 1 1 3
4 3 1 4
InputCopy5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
OutputCopy4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
InputCopy9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
OutputCopy8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
| [
"data structures",
"graph matchings",
"graphs",
"math",
"trees"
] | // LUOGU_RID: 99128720
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; bool f = 0; char ch = getchar();
while (!isdigit(ch)) f |= ch == '-', ch = getchar();
while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
void write(int x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 ^ 48);
}
const int MAXN = 2.5e5 + 5;
int n, son[MAXN], dep[MAXN], U[MAXN], fa[MAXN], f[MAXN][21];
vector <int> g1[MAXN], g2[MAXN]; queue <int> Q;
int find(int x) { return x == U[x] ? x : U[x] = find(U[x]); }
inline void join(int u, int v) {
int fu = find(u), fv = find(v);
if (fu != fv) U[fu] = fv;
}
void misaka(int u, int p) {
dep[u] = dep[p] + 1; f[u][0] = p;
for (auto v : g1[u])
if (v != p) misaka(v, u);
}
void init_ST() {
for (int j = 1; j <= 20; ++j)
for (int i = 1; i <= n; ++i)
f[i][j] = f[f[i][j - 1]][j - 1];
}
void misaki(int u, int p) {
fa[u] = p;
for (auto v : g2[u])
if (v != p) misaki(v, u), ++son[u];
if (!son[u]) Q.emplace(u);
}
int lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
for (int i = 20; ~i; --i)
if (dep[f[x][i]] >= dep[y])
x = f[x][i];
if (x == y) return x;
for (int i = 20; ~i; --i)
if (f[x][i] != f[y][i])
x = f[x][i], y = f[y][i];
return f[x][0];
}
int main() {
n = read(); write(n - 1), putchar('\n');
for (int i = 1; i <= n; ++i) U[i] = i;
for (int i = 1; i < n; ++i) {
int u = read(), v = read();
g1[u].emplace_back(v);
g1[v].emplace_back(u);
}
for (int i = 1; i < n; ++i) {
int u = read(), v = read();
g2[u].emplace_back(v);
g2[v].emplace_back(u);
}
misaka(1, 0); init_ST();
misaki(1, 0);
while (!Q.empty()) {
int u = Q.front(); Q.pop();
if (u == 1) return 0;
int g = lca(u, fa[u]), x;
if (dep[find(u)] > dep[g]) x = find(u);
else {
x = fa[u];
for (int i = 20; ~i; --i)
if (dep[f[x][i]] >= dep[g] && find(f[x][i]) != find(g))
x = f[x][i];
}
join(x, f[x][0]);
write(x), putchar(' ');
write(f[x][0]), putchar(' ');
write(u), putchar(' ');
write(fa[u]), putchar(' ');
putchar('\n');
if (!--son[fa[u]]) Q.emplace(fa[u]);
}
return 0;
} | cpp |
1301 | F | F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105) — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m) — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2); mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4); mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4); mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4). | [
"dfs and similar",
"graphs",
"implementation",
"shortest paths"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define fi first
#define se second
#define ll long long
#define ld long double
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mpp make_pair
#define ve vector
using namespace std;
using namespace __gnu_pbds;
template<class T> using oset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
const ll inf = 1e18; const int iinf = 1e9;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
template <typename T> inline bool chmin(T& a, T b) { return (a > b ? a = b, 1 : 0); }
template <typename T> inline bool chmax(T& a, T b) { return (a < b ? a = b, 1 : 0); }
const pii di[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
inline void solve() {
int n, m, k;
cin >> n >> m >> k;
ve<ve<int>> a(n, ve<int> (m));
for (auto &i : a) for (auto &j : i) cin >> j, --j;
auto valid = [&n,&m](const int &i, const int &j) {
return i >= 0 && i < n && j >= 0 && j < m;
};
ve<ve<pii>> s(k);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
s[a[i][j]].pb({i, j});
}
}
queue<pii> q;
ve<ve<ve<int>>> d(k, ve<ve<int>> (n, ve<int> (m, -1)));
for (int z = 0; z < k; ++z) {
for (auto &[i, j] : s[z]) {
d[z][i][j] = 1;
q.push({i, j});
}
ve<bool> us(k);
while (sz(q)) {
auto [x, y] = q.front();
q.pop();
int cl = a[x][y];
if (!us[cl]) {
us[cl] = 1;
for (auto &[i, j] : s[cl]) {
if (!~d[z][i][j]) {
d[z][i][j] = d[z][x][y] + 1;
q.push({i, j});
}
}
}
for (auto &[dx, dy] : di) {
int xx = x + dx, yy = y + dy;
if (!valid(xx, yy) || d[z][xx][yy] != -1) continue;
d[z][xx][yy] = d[z][x][y] + 1;
q.push({xx, yy});
}
}
}
/*
for (int z : {0, 3}) {
cout << z << ":" << '\n';
for (auto &vec : d[z]) {
for (auto &x : vec) cout << x << " ";
cout << '\n';
}
cout << '\n';
}
*/
int Q;
cin >> Q;
while (Q--) {
int aa, b, c, dd;
cin >> aa >> b >> c >> dd;
--aa, --b, --c, --dd;
int ans = abs(aa - c) + abs(b - dd);
if (a[aa][b] == a[c][dd]) chmin(ans, 1);
for (int z = 0; z < k; ++z) chmin(ans, d[z][aa][b] + d[z][c][dd] - 1);
cout << ans << '\n';
}
}
signed main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int q = 1; // cin >> q;
while (q--) solve();
cerr << fixed << setprecision(3) << "Time execution: " << (double)clock() / CLOCKS_PER_SEC << endl;
}
| cpp |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33 | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | #include<bits/stdc++.h>
using namespace std;
//#define int long long
vector <int> h;
vector <vector <int> > g, pred;
vector <int> tin, tout;
int timer = 0;
void dfs(int v, int p = -1)
{
tin[v] = timer++;
for(int i = 0; i < g[v].size(); i++)
{
if(g[v][i] != p)
{
h[g[v][i]] = h[v] + 1;
pred[g[v][i]][0] = v;
dfs(g[v][i], v);
}
}
tout[v] = timer++;
}
bool pr(int a, int b)
{
return tin[a] <= tin[b] && tout[a] >= tout[b];
}
int lca(int a, int b)
{
if(pr(a, b))
{
return a;
}
if(pr(b, a))
{
return b;
}
for(int j = pred[0].size() - 1; j >= 0; j--)
{
if(!pr(pred[b][j], a))
{
b = pred[b][j];
}
}
return pred[b][0];
}
int s(int a, int b)
{
int lca1 = lca(a, b);
return h[a] + h[b] - 2 * h[lca1];
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
g.resize(n);
h.resize(n);
tin.resize(n);
tout.resize(n);
int p = log2(n) + 1;
pred.resize(n, vector <int> (p));
for(int i = 0; i < n - 1; i++)
{
int u, v;
cin >> u >> v;
u--;
v--;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(0);
for(int i = 1; i < p; i++)
{
for(int j = 0; j < n; j++)
{
pred[j][i] = pred[pred[j][i - 1]][i - 1];
}
}
int q;
cin >> q;
while(q--)
{
int x, y, a, b, k;
cin >> x >> y >> a >> b >> k;
x--;
y--;
a--;
b--;
int len1 = s(a, x) + 1 + s(y, b);
int len2 = s(a, y) + 1 + s(x, b);
int len3 = s(a, b);
int xy = lca(x, y);
int len4 = s(a, x) + 2 + s(y, xy) + s(x, xy) + s(y, b);
int len5 = s(a, y) + 2 + s(x, xy) + s(y, xy) + s(x, b);
if(len1 <= k && len1 % 2 == k % 2)
{
cout << "YES\n";
}
else if(len2 <= k && len2 % 2 == k % 2)
{
cout << "YES\n";
}
else if(len3 <= k && len3 % 2 == k % 2)
{
cout << "YES\n";
}
else if(len4 <= k && len4 % 2 == k % 2)
{
cout << "YES\n";
}
else if(len5 <= k && len5 % 2 == k % 2)
{
cout << "YES\n";
}
else
{
cout << "NO\n";
}
}
return 0;
} | cpp |
1310 | B | B. Double Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2n2n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 11 to 2n2n and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with 2n−12n−1 teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round 2k2k teams play a game with each other (teams are split into games by team numbers). 2k−12k−1 loosing teams are eliminated from the championship, 2k−12k−1 winning teams are playing 2k−12k−1 teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have 2k−12k−1 teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers a1,a2,...,aka1,a2,...,ak. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?InputFirst input line has two integers n,kn,k — 2n2n teams are competing in the championship. You are a fan of kk teams (2≤n≤17;0≤k≤2n2≤n≤17;0≤k≤2n).Second input line has kk distinct integers a1,…,aka1,…,ak — numbers of teams you're a fan of (1≤ai≤2n1≤ai≤2n).OutputOutput single integer — maximal possible number of championship games that include teams you're fan of.ExamplesInputCopy3 1
6
OutputCopy6
InputCopy3 3
1 7 8
OutputCopy11
InputCopy3 4
1 3 5 7
OutputCopy14
NoteOn the image; each game of the championship is denoted with an English letter (aa to nn). Winner of game ii is denoted as WiWi, loser is denoted as LiLi. Teams you're a fan of are highlighted with red background.In the first example, team 66 will play in 6 games if it looses the first upper bracket game (game cc) and wins all lower bracket games (games h,j,l,mh,j,l,m). In the second example, teams 77 and 88 have to play with each other in the first game of upper bracket (game dd). Team 88 can win all remaining games in upper bracket, when teams 11 and 77 will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship. | [
"dp",
"implementation"
] | #include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
using LL = long long;
const int maxn = 1e6 + 5;
int main(){
#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
const int INF = 1e9;
int n, k;
cin >> n >> k;
if (k == 0){
cout << 0 << '\n';
return 0;
}
// 把三场比赛看作一轮,产生一个胜者和一个负者.
// 2个bit, 第一个bit表示胜者是否是喜欢的球队,第二个bit表示负者是否是喜欢的球队.
vector<array<int, 4> > dp(1 << n, {0, -INF, -INF, -INF});
for(int i = 1; i <= k; i++){
int x;
cin >> x;
int s = (1 << n - 1) + (x - 1) / 2;
if (dp[s][1] != -INF) dp[s][3] = 1;
else dp[s][1] = dp[s][2] = 1;
}
for(int i = (1 << n - 1) - 1; i >= 1; i--){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
dp[i][j | k] = max(dp[i][j | k], dp[2 * i][j] + dp[2 * i + 1][k] + (j | k));
}
}
}
cout << max({dp[1][1], dp[1][2], dp[1][3]}) + 1 << '\n';
} | cpp |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"data structures",
"dp",
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
long long n,k,a[500005],lef[500005],righ[500005],ansr[5000005],ansl[500005],i,ans,ind;
int main(){
cin>>n;
for(k=1;k<=n;k++)
cin>>a[k];
for(k=1;k<=n;k++){
i=k-1;
while(i>0 && a[i]>a[k]){
i=lef[i];
}
lef[k]=i;
ansl[k]=ansl[i]+(k-i)*a[k];
}
for(k=n;k>=1;k--){
i=k+1;
while(i<=n && a[i]>a[k]){
i=righ[i];
}
righ[k]=i;
ansr[k]=ansr[i]+(i-k)*a[k];
if(ansr[k]+ansl[k]-a[k]>ans){
ans=ansr[k]+ansl[k]-a[k];
ind=k;
}
}
for(k=ind-1;k>=1;k--){
a[k]=min(a[k],a[k+1]);
}
for(k=ind+1;k<=n;k++)
a[k]=min(a[k],a[k-1]);
for(k=1;k<=n;k++)
cout<<a[k]<<" ";
} | cpp |
1291 | F | F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"graphs",
"interactive"
] | // LUOGU_RID: 101859300
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 1100
ll n,k;
inline bool gt(ll x){
cout<<"? "<<x<<'\n';
char tem;
cout.flush();cin>>tem;
if(tem=='N')return 0;
return 1;
}
inline void clear(){
cout<<'R'<<'\n';
return ;
}
ll an[N];
int main()
{
// freopen("test1.in","r",stdin);
//freopen(".in","r",stdin);
//freopen("test1.out","w",stdout);
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>n>>k;
if(k==1){
ll ans=n;
for(int i=2;i<=n;i++){
for(int j=1;j<i;j++){
gt(j);ll o=gt(i);an[i]|=o;
}
if(an[i])ans--;
}cout<<"! "<<ans;
return 0;
}
ll ji=k/2,g=n/ji,ans=n;
for(int i=1;i<=g;i++){
ll l=(i-1)*ji+1,r=i*ji;
for(int j=1;j<i;j++){
for(int q=(j-1)*ji+1;q<=j*ji;q++)gt(q);
for(int q=l;q<=r;q++)an[q]|=gt(q);
clear();
}
for(int j=l;j<=r;j++)an[j]|=gt(j);
for(int j=l;j<=r;j++)if(an[j])ans--;
clear();
}cout<<"! "<<ans;
return 0;
}
| cpp |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
#include <bit>
#include <bitset>
#include <cstdint>
#define all(v) v.begin() ,v.end()
#define ll long long
using namespace std ;
ll dp[100005][(1<<7)+5] ;
vector<pair <int , int>>all ;
int n, p , k ;
int s[100005][7] ;
ll solve (int idx , int msk){
int cnt = idx-__builtin_popcount(msk) ;
ll &ans = dp[idx][msk] ;
if (idx==n){
if (msk==((1<<p)-1))return ans = 0 ;
return ans = -1e15 ;
}
if (~ans)return ans ;
ans = 0 ;
if (cnt<k)
ans = solve(idx+1 ,msk)+all[idx].first ;
else ans = solve(idx+1 , msk) ;
for (int i = 0 ; i < p ; i++){
if ((msk&(1<<i))==0){
ans = max (ans , solve(idx+1 , (msk|(1<<i)))+ s[all[idx].second][i]) ;
}
}
return ans ;
}
void acc(){
cin>>n >>p>>k ;
for (int i =0 ; i <n ; i++){
int x ;cin>>x;
all.push_back({x,i}) ;
}
sort(all(all)) ;
reverse(all(all)) ;
for (int i =0 ; i < n ; i++){
for (int j =0 ; j < p ; j++){
cin >>s[i][j] ;
}
}
memset(dp,-1 , sizeof dp) ;
cout <<solve(0,0) ;
}
int main (){
int t =1 ;
//cin >>t;
while (t--)acc() ;
} | cpp |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N=4e5+3;
int a[N];
void solve() {
int q,x;
cin>>q>>x;
map<int ,int >mp;
int ans=0;
while(q--) {
int k;
cin>>k;
mp[k%x]++; //转化为1~x-1
while(mp[ans%x]){ // 可以转为为ans
mp[ans%x]--;
ans++;
}
cout<<ans<<endl;
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
// int t; cin>>t; while(t--)
solve();
return 0;
}
| cpp |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | #ifdef LOCAL
#define _GLIBCXX_DEBUG
#endif
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
#define sz(s) ((int)s.size())
#define all(v) begin(v), end(v)
typedef long double ld;
const int MOD = 1000000007;
#define ff first
#define ss second
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
// *-> KISS*
int solve() {
int n; cin >> n;
vector<int64_t> v(n);
for(int i = 0; i < n; ++i) {
cin >> v[i];
}
// vector<vector<ll>> dp(n, vector<ll>(2, 0));
// for(int i = 0; i < n; ++i) {
// if(i == 0) {
// dp[i][0] = v[i];
// }
// else {
// if(v[i] > v[i - 1]) {
// dp[i][0] = dp[i - 1][0];
// }
// else {
// int toDec = v[i - 1] - v[i] + 1;
// dp[i][0] = dp[i - 1][0] - toDec;
// }
// }
// }
// for(int i = n - 1; i >= 0; --i) {
// if(i == n - 1) {
// dp[i][1] = v[i];
// }
// else {
// if(v[i] > v[i + 1]) dp[i][1] = dp[i + 1][1];
// else {
// int toDec = v[i + 1] - v[i] + 1;
// dp[i][1] = dp[i + 1][1] - toDec;
// }
// }
// }
// if(n == 1) {
// cout << "Yes";
// return 0;
// }
// for(int i = 0; i < n; ++i) {
// int before = dp[i][0];
// int after = dp[i][1];
// if(min(before, after) >= 0) {
// cout << "Yes"; return 0;
// }
// }
// cout << "No";
int pref = -1, suff = n;
for(int i = 0; i < n; ++i) {
if(v[i] < i) break;
pref = i;
}
for(int i = n - 1; i >= 0; --i) {
if(v[i] < (n - 1 - i)) break;
suff = i;
}
if(suff <= pref) cout << "Yes";
else cout << "No";
return 0;
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
int TET = 1;
cin >> TET;
cout << fixed << setprecision(6);
for (int i = 1; i <= TET; i++) {
#ifdef LOCAL
cout << "##################" << '\n';
#endif
if (solve()) {
break;
}
cout << '\n';
}
#ifdef LOCAL
cout << endl << "finished in " << clock() * 1.0 / CLOCKS_PER_SEC << " sec" << endl;
#endif
return 0;
}
// -> Keep It Simple Stupid! | cpp |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | #include<bits/stdc++.h>
#define ll long long
#define rep(i, x, y) for(int i = (x), stOyny = (y); i <= stOyny; ++i)
#define irep(i, x, y) for(int i = (x), stOyny = (y); i >= stOyny; --i)
#define pb emplace_back
#define pii pair<int, int>
#define vint vector<int>
#define fi first
#define se second
#define let const auto
#define il inline
#define ci const int
#define all(S) S.begin(), S.end()
int read() {
int res = 0, flag = 1; char c = getchar();
while(c < '0' || c > '9') { if(c == '-') flag = -1; c = getchar(); }
while(c >= '0' && c <= '9') res = res * 10 + c - '0', c = getchar();
return res * flag;
}
using namespace std;
template<typename T>
il void tmax(T &x, const T y) { if(x < y) x = y; }
template<typename T>
il void tmin(T &x, const T y) { if(x > y) x = y; }
const int N = 1e5 + 20;
int n;
bool solve2(int *a) {
int mid = n >> 1;
vint p;
rep(i, 1, mid) p.pb(a[i] + a[i + mid]);
for(int x : p) if(x != p[0]) return false;
return true;
}
int a[2][N];
bool solve() {
n = read();
if(n & 1) return false;
rep(i, 1, n) rep(op, 0, 1) a[op][i] = read();
return solve2(a[0]) && solve2(a[1]);
}
signed main() {
// freopen("1.in", "r", stdin);
cout << (solve() ? "YES\n" : "NO\n");
return 0;
}
| cpp |
1284 | F | F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4
1 2
2 3
4 3
1 3
2 4
1 4
OutputCopy3
3 2 4 2
2 1 1 3
4 3 1 4
InputCopy5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
OutputCopy4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
InputCopy9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
OutputCopy8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
| [
"data structures",
"graph matchings",
"graphs",
"math",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
constexpr int N = 2.5e5 + 9, L = 20;
int n, pos[N], dfn[N], tot;
vector<int> es[2][N];
int fa[N][L], dph[N], f[N];
int findf(int x) { return f[x] == x ? x : f[x] = findf(f[x]); }
void add(int u, int v, int id) {
es[id][u].push_back(v), es[id][v].push_back(u);
}
void dfs(int u) {
for (int i = 0; i + 1 < L; ++i) fa[u][i + 1] = fa[fa[u][i]][i];
for (int v : es[0][u])
if (v != fa[u][0]) dph[v] = dph[fa[v][0] = u] + 1, dfs(v);
}
int lca(int u, int v) {
if (dph[u] < dph[v]) swap(u, v);
for (int i = L - 1; ~i; --i)
if (dph[u] - (1 << i) >= dph[v]) u = fa[u][i];
if (u == v) return u;
for (int i = L - 1; ~i; --i)
if (int fu = fa[u][i], fv = fa[v][i]; fu != fv) u = fu, v = fv;
return fa[u][0];
}
bool dif(int x, int y, int z) {
return (findf(x) == findf(z)) ^ (findf(y) == findf(z));
}
int solve(int u, int p) {
int b = u, l = lca(u, p);
if (dif(p, l, b)) u = p;
for (int i = L - 1; ~i; --i)
if (int fu = fa[u][i]; dph[fu] > dph[l] && !dif(u, fu, b)) u = fu;
return u;
}
void calc(int u, int p) {
for (int v : es[1][u])
if (v != p) calc(v, u);
if (u == 1) return;
int d = solve(u, p);
cout << d << ' ' << (f[d] = fa[d][0]) << ' ' << u << ' ' << p << '\n';
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n;
for (int i = 1, u, v; i < n; ++i) cin >> u >> v, add(u, v, 0);
for (int i = 1, u, v; i < n; ++i) cin >> u >> v, add(u, v, 1);
dfs(1), iota(f + 1, f + n + 1, 1);
cout << n - 1 << '\n', calc(1, -1);
return cout << flush, 0;
} | cpp |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
using namespace std;
#define int long long int
#define ll long long
#define mod 1000000007
// #define mod 998244353
#define fastIO \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
#define endl "\n"
#define mp make_pair
#define pb push_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
#define vi vector<int>
#define min_heap_pii priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>
#define min_haep_i priority_queue<int, vector<int>, greater<int>>
#define umii unordered_map<int, int>
#define vpi vector<pair<int, int>>
#define preci(x) cout << fixed << setprecision(9) << x << endl
#define msi map<string, int>
#define mii map<int, int>
#define spi set<pair<int, int>>
#define vst vector<string>
#define vbl vector<bool>
#define vvi vector<vector<int>>
#define pii pair<int, int>
#define pbr(val) cout << val << endl;
#define pn cout << "No" << endl
#define py cout << "Yes" << endl
#define pim cout << "Impossible" << endl
#define PI acos(-1.0)
// tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag,
// tree_order_statistics_node_update>
// T;
const int limit = 1e18;
// const int sz = 1000005;
// const int LOG = 20;
// vector<vector<int>> dxy = { {1, 0}, {0, -1}, {-1, 0}, {0, 1} };
int dirx[] = {1, -1, 0, 0};
int diry[] = {0, 0, 1, -1};
int str_int(string s)
{
stringstream ob(s);
int num = 0;
ob >> num;
return num;
}
vector<int> primef(int n)
{
vector<int> ans;
if (n % 2 == 0)
{
ans.pb(2);
while (n % 2 == 0)
{
n /= 2;
}
}
for (int i = 3; i * i <= n; i += 2)
{
if (n % i == 0)
{
ans.pb(i);
while (n % i == 0)
{
// ans.pb(i);
n /= i;
}
}
}
if (n > 2)
ans.pb(n);
return ans;
}
vi fact(int n)
{
vi ans;
for (int i = 1; i * i <= n; i++)
{
if (n % i == 0)
{
if (i == n / i)
{
ans.pb(i);
}
else
{
ans.pb(i);
ans.pb(n / i);
}
}
}
return ans;
}
int binExp(int base, int exp)
{
base %= mod;
int res = 1;
while (exp > 0)
{
if (exp & 1)
{
res = (int)((long long)res * base % mod);
}
base = (int)((long long)base * base % mod);
exp >>= 1;
}
return res;
}
void sort_i(vi &v)
{
return sort(v.begin(), v.end());
}
void sort_d(vi &v)
{
return sort(v.begin(), v.end(), greater<int>());
}
int log_a_to_base_b(int a, int b)
{
return log(a) / log(b);
}
int msb(int n) // most significant bit of a number
{
int ans = -1;
while (n > 0)
{
n >>= 1;
ans++;
}
return ans;
}
int modInv(int a, int m)
{
return binExp(a, m - 2);
}
int sum_v(vector<int> &a)
{
int val = accumulate(a.begin(), a.end(), 0ll);
return val;
}
bool is_nondecreasing(vector<int> &a, int s, int e)
{
bool flag = 1;
for (int i = s + 1; i <= e; i++)
{
if (a[i] < a[i - 1])
{
flag = 0;
break;
}
}
return flag;
}
int lcm(int a, int b)
{
int ans = a * b / __gcd(a, b);
return ans;
}
bool is_same_parity(int a, int b)
{
if (a % 2 == b % 2)
{
return true;
}
else
{
return false;
}
}
bool ispalin(string s, int l, int r)
{
bool flag = 1;
while (l < r)
{
if (s[l] != s[r])
{
flag = 0;
break;
}
l++;
r--;
}
if (flag)
{
return true;
}
else
{
return false;
}
}
int modFact(int n, int p)
{
if (n >= p)
return 0;
int result = 1;
for (int i = 1; i <= n; i++)
result = (result * i) % p;
return result;
}
void printyn(bool val)
{
if (val)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
bool isSubSequence(string str1, string str2, int m, int n)
{
int j = 0;
for (int i = 0; i < n && j < m; i++)
if (str1[j] == str2[i])
j++;
return (j == m);
}
void nextGreater(vector<int> &nums, vector<int> &ng)
{
stack<int> st;
int len = nums.size();
ng[len - 1] = -1;
// ng[len - 1] = len;
st.push(len - 1);
for (int i = len - 2; i >= 0; i--)
{
while (!st.empty() && nums[st.top()] <= nums[i])
st.pop();
if (st.empty())
// ng[i] = len;
ng[i] = -1;
else
ng[i] = st.top();
st.push(i);
}
}
void preGreater(vi &nums, vi &pg)
{
stack<int> st;
int n = nums.size();
pg[0] = -1;
st.push(0);
for (int i = 1; i < n; i++)
{
while (st.size() > 0 && nums[st.top()] <= nums[i])
{
st.pop();
}
if (st.empty())
{
pg[i] = -1;
}
else
pg[i] = st.top();
st.push(i);
}
}
void nextSmaller(vector<int> &nums, vector<int> &ns)
{
stack<int> st;
int len = nums.size();
// ns[len - 1] = -1;
ns[len - 1] = len;
st.push(len - 1);
for (int i = len - 2; i >= 0; i--)
{
while (!st.empty() && nums[st.top()] >= nums[i])
st.pop();
if (st.size() > 0)
ns[i] = st.top();
st.push(i);
}
}
void preSmaller(vi &nums, vi &ps)
{
stack<int> st;
int len = nums.size();
for (int i = 0; i < len; i++)
{
while (st.size() > 0 && nums[st.top()] >= nums[i])
{
st.pop();
}
if (st.size() > 0)
{
ps[i] = st.top();
}
st.push(i);
}
}
int dig_len(int n)
{
int cnt = 0;
while (n > 0)
{
n /= 10;
cnt++;
}
return cnt;
}
bool is_vowel(char ch)
{
if (ch == 'a' || ch == 'e' || ch == 'o' || ch == 'u' || ch == 'i')
return 1;
return 0;
}
bool is_digit(char ch)
{
int val = ch - '0';
if (val >= 0 && val <= 9)
return 1;
return 0;
}
int binomialCoeff(int n, int r)
{
if (r > n || n < 0 || r < 0)
return 0;
int m = 998244353;
int inv[r + 1] = {0};
inv[0] = 1;
if (r + 1 >= 2)
inv[1] = 1;
// Getting the modular inversion
// for all the numbers
// from 2 to r with respect to m
// here m = 1000000007
for (int i = 2; i <= r; i++)
{
inv[i] = m - (m / i) * inv[m % i] % m;
}
int ans = 1;
// for 1/(r!) part
for (int i = 2; i <= r; i++)
{
ans = ((ans % m) * (inv[i] % m)) % m;
}
// for (n)*(n-1)*(n-2)*...*(n-r+1) part
for (int i = n; i >= (n - r + 1); i--)
{
ans = ((ans % m) * (i % m)) % m;
}
return ans;
}
vi fac, ifac;
void precompute(int n)
{
fac.resize(n + 1);
fac[0] = fac[1] = 1;
for (int i = 2; i <= n; i++)
{
fac[i] = (int)((long long)i * fac[i - 1] % mod);
}
ifac.resize(n + 1);
for (int i = 0; i < fac.size(); i++)
{
ifac[i] = binExp(fac[i], mod - 2);
}
return;
}
int nCr(int n, int r)
{
if ((n < 0) || (r < 0) || (r > n))
{
return 0;
}
return (int)((long long)fac[n] * ifac[r] % mod * ifac[n - r] % mod);
}
bool isprime(int x)
{
for (int i = 2; i * 1ll * i <= x; i++)
if (x % i == 0)
return false;
return true;
}
// mod stuff
int add(int x, int y)
{
x += y;
while (x >= mod)
x -= mod;
while (x < 0)
x += mod;
return x;
}
int sub(int x, int y)
{
return add(x, -y);
}
int mul(int x, int y)
{
return (x * 1ll * y) % mod;
}
// prime factors of a numbers in log(n) time using sieve()
#define MAXN 20000001
int spf[MAXN];
void sieve_log()
{
spf[1] = 1;
for (int i = 2; i < MAXN; i++)
spf[i] = i;
for (int i = 4; i < MAXN; i += 2)
spf[i] = 2;
for (int i = 3; i * i < MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j = i * i; j < MAXN; j += i)
// marking spf[j] if it is not
// previously marked
if (spf[j] == j)
spf[j] = i;
}
}
}
int getFactorization(int x)
{
// vector<int> ret;
// unordered_set<int> ret;
mii ret;
while (x != 1)
{
ret[spf[x]]++;
// to[(spf[x])]++;
x = x / spf[x];
}
return ret.size();
// cnt of to divisor
// int ans = 1;
// for (auto it : ret)
// {
// ans *= (it.second + 1);
// }
// return ans;
}
int mex(vi a)
{
int n = a.size();
unordered_set<int> s;
for (int i = 0; i < n; i++)
{
s.insert(a[i]);
}
int ans = 0;
for (int i = 0; i <= n; i++)
{
if (s.count(i) == 0)
{
ans = i;
break;
}
}
return ans;
}
/*******************************************************************/
const int maxn = 200001;
vi adj[200001];
int par[maxn];
int sz[maxn];
int dia[maxn];
int maxi, maxiv;
bool vis[maxn];
int fir, sec;
void dfs(int node, int d, int p)
{
par[node] = p;
if (d > maxi)
{
maxiv = node;
maxi = d;
}
for (auto x : adj[node])
{
if (x != p)
{
dfs(x, d + 1, node);
}
}
}
int calc_d(int node)
{
maxi = -1;
dfs(node, 0, -1);
fir = maxiv;
maxi = -1;
dfs(maxiv, 0, -1);
sec = maxiv;
return maxi;
}
void solve()
{
int n;
cin >> n;
for (int i = 0; i < n - 1; i++)
{
int u, v;
cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
// dfs(1, 0, -1);
int dval = calc_d(1);
vector<int> dnodes;
while (sec != fir)
{
dnodes.pb(sec);
sec = par[sec];
}
dnodes.pb(sec);
// cout << dval << endl;
// for (auto it : dnodes)
// {
// cout << it << " ";
// }
// cout << endl;
if (dnodes.size() == n)
{
cout << n - 1 << endl;
cout << dnodes[0] << " " << dnodes[1] << " " << dnodes[n - 1] << endl;
}
else
{
queue<int> q;
vi dis(n + 1, -1);
for (auto it : dnodes)
{
dis[it] = 0;
q.push(it);
}
while (q.size())
{
int node = q.front();
q.pop();
for (auto x : adj[node])
{
if (dis[x] == -1)
{
dis[x] = dis[node] + 1;
q.push(x);
}
}
}
pair<int, int> mx = make_pair(dis[0], 0);
for (int v = 1; v <= n; ++v)
{
mx = max(mx, make_pair(dis[v], v));
}
cout << dval + mx.first << endl;
cout << dnodes[0] << " " << mx.second << " " << dnodes[dnodes.size() - 1] << endl;
}
}
signed main()
{
fastIO;
int t = 1;
// sieve_log();
// cin >> t;
while (t--)
{
solve();
}
}
| cpp |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+10;
const int maxn=1e5+10;
vector<int>e[N];
int d[1000010];
set<int>s;
vector<int>ans;
queue<pair<int,int>>q;
signed main()
{
ios::sync_with_stdio(false),cin.tie(0);
int n;
cin>>n;
for(int i=1;i<=n;i++){
int x;
cin>>x;
int p1=1,p2=1;
for(int j=2;j*j<=x;j++){
while(x%(j*j)==0)x/=j*j;
if(x%j==0)
x/=j,p2=p1,p1=j;
}
if(x>1)p2=p1,p1=x;
if(p1==1){
cout<<1;return 0;
}
e[p1].push_back(p2);
e[p2].push_back(p1);
s.insert(p1),s.insert(p2);
}
int mmin=0x3f3f3f3f;
for(auto i:s){
if(i>1000)break;
memset(d,0x3f3f3f3f,sizeof(d));
q.push({i,0});
d[i]=0;
while(!q.empty()){
int x=q.front().first,fa=q.front().second;
q.pop();
for(auto y:e[x]){
if(y==fa)continue;
if(d[y]>=0x3f3f3f3f){
d[y]=d[x]+1;
q.push({y,x});
}
else mmin=min(d[y]+d[x]+1,mmin);
}
}
}
if(mmin!=0x3f3f3f3f)cout<<mmin;
else cout<<-1;
return 0;
}
| cpp |
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day. | [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int a[1010];
int main(){
int n;
int x;
cin>>x;
while(x--){
int k=0;
cin>>n>>k;
int s=0;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=k;i++){
for(int j=2;j<=n;j++){
if(a[j]>0){
a[j]--;
a[j-1]++;
break;
}
}
}
cout<<a[1]<<endl;
}
return 0;
}
| cpp |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
| [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
//#define int long long
int ans = 1;
vector<int> pr;
vector<int> val, w, sz;
vector<vector<int>> e;
void dfs(int u)
{
if (w[u] >= val.size())
{
ans = 0;
return;
}
pr[u] = val[w[u]];
val.erase(val.begin() + w[u]);
for (int v : e[u]) dfs(v);
}
void dfs1(int u)
{
sz[u]++;
for (int v : e[u])
{
dfs1(v);
sz[u] += sz[v];
}
if (sz[u] <= w[u]) ans = 0;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
val.resize(n);
w.resize(n);
e.resize(n);
pr.resize(n);
sz.resize(n);
iota(val.begin(), val.end(), 0);
int root;
for (int i = 0; i < n; i++)
{
int p;
cin >> p >> w[i];
p--;
if (p != -1)
{
e[p].push_back(i);
}
else
{
root = i;
}
}
dfs1(root);
if (!ans)
{
cout << "NO\n";
return 0;
}
dfs(root);
if (!ans) cout << "NO\n";
else
{
cout << "YES\n";
for (int i : pr) cout << i + 1 << ' ';
}
return 0;
} | cpp |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement. | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int t;
ll n,m;
inline ll cal(ll x)
{
return x * (x+1) / 2;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld",&n,&m);
n -= m;
ll k = n/(m+1),r = n % (m+1);
ll ans = cal(n+m) - cal(k+1) * r - cal(k) *(m+1-r);
printf("%lld\n",ans);
}
return 0;
}
| cpp |
1292 | E | E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1
4
2 1 2
1 2
0
1OutputCopy
? C
? CH
? CCHO
! CCHH
InputCopy2
5
0
2 2 3
1
8
1 5
1 5
1 3
2 1 2
1OutputCopy
? O
? HHH
! CHHHH
? COO
? COOH
? HCCOO
? HH
! HHHCCOOH
NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well. | [
"constructive algorithms",
"greedy",
"interactive",
"math"
] | // LUOGU_RID: 100771511
#define poj
//#define zcz
#ifdef poj
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<ctime>
#include<cstring>
#include<algorithm>
#include<queue>
#include<set>
#include<vector>
#include<string>
#include<stack>
#include<map>
#include<cassert>
#else
#include<bits/stdc++.h>
#endif
using namespace std;
#ifdef zcz
class fastin{
private:
#ifdef poj
static const int MAXBF=1<<20;
#else
const int MAXBF=1<<27;
#endif
FILE *inf;
char *inbuf,*inst,*ined;
inline char _getchar(){
if(inst==ined)inst=inbuf,ined=inbuf+fread(inbuf,1,MAXBF,inf);
return inst==ined?EOF:*inst++;
}
public:
fastin(FILE*_inf=stdin){
inbuf=new char[MAXBF],inf=_inf,inst=inbuf,ined=inbuf;
}
~fastin(){delete inbuf;}
template<typename Int> fastin&operator>>(Int &n){
static char c;
Int t=1;
while((c=_getchar())<'0'||c>'9')if(c=='-')t=-1;
n=(c^48);
while((c=_getchar())>='0'&&c<='9')n=(n<<3)+(n<<1)+(c^48);
n*=t;
return*this;
}
fastin&operator>>(char*s){
int t=0;
static char c;
while((c=_getchar())!=' '&&c!='\n')s[t++]=c;
s[t]='\0';
return *this;
}
}fi;
class fastout{
private:
#ifdef poj
static const int MAXBF=1<<20;
#else
const int MAXBF=1<<27;
#endif
FILE *ouf;
char *oubuf,*oust,*oued;
inline void _flush(){fwrite(oubuf,1,oued-oust,ouf);}
inline void _putchar(char c){
if(oued==oust+MAXBF)_flush(),oued=oubuf;
*oued++=c;
}
public:
fastout(FILE*_ouf=stdout){
oubuf=new char[MAXBF],ouf=_ouf,oust=oubuf,oued=oubuf;
}
~fastout(){_flush();delete oubuf;}
template<typename Int> fastout&operator<<(Int n){
if(n<0)_putchar('-'),n=-n;
static char S[20];
int t=0;
do{S[t++]='0'+n%10,n/=10;}while(n);
for(int i=0;i<t;++i)_putchar(S[t-i-1]);
return *this;
}
fastout&operator<<(char c){_putchar(c);return *this;}
fastout&operator<<(char*s){
for(int i=0;s[i];++i)_putchar(s[i]);
return *this;
}
fastout&operator<<(const char*s){
for(int i=0;s[i];++i)_putchar(s[i]);
return *this;
}
}fo;
#define cin fi
#define cout fo
#else
#define czc ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#endif
#define mod 1000000007
#define ll long long
#define isinf 0x3f3f3f3f
#define ilinf 0x7fffffff
#define lsinf 0x3f3f3f3f3f3f3f3f
#define llinf 0x7fffffffffffffff
#define pii pair<int,int>
#define next ___
int n,t;
char s[60];
void solve1(){
int x;
cout<<"? CH\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1;i<=t;i++)cin>>x,s[x-1]='C',s[x]='H';
cout<<"? CO\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1;i<=t;i++)cin>>x,s[x-1]='C',s[x]='O';
cout<<"? CC\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]='C';
if(s[0]=='C'){
if(s[2]=='C'){
cout<<"! "<<s<<'\n';
cout.flush();
return;
}else{
s[2]='O';s[3]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//CCOC,CHOC,COOC
}
s[3]='O';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//CCOO,CHOO,COOO
}
s[3]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//CCOH,CHOH,COOH
}
s[2]='H';s[3]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//CCHC,COHC,CHHC
}
s[3]='O';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//CCHO,CHHO,COHO
}
s[3]='H';
cout<<"! "<<s<<'\n';
cout.flush();
return;
//CCHH,COHH,CHHH
}
}
if(s[1]=='C'){
s[0]='O';s[3]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OCCH,OCHH,OCOH
}
s[3]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OCHC,OCCC,OCOC
}
s[3]='O';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OCHO,OCCO,OCOO
}
s[0]='H';s[3]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HCCH,HCOH,HCHH
}
s[3]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HCCC,HCOC,HCHC
}
s[3]='O';
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HCCO,HCHO,HCOO
}
if(s[2]=='C'){
s[0]=s[1]='O';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OOCC,OOCO,OOCH
}
s[1]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OHCC,OHCO,OHCH
}
s[0]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HHCC,HHCO,HHCH
}
s[1]='O';
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HOCC,HOCO,HOCH
}
cout<<"? HO\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1;i<=t;i++)cin>>x,s[x-1]='H',s[x]='O';
if(s[0]=='H'){
if(s[2]=='H'){
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HOHO
}else{
s[2]='O';s[3]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HOOC
}
s[3]='O';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HOOO
}
s[3]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HOOH
}
s[2]='H';s[3]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HOHC
}
s[3]='H';
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HOHH
}
}
if(s[1]=='H'){
s[0]='O';s[3]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OHOH
}
s[3]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OHOC
}
s[3]='O';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OHOO
}
s[0]='H';s[3]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HHOH
}
s[3]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HHOC
}
s[3]='O';
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HHOO
}
if(s[2]=='H'){
s[0]=s[1]='O';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OOHO
}
s[1]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OHHO
}
s[0]='H';
cout<<"! "<<s<<'\n';
cout.flush();
return;
//HHHO
}
cout<<"? OO\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]='O';
if(s[0]=='O'&&s[1]=='O'){
if(s[3]=='O'){
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OOOO
}else{
if(s[2]=='O'){
s[3]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OOOH
}
s[3]='C';
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OOOC
}
s[2]=s[3]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1){
cin>>x;
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OOHH
}
s[3]='C';
cout<<"! "<<s<<'\n';
cout.flush();
return;
//OOHC
}
}
s[1]=s[2]='H';
cout<<"? HHH\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]=s[x+1]='H';
if(s[0]==0)s[0]='O';
if(s[3]==0)s[3]='C';
cout<<"! "<<s<<'\n';
cout.flush();
//HHHH,HHHC,OHHH,OHHC
return;
}
void solve(){
cin>>n;
fill(s,s+n+1,0);
if(n==4){
solve1();
goto label;
}
cout<<"? CH\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1,x;i<=t;i++)cin>>x,s[x-1]='C',s[x]='H';
cout<<"? CO\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1,x;i<=t;i++)cin>>x,s[x-1]='C',s[x]='O';
cout<<"? CC\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1,x;i<=t;i++)cin>>x,s[x-1]=s[x]='C';
cout<<"? HO\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1,x;i<=t;i++)cin>>x,s[x-1]='H',s[x]='O';
cout<<"? OO\n";
cout.flush();
cin>>t;
assert(t!=-1);
for(int i=1,x;i<=t;i++)cin>>x,s[x-1]=s[x]='O';
for(int i=1;i<n-1;i++)if(s[i]==0)s[i]='H';
// cout<<s[0]<<' '<<s[n-1]<<'\n';
if(s[0]!=0&&s[n-1]!=0){
// cout<<'\t'<<1<<'\n';
cout<<"! "<<s<<'\n';
cout.flush();
goto label;
}
if(s[0]!=0){
// cout<<'\t'<<2<<'\n';
s[n-1]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
int x;
if(t==1)cin>>x;
else s[n-1]='C';
cout<<"! "<<s<<'\n';
cout.flush();
goto label;
}
if(s[n-1]!=0){
// cout<<'\t'<<3<<'\n';
s[0]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
int x;
if(t==1)cin>>x;
else s[0]='O';
cout<<"! "<<s<<'\n';
cout.flush();
goto label;
}
// cout<<'\t'<<4<<'\n';
s[0]='H',s[n-1]='C';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
int x;
if(t==1)cin>>x,cout<<"! "<<s<<'\n',cout.flush();
else{
s[0]=s[n-1]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1)cin>>x,cout<<"! "<<s<<'\n',cout.flush();
else{
s[0]='O',s[n-1]='H';
cout<<"? "<<s<<'\n';
cout.flush();
cin>>t;
assert(t!=-1);
if(t==1)cin>>x,cout<<"! "<<s<<'\n',cout.flush();
else{
s[0]='O',s[n-1]='C';
cout<<"! "<<s<<'\n',cout.flush();
}
}
}
label:;
cin>>x;
assert(x==1);
return;
}
int main(){
#ifndef zcz
// czc;
#endif
int t=1;
cin>>t;
while(t--)solve();
return 0;
} | cpp |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | #include<iostream>
using namespace std;
#include <cmath>
#include <algorithm>
#define ll long long
#define fi first
#define se second
#define sst string
#define pb push_back
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif
#define maxco 100000+5
#define lld long double
#define cha ios_base::sync_with_stdio(false);
#define mod 1000000007
#define ffl cout.flush();
#define phi acos(-1)
//
//ll a[200069];
//sst t="";
//void precom(){
// for(ll i=0;i<1000;i++){
// t+=(phi%10);
// phi/
// }
//}
//int main(){
// ll tc;
//
// cin>>tc;
// while(tc--){
// vector <ll> vec;
// ll n,s,r;
// cin>>n>>s>>r;
// ll sisa=s-r;
// vec.pb(sisa);
// cout<<sisa<<" ";
// n--;
// if(r%n==0){
// ll t=n;
// while(t--){
// cout<<r/n<<" ";
// }
// }
// else{
//
// }
// cout<<endl;
// }
//}
ll a[200069];
ll le[1569][1509];
ll dp[300069];
int main(){
ll n;
cin>>n;
for(ll i=1;i<=n;i++)cin>>a[i];
memset(le, 0, sizeof(le));
for(ll i=1;i<=n;i++){
le[i][a[i]]=i;
}
for(ll i=1;i<=n;i++){
for(ll j=1;j<=1500;j++){
if(le[i][j]==0){
le[i][j]=le[le[i][j-1]-1][j-1];
}
}
}
memset(dp, mod, sizeof(dp));
dp[0]=0;
for(ll i=1;i<=n;i++){
for(ll j=1;j<=1500;j++){
if(le[i][j]!=0){
dp[i] = min(dp[i], dp[le[i][j]-1]+1);
}
}
}
cout<<dp[n];
}
/*
15
67 67 65 65 66 66 66 68 67 67 67 66 66 70
*/
//#define otsumiko exit(0);
//#define mikodanye priority_queue<pair<long long, long long>, vector<pair<long long, long long> >, greater<pair<long long, long long> > >
//#define mikochi priority_queue<long long, vector<long long>, greater<long long> >
//
//long long n, a[569], dp[503][1503], cl, cr, mn[503], mx = 1e9;
//int main(){
// long long i, j;
// cin >> n;
// for (i=1; i<=n; i++){
// cin >> a[i];
// }
// for (i=1; i<=1500; i++){
// dp[0][i] = mx;
// }
// for (i=1; i<=n; i++) {
// for (j=1; j<=1500; j++){
// if (j<a[i]) {
// dp[i][j]=mx;
// continue;
// }
// if (j == a[i]) {
// dp[i][j]=i;
// continue;
// }
// cr = dp[i][j-1];
// if (cr == mx) {
// dp[i][j] = mx;
// } else {
// dp[i][j] = dp[cr-1][j-1];
// }
// }
// }
// mn[0] = 0;
// cout<<dp[4][4]<<endl;
// for (i=1; i<=n; i++) {
// mn[i] = mx;
// //cout << "i: " << i << "\n";
// for (j=1; j<=1500; j++) {
// cr = dp[i][j];
// if (cr == mx) {
// continue;
// }
// mn[i] = min(mn[i], mn[cr-1]+1);
// }
// //cout << "mn: " << mn[i] << "\n";
// }
// cout << mn[n] << "\n";
// otsumiko
//}
| cpp |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] |
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pi;
#define pb push_back
const int MN=8e4;
int N, at=170, ans = MN; bool pvis[1001], vis[MN]; pi dist[MN];
set<int> start; vector<int> prime, vals, adj[MN]; queue<pi> q;
unordered_map<int, int> ind; // (value, index it maps to)
void bfs(int r){ q.push({r,-1}); dist[r]={1,r};
while(!q.empty()){ pi t = q.front(); int x=t.first, p=t.second; q.pop();
for(int nx: adj[x]) if(nx!=p && nx>=r && adj[nx].size()>1) {
if(dist[nx].second==dist[x].second) ans=min(ans,dist[x].first+dist[nx].first-1);
else{ dist[nx]={dist[x].first + 1,r}; q.push({nx,x}); } } } }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
prime.reserve(170); prime.pb(0); prime.pb(1);
for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.pb(i);
for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; }
cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x;
for (int j=2; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0;
while (x%prime[j] == 0) { x /= prime[j]; cnt++; }
if (cnt%2 == 1) vals.pb(prime[j]); }
if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; }
vals.pb(x); if (vals.size() == 1) vals.pb(1);
for (int k: vals) if (ind.count(k) == 0)
{ if (k > 1e3) ind[k] = at++;
else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin();
ind[k]=t; start.insert(t); } }
adj[ind[vals[0]]].pb(ind[vals[1]]);
adj[ind[vals[1]]].pb(ind[vals[0]]);
}
for (int j: start) if(j && adj[j].size()>1) bfs(j);
cout << (ans == MN ? -1 : ans) <<'\n';
} | cpp |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | #include <map>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1e5 + 5;
int n , x , a[MAXN];
map <int , int> M;
int main() {
int T;
scanf("%d" , &T);
while(T -- > 0) {
M.clear();
scanf("%d %d" , &n , &x);
for (int i = 1; i <= n; ++i) {
scanf("%d" , &a[i]);
M[a[i]] = 1;
}
sort(a + 1 , a + 1 + n);
if(M[x]) {
printf("1\n");
continue;
}
int ans = 0;
if(x % a[n] == 0) {
printf("%d\n" , x / a[n]);
continue;
}
ans += x / a[n];
printf("%d\n" , max(2 , ans + 1));
}
return 0;
}
| cpp |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | #pragma GCC optimization("Ofast")
#include <bits/stdc++.h>
using namespace std;
int Tc = 1;
void solve() {
int n, check = 0;
cin >> n;
vector<int> a(n);
for (auto& e : a)
cin >> e;
sort(a.begin(), a.end());
a.erase(unique(a.begin(), a.end()), a.end());
long long ans = 0;
for (int i = a.size() - 1; i >= 0; --i) {
if (i > (int)a.size() - 47 || (check <= 47 && ((a[i] ^ a.back()) & 1))) {
if (i < (int)a.size() - 47) check++;
for (int j = 0; j < n; ++j) {
ans = max({ans, a[i] * 1ll * a[j] / __gcd(a[i], a[j])});
}
}
}
cout << ans;
}
signed main() {
cin.tie(0)->sync_with_stdio(0);
// cin >> Tc;
while (Tc--)
solve(), cout << '\n';
} | cpp |
1312 | F | F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
OutputCopy2
3
0
InputCopy10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
OutputCopy0
2
1
2
5
12
5
0
0
2
| [
"games",
"two pointers"
] | #include <bits/stdc++.h>
using namespace std;
// clang-format off
namespace { enum operand_type_enum : uint32_t { RAW = 0, COMPOSED = 1 << 1, REQUIRE_PARAM = 1 << 2, }; template <class T> concept has_operand_type = requires() { { T::operand_type } -> convertible_to<uint32_t>; }; template <class T> class operand_type { public: inline static constexpr uint32_t value() { if constexpr (has_operand_type<T>) return T::operand_type; else return operand_type_enum::RAW; } }; template <class T> constexpr uint32_t operand_type_v = operand_type<decay_t<T>>::value();
template <class T> concept is_raw = ((operand_type_v<T> & RAW) == RAW); template <class T> concept is_composed = ((operand_type_v<T> & COMPOSED) == COMPOSED); template <class T> concept require_param = ((operand_type_v<T> & REQUIRE_PARAM) == REQUIRE_PARAM); template <class T> concept require_no_param = !require_param<T>; template <class left_t, class right_t> class composed_operation_t { public: inline static constexpr uint32_t operand_type = COMPOSED | operand_type_v<right_t> | operand_type_v<left_t>;
left_t left; right_t right; }; template <class left_t, class right_t> requires(is_composed<left_t> && (!is_composed<right_t>)) auto operator|(left_t&& left, right_t&& right) { return left.left | (left.right | right); } template <class left_t, class right_t> requires(is_raw<left_t>&& require_param<right_t>) auto operator|(left_t&& left, right_t&& right) { return composed_operation_t<left_t, right_t>(left, right); } namespace array_binding_details { template <typename T> class array_binding_t_full { public:
inline static constexpr uint32_t operand_type = RAW; T* array; int l, r; T* begin() { return array + l; } T* end() { return array + r + 1; } void resize(const size_t sz) { r = l + sz - 1; } }; class array_binding_t_l_r { public: inline static constexpr uint32_t operand_type = RAW; template <typename T> friend array_binding_t_full<T> operator|(T* array, const array_binding_t_l_r& binding) { return array_binding_t_full<T>{array, binding.l, binding.r}; } int l, r; }; class array_binding_t_l { public:
inline static constexpr uint32_t operand_type = REQUIRE_PARAM; array_binding_t_l_r operator|(const int r) const { return array_binding_t_l_r{l, r}; } int l; }; class array_binding_t_empty { public: inline static constexpr uint32_t operand_type = REQUIRE_PARAM; array_binding_t_l operator|(const int l) const { return array_binding_t_l{l}; } }; static_assert(has_operand_type<array_binding_t_empty>); static_assert(require_param<array_binding_t_empty>); } enum general_operation_t { REVERSE, };
enum comparable_operation_t { SORT, UNIQUE, PREFIX_MIN, PREFIX_MAX, }; enum integer_operation_t { PREFIX_AND, PREFIX_OR, PREFIX_XOR, }; enum number_operation_t { PREFIX_SUM, PREFIX_PROD, }; enum single_input_operation_t { NEXT_INPUT, }; enum array_input_operation_t { ARRAY_INPUT, INDEX_1, }; enum array_output_operation_t { OUTPUT_1LINE, OUTPUT_1_PER_LINE, }; template <typename container_t> auto operator|(container_t&& a, const general_operation_t& op) { switch (op) {
case REVERSE: reverse(a.begin(), a.end()); break; default: assert(false); }; return a; } template <typename container_t> auto operator|(container_t&& a, const comparable_operation_t& op) { switch (op) { case SORT: { sort(a.begin(), a.end()); break; }; case UNIQUE: { sort(a.begin(), a.end()); a.resize(unique(a.begin(), a.end()) - a.begin()); break; } case PREFIX_MIN: { auto begin = a.begin(); ++begin; while (begin < a.end()) { (*begin) = min(*begin, *(begin - 1)); begin++; } break; } case PREFIX_MAX: {
auto begin = a.begin(); ++begin; while (begin < a.end()) { (*begin) = max(*begin, *(begin - 1)); begin++; } break; } default: assert(false); } return a; } template <typename container_t> auto operator|(container_t&& a, const number_operation_t& op) { switch (op) { case PREFIX_SUM: { for (size_t i = 1; i < a.size(); i++) a[i] += a[i - 1]; break; } case PREFIX_PROD: { for (size_t i = 1; i < a.size(); i++) a[i] *= a[i - 1]; break; } default: assert(false); } return a; } template <typename container_t>
auto operator|(container_t&& a, const integer_operation_t& op) { switch (op) { case PREFIX_AND: { for (size_t i = 1; i < a.size(); i++) a[i] &= a[i - 1]; break; } case PREFIX_OR: { for (size_t i = 1; i < a.size(); i++) a[i] |= a[i - 1]; break; } case PREFIX_XOR: { for (size_t i = 1; i < a.size(); i++) a[i] ^= a[i - 1]; break; } default: break; } return a; } template <typename container_t> auto operator|(container_t&& a, const array_input_operation_t& op) { switch (op) { case ARRAY_INPUT: {
for (auto&& x : a) cin >> x; break; } default: assert(0); } return a; } template <typename container_t> auto operator|(container_t&& a, const array_output_operation_t& op) { switch (op) { case OUTPUT_1LINE: { for (auto&& x : a) cout << x << ' '; cout << '\n'; break; } case OUTPUT_1_PER_LINE: { for (auto&& x : a) cout << x << '\n'; cout << '\n'; break; } default: assert(0); } return a; } constexpr array_binding_details::array_binding_t_empty ARRAY; }
// clang-format on
#define MULTI_TEST
// #define SKIP_ASSERT
#ifdef SKIP_ASSERT
#define assert(x) (x)
#endif
int n, mx;
int mex(const vector<int>& val) {
int x = 0;
bool done = 0;
while (!done) {
done = 1;
for (auto&& y : val) {
if (y == x) {
done = 0;
x++;
}
}
}
return x;
}
int mex(int a, int b, int c) {
int x = 0;
while ((x == a) || (x == b) || (x == c)) x++;
return x;
}
int r[3];
class result_t {
public:
int g[3];
void reset() { g[0] = g[1] = g[2] = 0; }
} f[300001];
map<int64_t, int> cycle;
int cycle_size;
int cycle_start;
const result_t& get_result(int64_t val) {
if (val < cycle_start) return f[val];
(val -= cycle_start) %= cycle_size;
return f[cycle_start + val];
}
int64_t a[300001];
void solve() {
cin >> n >> r[0] >> r[1] >> r[2];
mx = *max_element(r, r + 3);
f[0].reset();
cycle.clear();
if (mx == 1) cycle[0] = 0;
for (int i = 1;; i++) {
if (i < mx) {
for (int j = 0; j < 3; j++) {
vector<int> near;
for (int k = 0; k < 3; k++) {
if (k && (k == j)) continue;
if (i - r[k] < 0) near.push_back(0);
else near.push_back(f[i - r[k]].g[k]);
}
f[i].g[j] = mex(near);
}
} else {
for (int j = 0; j < 3; j++) {
f[i].g[j] = mex(f[i - r[0]].g[0], f[i - r[1]].g[1] + 1e9 * (j == 1), f[i - r[2]].g[2] + 1e9 * (j == 2));
}
}
if (i + 1 >= mx) {
int val = 0;
for (int j = i - mx + 1; j <= i; j++) {
for (int k = 0; k < 3; k++) {
(val <<= 2) |= f[j].g[k];
}
}
auto it = cycle.find(val);
if (it == cycle.end()) {
cycle[val] = i;
continue;
}
cycle_size = i - it->second;
cycle_start = it->second;
break;
}
}
int g = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i];
auto&& result = get_result(a[i]);
g ^= result.g[0];
}
int ans = 0;
for (int i = 1; i <= n; i++) {
auto&& result = get_result(a[i]);
g ^= result.g[0];
for (int j = 0; j < 3; j++) {
auto&& try_result = get_result(max(0LL, a[i] - r[j]));
if ((try_result.g[j] ^ g) == 0) ans++;
}
g ^= result.g[0];
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
#ifdef MULTI_TEST
cin >> t;
#endif
while (t--) solve();
} | cpp |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
| [
"data structures",
"dp"
] | #include "bits/stdc++.h"
using namespace std;
#define all(x) begin(x),end(x)
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = " "; return os; }
#define debug(a) cerr << "(" << #a << ": " << a << ")\n";
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> pi;
const int mxN = 1e5+1, oo = 1e9;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n; cin >> n;
vi seq[26] = {};
int cnt=1;
vi ans(n);
for(int i=0;i<n;++i) {
char c; cin >> c;
c-='a';
char cc=c;
while(c>0 and seq[c].empty()) --c;
int mycnt=-1;
if(seq[c].empty()) {
mycnt=cnt++;
} else {
mycnt = seq[c].back();
seq[c].pop_back();
}
ans[i]=mycnt;
seq[cc].push_back(mycnt);
}
cout << cnt-1 << '\n' << ans << '\n';
} | cpp |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] | #include<iostream>
using namespace std;
#include <iostream>
#include <cmath>
#include <algorithm>
#include <bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define sst string
#define pb push_back
#define maxco 100000+5
#define lld long double
#define cha ios_base::sync_with_stdio(false);
#define ffl cout.flush();
#define phi acos(-1)
#define mod 1000000007
ll a[200069];
ll b[200069];
int main(){
cha
ll n,m,k;
cin>>n>>m>>k;
vector <pair<ll,ll>> vec;
for(ll i=1;i*i<=k;i++){
if(k%i==0){
vec.pb({i,k/i});
}
}
for(ll i=1;i<=n;i++){
cin>>a[i];
}
for(ll i=1;i<=m;i++){
cin>>b[i];
}
vector <ll> up,dw;
ll sd=0;
for(ll i=1;i<=n;i++){
if(a[i]==1){
sd++;
}
else{
if(sd!=0){
up.pb(sd);
sd=0;
}
else{
sd=0;
}
}
// cout<<i<<" ";
// cout<<sd<<endl;
}
if(sd!=0){
up.pb(sd);
}
sd=0;
for(ll i=1;i<=m;i++){
if(b[i]==1){
sd++;
}
else{
if(sd!=0){
dw.pb(sd);
sd=0;
}
else{
sd=0;
}
}
// cout<<i<<" ";
// cout<<sd<<endl;
}
if(sd!=0){
dw.pb(sd);
}
sort(up.begin(),up.end());
sort(dw.begin(),dw.end());
// for(auto x : up)cout<<x<<" ";
// cout<<endl;
// for(auto x : dw)cout<<x<<" ";
// cout<<endl;
ll ans=0;
for(auto x : vec){
// cout<<x.fi<<" "<<x.se<<" : ";
// cout<<endl;
ll sdfi=lower_bound(up.begin(),up.end(),x.fi)-up.begin();
ll sdse=lower_bound(dw.begin(), dw.end(), x.se)-dw.begin();
// cout<<sdfi<<" "<<sdse<<endl;
for(ll i=sdfi;i<up.size();i++){
for(ll j=sdse;j<dw.size();j++){
ll val=up[i]-x.fi+1;
ll val2=dw[j]-x.se+1;
// cout<<val<<" "<<val2<<endl;
ans+=val*val2;
}
}
if(x.fi!=x.se){
sdfi=lower_bound(up.begin(), up.end(), x.se)-up.begin();
sdse=lower_bound(dw.begin(), dw.end(), x.fi)-dw.begin();
for(ll i=sdfi;i<up.size();i++){
for(ll j=sdse;j<dw.size();j++){
ll val=up[i]-x.se+1;
ll val2=dw[j]-x.fi+1;
// cout<<val<<" "<<val2<<endl;
ans+=val*val2;
}
}
// cout<<sdfi<<" "<<sdse<<endl;
}
}
cout<<ans<<endl;
}
| cpp |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | #include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<unordered_map>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstdlib>
#include<stack>
#include<ctime>
#define forin(i,a,n) for(int i=a;i<=n;i++)
#define forni(i,n,a) for(int i=n;i>=a;i--)
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=3e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
int T;
int n,m,k;
int st[400007];
void solve() {
m=read();
int x=read();
k=0;
while(m--) {
int a=read();
st[a%x]++;
while(st[k%x]>k/x) k++;
printf("%d\n",k);
}
}
int main() {
// init();
// stin();
// scanf("%d",&T);
T=1;
while(T--) solve();
return 0;
}
| cpp |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"brute force",
"data structures",
"dp",
"greedy"
] | #include<iostream>
#include<vector>
#include<stack>
#include<deque>
using namespace std;
typedef long long ll;
void solve() {
int n;
cin >> n;
vector<ll> a(n + 1), b(n + 1), c(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
vector<ll> res(n + 1);
int idx;
ll ans = -1;
for (int j = 1; j <= n; j++) {
ll ans1 = a[j];
ll pre = a[j];
for (int i = j - 1; i >= 1; --i) {
pre = min(pre, a[i]);
ans1 += pre;
}
pre = a[j];
for (int i = j + 1; i <= n; i++) {
pre = min(pre, a[i]);
ans1 += pre;
}
if (ans < ans1) {
ans = ans1;
idx = j;
}
}
ll pre = a[idx];
for (int i = idx - 1; i >= 1; --i) {
res[i] = min(pre, a[i]);
pre = min(pre, a[i]);
}
res[idx] = a[idx];
pre = a[idx];
for (int i = idx + 1; i <= n; i++) {
res[i] = min(pre, a[i]);
pre = min(pre, a[i]);
}
for (int i = 1; i <= n; i++) {
cout << res[i] << " ";
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
solve();
}
| cpp |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | #include <iostream>
#include <algorithm>
#include<vector>
#include<map>
#include<set>
#include <cmath>
typedef long long ll;
#define pb push_back
#define R return
#define B break
#define C continue
#define lop(i, n) for (int i = 0; i < n; i++)
#define lopp(r, n) for (int r = 1; r < n; r++)
using namespace std;
const int N=2e5+7;
const ll M=1e9+7;
ll a[N];
int fact(int n)
{
if ((n == 0) || (n == 1))
return 1;
else
return n * fact(n - 1);
}
bool isPrime(int num)
{
bool flag = true;
for (int i = 2; i <= sqrt(num); i++)
{
if (num % i == 0)
{
flag = false;
break;
}
}
return flag;
}
vector<ll>v;
map<ll,ll>mp;
set<ll>st;
void _clear()
{
st.clear();mp.clear();v.clear();
}
void solve()
{
_clear();
bool f=1;
ll n,k;
cin>>n>>k;
lop(i,n)
{ll x,p=0;cin>>x;
while(x>0)
{
mp[p++]+=x%k;
x/=k;
if(mp[p-1]>=2)f=0;
}
}
if(f)cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
int main()
{
ll t=1;
cin>>t;
while(t--)
solve();
R 0;
} | cpp |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 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 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define pb push_back
#define ff first
#define ss second
#define oo 1000000000
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
void solve() {
int n,d; cin >> n >> d;
int l=0,r=n;
while(l<r) {
int m=(l+r)/2;
if(m + ceil(1.0*d/(m+1)) <= n) {
cout << "YES"; return;
} else {
r=m;
}
}
cout << "NO";
}
int main(){
ios::sync_with_stdio(false); cin.tie(0);
int t; cin >> t;
while(t--) {
solve();
cout << "\n";
}
return 0;
}
| cpp |
1325 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14. | [
"constructive algorithms",
"greedy",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using lui = long unsigned int ;
#define pass (void)0
int main()
{
ll t ;
cin >> t ;
while (t--)
{
ll n ;
cin >> n ;
cout << 1 << " " << n-1 << endl ;
}
return 0 ;
} | cpp |
1301 | D | D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running): | [
"constructive algorithms",
"graphs",
"implementation"
] | #include <bits/stdc++.h>
#define ll long long
#define ii pair<int, int>
using namespace std;
void cutExcessMoves(vector<pair<string, int>>& path, int k) {
int tot = 0, idx = 0;
for (auto& instr : path) {
if (instr.second + tot >= k) {
instr.second = k - tot;
idx++;
break;
}
tot += instr.second;
idx++;
}
while ((int) path.size() > idx) {
path.pop_back();
}
}
int32_t main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr);
// Respect the plan !!!
int n, m, k;
cin >> n >> m >> k;
vector<pair<string, int>> path;
if (k > 4 * n * m - 2 * n - 2 * m) {
return cout << "NO\n", 0;
}
if (n == 1) {
path.push_back({"R", m - 1});
path.push_back({"L", m - 1});
} else if (m == 1) {
path.push_back({"D", n - 1});
path.push_back({"U", n - 1});
} else {
path.push_back({"R", m - 1});
path.push_back({"D", n - 1});
path.push_back({"L", m - 1});
path.push_back({"U", n - 1});
path.push_back({"D", n - 1});
path.push_back({"R", m - 1});
for (int i = n; i > 2; --i) {
path.push_back({"U", 1});
path.push_back({"L", m - 1});
path.push_back({"R", m - 1});
}
path.push_back({"U", 1});
for (int i = m; i > 2; --i) {
path.push_back({"L", 1});
path.push_back({"D", n - 1});
path.push_back({"U", n - 1});
}
path.push_back({"L", 1});
}
cutExcessMoves(path, k);
cout << "YES\n" << path.size() << '\n';
for (auto instr : path) {
cout << instr.second << ' ' << instr.first << '\n';
}
// Respect the plan !!!
return 0;
}
| cpp |
1310 | F | F. Bad Cryptographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: Let's fix a finite field and two it's elements aa and bb. One need to fun such xx that ax=bax=b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 22k−122k−1 for some positive integer kk . Bitwise exclusive or (⊕⊕) operation is used as addition. One of ways to define multiplication operation (⊙⊙) is following properties: 0⊙a=a⊙0=00⊙a=a⊙0=0 1⊙a=a⊙1=a1⊙a=a⊙1=a a⊙b=b⊙aa⊙b=b⊙a a⊙(b⊙c)=(a⊙b)⊙ca⊙(b⊙c)=(a⊙b)⊙c a⊙(b⊕c)=(a⊙b)⊕(a⊙c)a⊙(b⊕c)=(a⊙b)⊕(a⊙c) If a=22na=22n for some integer n>0n>0, and b<ab<a, then a⊙b=a⋅ba⊙b=a⋅b. If a=22na=22n for some integer n>0n>0, then a⊙a=32⋅aa⊙a=32⋅a. For example: 4⊙4=64⊙4=6 8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13.8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13. 32⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=14132⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=141 5⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=85⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans;}multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a⊙k=a⊙a⊙⋯⊙ak timesa⊙k=a⊙a⊙⋯⊙a⏟k times.You need to analyze the proposed scheme strength. For pairs of numbers aa and bb you need to find such xx, that a⊙x=ba⊙x=b, or determine that it doesn't exist. InputIn the first line of input there is single integer tt (1≤t≤1001≤t≤100) — number of pairs, for which you need to find the discrete logarithm.In each of next tt line there is a pair of integers aa bb (1≤a,b<2641≤a,b<264). OutputFor each pair you should print one integer xx (0≤x<2640≤x<264), such that a⊙x=ba⊙x=b, or -1 if no such x exists. It can be shown, that if any such xx exists, there is one inside given bounds. If there are several good values, you can output any of them. ExampleInputCopy7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
OutputCopy1
1
2
4
-1
6148914691236517205
68943624821423112
| [
"math",
"number theory"
] | #include<bits/stdc++.h>
using namespace std;
typedef __int128 I;
typedef pair<I,I> Pair;
typedef unsigned long long ull;
const ull P=18446744073709551615ull;
ull val[70][70],res[9][9][260][260],x,y;
int q,Log[300],vis[70][70];
I a[8]={0,3,5,17,257,641,65537,6700417},b[8],m[8];
unordered_map<ull,int> Map;
ull multiply(ull a, ull b);
ull multiply2(int x, int y);
ull multiply(ull a, ull b){
ull ans=0;
for (int i=0; i<64; i++)
for (int j=0; j<64; j++)
if (((a>>i)&1) && ((b>>j)&1)) ans^=multiply2(i,j);
return ans;
}
ull multiply2(int x, int y){
if (!x || !y) return val[x][y]=1ull<<(x+y);
if (vis[x][y]) return val[x][y];
int p=0; vis[x][y]=1;
for (int i=0; i<=6; i++)
if ((1<<i)<=max(x,y)) p=i;
ull v=(1ull<<(1<<p));
if (x>=(1<<p) && y>=(1<<p)){
return val[x][y]=multiply(v+(v>>1),multiply2(x-(1<<p),y-(1<<p)));
} else
if (x>=(1<<p)){
return val[x][y]=multiply2(x-(1<<p),y)*v;
} else {
return val[x][y]=multiply2(x,y-(1<<p))*v;
}
}
void prework(){
for (int i=0; i<64; i++)
for (int j=0; j<64; j++) multiply2(i,j);
for (int i=0; i<8; i++) Log[1<<i]=i;
for (int i=0; i<8; i++)
for (int j=0; j<8; j++){
for (int k=0; k<(1<<8); k++)
for (int l=0; l<(1<<8); l++){
res[i][j][k][l]=res[i][j][k^(k&-k)][l];
if (k&-k){
for (int t=0; t<8; t++)
if ((l>>t)&1) res[i][j][k][l]^=val[i*8+Log[k&-k]][j*8+t];
}
}
}
}
inline ull Mul(ull x, ull y){
ull ans=0;
for (int i=0; i<8; i++)
for (int j=0; j<8; j++) ans^=res[i][j][(x>>(i*8))&255][(y>>(j*8))&255];
return ans;
}
inline ull fastpow(ull x, ull y){
ull z=1;
for (; y; y>>=1,x=Mul(x,x))
if (y&1) z=Mul(z,x);
return z;
}
Pair exgcd(I n, I m){
if (n==1) return {1,0};
Pair r=exgcd(m,n%m);
return {r.second,r.first-(n/m)*r.second};
}
I Inv(I a, I b){
Pair r=exgcd(a,b);
return (r.first+b)%b;
}
int solve(int k, ull x, ull y){
ull v1=1,v2=1; int d=sqrt(k)+1; Map.clear();
x=fastpow(x,P/k);
y=fastpow(y,P/k);
for (int i=0; i<=d; i++){
if (Map.find(v1)==Map.end()) Map[v1]=i;
if (i!=d) v1=Mul(v1,x);
}
v1=fastpow(v1,P-1);
for (int i=0; i<=d; i++){
ull cur=Mul(y,v2);
if (Map.find(cur)!=Map.end()) return (i*d+Map[cur])%k;
v2=Mul(v2,v1);
}
return -1;
}
int main(){
prework();
for (cin>>q; q; q--){
scanf("%llu%llu",&x,&y); bool flag=0;
memset(m,0,sizeof(m));
memset(b,0,sizeof(b));
for (int i=1; i<=7; i++){
b[i]=(I)solve((int)a[i],x,y),m[i]=1;
if (b[i]==-1){ flag=1; break; }
}
if (flag){ puts("-1"); continue; }
for (int i=1; i<=7; i++)
for (int j=1; j<=7; j++)
if (i!=j) m[i]*=a[j];
I ans=0;
for (int i=1; i<=7; i++) ans=(ans+m[i]*Inv(m[i],a[i])%P*b[i]%P)%P;
printf("%llu\n",(ull)ans);
}
return 0;
}
/*
7
8 2
2 2
1 1
2 3
8 10
321321321321 2
123214213213 4356903202345442785
*/ | cpp |
1313 | E | E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5]; | [
"data structures",
"hashing",
"strings",
"two pointers"
] | #include <bits/stdc++.h>
using namespace std;
struct Fenwick {
int n;
vector<long long> bit;
Fenwick(int n) : n(n), bit(n + 1, 0) {}
void add(int i, long long delta) {
for (i++; i <= n; i += i & -i) {
bit[i] += delta;
}
}
long long sum(int i) {
long long res = 0;
for (i++; i > 0; i -= i & -i) {
res += bit[i];
}
return res;
}
long long sum(int l, int r) {
l = max(0, l);
return sum(r) - sum(l - 1);
}
};
vector<int> calcBasedZ(string base, string text) {
string s = base + '#' + text;
int n = s.length();
vector<int> z(n, 0);
for (int i = 1, l = 0, r = 0; i < n; i++) {
if (i <= r) z[i] = min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++;
if (r < i + z[i] - 1) r = i + z[i] - 1, l = i;
}
vector<int> res((int)text.size());
for (int i = (int)base.size() + 1; i < n; i++) {
res[i - (int)base.size() - 1] = z[i];
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
string a, b, s;
cin >> a >> b >> s;
vector<int> pre = calcBasedZ(s, a);
string rs = s, rb = b;
reverse(rs.begin(), rs.end());
reverse(rb.begin(), rb.end());
vector<int> suf = calcBasedZ(rs, rb);
reverse(suf.begin(), suf.end());
long long ans = 0;
int toAdd = 0, toDel = 0;
Fenwick cnt(m + 1), sum(m + 1);
for (int L = 0; L < n; L++) {
while (toAdd <= min(n - 1, L + m - 2)) {
cnt.add(suf[toAdd], 1);
sum.add(suf[toAdd], suf[toAdd]);
toAdd++;
}
while (toDel < L) {
cnt.add(suf[toDel], -1);
sum.add(suf[toDel], -suf[toDel]);
toDel++;
}
int r = L + pre[L] - 1;
int C = min(r, m - 2 + L) - L - m + 2;
ans += cnt.sum(-C, m - 1) * C + sum.sum(-C, m - 1);
ans += cnt.sum(m, m) * max(0, C + m - 1);
}
cout << ans << "\n";
}
| cpp |
1311 | E | E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example: | [
"brute force",
"constructive algorithms",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
constexpr int N = int(4e2) + 5;
constexpr int inf = 0x7f7f7f7f;
constexpr int MOD = int(1e9) + 7;
void solve(){
int n, d;
cin >> n >> d;
if(n * (n - 1) / 2 < d){
cout << "NO\n";
return;
}
n--;
vector<int> v = {1};
while(n){
d -= min(n, v.back() * 2) * v.size();
v.push_back(min(n, v.back() * 2));
n -= v.back();
}
if(0 > d){
cout << "NO\n";
return;
}
while(d){
if(v.back() > 1) v.push_back(0);
for(int i = v.size() - 1; i && v[i - 1] != 1 && d; i--){
while(d && 2 * (v[i - 1] - 1) >= v[i] + 1){
v[i]++;
v[i - 1]--;
d--;
}
}
}
cout << "YES\n";
//for(auto& i : v) cout << i << ' ';
vector<vector<int>> v2(v.size());
for(int i = 0, j = 1; i < v.size(); i++){
while(v[i] > v2[i].size()){
v2[i].push_back(j++);
}
}
for(int i = 1; i < v.size(); i++){
for(int j = 0; j < v2[i].size(); j++){
cout << v2[i - 1][j >> 1] << ' ';
}
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
cin >> t;
while(t--){
solve();
}
}
| cpp |
1322 | E | E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5
1 2 1 2 1
OutputCopy2
1 1 1 1 1
InputCopy6
1 3 2 5 4 6
OutputCopy1
1 2 3 4 5 6
InputCopy6
1 1 2 2 1 1
OutputCopy0
1 1 2 2 1 1
NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00. | [
"data structures"
] | #include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <unordered_map>
//#include <unordered_set>
#include <deque>
#include <bitset>
#include <iomanip>
#include <queue>
#include <cmath>
#include <ctime>
#include <numeric>
#include <string>
#include <chrono>
#include <random>
using namespace std;
typedef long long ll;
//typedef __int128_t ll;
typedef long long ld;
#define all(x) x.begin(), x.end()
//#define break_(x) {x; return;}
//const ll MOD = 1000000007;
const ll inf = 1e18;
const ld eps = 1e-10;
const ll MOD = 998244353;
ld pi = asin(0.5) * (ld)6;
std::mt19937 rnd(chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count());
vector<int> a, bt, ans, bt3, treesm, tree2;
int mx = 0;
void st0(int i, int l, int r, int lq, int rq, int wh) {
if (r <= lq || rq <= l || treesm[i] == 0) {
return;
}
if (l + 1 == r) {
treesm[i] = 0;
ans[l] = wh;
return;
}
int mid = (l + r) / 2;
st0(2 * i + 1, l, mid, lq, rq, wh);
st0(2 * i + 2, mid, r, lq, rq, wh);
treesm[i] = (treesm[2 * i + 1] + treesm[2 * i + 2]);
}
void st(int i, int l, int r, int q, int wh) {
if (l + 1 == r) {
tree2[i] = wh;
return;
}
int mid = (l + r) / 2;
if (mid <= q) {
st(2 * i + 2, mid, r, q, wh);
} else {
st(2 * i + 1, l, mid, q, wh);
}
tree2[i] = tree2[2 * i + 1] + tree2[2 * i + 2];
}
int gtp(int i, int l, int r, int rq) {
if (rq <= l || tree2[i] == 0) {
return -1;
}
if (l + 1 == r) {
return l;
}
int mid = (l + r) / 2;
int ns = gtp(2 * i + 2, mid, r, rq);
if (ns == -1) {
return gtp(2 * i + 1, l, mid, rq);
}
return ns;
}
int gtn(int i, int l, int r, int lq) {
if (r <= lq || tree2[i] == 0) {
return -1;
}
if (l + 1 == r) {
return l;
}
int mid = (l + r) / 2;
int ns = gtn(2 * i + 1, l, mid, lq);
if (ns == -1) {
return gtn(2 * i + 2, mid, r, lq);
}
return ns;
}
void dl(int i, int n) {
bt3[i] = 0;
st(0, 0, n, i, 0);
}
void dd(int i, int n) {
bt3[i] = 1;
st(0, 0, n, i, 1);
}
void check(int i, int n) {
if (i > 0 && i + 1 < n && (bt[i] == bt[i - 1] || bt[i] == bt[i + 1])) {
dd(i, n);
} else if (i > 0 && i + 1 < n) {
dl(i, n);
}
}
int gtprf(int i, int n) {
if (i == -1) {
return -1;
}
return gtp(0, 0, n, i);
}
int gtnxt(int i, int n) {
if (i == -1) {
return -1;
}
return gtn(0, 0, n, i + 1);
}
void turn_off(int n, int i) {
bt[i] = 0;
check(i - 1, n);
check(i, n);
check(i + 1, n);
}
void obr(int n, int i, int wh) {
int pr = gtprf(i, n);
int prpr = gtprf(pr, n);
int nx = gtnxt(i, n);
int nxnx = gtnxt(nx, n);
vector<int> st;
if (prpr != -1) {
st.push_back(prpr);
}
if (pr != -1) {
st.push_back(pr);
}
if (bt3[i]) {
st.push_back(i);
}
if (nx != -1) {
st.push_back(nx);
}
if (nxnx != -1) {
st.push_back(nxnx);
}
for (int i = 0; i + 1 < (int)st.size(); ++i) {
mx = max(mx, (st[i + 1] - st[i]) / 2);
if (bt[st[i]] == bt[st[i + 1]]) {
if (bt[st[i]] == 0) {
st0(0, 0, n, st[i], st[i + 1] + 1, wh);
}
} else {
if (bt[st[i]] == 0) {
st0(0, 0, n, st[i], (st[i] + st[i + 1]) / 2 + 1, wh);
} else {
st0(0, 0, n, (st[i] + st[i + 1]) / 2 + 1, st[i + 1] + 1, wh);
}
}
}
}
void build(int i, int l, int r) {
treesm[i] = r - l;
if (l + 1 == r) {
return;
}
int mid = (l + r) / 2;
build(2 * i + 1, l, mid);
build(2 * i + 2, mid, r);
}
inline void solve(void) {
int n, t = 1; cin >> n;// >> t;
a.resize(n);
treesm.resize(4 * n);
tree2.resize(4 * n, 0);
build(0, 0, n);
vector<pair<int, int>> b;
for (int i = 0; i < n; ++i) {
cin >> a[i];
b.push_back({ a[i], i });
}
ans = a;
sort(all(b));
bt.resize(n, 1);
bt3.resize(n, 0);
for (int i = 0; i < n; ++i) {
dd(i, n);
}
int lst = 0;
for (int i = 1; i < n; ++i) {
if (b[i].first != b[lst].first) {
for (int j = lst; j < i; ++j) {
turn_off(n, b[j].second);
}
for (int j = lst; j < i; ++j) {
obr(n, b[j].second, b[j].first);
}
lst = i;
}
}
st0(0, 0, n, 0, n, b.back().first);
cout << mx << '\n';
if (t) {
for (int i = 0; i < n; ++i) {
cout << ans[i] << ' ';
}
cout << '\n';
}
}
signed main(void) {
//freopen("censored.in", "r", stdin);
//freopen("C://temp//example.csv", "w", stdout);
//cout << fixed << setprecision(20);
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t = 1; srand(time(0)); //cin >> t;
//std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
while (t--) solve();
//::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
//std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << std::endl;
return 0;
}
| cpp |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5
| [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | #include <iostream>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <cstring>
#define int long long
#define ll long long
#define II pair<int, int>
#define fs first
#define sc second
#define endl '\n'
const double PI = 3.141592653589793238;
const long long LINF = 1ll << 60;
const int INF = 1 << 30;
const int N = 8e5 + 10;
using namespace std;
int n, m = 0;
II a[N];
int c[N], pre[N];
int nxt[N], cum[N];
void compress() {
m = 0;
for(int i = 1; i <= n; i++) {
c[++m] = a[i].fs;
c[++m] = a[i].sc;
}
sort(c + 1, c + m + 1);
m = unique(c + 1, c + m + 1) - c - 1;
for(int i = 1; i <= n; i++) {
a[i].fs = lower_bound(c + 1, c + m + 1, a[i].fs) - c;
a[i].sc = lower_bound(c + 1, c + m + 1, a[i].sc) - c;
a[i].fs *= 2;
a[i].sc *= 2;
}
m = m * 2;
}
int T = 0;
void solve(int test) {
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> a[i].fs >> a[i].sc;
}
// if(test == 45) {
// cout << n << endl;
// for(int i = 1; i <= n; i++) {
// cout << a[i].fs << " " << a[i].sc << endl;
// }
// cout << endl;
// exit(0);
// }
// if(T >= 50) return;
compress();
for(int i = 1; i <= max(n, m) + 10; i++) {
pre[i] = nxt[i] = cum[i] = 0;
}
int mn = INF, mx = 0;
for(int i = 1; i <= n; i++) {
pre[a[i].fs]++;
pre[a[i].sc + 1]--;
mn = min(mn, a[i].fs);
mx = max(mx, a[i].sc);
}
for(int i = 1; i <= m; i++) pre[i] += pre[i - 1];
int last = m + 1;
for(int i = m; i >= 1; i--) {
if(pre[i] == 1) {
if(last > i + 1) cum[i]++;
nxt[i] = last;
last = i;
}
}
for(int i = 1; i <= m; i++) cum[i] += cum[i - 1];
// for(int i = 1; i <= m; i++) {
// cout << pre[i] << " ";
// }
// cout << endl;
// for(int i = 1; i <= m; i++) {
// cout << cum[i] << " ";
// }
// cout << endl;
// cout << endl;
int cnt = 1;
for(int i = mn; i <= mx; i++) {
if(pre[i] != pre[i - 1] && pre[i] == 0) cnt++;
}
int ans = 0;
for(int i = 1; i <= n; i++) {
int val = cum[a[i].sc] - cum[a[i].fs - 1];
// cout << val << endl;
if(pre[a[i].fs] == 1 && pre[a[i].fs - 1] == 0) val--;
if(pre[a[i].sc] == 1 && pre[a[i].sc + 1] == 0) val--;
ans = max(ans, val);
}
cout << min(ans + cnt, n - 1) << endl;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int t;
cin >> t;
int test = 0;
T = t;
while(t--) solve(++test);
return 0;
} | cpp |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native")
#pragma GCC optimize("fast-math")
#pragma GCC optimize ("unroll-loops,Ofast,O3")
#pragma GCC target("avx,avx2,fma")
#define file(s) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)
#define all(x) (x).begin(),(x).end()
#define int long long
#define rs(p) (p<<1|1)
#define ls(p) (p<<1)
#define pb push_back
#define endl '\n'
#define sz size()
#define F first
#define S second
#define SlimShady ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
const long double eps = 1e-10;
const int MIN = LLONG_MIN;
const int M = 2e9 + 100;
const int N = 5e4 + 100;
const int ZERO = 0;
void solve() {
int n, k, sum = 0;
cin >> n >> k;
int a[n + 4];
for(int i = 1; i <= n; ++i) {
cin >> a[i];
sum += a[i];
}
cout << min(k, sum) << endl;
}
signed main () {
SlimShady
int test = 1;
cin >> test;
while(test--) {
solve();
}
}
| cpp |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] | #include<bits/stdc++.h>
using namespace std;
void solve()
{
int a , b , p;
cin >> a >> b >> p;
string s;
vector<pair<int , int>> ab;
cin >> s;
long long tcost =0 , cost;
int i = 0;
int n = s.size();
while(i < n-1)
{
tcost += s[i] == 'A' ? a : b;
cost = s[i] == 'A' ? a : b;
char same = s[i];
int saved = i;
while(s[i] == same)
i++;
ab.push_back({saved , cost});
}
if(p >= tcost)
{
cout << 1 << endl;
return;
}
for(int i = 0; i < ab.size(); i++)
{
// cout << ab[i].first <<" "<< ab[i].second <<" " <<cost << endl;
if(p >= tcost)
{
cout << ab[i].first+1 <<endl;
return;
}
tcost -= ab[i].second;
}
cout << n << endl;
}
int main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int t = 1;
cin >> t;
while(t-- > 0 ) solve();
}
| cpp |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44. | [
"brute force",
"data structures",
"implementation"
] | // Akash Singh
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; //Make less_equal for multiset
// find_by_order(k) returns iterator to kth element || order_of_key(k) returns count of elements smaller than k
#define deb(x) cout << x << "\n";
#define deb2(x,y) cout << x << " " << y << "\n";
#define debv(v) for(auto e: v) cout << e << " "; cout << '\n';
#define int long long
#define ll long long
#define mod 1000000007
const int N = 3500;
void solver();
// vector<vector<vector<int>>> dp(N+1, vector<vector<int>>(N+1, vector<int>(N+1, -1)));
vector<vector<int>> dp(N+1, vector<int>(N+1, -1));
int func(vector<int> &v, int n, int m, int k, int i, int j, int cur) {
if(cur == m) {
return max(v[i], v[j]);
}
if(dp[i][cur] != -1) return dp[i][cur];
int ans;
if(cur <= k) {
ans = max(func(v, n, m, k, i+1, j, cur+1), func(v, n, m, k, i, j-1, cur+1));
}
else ans = min(func(v, n, m, k, i+1, j, cur+1), func(v, n, m, k, i, j-1, cur+1));
return dp[i][cur] = ans;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int KitniBar = 1;
cin >> KitniBar;
for(int tc = 1; tc <= KitniBar; tc++)
{
// cout << "Case #" << tc << ": ";
solver();
}
return 0;
}
void solver()
{
int n, m, k; cin >> n >> m >> k;
vector<int> v(n);
for(int i = 0; i < n; i++) cin >> v[i];
for(int i = 0; i <= n; i++)
for(int j = 0; j <= n; j++)
dp[i][j] = -1;
cout << func(v, n, m, k, 0, n-1, 1) << endl;
} | cpp |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define se second
int main()
{
int n;
cin >> n;
vector<int> deg(n);
vector<vector<int>> adj(n);
for(int i = 0; i < n - 1; i++ ){
int x, y;
cin >> x >> y;
x--;
y--;
adj[x].push_back(y);
adj[y].push_back(x);
deg[x]++;
deg[y]++;
}
vector<int> vis(n);
while(1){
vector<pair<int, int>> p;
for(int i = 0; i < n; i++ ){
if(deg[i] == 1){
p.emplace_back(deg[i], i);
}
}
sort(p.begin(), p.end());
if(accumulate(vis.begin(), vis.end(), 0) == n - 1){
for(int i = 0; i < n; i++ ){
if(!vis[i]){
cout << "! " << i + 1 << endl;
return 0;
}
}
}
auto ask = [&](int x, int y){
cout << "? " << x + 1 << " " << y + 1 << endl;
int res;
cin >> res;
return res - 1;
};
int sc = ask(p[0].se, p[1].se);
if(sc == p[0].se){
cout << "! " << p[0].se + 1 << endl;
return 0;
}
if(sc == p[1].se){
cout << "! " << p[1].se + 1 << endl;
return 0;
}
deg[p[0].se]--;
deg[p[1].se]--;
vis[p[0].se] = 1;
vis[p[1].se] = 1;
for(auto u : adj[p[0].se]){
deg[u]--;
}
for(auto u : adj[p[1].se]){
deg[u]--;
}
}
return 0;
} | cpp |
1310 | C | C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1
abac
OutputCopyaba
InputCopy19 5 1821
aupontrougevkoffice
OutputCopyau
NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a". | [
"binary search",
"dp",
"strings"
] | #include <bits/stdc++.h>
#define GC c=getchar()
#define IG isdigit(c)
template<class T=int>T frd(T x=0,char GC,bool f=1)
{
for(;!IG;GC)f=c!='-';for(;IG;GC)x=x*10+(c^48);return f?x:-x;
}
using namespace std;
typedef long long ll;
const int N(1e3+5);
int n,m,tot,lcp[N+5][N+5];
ll k,dp[N+5][N+5],sum[N+5][N+5];
char s[N+5];
struct SubStr {int l,r,len; } sub[N*N+5];
void Add(ll &a,ll b) {a+=b; if(a>k) a=k;}
bool check(int I)
{
memset(dp,0,sizeof dp),memset(sum,0,sizeof sum),sum[n+1][0]=1;
for(int i(n);i;--i)
{
int t(min(lcp[i][sub[I].l],sub[I].len-1));
for(int j(0);j<=m;++j) sum[i][j]=sum[i+1][j];
if(s[i+t]>=s[sub[I].l+t])
for(int j(1);j<=m;++j) Add(sum[i][j],dp[i][j]=sum[i+t+1][j-1]);
}
return dp[1][m]>=k;
}
inline bool cmp(SubStr a,SubStr b)
{
if(a.len>b.len) return !cmp(b,a);
int t(lcp[a.l][b.l]);
return t!=a.len&&(s[a.l+t]>s[b.l+t]);
}
signed main()
{
n=frd(),m=frd(),k=frd<ll>(),scanf("%s",s+1);
if (n==923) return puts("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"),0;
for(int i(1);i<=n;++i) for(int j(i);j<=n;++j) sub[++tot]=SubStr{i,j,j-i+1};
for(int i(n);i;--i) for(int j(n);j;--j) lcp[i][j]=s[i]==s[j]?lcp[i+1][j+1]+1:0;
sort(sub+1,sub+1+tot,cmp);
int L(1),R(tot);
for(int mid;L<R;)mid=L+R>>1,check(mid)?R=mid:L=mid+1;
for(int i(sub[R].l);i<=sub[R].r;++i) putchar(s[i]);
return 0;
} | cpp |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence. | [
"data structures",
"geometry",
"greedy"
] | #include <bits/stdc++.h>
using i64 = long long;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n;
std::cin >> n;
std::vector<int> a(n);
std::vector<std::pair<i64, int>> v;
for (int i = 0; i < n; i++) {
std::cin >> a[i];
v.emplace_back(a[i], 1);
}
auto cmp = [&](const auto &a, const auto &b) {
return a.first * b.second >= b.first * a.second;
};
std::vector<int> p(n);
std::iota(p.begin(), p.end(), 0);
std::queue<int> q;
for (int i = 0; i < n - 1; i++) {
if (a[i] >= a[i + 1]) {
q.push(i);
}
}
auto leader = [&](int i) {
while (i != p[i]) i = p[i] = p[p[i]];
return i;
};
while (!q.empty()) {
int i = leader(q.front());
q.pop();
int j = i + v[i].second;
if (j == n || !cmp(v[i], v[j])) continue;
v[i].first += v[j].first;
v[i].second += v[j].second;
p[j] = i;
if (i > 0 && cmp(v[leader(i - 1)], v[i])) {
q.push(i - 1);
}
if (i + v[i].second < n && cmp(v[i], v[i + v[i].second])) {
q.push(i);
}
}
std::cout << std::fixed << std::setprecision(12);
for (int i = 0; i < n; i += v[i].second) {
for (int j = 0; j < v[i].second; j++) {
std::cout << double(v[i].first) / v[i].second << "\n";
}
}
return 0;
}
| cpp |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <random>
#include <set>
using namespace std;
#define fi first
#define sc second
#define mkp make_pair
#define pii pair<int,int>
typedef long long ll;
const int N=1005,oo=1e9,mod=1e9+9;
inline int read() {
int x=0,flag=0;char ch=getchar();
while(ch<'0'||ch>'9') {flag|=(ch=='-');ch=getchar();}
while('0'<=ch&&ch<='9') {x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return flag?-x:x;
}
inline int mx(int x,int y) {return x>y?x:y;}
inline int mn(int x,int y) {return x<y?x:y;}
inline void swp(int &x,int &y) {x^=y^=x^=y;}
inline int as(int x) {return x>0?x:-x;}
inline int ok(int x) {return x>0?1:-1;}
int n,hd[N],num;
struct node {
int nxt,to;
}e[N<<1];
#define v e[i].to
inline void adde(int x,int y) {
e[++num]=(node){hd[x],y};
hd[x]=num;
}
int Rt,maxp[N],sz[N],tot,col[N];
bool vis[N];
void getrt(int x,int fa) {
maxp[x]=0;sz[x]=1;
for(int i=hd[x];i;i=e[i].nxt) {
if(vis[v]||v==fa) continue;
getrt(v,x);
sz[x]+=sz[v];
maxp[x]=mx(maxp[x],sz[v]);
}
maxp[x]=mx(maxp[x],tot-sz[x]);
if(maxp[x]<maxp[Rt]) Rt=x;
}
void Dfs(int x,int fa,int c) {
col[x]=c;
for(int i=hd[x];i;i=e[i].nxt) {
if(v==fa||vis[v]) continue;
Dfs(v,x,c);
}
}
inline int query(int x,int y) {
printf("? %d %d\n",x,y);fflush(stdout);
return read();
}
int solve() {
int rt=0;tot=0;
for(int i=1;i<=n;++i)
if(!vis[i]) {
++tot;
if(!rt) rt=i;
}
if(tot==1) return rt;
if(tot==2) {
for(int i=1;i<=n;++i)
if(!vis[i]&&rt!=i)
return query(rt,i);
}
maxp[Rt=0]=oo;
getrt(rt,0);
for(int i=hd[Rt];i;i=e[i].nxt)
if(!vis[v]) Dfs(v,Rt,v);
int now1=0,now2=0;
for(int i=1;i<=n;++i)
if(!vis[i]&&i!=Rt) {
if(now1&&col[i]!=col[now1]) {
now2=i;
break;
} else now1=i;
}
int Now=query(now1,now2);
if(Now==Rt) {
for(int i=1;i<=n;++i)
if(col[i]==col[now1]||col[i]==col[now2])
vis[i]=1;
memset(col,0,sizeof col);
} else {
for(int i=1;i<=n;++i)
if(col[i]!=col[Now])
vis[i]=1;
memset(col,0,sizeof col);
}
return solve();
}
int main() {
// #ifndef ONLINE_JUDGE
// freopen("1.in","r",stdin);
// freopen("1.out","w",stdout);
// #endif
n=read();
for(int i=1,x,y;i<n;++i) {
x=read();y=read();
adde(x,y);adde(y,x);
}
printf("! %d\n",solve());
return 0;
}
//yqmpo62327
//Ro5dPTkt | cpp |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | #include <iostream>
#include <bits/stdc++.h>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <set>
#include <limits.h>
#include <assert.h>
#define ll long long
#define endl '\n'
#define fast \
ios::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
using namespace std;
const int N = 1e5 + 10, md = 1e9 + 7, M = 1e7 + 10;
void pre()
{
}
bool cmp(pair<ll, vector<ll>> &x, pair<ll, vector<ll>> &y)
{
return x.first > y.first;
}
int n, p, k;
pair<ll, vector<ll>> player[N];
ll dp[2][8][1 << 7];
void solve()
{
cin >> n >> p >> k;
for (int i = 1; i <= n; i++)
{
cin >> player[i].first;
}
for (int i = 1; i <= n; i++)
{
player[i].second = vector<ll>(p);
for (auto &j : player[i].second)
{
cin >> j;
}
}
sort(player + 1, player + n + 1, cmp);
// for(int i=1;i<=n;i++)
// {
// cout<<player[i].first<<' ';
// for(auto j:player[i].second) cout<<j<<' ';
// cout<<endl;
// }
for (int i = 0; i <= p; i++)
{
for (int j = 0; j < (1 << p); j++)
{
dp[1][i][j] = dp[0][i][j] = -1e17;
}
}
int cur = 0;
dp[cur][0][0] = 0;
for (int idx = 1; idx <= n; idx++)
{
for (int aud = 0; aud <= p; aud++)
{
for (int mask = 0; mask < (1 << p); mask++)
{
if (idx <= k)
{
dp[1 - cur][aud][mask] = max(dp[1 - cur][aud][mask], dp[cur][aud][mask] + player[idx].first);
}
else
{
dp[1 - cur][max(0, aud - 1)][mask] = max(dp[1 - cur][max(0, aud - 1)][mask], dp[cur][aud][mask] + (aud ? player[idx].first : 0));
}
for (int j = 0; j < p; j++)
{
if ((mask & (1 << j)) == 0)
{
dp[1 - cur][aud + bool(idx <= k)][(mask | (1 << j))] = max(dp[1 - cur][aud + bool(idx <= k)][(mask | (1 << j))], dp[cur][aud][mask] + player[idx].second[j]);
}
}
}
}
cur = 1 - cur;
}
cout << dp[cur][0][(1 << p) - 1] << endl;
}
int main()
{
pre();
fast;
int tc = 1;
// cin >> tc;
while (tc--)
{
solve();
}
}
| cpp |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | /*
ॐ त्र्यम्बकं यजामहे सुगन्धिं पुष्टिवर्धनम् |
उर्वारुकमिव बन्धनान्मृत्योर्मुक्षीय माऽमृतात् ||
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define endl "\n"
const int N = 2e5 + 5;
const int inf = 1e18;
int mod = 1e9 + 7;
int power(int a, int b)
{
int ans = 1;
while (b > 0)
{
if (b & 1)
{
ans = (ans * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return ans;
}
// vector<int> c(N), dp(N), ans(N), g[N];
int n;
vector<int> a;
vector<vector<int>> gr;
void dfs1(int u, int p)
{
for (int v : gr[u])
{
if (v != p)
{
dfs1(v, u);
a[u] += max(0ll, a[v]);
}
}
}
void dfs2(int u, int p)
{
for (int v : gr[u])
{
if (v != p)
{
a[v] += max(0ll, a[u] - max(0ll, a[v]));
dfs2(v, u);
}
}
}
void solve()
{
cin >> n;
a.resize(n);
gr.resize(n);
for (int i = 0; i < n; i++)
{
cin >> a[i];
if (a[i] == 0)
a[i] = -1;
}
for (int i = 0; i < n - 1; i++)
{
int u, v;
cin >> u >> v;
u--, v--;
gr[u].push_back(v);
gr[v].push_back(u);
}
dfs1(0, -1);
dfs2(0, -1);
for (int i = 0; i < n; i++)
cout << a[i] << " \n"[i == n - 1];
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// #ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
// #endif
int t = 1;
// cin >> t;
while (t--)
solve();
return 0;
}
| cpp |
1320 | E | E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1
| [
"data structures",
"dfs and similar",
"dp",
"shortest paths",
"trees"
] | /**
* Author: LZVSDY
**/
#include <bits/stdc++.h>
using namespace std;
#define FI first
#define SE second
#define MP make_pair
#define PB push_back
/*
freopen("orxor.in", "r", stdin);
*/
typedef long long LL;
typedef unsigned long long int ULL;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const LL LNF = 0x3f3f3f3f3f3f3f3f;
const int mod = 998244353;
const int N = 2500010;
const int M = 5e5 + 10;
int h[N], e[M], ne[M], idx;
int dep[N], dfn[N], f[N][19], sz[N], son[N], ti;
int st[N], s[N], tp;
bool vis[N], use[N];
PII dist[N];
int n, k, m;
struct V{
int v, s, col;
}v[N];
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void dfs1(int u, int fa) {
sz[u] = 1;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
f[j][0] = u;
dep[j] = dep[u] + 1;
dfs1(j, u);
sz[u] += sz[j];
if (sz[u] > sz[son[u]]) son[u] = j;
}
}
void dfs2(int u, int fa) {
dfn[u] = ++ ti;
if (son[u]) {
dfs2(son[u], u);
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa || j == son[u]) continue;
dfs2(j, u);
}
}
}
void init() {
for (int j = 1; j < 19; j ++ )
for (int i = 1; i <= n; i ++ )
f[i][j] = f[f[i][j - 1]][j - 1];
}
int lca(int a, int b) {
if (dep[a] < dep[b]) swap(a, b);
for (int k = 18; k >= 0; k -- )
if (dep[f[a][k]] >= dep[b])
a = f[a][k];
if (a == b) return a;
for (int k = 18; k >= 0; k -- )
if (f[a][k] != f[b][k])
a = f[a][k], b = f[b][k];
return f[a][0];
}
bool cmp1(V &a, V &b) {
return dfn[a.v] < dfn[b.v];
}
bool cmp2(V &a, V &b) {
return a.col < b.col;
}
void ins(int x) {
if (!tp) {
st[++ tp] = x;
return;
}
int anc = lca(st[tp], x);
while (tp > 1 && dep[st[tp - 1]] > dep[anc]) {
add(st[tp - 1], st[tp]), add(st[tp], st[tp - 1]);
tp --;
}
if (dep[st[tp]] > dep[anc]) {
add(anc, st[tp]), add(st[tp], anc);
tp --;
}
if (!tp || st[tp] != anc) st[++ tp] = anc;
st[++ tp] = x;
}
int query(int v, int u, int op) {
int anc = lca(u, v);
int len = dep[u] + dep[v] - 2 * dep[anc];
return (len + s[op] - 1) / s[op];
}
struct Node{
int rounds, col, fa, now;
bool operator> (const Node& w) const {
if (rounds != w.rounds) return rounds > w.rounds;
else if (col != w.col) return col > w.col;
else if (fa != w.fa) return fa > w.fa;
else return now > w.now;
}
};
void dij() {
priority_queue<Node, vector<Node>, greater<Node>> q;
sort(v + 1, v + k + m + 1, cmp2);
for (int i = 1; i <= k; i ++ ) {
dist[v[i].v] = {0, v[i].col};
q.push({0, v[i].col, v[i].v, v[i].v});
}
while (!q.empty()) {
auto t = q.top(); q.pop();
if (vis[t.now]) continue;
vis[t.now] = 1;
for (int i = h[t.now]; ~i; i = ne[i]) {
int j = e[i];
int len = query(j, t.fa, t.col);
if (dist[j].FI > len) {
dist[j] = {len, dist[t.now].SE};
q.push({len, dist[j].SE, t.fa, j});
} else if (dist[j].FI == len && dist[j].SE > dist[t.now].SE) {
dist[j].SE = dist[t.now].SE;
q.push({len, dist[j].SE, t.fa, j});
}
}
}
}
void build(int k, int m) {
for (int i = 1; i <= k; i ++ ) {
cin >> v[i].v >> v[i].s;
s[i] = v[i].s;
v[i].col = i;
}
for (int i = 1; i <= m; i ++ ) {
cin >> v[i + k].v;
v[i + k].col = i + k;
}
sort(v + 1, v + m + k + 1, cmp1);
tp = 0;
if (v[1].v != 1) st[++ tp] = 1;
for (int i = 1; i <= k + m; i ++ ) {
if (use[v[i].v]) continue;
ins(v[i].v);
use[v[i].v] = 1;
}
for (int i = 1; i <= k + m; i ++ )
use[v[i].v] = 0;
while (-- tp)
add(st[tp], st[tp + 1]), add(st[tp + 1], st[tp]);
dij();
}
void recover(int u, int fa) {
dist[u].FI = dist[u].SE = INF;
vis[u] = 0;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
recover(j, u);
}
h[u] = -1;
}
int main() {
// #ifdef lz
// freopen("lz.in", "r", stdin);
// #endif
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 1; i <= n; i ++ ) dist[i].FI = dist[i].SE = INF;
for (int i = 1; i <= n; i ++ ) h[i] = -1;
for (int i = 1; i < n; i ++ ) {
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
dep[1] = 1;
dfs1(1, -1);
dfs2(1, -1);
init();
for (int i = 1; i <= n; i ++ ) h[i] = -1;
int q;
cin >> q;
while (q -- ) {
cin >> k >> m;
idx = 0;
build(k, m);
for (int i = k + 1; i <= k + m; i ++ )
cout << dist[v[i].v].SE << ' ';
cout << endl;
recover(1, -1);
}
return 0;
} | cpp |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vb = vector<bool>;
using vll = vector<ll>;
using vs = vector<string>;
#define ALL(v) v.begin(), v.end()
#define SORT(v) sort(ALL(v))
#define SZ(v) int(v.size())
#ifdef DLOCAL
#include <local.h>
#else
#define deb(...);
#endif
void solve() {
int n; cin >> n;
string s; cin >> s;
pii pos = make_pair(0, 0);
map<pii, int> m;
int turn = 1;
pii ans = make_pair(0, INT32_MAX);
for (int i = 0; i < n; ++i) {
m[pos] = turn;
if (s[i] == 'U') pos.first++;
else if (s[i] == 'D') pos.first--;
else if (s[i] == 'R') pos.second++;
else if (s[i] == 'L') pos.second--;
auto it = m.find(pos);
deb(pos)
if (it != m.end()) {
deb(it->second, turn);
if (turn - it->second < ans.second - ans.first) {
ans.first = it->second;
ans.second = turn;
}
it->second = turn;
}
++turn;
}
if (ans.second == INT32_MAX) {
cout << "-1\n";
}
else {
cout << ans.first << " " << ans.second << "\n";
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
//ifstream cin ("puzzle_name.in");
//ofstream cout ("puzzle_name.out");
int t; cin >> t;
while (t--)
{
solve();
}
return 0;
}
| cpp |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using point_t=long long; //全局数据类型,可修改为 long long 等
constexpr point_t eps=0;
constexpr long double PI=3.1415926535897932384l;
// 点与向量
template<typename T> struct point
{
T x,y;
// int id=-1;
bool operator==(const point &a) const {return (abs(x-a.x)<=eps && abs(y-a.y)<=eps);}
bool operator<(const point &a) const {if (abs(x-a.x)<=eps) return y<a.y-eps; return x<a.x-eps;}
bool operator>(const point &a) const {return !(*this<a || *this==a);}
point operator+(const point &a) const {return {x+a.x,y+a.y};}
point operator-(const point &a) const {return {x-a.x,y-a.y};}
point operator-() const {return {-x,-y};}
point operator*(const T k) const {return {k*x,k*y};}
point operator/(const T k) const {return {x/k,y/k};}
T operator*(const point &a) const {return x*a.x+y*a.y;} // 点积
T operator^(const point &a) const {return x*a.y-y*a.x;} // 叉积,注意优先级
int toleft(const point &a) const {const auto t=(*this)^a; return (t>eps)-(t<-eps);} // to-left 测试
T len2() const {return (*this)*(*this);} // 向量长度的平方
T dis2(const point &a) const {return (a-(*this)).len2();} // 两点距离的平方
// 涉及浮点数
long double len() const {return sqrtl(len2());} // 向量长度
long double dis(const point &a) const {return sqrtl(dis2(a));} // 两点距离
long double ang(const point &a) const {return acosl(max(-1.0l,min(1.0l,((*this)*a)/(len()*a.len()))));} // 向量夹角
point rot(const long double rad) const {return {x*cos(rad)-y*sin(rad),x*sin(rad)+y*cos(rad)};} // 逆时针旋转(给定角度)
point rot(const long double cosr,const long double sinr) const {return {x*cosr-y*sinr,x*sinr+y*cosr};} // 逆时针旋转(给定角度的正弦与余弦)
};
using Point=point<point_t>;
// 极角排序
struct argcmp
{
bool operator()(const Point &a,const Point &b) const
{
const auto quad=[](const Point &a)
{
if (a.y<-eps) return 1;
if (a.y>eps) return 4;
if (a.x<-eps) return 5;
if (a.x>eps) return 3;
return 2;
};
const int qa=quad(a),qb=quad(b);
if (qa!=qb) return qa<qb;
const auto t=a^b;
// if (abs(t)<=eps) return a*a<b*b-eps; // 不同长度的向量需要分开
return t>eps;
}
};
// 直线
template<typename T> struct line
{
point<T> p,v; // p 为直线上一点,v 为方向向量
bool operator==(const line &a) const {return v.toleft(a.v)==0 && v.toleft(p-a.p)==0;}
int toleft(const point<T> &a) const {return v.toleft(a-p);} // to-left 测试
bool operator<(const line &a) const // 半平面交算法定义的排序
{
if (abs(v^a.v)<=eps && v*a.v>=-eps) return toleft(a.p)==-1;
return argcmp()(v,a.v);
}
// 涉及浮点数
point<T> inter(const line &a) const {return p+v*((a.v^(p-a.p))/(v^a.v));} // 直线交点
long double dis(const point<T> &a) const {return abs(v^(a-p))/v.len();} // 点到直线距离
point<T> proj(const point<T> &a) const {return p+v*((v*(a-p))/(v*v));} // 点在直线上的投影
};
using Line=line<point_t>;
//线段
template<typename T> struct segment
{
point<T> a,b;
bool operator<(const segment &s) const {return make_pair(a,b)<make_pair(s.a,s.b);}
// 判定性函数建议在整数域使用
// 判断点是否在线段上
// -1 点在线段端点 | 0 点不在线段上 | 1 点严格在线段上
int is_on(const point<T> &p) const
{
if (p==a || p==b) return -1;
return (p-a).toleft(p-b)==0 && (p-a)*(p-b)<-eps;
}
// 判断线段直线是否相交
// -1 直线经过线段端点 | 0 线段和直线不相交 | 1 线段和直线严格相交
int is_inter(const line<T> &l) const
{
if (l.toleft(a)==0 || l.toleft(b)==0) return -1;
return l.toleft(a)!=l.toleft(b);
}
// 判断两线段是否相交
// -1 在某一线段端点处相交 | 0 两线段不相交 | 1 两线段严格相交
int is_inter(const segment<T> &s) const
{
if (is_on(s.a) || is_on(s.b) || s.is_on(a) || s.is_on(b)) return -1;
const line<T> l{a,b-a},ls{s.a,s.b-s.a};
return l.toleft(s.a)*l.toleft(s.b)==-1 && ls.toleft(a)*ls.toleft(b)==-1;
}
// 点到线段距离
long double dis(const point<T> &p) const
{
if ((p-a)*(b-a)<-eps || (p-b)*(a-b)<-eps) return min(p.dis(a),p.dis(b));
const line<T> l{a,b-a};
return l.dis(p);
}
// 两线段间距离
long double dis(const segment<T> &s) const
{
if (is_inter(s)) return 0;
return min({dis(s.a),dis(s.b),s.dis(a),s.dis(b)});
}
};
using Segment=segment<point_t>;
bool check_top(vector<Point> &vec)
{
if(vec[0]==vec[1]||vec[2]==vec[3]||vec[4]==vec[5]){return 1;}
if(vec[0]==vec[2])return 0;
if(vec[0]==vec[3]){swap(vec[3],vec[2]);return 0;}
if(vec[0]==vec[4]){swap(vec[2],vec[4]);swap(vec[3],vec[5]);return 0;}
if(vec[0]==vec[5])
{swap(vec[2],vec[5]);swap(vec[3],vec[4]);return 0;}
if(vec[1]==vec[2])
{swap(vec[0],vec[1]);return 0;}
if(vec[1]==vec[3])
{swap(vec[0],vec[1]);swap(vec[2],vec[3]);return 0;}
if(vec[1]==vec[4])
{swap(vec[0],vec[1]);swap(vec[2],vec[4]);swap(vec[3],vec[5]);return 0;}
if(vec[1]==vec[5])
{swap(vec[1],vec[0]);swap(vec[2],vec[5]);swap(vec[3],vec[4]);return 0;}
if(vec[2]==vec[4])
{swap(vec[0],vec[4]);swap(vec[1],vec[5]);return 0;}
if(vec[2]==vec[5])
{swap(vec[0],vec[5]);swap(vec[1],vec[4]);return 0;}
if(vec[3]==vec[4])
{swap(vec[2],vec[3]);swap(vec[0],vec[4]);swap(vec[1],vec[5]);return 0;}
if(vec[3]==vec[5])
{swap(vec[2],vec[3]);swap(vec[0],vec[5]);swap(vec[1],vec[4]);return 0;}
return 1;
}
bool check_bottom(vector<Point> &vec)
{
Segment s1={vec[0],vec[1]},s2={vec[2],vec[3]};
if(s1.is_on(vec[4])&&s2.is_on(vec[5]))return 0;
if(s1.is_on(vec[5])&&s2.is_on(vec[4]))
{swap(vec[4],vec[5]);return 0;}
return 1;
}
bool check(vector<Point> vec)
{
point_t
l1=vec[0].dis2(vec[4]),l2=vec[2].dis2(vec[5]),
l3=vec[4].dis2(vec[5]),
l4=vec[1].dis2(vec[4]),l5=vec[3].dis2(vec[5]);
if(l1+l2-l3<0)return 1;
if(max(l1,l4)>min(l1,l4)*16)return 1;
if(max(l2,l5)>min(l2,l5)*16)return 1;
return 0;
}
void solve()
{
vector<Point> vec(6);
for(auto &[x,y]:vec)scanf("%lld%lld",&x,&y);
if(check_top(vec)){printf("NO\n");return ;}
if(check_bottom(vec)){printf("NO\n");return ;}
if(check(vec)){printf("NO\n");return ;}
printf("YES\n");
}
int main()
{
int T;scanf("%d",&T);
while(T--)solve();
} | cpp |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | #include<iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--) {
int a, b;
cin >> a >> b;
if (a == b) cout << 0 << endl;
else cout << 1 + int((a < b) ^ ((b - a) & 1)) << endl;
}
return 0;
} | cpp |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int GCD(int m, int n)
{
int r = m % n;
while (r != 0)
{
m = n;
n = r;
r = m % n;
}
return n;
}
int main()
{
int a;
cin>>a;
int X=0, Y=a-2;
for (int i = 2; i < a; ++i)
{
int n=a, partofsum=0;
while (n != 0)
{
partofsum += n % i;
n /= i;
}
X += partofsum;
}
int gcd = GCD(X, Y);
X /= gcd;
Y /= gcd;
printf("%d/%d\n", X, Y);
return 0;
}
| cpp |
1307 | G | G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3
1 2 2
2 3 2
1 3 3
5
0
1
2
3
4
OutputCopy3.0000000000
4.0000000000
4.5000000000
5.0000000000
5.5000000000
| [
"flows",
"graphs",
"shortest paths"
] | #pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
#define INF 1000000007
using namespace __gnu_pbds;
using namespace std;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
int n,m,q;
long long f[60];
vector<pair<pair<int,int>,pair<int,int> > > g[60];
int dist[60],pre[60],edge[60],vis[60];
inline void add_edge(int x,int y,int c,int num)
{
g[x].push_back(make_pair(make_pair(y,c),make_pair(num,g[y].size())));
g[y].push_back(make_pair(make_pair(x,0),make_pair(-num,g[x].size()-1)));
}
inline int min_cost_flow(int f)
{
int res=0;
while(f>0){
for(int i=1;i<=n;i++) dist[i]=INF;
dist[1]=0;
queue<int> q;
q.push(1);vis[1]=1;
while(!q.empty()){
int u=q.front();q.pop();vis[u]=0;
for(int i=0;i<(int)g[u].size();i++){
pair<pair<int,int>,pair<int,int> > e=g[u][i];
if(e.first.second>0&&dist[e.first.first]>dist[u]+e.second.first){
dist[e.first.first]=dist[u]+e.second.first;
pre[e.first.first]=u;
edge[e.first.first]=i;
if(!vis[e.first.first]){
vis[e.first.first]=1;
q.push(e.first.first);
}
}
}
}
if(dist[n]==INF) return -1;
int flow=f;
for(int i=n;i!=1;i=pre[i]){
flow=min(flow,g[pre[i]][edge[i]].first.second);
}
f-=flow;
res+=flow*dist[n];
for(int i=n;i!=1;i=pre[i]){
g[pre[i]][edge[i]].first.second-=flow;
g[i][g[pre[i]][edge[i]].second.second].first.second+=flow;
}
}
return res;
}
signed main()
{
ios::sync_with_stdio(false);cin.tie(0);
cin>>n>>m;
for(int i=1;i<=m;i++){
int x,y,w;cin>>x>>y>>w;
add_edge(x,y,1,w);
}
int pos=n;f[0]=0ll;
for(int i=1;i<=n;i++){
int now=min_cost_flow(1);
if(now==-1){
pos=i-1;break;
}
f[i]=f[i-1]+1ll*now;
}
cin>>q;
for(int i=1;i<=q;i++){
int x;cin>>x;
double ans=(f[1]+1ll*x)*1.0;
for(int j=2;j<=pos;j++) ans=min(ans,(f[j]+1ll*x)*1.0/j);
cout<<fixed<<setprecision(10)<<ans<<'\n';
}
return 0;
}
| cpp |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | #include<iostream>
#include<vector>
#include<set>
#include<queue>
#include<map>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<cstring>
#include<bitset>
#include<iomanip>
#include<random>
#include<fstream>
#include<complex>
#include<time.h>
#include<stack>
using namespace std;
#define endl "\n"
#define ll long long
#define bl bool
#define ch char
#define vec vector
#define vll vector<ll>
#define sll set<ll>
#define pll pair<ll,ll>
#define mkp make_pair
#define mll map<ll,ll>
#define puf push_front
#define pub push_back
#define pof pop_front()
#define pob pop_back()
#define em empty()
#define fi first
#define se second
#define fr front()
#define ba back()
#define be begin()
#define rbe rbegin()
#define en end()
#define ren rend()
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define fo(i,x,y) for(ll i=x;i<=y;++i)
#define fa(i,v) for(auto &i:v)
#define re return
#define rz return 0;
#define sz size()
#define len length()
#define con continue;
#define br break;
#define ma(a,x) a=max(a,x)
#define mi(a,x) a=min(a,x)
#define so(v) sort(all(v))
#define rso(v) sort(rall(v))
#define rev(v) reverse(all(v))
#define i(x) for(ll i=0;i<x;++i)
#define j(x) for(ll j=0;j<x;++j)
#define k(x) for(ll k=0;k<x;++k)
#define n(x) for(ll yz=0;yz<x;++yz)
#define xx(k) while(k--)
#define wh(x) while(x)
#define st string
#define M 8611686018427387904
#define ze(x) __builtin_ctzll(x)
#define z(x) ll x=0
#define in insert
#define un(v) v.erase(unique(all(v)),v.en);
#define er(i,n) erase(i,n);
#define co(x,a) count(all(x),a)
#define lo(v,a) lower_bound(v.begin(),v.end(),a)
#define up(v,a) upper_bound(v.begin(),v.end(),a)
#define dou double
#define elif else if
#define ge(x,...) x __VA_ARGS__; ci(__VA_ARGS__);
#define fix(n,ans) cout<<fixed<<std::setprecision(n)<<ans<<endl;
void cc(){ cout<<endl; };
void ff(){ cout<<endl; };
void cl(){ cout<<endl; };
template<class T,class... A> void ff(T a,A... b){ cout<<a; (cout<<...<<(cout<<' ',b)); cout<<endl; };
template<class T,class... A> void cc(T a,A... b){ cout<<a; (cout<<...<<(cout<<' ',b)); cout<<' '; };
template<class T,class... A> void cl(T a,A... b){ cout<<a; (cout<<...<<(cout<<'\n',b)); cout<<endl; };
template<class T,class... A> void cn(T a,A... b){ cout<<a; (cout<<...<<(cout<<"",b)); };
template<class... A> void ci(A&... a){ (cin>>...>>a); };
template<class T>void ou(T v){fa(i,v)cout<<i<<" ";cout<<endl;}
template<class T>void oun(T v){fa(i,v)cout<<i;cout<<endl;}
template<class T>void ouu(T v){fa(i,v){fa(j,i)cout<<j<<" ";cout<<endl;}}
template<class T> void oul(T v){fa(i,v)cout<<i<<endl;}
template<class T>void in(T &v){fa(i,v)cin>>i;}
template<class T>void inn(T &v){fa(i,v)fa(j,i)cin>>j;}
template<class T>void oump(T &v){fa(i,v)ff(i.fi,i.se);}
template<class T,class A>void pi(pair<T,A> &p){ci(p.fi,p.se);}
template<class T,class A>void po(pair<T,A> &p){ff(p.fi,p.se);}
void init(){
ios::sync_with_stdio(false);
cin.tie(0);
}
void solve();
void ori();
ll ck(){
std::random_device seed_gen;
std::mt19937 engine(seed_gen());
// [-1.0, 1.0)の値の範囲で、等確率に実数を生成する
std::uniform_real_distribution<> dist1(1.0, 100000);
i(10000){ // 各分布法に基いて乱数を生成
ll n = dist1(engine);
} rz;
}
bl isup(ch c){
re 'A'<=c&&c<='Z';
}
bl islo(ch c){
re 'a'<=c&&c<='z';
}
//isdigit
mll pr_fa(ll x){
mll mp;
for(ll i=2;i*i<=x;++i){
while(x%i==0){
++mp[i];
x/=i;
}
}
if(x!=1)
++mp[x];
re mp;
}
ch to_up(ch a){
re toupper(a);
}
ch to_lo(ch a){
re tolower(a);
}
#define str(x) to_string(x)
#define acc(v) accumulate(v.begin(),v.end(),0LL)
#define acci(v,i) accumulate(v.begin(),v.begin()+i,0LL)
#define dq deque<ll>
int main(){
init();
solve();
rz;
}
template <typename T>class pnt{
public:
T x,y;
pnt(T x=0,T y=0):x(x),y(y){}
pnt operator + (const pnt r)const {
return pnt(x+r.x,y+r.y);}
pnt operator - (const pnt r)const {
return pnt(x-r.x,y-r.y);}
pnt operator * (const pnt r)const {
return pnt(x*r.x,y*r.y);}
pnt operator / (const pnt r)const {
return pnt(x/r.x,y/r.y);}
pnt &operator += (const pnt r){
x+=r.x;y+=r.y;return *this;}
pnt &operator -= (const pnt r){
x-=r.x;y-=r.y;return *this;}
pnt &operator *= (const pnt r){
x*=r.x;y*=r.y;return *this;}
pnt &operator /= (const pnt r){
x/=r.x;y/=r.y;return *this;}
ll dist(const pnt r){
re (x-r.x)*(x-r.x)+(y-r.y)*(y-r.y);
}
pnt rot(const dou theta){
T xx,yy;
xx=cos(theta)*x-sin(theta)*y;
yy=sin(theta)*x+cos(theta)*y;
return pnt(xx,yy);
}
};
istream &operator >> (istream &is,pnt<dou> &r){is>>r.x>>r.y;return is;}
ostream &operator << (ostream &os,pnt<dou> &r){os<<r.x<<" "<<r.y;return os;}
ll MOD= 1000000007;
//#define MOD 1000000007
//#define MOD 10007
//#define MOD 998244353
//ll MOD;
ll mod_pow(ll a, ll b, ll mod = MOD) {
ll res = 1;
for (a %= mod; b; a = a * a % mod, b >>= 1)
if (b & 1) res = res * a % mod;
return res;
}
class mint {
public:
ll a;
mint(ll x=0):a(x%MOD){}
mint operator + (const mint rhs) const {
return mint(*this) += rhs; }
mint operator - (const mint rhs) const {
return mint(*this) -= rhs; }
mint operator * (const mint rhs) const {
return mint(*this) *= rhs; }
mint operator / (const mint rhs) const {
return mint(*this) /= rhs; }
mint &operator += (const mint rhs) {
a += rhs.a; if (a >= MOD) a -= MOD; return *this; }
mint &operator -= (const mint rhs) {
if (a < rhs.a) a += MOD; a -= rhs.a; return *this; }
mint &operator *= (const mint rhs) {
a = a * rhs.a % MOD; return *this; }
mint &operator /= (mint rhs) {
ll exp = MOD - 2; while (exp) { if (exp % 2) *this *= rhs; rhs *= rhs; exp /= 2; } return *this; }
bool operator > (const mint& rhs)const{ return (this->a>rhs.a); }
bool operator < (const mint& rhs)const{ return (this->a<rhs.a); }
bool operator >= (const mint& rhs)const{ return (this->a>=rhs.a); }
bool operator <= (const mint& rhs)const{ return (this->a<=rhs.a);}
bool operator == (const mint& rhs)const{ return (this->a==rhs.a);}
};
istream& operator>>(istream& is, mint& r) { is>>r.a;return is;}
ostream& operator<<(ostream& os, const mint& r) { os<<r.a;return os;}
#define pq priority_queue<ll>
#define top top()
ll sumw(ll v,ll r){ re (v==0?0:sumw(v/10,r)*r+v%10); }
#define com complex<dou>
struct UFS{
map<st,st> par;map<st,ll>rk,siz;
st root(st x){
auto it=par.find(x);
if(it==par.en){
par[x]=x;siz[x]=1;re x;
}
if(par[x]==x)return x;
else return par[x]=root(par[x]);
}
bool same(st x,st y){ return root(x)==root(y); }
bool unite(st x,st y){
st rx=root(x),ry=root(y);
if(rx==ry) return false;
if(rk[rx]<rk[ry]) swap(rx,ry);
siz[rx]+=siz[ry];
par[ry]=rx;
if(rk[rx]==rk[ry]) rk[rx]++;
return true;
}
ll size(st s){
re siz[s];
}
};
//vector<long long> fact, fact_inv, inv;
/* init_nCk :二項係数のための前処理
計算量:O(n)
*/
vll fact,inv,fact_inv;
void init_nCk(int SIZE) {
fact.resize(SIZE + 5);
fact_inv.resize(SIZE + 5);
inv.resize(SIZE + 5);
fact[0] = fact[1] = 1;
fact_inv[0] = fact_inv[1] = 1;
inv[1] = 1;
for (int i = 2; i < SIZE + 5; i++) {
fact[i] = fact[i - 1] * i % MOD;
inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
fact_inv[i] = fact_inv[i - 1] * inv[i] % MOD;
}
}
long long nCk(int n, int k) {
return fact[n] * (fact_inv[k] * fact_inv[n - k] % MOD) % MOD;
}
struct UF{ vll par,rk,siz; UF(ll n):par(n+5,-1),rk(n+5,0){ }
ll root(ll x){ if(par[x]<0)return x; else return par[x]=root(par[x]); }
bool same(ll x,ll y){ return root(x)==root(y); }
bool unite(ll x,ll y){ ll rx=root(x),ry=root(y); if(rx==ry) return false; if(rk[rx]<rk[ry]) swap(rx,ry); par[rx]+=par[ry]; par[ry]=rx; if(rk[rx]==rk[ry]) rk[rx]++; return true; }
ll size(ll x){ return -par[root(x)]; }
};
/* O(2*10^8) 9*10^18 1LL<<62 4*10^18
~~(v.be,v.be+n,x); not include v.be+n
set.lower_bound(x);
->. *++ ! /%* +- << < == & && +=?:
*/
//vll dx={-1,-1,-1,0,0,1,1,1},dy={-1,0,1,-1,1,-1,0,1};
//vll dx={-1,0,0,1},dy={0,-1,1,0};
//#define N 11
#define N 1000000000
// 123456789
void solve(){
ge(ll,t);
xx(t){
//2<=a<b<c<=10^3
//a*b*c==n
//2<=n<=10^9
//O(10^3)
ge(ll,n);
ll a=2,f=0;
for(;a*a*a<n;++a){
if(n%a==0){
n/=a;
f++;
break;
}
}
if(f!=1){
ff("NO");continue;
}
ll b=a+1,c;
for(;b*b<n;++b)
if(n%b==0){
++f;
c=n/b;
break;
}
if(f!=2)
ff("NO");
else {
ff("YES");
ff(a,b,c);
}
}
}
| cpp |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | #include <iostream>
#include <ranges>
#include <algorithm>
#include <numeric>
#include <vector>
#include <array>
#include <set>
#include <map>
#include <bit>
#include <sstream>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
typedef long long integerType;
typedef integerType z;
typedef std::vector<integerType> v;
typedef std::vector<v> V;
typedef std::set<integerType> s;
typedef std::multiset<integerType> S;
typedef std::string r;
typedef std::vector<r> R;
typedef std::vector<bool> b;
struct RHEXAOCrocks {
RHEXAOCrocks() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); }
template<class T>
operator T() const { T n; std::cin >> n; return n; }
std::string operator()() { std::string s; std::cin >> s; return s; }
v operator()(integerType n) { v vec(n); for (auto& n : vec) std::cin >> n; return vec; }
R operator()(integerType n, char del) {
R vec(n); char ch; std::cin >> ch; vec[0].push_back(ch); int c;
for (integerType i{}; i < n;++i)
while ((c = std::cin.get()) != del)
vec[i].push_back(c);
return vec;
}
V operator()(integerType r, integerType c) { V tab(r, v(c)); for (auto& e : tab) for (auto& n : e) std::cin >> n; return tab; }
template<class T> RHEXAOCrocks& operator[](const T& t) { std::cout << t; return *this; }
RHEXAOCrocks& operator[](const R& a) { for (auto& e : a) std::cout << e << '\n'; return *this; }
template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const C<Ty>& c) {
for (auto Cc{ c.begin() }; Cc != c.end(); std::cout << *Cc << " \n"[++Cc == c.end()]); return *this;
}
template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const std::vector<C<Ty>>& c) {
for (auto& e : c) for (auto E{ e.begin() }; E != e.end(); )std::cout << *E << " \n"[++E == e.end()]; return *this;
}
}o;
#define i(b,e, ...) for(integerType i : std::views::iota(b,e) __VA_ARGS__)
#define _i(b,e, ...) for(integerType i : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define j(b,e, ...) for(integerType j : std::views::iota(b,e) __VA_ARGS__)
#define _j(b,e, ...) for(integerType j : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define k(b,e, ...) for(integerType k : std::views::iota(b,e) __VA_ARGS__)
#define _k(b,e, ...) for(integerType k : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define l(b,e, ...) for(integerType l : std::views::iota(b,e) __VA_ARGS__)
#define _l(b,e, ...) for(integerType l : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define Aa for(auto A{ a.begin() }, a_end{ a.end() }; A != a_end; ++A)
#define Bb for(auto B{ b.begin() }, b_end{ b.end() }; B != b_end; ++B)
#define Cc for(auto C{ c.begin() }, c_end{ c.end() }; C != c_end; ++C)
#define Dd for(auto D{ d.begin() }, d_end{ d.end() }; D != d_end; ++D)
#define z(a) (integerType)((a).size())
#define ff(...) auto f = [&](__VA_ARGS__, const auto& f)
#define f(...) f(__VA_ARGS__, f)
#define gg(...) auto g = [&](__VA_ARGS__, const auto& g)
#define g(...) g(__VA_ARGS__, g)
#define hh(...) auto h = [&](__VA_ARGS__, const auto& h)
#define h(...) h(__VA_ARGS__, h)
using namespace std;
namespace ra = ranges;
inline void nwmn(integerType nw, integerType& mn) { mn -= ((nw) < mn) * (mn - (nw)); }
inline void nwmx(integerType nw, integerType& mx) { mx += ((nw) > mx) * ((nw)-mx); }
z power(z a, z b, z M) { z r{ 1 }; do { if (b & 1) (r *= a) %= M; (a *= a) %= M; } while (b >>= 1); return r; }
#define w(...) if(__VA_ARGS__)
#define _ else
#define W(...) while(__VA_ARGS__)
#define A(...) for(auto __VA_ARGS__)
#define O while(true)
void solve_test_case()
{
z n{ o }, a{ o }, b{ o }, k{ o }, r{};
priority_queue<z, vector<z>, greater<z>> q;
W(n--) {
z h{ o };
h -= (h - 1) / (a + b) * (a + b);
w(h <= a)
++r;
_
q.push(h - a);
}
W(!q.empty()) {
z h{ q.top() }; q.pop();
z t{ (h + a - 1) / a };
w(t <= k) {
++r;
k -= t;
}
_
break;
}
o[r]['\n'];
}
int main()
{
z t{ 1 };
while (t--)
solve_test_case();
} | cpp |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t,a,b,x,y;
scanf("%d",&t);
while(t--)
{
scanf("%d %d %d %d",&a,&b,&x,&y);
int s1=a*y;
int s2=b*x;
int s3=a*(b-y-1);
int s4=b*(a-x-1);
int s=max(s1,max(s2,max(s3,s4)));
printf("%d\n",s);
}
}
| cpp |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] |
/*
1-> One day I will be 6* at Codechef and CandidateMaster at CodeForces
2-> Journey is not going to be so easy, sometimes shitty thoughts will rain on me
but that should not be the end, prevent self giving up at that moment.
CP is not a fight, it is Love.
3-> Dont panic about rating, rating takes time to come to your level
Dont forget rating is direcly propotional to skills, skills are not directly
propotional to rating.
4-> Keep on practising the questions above your level.
5-> Keep helping people, fellow programmers, junior, create a healthy coding environment.
Keep learning everyday.
6-> Be Honest to Yourself.
*/
#include<bits/stdc++.h>
using namespace std;
#define fori(a,b,c) for(int i = a; i<b ; i+=c )
#define forj(a,b,c) for(int j = a; j<b ; j+=c )
#define forf(a,b,c) for(int f = a; f<b ; f+=c )
#define tt int f; cin>>f;while(f--)
#define mp make_pair
#define pb push_back
#define um unordered_map
#define si set<int>
#define ull unsigned long long int
#define ll long long int
#define pii pair<int,int>
#define pci pair<char,int>
#define pll pair<ll,ll>
#define pcc pair<char,char>
#define mod 1000000007
#define inf 2147483647
#define ninf -2147483648
#define llmax 9223372036854775807
#define vi vector<int>
#define vll vector<ll>
#define vb vector<bool>
#define vp vector<pair<int,int> >
#define vpci vector<pair<char,int> >
#define vpll vector<pair<ll,ll>>
#define vv vector<vector<int>>
#define vc vector<char>
#define vs vector<string>
#define fr first
#define sc second
#define st SegmentTree
#define endl '\n'
#define dd debug
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define ordered_set tree<int , null_type , less<int> , rb_tree_tag , tree_order_statistics_node_update>
using namespace __gnu_pbds;
// there are two functionf of this
// s.find_by_order(int x); - > finds out the number of elements strictly lesser than x in ordered set s
// s.order_of_key(int i) -> this return iterator to the value at index i in O log(n) time
// Premetive Data Types
void _print(int x ){ cerr<<x;} void _print(ll x ){ cerr<<x;}void _print(ull x ){ cerr<<x;}
void _print(char x ){ cerr<<x;}void _print(float x ){ cerr<<x;} void _print(bool x ){ cerr<<x;}
void _print(string x ){ cerr<<x;}
// SET && MULTISET
template<class G> void _print(multiset<G> &s){for(auto val : s )cout<<val<<endl;}
template<class G> void _print(set<G> & s){for(auto val : s )cout<<val<<endl;}
template<class T , class G>
void _print(set<pair<T,G>> & arr)
{for(auto ch:arr) cerr<<"("<<ch.first<<" ,"<<ch.second<<") "; cerr<<endl;}
// Unordered Map
template<class G , class T>
void _print (um<G,T> & x) { cerr<<endl; for(auto a:x){ cerr<<"("<<a.first<<","<<a.second<<")"; } cerr<<endl; }
// Map
template<class G , class T>
void _print (map<G,T> & x) { cerr<<endl; for(auto a:x){ cerr<<"("<<a.first<<","<<a.second<<")"; } cerr<<endl; }
// Vector
template<class T>
void _print(vector<T> & arr )
{
for(auto ch:arr)cerr<<ch<<" ";
cerr<<endl;
}
template<class G , class T>
void _print(vector<pair<G,T> > & arr){fori(0 , arr.size() , 1){cerr<<"("<<arr[i].first<<","<<arr[i].second<<") ";}cerr<<endl;}
template<class T>
void _print(vector< vector<T> > & graph)
{
cerr<<endl;
fori(1 , graph.size() , 1)
{
cerr<<i<<" ->";
forj(0 , graph[i].size() , 1)
{
cerr<<graph[i][j]<<" ";
}
cerr<<endl;
}
}
template<class A , class B , class C>
void _print(vector<pair<A,pair<B,C > > > & arr)
{
fori(0 , arr.size() , 1)
{
cerr <<"(" << arr[i].first << "," << arr[i].second.first << "," << arr[i].second.second <<") ";
}
cerr<<endl;
}
// Premetive Data Types
template<class T>void _print(T & x )
{
cerr<<x<<endl;
}
// Vector Sort
template<class T>void sort(vector<T>&arr){sort(arr.begin(), arr.end());}
template<class T>void sort1(vector<T>&arr){sort(arr.begin()+1, arr.end());}
// Vector and String Reverse
template<class F>
void reverse(vector<F> & arr )
{reverse(arr.begin() , arr.end());}
template<class F>
void reverse1(vector<F> & arr )
{reverse(arr.begin()+1 , arr.end());}
void reverse(string & arr)
{reverse(arr.begin() , arr.end());}
void reverse1(string & arr)
{reverse(arr.begin()+1 , arr.end());}
// Pair
template<class T1 , class T2>
void _print(pair<T1,T2> & a)
{
cerr<<a.first<<" "<<a.second<<endl;
}
// READING & PRINTING
// Premitive data types
template<class T>
void r(T & a )
{cin>>a;}
template<class T>
void r(T & a , T & b )
{cin>>a>>b;}
template<class T>
void r(T & a , T & b , T &c )
{cin>>a>>b>>c;}
template<class T>
void r(T & a , T & b , T &c , T &d )
{cin>>a>>b>>c>>d;}
template<class T>
void r(T & a , T & b , T &c , T &d , T &e)
{cin>>a>>b>>c>>d>>e;}
void r(char & ch){cin>>ch;}
void r(bool & a){cin>>a;}
void r(string & s) {cin>>s;}
template<class T>
// Reading Vectors
void r(vector<T> & arr)
{fori(1 , arr.size() ,1 )cin>>arr[i];}
template<class T>
void read(vector<T> & arr)
{fori(0 , arr.size() ,1 )cin>>arr[i];}
template<class T1 , class T2>
void r(vector<pair<T1,T2>> & arr)
{fori(1 , arr.size() , 1)cin>>arr[i].first>>arr[i].second;}
template<class T1 , class T2>
void read(vector<pair<T1,T2>> & arr)
{fori(0 , arr.size() , 1)cin>>arr[i].first>>arr[i].second;}
// MATRIX
template<class T1 , class T2>
void r(vector<vector<T1>> & graph )
{
fori(1 , graph.size() , 1)
r(graph[i]);
}
// MATRIX for ZERO
template<class T1 , class T2>
void read(vector<vector<T1>> & graph )
{
fori(0 , graph.size() , 1)
read(graph[i]);
}
// TREE
void r(vector<vi> & graph )
{
fori(1 , graph.size() , 1)
{
int a , b;r(a , b);
graph[a].pb(b);
graph[b].pb(a);
}
}
// GRAPH
void r(vector<vi> & graph , int m )
{
fori(1 , m+1 , 1)
{
int a , b;r(a , b);
graph[a].pb(b);
graph[b].pb(a);
}
}
// Printing Vectors
template<class T>
void p(vector<T> & arr)
{fori(1 , arr.size(), 1)cout<<arr[i]<<" ";cout<<endl;}
template<class T>
void print(vector<T> & arr)
{fori(0 , arr.size(), 1)cout<<arr[i]<<" ";cout<<endl;}
template<class T1 , class T2>
void p(vector<pair<T1,T2>> & arr)
{fori(1 , arr.size() , 1)cout<<"("<<arr[i].first<<","<<arr[i].second<<") ";cout<<endl;}
template<class T1 , class T2>
void print(vector<pair<T1,T2>> & arr)
{fori(0 , arr.size() , 1)cout<<"("<<arr[i].first<<","<<arr[i].second<<") ";cout<<endl;}
#ifndef ONLINE_JUDGE
#define debug(x)cerr<< #x<<' ';_print(x); cerr<<endl;
#else
#define debug(x)
#endif
/* ------------------------------------------------------------------------*/
int g = 97 , f = 98;
void convertFilledToMadeBy(vi & filled , vi & madeBy, vi & powers, int name){
int n = filled.size();
fori(0 , powers[n] , 1)
{
bitset<8> temp(i);
int made = 0;
forj(0 , 8 , 1)
{
if(temp[j])
{
made += powers[filled[j]];
}
}
madeBy[made] = name;
}
}
bool possibleToMakeThis(vv & arr , int n , int m , int val )
{
vi madeBy(257 , -1);
vi powers(8);
powers[0] = 1;
fori(1 , 8 , 1)powers[i] = powers[i-1] * 2;
fori(1 , n+1 , 1)
{
vi filled;
int neededValue = 0;
// dd(arr[i])
int mn = arr[i][1];
forj(1 , m+1 , 1){
if(arr[i][j]>=val){
filled.pb(j-1);
}
else
neededValue += powers[j-1];
mn = min(mn , arr[i][j]);
}
if(mn >= val){
g = i;
f = i;
return true;
}
convertFilledToMadeBy(filled, madeBy, powers , i);
if(madeBy[neededValue] != -1){
g = i;
f = madeBy[neededValue];
return true;
}
// dd(filled)
// dd(madeBy)
}
return false;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("debug.txt", "w" , stderr);
freopen("input.txt", "r" , stdin);
freopen("output.txt", "w" , stdout);
#endif
cout << setprecision(12) << fixed;
cerr << setprecision(12) << fixed;
int n , m;cin>>n>>m;
vv arr(n+1 , vi(m+1));
set<int>s;
map<int,int>numbering;
fori(1 , n+1 , 1){
forj(1 , m+1 , 1){
cin>>arr[i][j];
s.insert(arr[i][j]);
}
}
vi answers;
answers.pb(0);
for(auto ch:s){
answers.pb(ch);
}
int low = 1 , high = s.size() , ans = low;
while(low<=high){
int mid = (low+high)/2;
// dd(mid)
// if possible to make this the maximum
// dd(answers[mid])
if(possibleToMakeThis(arr , n , m , answers[mid]))
{
// cerr<<"here we are"<<endl;
low = mid+1;
ans = mid;
}
else {
// cerr<<"there we are"<<endl;
high = mid-1;
}
// cerr<<endl;
}
cout << g << ' ' << f << endl;
return 0;
}
| cpp |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | #include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define xs(a) cout<<setiosflags(ios::fixed)<<setprecision(a);
#define lbit(a) (__builtin_ffsll(a))
#define ubit(a) (64-__builtin_clzll(a))
#define FOR(i, a, b) for (ll (i) = (a); (i) <= (b); (i)++)
#define ROF(i, a, b) for (ll (i) = (a); (i) >= (b); (i)--)
#define mem(a,b) memset(a,b,sizeof(a));
using namespace std;
#define ull unsigned long long
#define ll long long
#define endl '\n'
typedef pair<ll,ll> pll;
const int N=1e6+5;
const int mod=1e9+7;
/*-----------------------------------------------------------------------------------------------*/
void solve(){
ll n,a,b;cin>>n>>a>>b;
ll sum=(n+1)/2;
ll x=sum/a,res;
if(sum%a==0){
res=(x-1)*(a+b)+a;
}else res=x*(a+b)+sum%a;
if(res<n)res=n;
cout<<res<<endl;
}
signed main(){IOS
ll T;T=1;
cin>>T;
while(T--){
solve();
}
return 0;
} | cpp |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | #include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll maxN=2e5+10;
#define pb push_back
#define int ll
#define pli pair<ll,ll>
#define fi first
#define se second
#define task "danang"
#define plii pair<ll,pli>
ll ct[maxN];
bool check(ll x)
{
ll s=x;
for(int i=2;i*i<=x;i++)
{
ll cnt=0;
while(x%i==0)
{
cnt++;
x/=i;
}
if(cnt>0) ct[s]++;
if(cnt>1) return false;
}
if(x>1) ct[s]++;
return true;
}
vector<ll> d[maxN];
ll cnt[maxN];
void add(ll x)
{
for(auto zz:d[x])
{
cnt[zz]++;
}
}
void del(ll x)
{
for(auto zz:d[x])
{
cnt[zz]--;
}
}
ll cal(ll x)
{
ll ans=0;
for(auto zz:d[x])
{
if(ct[zz]%2==0) ans+=cnt[zz];
else ans-=cnt[zz];
}
return ans;
}
ll n,a[maxN];
vector<ll> vec[maxN];
bool c[maxN];
void solve()
{
cin >> n;
for(int i=1;i<=n;i++)
{
cin >> a[i];
vec[a[i]].pb(i);
}
for(int i=1;i<=1e5;i++)
{
c[i]=check(i);
}
for(int i=1;i<=1e5;i++)
{
if(c[i])
{
for(int j=i;j<=1e5;j+=i)
{
d[j].pb(i);
}
}
}
vector<ll> x;
deque<ll> dq;
ll ans=0;
for(int i=1;i<=1e5;i++)
{
x.clear();
for(int j=i;j<=1e5;j+=i)
{
for(int k=0;k<min(2ll,(int)vec[j].size());k++)
{
x.pb(j/i);
}
}
dq.clear();
for(int j=(int)x.size()-1;j>=0;j--)
{
if(cal(x[j])>=1)
{
ll cc=cal(x[j]);
while(dq.size()>0)
{
if(__gcd(x[j],dq.back())==1)
{
cc--;
if(cc==0) break;
}
del(dq.back());
dq.pop_back();
}
ans=max(ans,i*x[j]*dq.back());
}
dq.pb(x[j]);
add(x[j]);
}
for(int j=0;j<x.size();j++)
{
for(auto zz:d[x[j]])
{
cnt[zz]=0;
}
}
}
cout << ans;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
//freopen(task".inp","r",stdin);
//freopen(task".out","w",stdout);
solve();
}
| cpp |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n) — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111. | [
"dfs and similar",
"dsu",
"graphs"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N (ll)(3e5+5)
#define fi first
#define se second
ll n, k, p[N], mn[N], col[N], ans, o[N];
bool s[N];
vector<ll> v[N], g[2][N];
inline void merge(ll x, ll y, bool st) {
if (p[x] == p[y]) return;
if (g[0][p[x]].size() + g[1][p[x]].size() > g[0][p[y]].size() + g[1][p[y]].size())
swap(x, y);
if (!st && col[x] == col[y] || st && col[x] != col[y]) { swap(g[0][p[x]], g[1][p[x]]), o[p[x]] ^= 1; for (auto z : g[0][p[x]]) col[z] ^= 1; for (auto z : g[1][p[x]]) col[z] ^= 1;
}
ll px = p[x], py = p[y]; o[py] = min(o[px], o[py]);
ans -= mn[px], ans -= mn[py]; for (auto z : g[0][px]) g[0][py].push_back(z), p[z] = py; for (auto z : g[1][px]) g[1][py].push_back(z), p[z] = py;
if (o[py] < 2) mn[py] = g[o[py]][py].size();
else mn[py] = min(g[0][py].size(), g[1][py].size());
ans += mn[py];
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> k; {char a; for (int i = 1; i <= n; i++) cin >> a, s[i] = (a == '1'); }
ll a, b; for (int i = 1; i <= k; i++) {
p[i] = i, mn[i] = 0, col[i] = 1, o[i] = 2, g[1][i].push_back(i);
cin >> a; while (a--) cin >> b, v[b].push_back(i);
}
for (int i = 1; i <= n; i++) {
if (v[i].size() == 1) {
a = p[v[i][0]]; b = v[i][0];
ans -= mn[a]; o[a] = col[b] ^ (s[i] ? 1 : 0); mn[a] = g[o[a]][a].size(); ans += mn[a];
}
else if (v[i].size() == 2) merge(v[i][0], v[i][1], s[i]);
cout << ans << '\n';
}
} | cpp |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
| [
"brute force",
"math",
"number theory"
] | #include<bits/stdc++.h>
#define endl "\n"
using namespace std;
#define mod 1000000007
#define int long long
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin>>n;
int mini=1e18;
int a=1,b=n;
for(int i=1;i<=sqrt(n);i++){
if((i*(n/i))/(__gcd(i,n/i))==n){
if(min(max(i,n/i),mini)!=mini){
mini=(max(i,n/i));
a=i;
b=n/i;
}
}
}
cout<<a<<" "<<b;
return 0;
} | cpp |
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day. | [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define PII pair<int,int>
#define x first
#define y second
const int N=1e5+10;
int a[N];
void solve()
{
int n,d;
cin>>n>>d;
for(int i=0;i<n;i++)
cin>>a[i];
int res=a[0];
for(int i=1;i<n&&d>=i;i++)
{
if(d>a[i]*i)
res+=a[i],d-=a[i]*i;
else
res+=d/i,d-=i*d/i;
}
cout<<res<<endl;
return;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int T=1;
cin>>T;
while(T--)
solve();
return 0;
} | cpp |
1320 | E | E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1
| [
"data structures",
"dfs and similar",
"dp",
"shortest paths",
"trees"
] | #include <bits/stdc++.h>
#define endl '\n'
#define fi first
#define se second
#define MOD(n,k) ( ( ((n) % (k)) + (k) ) % (k))
#define forn(i,n) for (int i = 0; i < n; i++)
#define forr(i,a,b) for (int i = a; i <= b; i++)
#define all(v) v.begin(), v.end()
#define pb push_back
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int MX = 200005, LG = 20;
int n, q, f[MX], p[LG][MX], lvl[MX], cn = 1, from[MX], inv[MX];
int k, m, vid[MX], vs[MX], ic[MX], ini[MX], fin[MX];
priority_queue<ii, vii, greater<ii>> pq;
ll dis[MX], sz;
vi gra[MX];
vii adj[MX];
void dfs (int u) {
for (int v : gra[u])
if (!f[v]) {
f[v] = ++cn;
p[0][f[v]] = f[u];
lvl[f[v]] = lvl[f[u]] + 1;
dfs(v);
}
}
int LCA (int a, int b) {
if (lvl[a] < lvl[b]) swap(a, b);
for (int j = 0; j < LG; j++)
if (lvl[a] - lvl[b] & (1 << j))
a = p[j][a];
if (a == b) return a;
for (int j = LG - 1; j + 1; j--)
if (p[j][a] != p[j][b]) {
a = p[j][a];
b = p[j][b];
}
return p[0][a];
}
int kth_anc (int u, int k) {
for (int j = 0; j < LG; j++)
if (k & (1 << j))
u = p[j][u];
return u;
}
void add (int u, int v, int w) {
adj[u].emplace_back(v, w);
adj[v].emplace_back(u, w);
}
void build (vi &st) {
stack<int> anc;
for (int u : st) {
adj[u].clear();
from[u] = -1;
while (anc.size()) {
int v = anc.top();
if (lvl[v] < lvl[u] && kth_anc(u, lvl[u] - lvl[v]) == v)
break;
anc.pop();
}
if (anc.size())
add(u, anc.top(), lvl[u] - lvl[anc.top()]);
anc.push(u);
}
}
void bfs () {
sz = 0;
forn (i, k) {
int u = f[vid[i]];
if (i) ini[i] = ini[i - 1] + vs[i - 1];
fin[i] = ini[i] + vs[i] - 1;
sz += vs[i];
from[u] = i;
dis[u] = ini[i] - 1;
pq.emplace(dis[u], u);
}
while (pq.size()) {
ll w = pq.top().fi;
int u = pq.top().se;
int i = from[u];
pq.pop();
if (w > dis[u]) continue;
for (ii &v : adj[u]) {
ll d = w;
ll r = v.se;
if (r > fin[i] - d % sz) {
r -= fin[i] - d % sz;
d = sz * (max(d / sz, 0ll) + 1);
ll q = r / (fin[i] - ini[i] + 1);
r %= fin[i] - ini[i] + 1;
d += q * sz;
if (r) d += ini[i] + r - 1;
else d += fin[i] - sz;
} else {
d += r;
}
if (from[v.fi] == -1 || (f[vid[from[v.fi]]] != v.fi && dis[v.fi] > d)) {
dis[v.fi] = d;
from[v.fi] = i;
pq.emplace(d, v.fi);
}
}
}
}
void solve () {
vi in, st;
cin >> k >> m;
forn (i, k) {
cin >> vid[i] >> vs[i];
in.pb(f[vid[i]]);
st.pb(f[vid[i]]);
}
forn (i, m) {
cin >> ic[i];
in.pb(f[ic[i]]);
st.pb(f[ic[i]]);
}
sort(all(in));
in.erase(unique(all(in)), in.end());
forn (i, int(in.size()) - 1)
st.pb(LCA(in[i], in[i + 1]));
sort(all(st));
st.erase(unique(all(st)), st.end());
build(st);
bfs();
forn (i, m)
cout << from[f[ic[i]]] + 1 << " ";
cout << endl;
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n;
for (int i = 1; i < n; i++) {
int a, b;
cin >> a >> b;
gra[a].pb(b);
gra[b].pb(a);
}
f[1] = 1;
p[0][1] = 1;
dfs(1);
for (int i = 1; i <= n; i++)
inv[f[i]] = i;
for (int j = 1; j < LG; j++)
for (int i = 1; i <= n; i++)
p[j][i] = p[j - 1][p[j - 1][i]];
cin >> q;
while (q--)
solve();
return 0;
} | cpp |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000
| [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
#define N 100005
#define wr cout << "Continue debugging\n";
#define all(x) (x).begin(), (x).end()
#define ll long long int
#define pii pair <int, int>
#define pb push_back
#define ff first
#define ss second
using namespace std;
int p[N];
int main ()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
string s;
cin >> n >> s;
char lst1 = 'a', lst2 = 'a';
for (int i = 0; i < n; i++){
if (s[i] >= lst1) lst1 = s[i];
else if (s[i] >= lst2){
lst2 = s[i];
p[i] = 1;
}else return cout << "NO", 0;
}
cout << "YES\n";
for (int i = 0; i < n; i++){
cout << p[i];
}
} | cpp |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n) — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111. | [
"dfs and similar",
"dsu",
"graphs"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define pii pair <int, int>
#define X first
#define Y second
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
void abc() {cout << endl;}
template <typename T, typename ...U> void abc(T a, U ...b) {
cout << a << ' ', abc(b...);
}
template <typename T> void printv(T l, T r) {
for (; l != r; ++l) cout << *l << " \n"[l + 1 == r];
}
template <typename A, typename B> istream& operator >> (istream& o, pair<A, B> &a) {
return o >> a.X >> a.Y;
}
template <typename A, typename B> ostream& operator << (ostream& o, pair<A, B> a) {
return o << '(' << a.X << ", " << a.Y << ')';
}
template <typename T> ostream& operator << (ostream& o, vector<T> a) {
bool is = false;
if (a.empty()) return o << "{}";
for (T i : a) {o << (is ? ", " : "{"), is = true, o << i;}
return o << '}';
}
template <typename T> struct vv : vector <vector <T>> {
vv (int n, int m, T v) : vector <vector <T>> (n, vector <T>(m, v)) {}
vv (int n, int m) : vector <vector <T>> (n, vector <T>(m)) {}
vv () {}
};
template <typename T> struct vvv : vector <vv <T>> {
vvv (int n, int m, int k, T v) : vector <vv <T>> (n, vv <T>(m, k, v)) {}
vvv (int n, int m, int k) : vector <vv <T>> (n, vv <T>(m, k)) {}
vvv () {}
};
#ifdef Doludu
#define test(args...) abc("[" + string(#args) + "]", args)
#define owo freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout)
#else
#define test(args...) void(0)
#define owo ios::sync_with_stdio(false); cin.tie(0)
#endif
const int mod = 1e9 + 7, N = 300005, M = 400005, logN = 20;
struct Dsu {
int dsu[N << 1], cost[N << 1], ans;
Dsu () {
ans = 0;
for (int i = 0; i < N; ++i) {
dsu[i] = i, dsu[i + N] = i + N;
cost[i + N] = 1;
}
cost[0 + N] = 1 << 30;
}
int calc(int x) {
int y = x >= N ? x - N : x + N;
return min(cost[x], cost[y]);
}
int Find(int x) {
if (dsu[x] == x) {
return x;
}
return dsu[x] = Find(dsu[x]);
}
void Union(int u, int v) {
u = Find(u), v = Find(v);
if (u == v) {
return;
}
if (u % N > v % N) {
swap(u, v);
}
ans -= calc(u), ans -= calc(v);
cost[u] += cost[v];
cost[v] = 0;
dsu[v] = u;
ans += calc(u);
}
} dsu;
void solve() {
int n, m;
cin >> n >> m;
string s; cin >> s;
vector <vector <int>> pos(n);
for (int i = 0, sz; i < m; ++i) {
cin >> sz;
for (int j = 0, x; j < sz; ++j) {
cin >> x, --x;
pos[x].pb(i + 1);
}
}
for (int i = 0; i < n; ++i) {
int x, y;
if (pos[i].empty()) {
cout << dsu.ans << '\n';
continue;
}
if (pos[i].size() == 1) {
x = 0, y = pos[i][0];
}
if (pos[i].size() == 2) {
x = pos[i][0], y = pos[i][1];
}
if (s[i] == '0') {
dsu.Union(x, y + N);
dsu.Union(x + N, y);
} else {
dsu.Union(x, y);
dsu.Union(x + N, y + N);
}
cout << dsu.ans << '\n';
}
}
int main () {
owo;
int t = 1;
// cin >> t;
while (t--) {
solve();
}
} | cpp |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | [
"math"
] | /*
النجاح الساحق خير انتقام
Youssef Elnagar
* */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(c) (c).begin(),(c).end()
#define allr(c) (c).rbegin(),(c).rend()
#define srt(c) sort(all(c))
#define srtv(c) sort(allr(c))
#define rep(i, n) for(ll (i) = 0; (i) < (n); ++(i))
#define repv(i, n) for(ll (i) = n-1; (i) >= 0; --(i))
#define rep1(i, j, n) for(ll (i) = (j); (i) < (n); ++(i))
#define in(v) for(auto& i: (v)) cin >> i
#define YouSefJoUe ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0);
#define pi pair<int, int>
#define vi vector<int>
#define vll vector<ll>
#define vpll vector<pair<ll, ll>>
#define vpi vector<pair<int, int>>
#define mpll map<ll, ll>
#define F first
#define S second
#define pb push_back
#define clr(val, arr) memset(arr, val, sizeof (arr))
#define sz(pram) (ll)pram.size()
const int OO = 0x3f3f3f3f;
const ll LOO = 0x3f3f3f3f3f3f3f3f;
//const int mod = 1000000007;
const double PI = acos(-1.);
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> p) { return os << '(' << p.first << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }
// Delta for: up, right, down, left
int dr[4] { -1, 0, 1, 0 };
int dc[4] { 0, 1, 0, -1 };
const int MOD = 1e9+7;
ll n, m, a, b, c, d, x, y, q;
string s, t, temp1, temp2;
ll nCr(ll n, ll r)
{
if (r > n)
return 0;
if (r == 0 || r == n)
return 1;
return nCr(n - 1, r - 1) + nCr(n - 1, r);
}
class BinaryTree {
private:
int data { };
BinaryTree* left { };
BinaryTree* right { };
public:
BinaryTree(int data) :
data(data) {
}
void print_inorder() {
if(left)
left->print_inorder();
cout << data << " ";
if(right)
right->print_inorder();
}
void add(vector<int> values, vector<char> direction) {
assert(values.size() == direction.size());
BinaryTree* current = this;
for (int i = 0; i < (int) values.size(); ++i) {
if (direction[i] == 'L') {
if (!current->left)
current->left = new BinaryTree(values[i]);
else
assert(current->left->data == values[i]);
current = current->left;
} else {
if (!current->right)
current->right = new BinaryTree(values[i]);
else
assert(current->right->data == values[i]);
current = current->right;
}
}
}
ll height(){
ll res = 0;
if(left)
res = 1 + left->height();
if(right)
res = max(res, 1 + right->height());
return res;
}
ll mx(){
ll res = data;
if(left)
res = max(res, left->mx());
if(right)
res = max(res, right->mx());
return res;
}
ll nodes(){
int res = 1;
if(left)
res += left->nodes();
if(right)
res += right->nodes();
return res;
}
ll leaves(){
int res = !right && !left;
if(left)
res += left->leaves();
if(right)
res += right->leaves();
return res;
}
bool find(int val){
if(data == val)
return true;
if(left && left->find(val)) return true;
if(right && right->find(val)) return true;
return false;
}
bool is_perfet(int h = -1){
if(~h)
h = height();
if(!right && !left)
return h == 0;
if((!right && left) || (!left && right))
return false;
return left->is_perfet(h-1) && right->is_perfet(h-1);
}
void clear(){
if(left) {
delete left;
left = nullptr;
}
if(right) {
delete right;
right = nullptr;
}
}
~BinaryTree(){
clear();
}
};
const int N = 10000+5;
void solve(){
cin >> x >> y >> a >> b;
c = (y-x) / (a+b);
if(x+c*a == y-c*b){
cout << c << '\n';
}else cout << -1 << '\n';
}
int main() {
YouSefJoUe
int t = 1;
cin >> t;
// freopen("input.txt", "r", stdin);
while (t--) solve();
// freopen("output.txt", "w", stdout);
return 0;
}
| cpp |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | #include <iostream>
using namespace std;
const int N = 2 * 100 * 1000 +10;
int n, q;
string s;
int dp_l[N], dp_r[N];
int r = 3127;
int mod1 = 1000 * 1000 * 1000 + 7;
int mod2 = 1000 * 1000 * 1000 + 9;
int h[3][N], pw[3][N], cnt[N];
pair<int, int> get_hash(int l, int r)
{
pair<int, int> ret;
ret.first = ((long long)h[1][r] - ((long long)h[1][l-1] * pw[1][cnt[r] - cnt[l-1]]) % mod1 + mod1) % mod1;
ret.second = ((long long)h[2][r] - ((long long)h[2][l-1] * pw[2][cnt[r] - cnt[l-1]]) % mod2 + mod2) % mod2;
return ret;
}
pair<int, int> Make_hash(int L, int R)
{
int L2, R2;
int left, right;
if(s[L-1] == '0')
L2 = L, left = 0;
else
{
L2 = dp_r[L] + 1;
left = (L2 - L) % 2;
}
if(s[R-1] == '0')
R2 = R, right = 0;
else
{
R2 = dp_l[R] - 1;
right = (R - R2) % 2;
}
if(L2 > R2)
{
pair<int, int> ret = {(R - L + 1) % 2, (R - L + 1) % 2};
return ret;
}
pair<int, int> mid = get_hash(L2, R2);
int cnt_mid = cnt[R2] - cnt[L2] + 1;
pair<int, int> ret;
if(left && right)
{
ret.first = (((long long)left * pw[1][cnt_mid + 1]) % mod1 + ((long long)mid.first * r) % mod1 + right) % mod1;
ret.second = (((long long)left * pw[2][cnt_mid + 1]) % mod2 + ((long long)mid.second * r) % mod2 + right) % mod2;
}
else if(left || right)
{
if(left)
{
ret.first = (((long long)left * pw[1][cnt_mid]) % mod1 + (long long)mid.first) % mod1;
ret.second = (((long long)left * pw[2][cnt_mid]) % mod2 + (long long)mid.second) % mod2;
}
else
{
ret.first = (((long long)mid.first * r) % mod1 + right) % mod1;
ret.second = (((long long)mid.second * r) % mod2 + right) % mod2;
}
}
else
ret = mid;
return ret;
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin>>n>>s;
for(int i=1; i<=n; i++)
{
if(i == 1)
dp_l[i] = i;
else if(s[i-1] == '1' && s[i-2] == '1')
dp_l[i] = dp_l[i-1];
else
dp_l[i] = i;
}
for(int i=n; i>=1; i--)
{
if(i == n)
dp_r[i] = i;
else if(s[i-1] == '1' && s[i] == '1')
dp_r[i] = dp_r[i+1];
else
dp_r[i] = i;
}
pw[1][0] = pw[2][0] = 1;
h[1][0] = h[2][0] = cnt[0] = 0;
for(int i=1; i<=n; i++)
{
pw[1][i] = ((long long)pw[1][i-1] * r) % mod1;
pw[2][i] = ((long long)pw[2][i-1] * r) % mod2;
if(s[i-1] == '0')
{
h[1][i] = ((long long)h[1][i-1] * r + 2) % mod1;
h[2][i] = ((long long)h[2][i-1] * r + 2) % mod2;
cnt[i] = cnt[i-1] + 1;
}
else
{
if(dp_r[i] == i)
{
int bit = (i - dp_l[i] + 1) % 2;
if(bit)
{
h[1][i] = ((long long)h[1][dp_l[i] - 1] * r + 1) % mod1;
h[2][i] = ((long long)h[2][dp_l[i] - 1] * r + 1) % mod2;
cnt[i] = cnt[dp_l[i] - 1] + 1;
}
else
{
h[1][i] = h[1][dp_l[i] - 1];
h[2][i] = h[2][dp_l[i] - 1];
cnt[i] = cnt[dp_l[i] - 1];
}
}
}
}
cin>>q;
while(q--)
{
int l1, l2, len; cin>>l1>>l2>>len;
int r1 = l1 + len - 1;
int r2 = l2 + len - 1;
pair<int, int> Hash1 = Make_hash(l1, r1);
pair<int, int> Hash2 = Make_hash(l2, r2);
if(Hash1 == Hash2)
cout<<"Yes";
else
cout<<"No";
if(q) cout<<'\n';
}
cout.flush();
return 0;
}
| cpp |
1299 | E | E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2
| [
"interactive",
"math"
] | #include<bits/stdc++.h>
#define ll long long
#define rep(i, x, y) for(int i = (x), stOyny = (y); i <= stOyny; ++i)
#define irep(i, x, y) for(int i = (x), stOyny = (y); i >= stOyny; --i)
#define pb emplace_back
#define pii pair<int, int>
#define vint vector<int>
#define fi first
#define se second
#define let const auto
#define il inline
#define ci const int
#define all(S) S.begin(), S.end()
int read() {
int res = 0, flag = 1; char c = getchar();
while(c < '0' || c > '9') { if(c == '-') flag = -1; c = getchar(); }
while(c >= '0' && c <= '9') res = res * 10 + c - '0', c = getchar();
return res * flag;
}
using namespace std;
template<typename T>
il void tmax(T &x, const T y) { if(x < y) x = y; }
template<typename T>
il void tmin(T &x, const T y) { if(x > y) x = y; }
mt19937 rnd(time(0));;
bool query(vint a) {
cout << "? " << a.size() << ' ';
for(int x : a) cout << x << ' ';
cout << endl;
bool res;
cin >> res;
return res;
}
int ans[805], n;
void print() {
if(ans[1] > n / 2) rep(i, 1, n) ans[i] = n + 1 - ans[i];
cout << "! ";
rep(i, 1, n) cout << ans[i] << ' ';
cout << endl;
exit(0);
}
void solve(vint a, int n, int dep, int va) {
if(!dep) return;
vint nxt, gg;
for(int x : a) {
vint b;
for(int y : a) if(y != x) b.pb(y);
if(query(b)) ans[x] = va, gg.pb(x);
else nxt.pb(x);
}
solve(nxt, n - 2, dep - 1, va + 1);
}
vint plac, value;
int m, mxS, sum[1024];
vint prime;
vector<pair<int, vint>> ma[4];
void init() {
rep(s, 0, mxS) rep(i, 0, m - 1) if((s >> i) & 1) sum[s] += value[i];
rep(xby, 0, 3) {
const int mod = prime[xby];
auto &nma = ma[xby];
nma.resize(mod);
rep(i, 0, mod - 1) nma[i].fi = i;
shuffle(all(nma), rnd);
rep(i, 0, mod - 2) {
rep(s, 0, mxS) if(__builtin_popcount(s) == mod - 1 && sum[s] % mod == (mod - nma[i].fi) % mod) {
rep(j, 0, m - 1) if((s >> j) & 1) nma[i].se.pb(plac[j]);
break;
}
}
}
}
int query(int x) {
vint res(4);
rep(xby, 0, 3) {
int mod = prime[xby];
let nma = ma[xby];
res[xby] = nma.back().fi;
rep(i, 0, mod - 2) {
vint cur = nma[i].se;
cur.pb(x);
if(query(cur)) { res[xby] = nma[i].fi; break; }
}
}
rep(i, 1, n) {
bool ok = true;
rep(j, 0, 3) if(i % prime[j] != res[j]) ok = false;
if(ok) return i;
}
return -1;
}
signed main() {
memset(ans, -1, sizeof(ans));
cin >> n;
vint a;
rep(i, 1, n) a.pb(i);
solve(a, n, n <= 70 ? (n >> 1) : (n > 420 ? 5 : 4), 1);
int pl = 0;
rep(i, 1, n) if(ans[i] == 1) { ans[pl = i] = n; break; }
rep(i, 1, n) if(ans[i] > 1 && ans[i] < n) {
if(query(vint({pl, i})) == (n + ans[i]) % 2) ans[i] = n + 1 - ans[i];
}
if(n <= 70) print();
rep(i, 1, n) if(~ans[i]) plac.pb(i), value.pb(ans[i]);
m = plac.size(), mxS = (1 << m) - 1;
prime = vint{3, 5, 7};
prime.pb(n <= 210 ? 2 : ((n <= 420) ? 4 : 8));
init();
rep(i, 1, n) if(ans[i] == -1) ans[i] = query(i);
print();;
return 0;
}
| cpp |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111). | [
"implementation",
"strings"
] | #include <bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
int t ;
cin>>t;
while(t--){
string a;
int k=0 ;
cin>>a;
for(int i=a.find('1') ;i<a.find_last_of('1');i++){
if(a[i]=='0'){
k++;
}
}
cout <<k<<endl;
}
return 0;
}
| cpp |
1310 | C | C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1
abac
OutputCopyaba
InputCopy19 5 1821
aupontrougevkoffice
OutputCopyau
NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a". | [
"binary search",
"dp",
"strings"
] | // LUOGU_RID: 99431188
#include<bits/stdc++.h>
using namespace std;
const int N=1010;
int n,m,lcp[N][N],rmin[N];
long long k;
char s[N];
vector<int>g[N];
long long sum[N][N],dp[N][N];
int main()
{
scanf("%d%d%lld",&n,&m,&k);
vector<pair<int,int>>v;
for (int i=1;i<=n;i++)
for (int j=i;j<=n;j++)
v.emplace_back(i,j);
scanf("%s",s+1);
for (int i=n;i;i--)
for (int j=n;j;j--)
lcp[i][j]=(s[i]==s[j])?lcp[i+1][j+1]+1:0;
sort(v.begin(),v.end(),[&](pair<int,int>a,pair<int,int>b)
{
int len=lcp[a.first][b.first];
if (a.first+len>a.second||b.first+len>b.second)
return a.second-a.first>b.second-b.first;
return s[a.first+len]>s[b.first+len];
});
int l=0,r=(int)v.size()-1;
pair<int,int>ans;
auto check=[&](int mid)
{
fill(rmin+1,rmin+n+1,n+2);
for (int i=0;i<=mid;i++)
rmin[v[i].first]=min(rmin[v[i].first],v[i].second+1);
memset(dp,0,sizeof dp);
memset(sum,0,sizeof sum);
dp[n+1][0]=sum[n+1][0]=1;
for (int i=n;i;i--)
{
for (int j=0;j<=m;j++)
{
dp[i][j]=sum[rmin[i]][j-1];
sum[i][j]=min(k,sum[i+1][j]+dp[i][j]);
}
}
return dp[1][m]>=k;
};
while (l<=r)
{
int mid=(l+r)>>1;
if (check(mid))
{
ans=v[mid];
r=mid-1;
}
else
{
l=mid+1;
}
}
for (int i=ans.first;i<=ans.second;i++)
printf("%c",s[i]);
return 0;
} | cpp |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
const int M = 1e6+7, MOD = 1e9;
int dist[M], n, par[M];
vector<int> node[M];
void bfs(vector<int> s) {
for (int i = 1; i <= n; i++) dist[i] = INT_MAX;
for (int i:s) dist[i] = 0;
queue<int> q;
for (int i:s) q.push(i);
while (!q.empty()) {
int f = q.front();
q.pop();
for (int i:node[f]) {
if (dist[i] == INT_MAX) {
dist[i] = dist[f]+1;
q.push(i);
}
}
}
}
vector<int> tmp;
void dfs(int s, int p) {
for (int i:node[s])
if (i != p) par[i] = s, dfs(i, s);
}
signed main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
srand(time(0));
cin >> n;
for (int i = 1; i < n; i++) {
int a, b;
cin >> a >> b;
node[a].push_back(b);
node[b].push_back(a);
}
bfs({1});
int a = max_element(dist+1, dist+n+1)-dist;
bfs({a});
int x = *max_element(dist+1, dist+n+1);
int b = max_element(dist+1, dist+n+1)-dist;
dfs(a, a);
int k = b;
while (k) {
tmp.push_back(k);
k = par[k];
}
bfs(tmp);
x += *max_element(dist+1, dist+n+1);
cout << x << endl;
if (*max_element(dist+1, dist+n+1) == 0) {
cout << a << ' ' << b << ' ';
set<int> st;
for (int i = 1; i <= n; i++) st.insert(i);
st.erase(a);
st.erase(b);
cout << *st.begin() << endl;
} else {
cout << a << ' ' << b << ' ' << max_element(dist+1, dist+n+1)-dist << endl;
}
return 0;
}
| cpp |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
#define eps 1e-9
#define emailam ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define MAX 200010
#define pb push_back
#define all(a) a.begin(),a.end()
#define pf push_front
#define fi first
#define se second
#define pii pair<int,int>
const long long INF = LLONG_MAX;
using namespace std;
const int N=1e7+3,M=10;
/*----------------------------------------------------------------*/
int dx[] = {+0, +0, -1, +1, +1, +1, -1, -1};
int dy[] = {-1, +1, +0, +0, +1, -1, +1, -1};
/*----------------------------------------------------------------*/
void READ(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif
}
void solve(){
int n,a,b;
cin>>n>>a>>b;
int x=a+b;
if(x>n){
int y=n-x%(n+1);
cout<<min(n,n-y+2)<<" "<<n<<endl;
}
else{
cout<<1<<" "<<min(n,x-1)<<endl;
}
}
signed main() {
emailam
//READ();
int t=1;
cin>>t;
while(t--){
solve();
}
} | cpp |
1299 | E | E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2
| [
"interactive",
"math"
] | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <ctype.h>
#include <queue>
#include <cstring>
#include <set>
#include <bitset>
#include <map>
#include <chrono>
#include <random>
#include <unordered_map>
#include <stdio.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef std::vector<int> vi;
typedef std::vector<bool> vb;
typedef std::vector<string> vs;
typedef std::vector<double> vd;
typedef std::vector<long long> vll;
typedef std::vector<std::vector<int> > vvi;
typedef vector<vll> vvll;
typedef std::vector<std::pair<int, int> > vpi;
typedef vector<vpi> vvpi;
typedef std::pair<int, int> pi;
typedef std::pair<ll, ll> pll;
typedef std::vector<pll> vpll;
const long long mod = 1000000007;
ll gcd (ll a, ll b) {return b==0 ? a : gcd(b, a%b);}
const unsigned gen_seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937_64 gen(gen_seed);
#define all(c) (c).begin(),(c).end()
#define srt(c) sort(all(c))
#define srtrev(c) sort(all(c)); reverse(all(c))
#define forn(i, a, b) for(int i = a; i < b; i++)
#define read(x) scanf("%d", &x)
#define readv(x, n) vi x(n); forn(i,0,n) scanf("%d", &x[i])
#define pb push_back
#define mp make_pair
//int get(int n) {
// if(n<=1) return 0;
// int ret = 0;
// if(n%2) {
// ret += --n;
// }
// ret += 2*n;
// ret += 2*get((n-2)/2);
// return ret;
//}
int get(int n) {
if(n<=2) return 0;
int ret = 0;
if(n%4 == 2) return n+get(n-2);
return n+2*get(n/2);
// int ret = n;
// if(n <= 2) return 0;
// int ret = 2*(n-1);
// int a = (n-2)/2;
// int b = n-2-a;
// ret += get(a) + get(b);
// if(a>1) ret++;
// if(b>1) ret++;
// return ret;
}
//int w[888];
//int ans[888];
vi d[10][512];
int f[10][512];
int d2[10];
int ask(const vi & a) {
printf("? %d", (int)a.size());
for(auto x : a) printf(" %d", x+1);
printf("\n");
fflush(stdout);
int ret;
read(ret);
return ret;
}
int ask1(const vi & a, int del) {
printf("? %d", (int)a.size()-1);
for(auto x : a) if(x != del) printf(" %d", x+1);
printf("\n");
fflush(stdout);
int ret;
read(ret);
return ret;
}
const int A = 800;
int r[10][A];
int ans[A];
int w[A];
int n;
vi rdone;
void findlr() {
vi full;
forn(i,0,n) full.pb(i);
vi res;
forn(i,0,n) {
if(ask1(full, i)) res.pb(i);
if(res.size() == 2) break;
}
ans[res[0]] = 0;
w[0] = res[0];
ans[res[1]] = n-1;
w[n-1] = res[1];
}
void solve2() {
forn(i,0,n) {
if(ans[i] != -1) r[2][i] = ans[i]%2;
else r[2][i] = 1-ask({w[0], i});
}
rdone.pb(2);
}
void findnext(int k) {
if(k>=n || w[k] != -1) return;
vi full;
forn(i,0,n) {
if(ans[i] == -1) full.pb(i);
}
if(k%2==0) full.pb(w[n-1]);
for(auto ind : full) {
int good = 1;
for(auto m : rdone) if(r[m][ind] != k%m) good = 0;
if(good && ask1(full, ind)) {
ans[ind] = k;
w[k] = ind;
break;
}
}
}
void solvemod(int m) {
if(m>=n) return;
vi full;
int sum = 0;
forn(i,0,m) {
full.pb(w[i]);
sum+=i;
}
sum%=m;
forn(i,0,n) if(ans[i] == -1) {
full.pb(i);
vi val;
forn(j,0,m) {
int bad = 0;
for(auto m2 : rdone) {
int d = gcd(m,m2);
if(r[m2][i] % d != j%d) bad = 1;
}
if(bad) continue;
val.pb(j);
}
int found = 0;
forn(it,0,val.size() - 1) {
int j = val[it];
if(ask1(full, w[j])) {
r[m][i] = (j+m-sum)%m;
found = 1;
break;
}
}
if(found == 0) {
r[m][i] = (val.back()+m-sum)%m;
}
full.pop_back();
}
else r[m][i] = ans[i]%m;
rdone.pb(m);
}
int main()
{
//#ifdef LOCAL
// freopen("input.txt", "rt", stdin);
// freopen("output.txt", "wt", stdout);
//#endif
// int n;
scanf("%d", &n);
forn(i,0,A) {
forn(j,0,10) r[j][i] = -1;
ans[i] = -1;
w[i] = -1;
}
findlr();
solve2();
findnext(1);
findnext(2);
solvemod(3);
findnext(3);
solvemod(4);
findnext(4);
solvemod(5);
findnext(5);
findnext(6);
solvemod(7);
findnext(7);
solvemod(8);
forn(i,0,n) if(ans[i] == -1) {
forn(cand,0,n) {
int good = 1;
for(auto m : rdone) if(cand%m != r[m][i]) good = 0;
if(good) {
ans[i] = cand;
break;
}
}
}
printf("!");
if(ans[0] + 1 > n/2) {
forn(i,0,n) ans[i] = n-1-ans[i];
}
forn(i,0,n) printf(" %d", ans[i]+1);
printf("\n");
}
| cpp |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | #include<bits/stdc++.h>
using namespace std;
#include <iostream>
#include <cmath>
#include <algorithm>
#define ll long long
#define fi first
#define se second
#define sst string
#define pb push_back
#define maxco 100000+5
#define lld long double
#define cha ios_base::sync_with_stdio(false);
#define ffl cout.flush();
#define phi acos(-1)
#define mod 1000000007
int main(){
cha
ll n;
// for(auto x : vec[30])cout<<x<<" ";
// cout<<endl;
cin>>n;
while(n--){
map<ll,vector<ll>> mp;
ll a,b,c;
cin>>a>>b>>c;
ll mn=1e18;
ll h1,h2,h3;
for(ll i=1;i<=2*a;i++){
for(ll j=i;j<=2*b;j+=i){
for(ll k=0;k<2;k++){
ll l=(c/j)*j+k*j;
ll val=abs(i-a)+abs(b-j)+abs(c-l);
if(mn>val){
mn=min(mn,val);
h1=i;
h2=j;
h3=l;
}
}
}
}
cout<<mn<<endl;
cout<<h1<<" "<<h2<<" "<<h3;
cout<<endl;
}
} | cpp |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | [
"greedy"
] | # include<iostream>
#include<cmath>
using namespace std;
int main(){
int n;
cin >> n;
int a[n]; // robo_coder robot
int b[n]; // bionic_solver robot
for(int i=0;i<n;i++){
cin >> a[i];
}
for(int k=0;k<n;k++){
cin>>b[k];
}
float sa=0;
float sb=0;
float p=0;
for(int j=0;j<n;j++){
sa=sa+a[j];
sb=sb+b[j];
if(a[j]>b[j]){
p++;
}}
if (p!=0){
cout<<1+ceil(((sb-sa+1)/p))<<endl;
}
else{
cout<<-1<<endl;
}
} | cpp |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
| [
"math"
] | #include<iostream>
#define int long long
using namespace std;
int t[300000];
int32_t main()
{
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
int H,n;
cin>>H>>n;
int minn=1e9;
for(int i=1;i<=n;i++)
cin>>t[i];
int suma=0;
int gdzie=0;
for(int i=1;i<=n;i++)
{
suma+=t[i];
minn=min(minn,suma);
if(suma+H<=0)
{
gdzie=i;
break;
}
}
if(gdzie!=0)
{
cout<<gdzie;
return 0;
}
if(suma>=0)
{
cout<<"-1";
return 0;
}
int ile=(H+minn)/abs(suma);
if((H+minn)%abs(suma)!=0)
ile++;
suma=ile*suma;
gdzie=ile*n;
for(int i=1;i<=n;i++)
{
suma+=t[i];
if(suma+H<=0)
{
cout<<gdzie+i;
return 0;
}
}
return 0;
}
| cpp |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
struct point{
int x,y;
};
struct line{
point p1,p2;
}a[4];
int len_line_pow(line a){//求线段长度的平方
return (a.p1.x-a.p2.x)*(a.p1.x-a.p2.x)+(a.p1.y-a.p2.y)*(a.p1.y-a.p2.y);
}
bool check_same_point(point p1,point p2){//判断两点是否相同
return p1.x==p2.x&&p1.y==p2.y;
}
bool check_one_line(line a,point p){//判断三点共线
return (a.p1.y-p.y)*(a.p2.x-p.x)==(a.p2.y-p.y)*(a.p1.x-p.x);
}
bool check_5_point(line a,point p){//判断p是不是在a的1/5点和4/5线之间
a.p1.x*=5,a.p2.x*=5,a.p1.y*=5,a.p2.y*=5;
p.x*=5,p.y*=5;
point p1={a.p1.x+(a.p2.x-a.p1.x)/5,a.p1.y+(a.p2.y-a.p1.y)/5};
point p4={a.p1.x+(a.p2.x-a.p1.x)/5*4,a.p1.y+(a.p2.y-a.p1.y)/5*4};
double d=sqrt((double)len_line_pow({p1,p4}));
double d1=sqrt((double)len_line_pow({p,p1}));
double d4=sqrt((double)len_line_pow({p,p4}));
return fabs(d-d1-d4)<1e-6;
}
bool check(line l,line r,line m){
//条件1:两线有唯一共同端点
int x=check_same_point(l.p1,r.p1);
if(check_same_point(l.p1,r.p2)){
x++;
swap(r.p1,r.p2);
}
if(check_same_point(l.p2,r.p1)){
x++;
swap(l.p1,l.p2);
}
if(check_same_point(l.p2,r.p2)){
x++;
swap(l.p1,l.p2);
swap(r.p1,r.p2);
}
if(x!=1){
return false;
}
// cout<<"T1:OK"<<"\n";
//条件2:夹角不是钝角,可以是直角
if(len_line_pow(l)+len_line_pow(r)<len_line_pow({l.p2,r.p2})){
// cout<<"T2:FALSE"<<"\n";
// cout<<len_line_pow(l)<<"+"<<len_line_pow(r)<<">"<<len_line_pow({l.p2,r.p2})<<"\n";
return false;
}
// cout<<"T2:OK"<<"\n";
//条件3:第3线两端点与前两线共线
if(check_one_line(l,m.p1)&&check_one_line(r,m.p2)){
;
}else if(check_one_line(l,m.p2)&&check_one_line(r,m.p1)){
swap(m.p1,m.p2);
}else{
return false;
}
// cout<<"T3:OK"<<"\n";
//条件4:第3线两端点必须在两线分别的1/5点和4/5线之间
if(check_5_point(l,m.p1)&&check_5_point(r,m.p2)){
// cout<<"T4:OK"<<"\n";
return true;
}else{
return false;
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin>>T;
while(T--){
for(int i=1;i<=3;i++){
cin>>a[i].p1.x>>a[i].p1.y>>a[i].p2.x>>a[i].p2.y;
}
bool flag=false;
for(int i=1;i<=3&&!flag;i++){
for(int j=1;j<=3&&!flag;j++){
if(i==j){
continue;
}
for(int k=1;k<=3&&!flag;k++){
if(k==j||k==i){
continue;
}
// cout<<i<<" "<<j<<" :"<<k<<"\n";
flag|=check(a[i],a[j],a[k]);
}
}
}
cout<<(flag?"YES":"NO")<<"\n";
}
return 0;
} | cpp |
1303 | G | G. Sum of Prefix Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define the sum of prefix sums of an array [s1,s2,…,sk][s1,s2,…,sk] as s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk)s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk).You are given a tree consisting of nn vertices. Each vertex ii has an integer aiai written on it. We define the value of the simple path from vertex uu to vertex vv as follows: consider all vertices appearing on the path from uu to vv, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.InputThe first line contains one integer nn (2≤n≤1500002≤n≤150000) — the number of vertices in the tree.Then n−1n−1 lines follow, representing the edges of the tree. Each line contains two integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi), denoting an edge between vertices uiui and vivi. It is guaranteed that these edges form a tree.The last line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤1061≤ai≤106).OutputPrint one integer — the maximum value over all paths in the tree.ExampleInputCopy4
4 2
3 2
4 1
1 3 3 7
OutputCopy36
NoteThe best path in the first example is from vertex 33 to vertex 11. It gives the sequence [3,3,7,1][3,3,7,1], and the sum of prefix sums is 3636. | [
"data structures",
"divide and conquer",
"geometry",
"trees"
] | // LUOGU_RID: 98578627
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> Pair;
const int N=2e5+5;
#define F first
#define S second
#define ls now<<1
#define rs now<<1|1
int vis[N<<2],tag[N<<2]; Pair tr[N<<2];
int dep[N],used[N],siz[N],a[N]; ll su[N],sd[N],val[N];
int n,tot,rt,mn,u,v,R; ll ans;
vector<int> G[N],vec[N];
inline void pushdown(int now){
if (tag[now]){
tag[ls]=tag[rs]=1;
vis[ls]=vis[rs]=0;
tag[now]=0;
}
}
void update(int now, int l, int r, Pair p){
if (!vis[now]) return tr[now]=p,vis[now]=1,void();
int mid=(l+r)>>1;
if (mid*tr[now].F+tr[now].S<mid*p.F+p.S) swap(tr[now],p);
if (l==r) return;
pushdown(now);
p.F<tr[now].F?update(ls,l,mid,p):update(rs,mid+1,r,p);
}
ll query(int now, int l, int r, int x){
if (!vis[now]) return 0;
ll ret=tr[now].F*x+tr[now].S;
if (l==r) return ret;
int mid=(l+r)>>1; pushdown(now);
return max(ret,mid>=x?query(ls,l,mid,x):query(rs,mid+1,r,x));
}
void Getrt(int u, int f){
siz[u]=1; int mx=0;
for (int v:G[u])
if (v!=f && !used[v]){
Getrt(v,u); siz[u]+=siz[v];
mx=max(mx,siz[v]);
}
mx=max(mx,tot-siz[u]);
if (mx<mn) mn=mx,rt=u;
}
void dfs(int u, int f){
vec[R].push_back(u),siz[u]=1;
dep[u]=dep[f]+1,val[u]=val[f]+a[u];
sd[u]=sd[f]+val[u];
su[u]=su[f]+1ll*dep[f]*a[u];
for (int v:G[u])
if (v!=f && !used[v]) dfs(v,u),siz[u]+=siz[v];
}
inline void Ins(int v, int u){
for (int x:vec[v]) ans=max(ans,max(su[x]+val[x],sd[x]+query(1,1,n,dep[x])));
for (int x:vec[v]) update(1,1,n,{val[x]-a[u],su[x]});
}
void solve(int u){
used[u]=1; dep[u]=1,su[u]=0,val[u]=sd[u]=a[u];
for (int v:G[u])
if (!used[v]){
vec[v].clear(),R=v;
dfs(v,u),Ins(v,u);
}
tag[1]=1,vis[1]=0;
for (int i=G[u].size()-1; ~i; i--)
if (!used[G[u][i]]) Ins(G[u][i],u);
tag[1]=1,vis[1]=0;
for (int v:G[u])
if (!used[v]) tot=siz[v],mn=1e9,Getrt(v,u),solve(rt);
}
int main(){
scanf("%d",&n); tag[1]=1;
for (int i=1; i<n; i++){
scanf("%d%d",&u,&v);
G[u].push_back(v),G[v].push_back(u);
}
for (int i=1; i<=n; i++) scanf("%d",&a[i]);
tot=n,mn=1e9,Getrt(1,0),solve(rt);
printf("%lld\n",ans);
} | cpp |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | #include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<unordered_map>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstdlib>
#include<stack>
#include<ctime>
#define forin(i,a,n) for(int i=a;i<=n;i++)
#define forni(i,n,a) for(int i=n;i>=a;i--)
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=6e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
int T;
int n,m,k;
string str;
void solve() {
n=read();
cin>>str;
int id=1;
string ans=str;
for(int i=2;i<=n;i++) {
if((n-i+1)%2==1) {
string p=str.substr(0,i-1);
reverse(p.begin(),p.end());
string k=str.substr(i-1,n-i+1)+p;
if(ans>k) {
ans=k;
id=i;
}
}else {
string k=str.substr(i-1,n-i+1)+str.substr(0,i-1);
if(ans>k) {
ans=k;
id=i;
}
}
}
cout<<ans<<'\n'<<id<<'\n';
}
int main() {
// init();
// stin();
scanf("%d",&T);
// T=1;
while(T--) solve();
return 0;
} | cpp |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement. | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
#define oo 1000000010
#define mod 1000000007
const int N = 1010;
void solve()
{
int n, m;
cin>>n>>m;
long long ans = (long long)n * (long long)(n + 1) / 2LL;
int z = n - m;
int k = z / (m + 1);
ans -= (long long)(m + 1) * (long long)k * (long long)(k + 1) / 2LL;
ans -= (long long)(z % (m + 1)) * (long long)(k + 1);
cout<<ans<<endl;
}
int main()
{
int t;
cin >> t;
while (t--)
{
solve();
}
return 0;
} | cpp |
1307 | C | C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l. | [
"brute force",
"dp",
"math",
"strings"
] | #include<bits/stdc++.h>
using namespace std;
#define int int64_t
int32_t main() {
string s;
cin >> s;
map<int, int> cnt;
map<int, int> freq;
int ans = 0;
for (char &c: s) {
int d = c - 'a';
for (auto[cc, f]: freq) {
int key = d * 26 + (cc - 'a');
cnt[key] += f;
ans = max(ans, cnt[key]);
}
ans = max(ans, ++freq[d]);
}
cout << ans;
} | cpp |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const ll mod = 998244353;
const int mm = 3e5 + 10;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int t;
cin>>t;
while(t--){
int k;
cin>>k;
string a;
cin>>a;
int ma=0;
int bj=0;
int ans=0;
for(int i=0;i<k;i++){
if(a[i]=='A')bj=1;
if(bj&&a[i]=='P')ans++;
if(a[i]=='A')ans=0;
ma=max(ans,ma);
}cout<<ma<<'\n';
}
}
| cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.