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 |
---|---|---|---|---|---|
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
int t; cin>>t;
while(t--){
int n; cin>>n;
if(n%2!=0){
cout<<7;
n-=3;
}
while(n>0){
cout<<1;
n-=2;
}
cout<<'\n';
}
return 0;
} | cpp |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m, p;
cin>>n>>m>>p;
vector<int> A(n);
vector<int> B(m);
int mina = n;
int minb = m;
for(int i = 0; i<n; i++){
cin>>A[i];
}
for(int i = 0; i<m; i++){
cin>>B[i];
}
for(int i = 0; i<n; i++){
if(A[i]%p != 0){
mina = i;
break;
}
}
for(int i = 0; i<m; i++){
if(B[i]%p != 0){
minb = i;
break;
}
}
cout<<mina+minb<<"\n";
return 0;
} | cpp |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | #include <bits/stdc++.h>
#define all(x) x.begin(), x.end()
#define r_all(x) x.rbegin(), x.rend()
#define sz(x)(ll) x.size()
#define g_max(x, y) x = max(x, y)
#define g_min(x, y) x = min(x, y)
#define rsz(a, n) a.resize(n)
#define ass(a, n) a.assign(n, 0)
#define YES() cout << "YES\n"
#define Yes cout << "Yes\n"
#define NO() cout << "NO\n"
#define No() cout << "No\n"
#define endl "\n"
#define print(a) for (auto &x: a) cout << x << " "; cout << endl
#define print_pair(a)
#define FOR(i, fr, to) for (long long i = fr; i <= to; i++)
#define RFOR(i, fr, to) for (long long i = fr; i >= to; i--)
#define pb push_back
#define eb emplace_back
#define is insert
#define F first
#define S second
using namespace std;
using ll = long long;
using ld = long double;
using vll = vector<ll>;
using vvll = vector<vll>;
using vc = vector<char>;
using vvc = vector<vc>;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
using vvpll = vector<vpll>;
using stkll = stack<ll>;
using qll = queue<ll>;
using dqll = deque<ll>;
using sll = set<ll>;
using msll = multiset<ll>;
using mll = map<ll, ll>;
using vsll = vector<sll>;
using sc = set<char>;
using pcll = pair<char, ll>;
ll dr[] = {0, 1, 0, -1}, dc[] = {-1, 0, 1, 0};
const ll INF = 1e18;
ll MOD = 1e9 + 7;
ll mod_add(ll u, ll v, ll mod = MOD) {
u %= mod, v %= mod;
return (u + v) % mod;
}
ll mod_sub(ll u, ll v, ll mod = MOD) {
u %= mod, v %= mod;
return (u - v + mod) % mod;
}
ll mod_mul(ll u, ll v, ll mod = MOD) {
u %= mod, v %= mod;
return (u * v) % mod;
}
ll mod_pow(ll u, ll p, ll mod = MOD) {
ll res = 1;
u %= mod;
if (u == 0) {
return 0;
}
while (p > 0) {
if (p & 1) {
res = (res * u) % mod;
}
p >>= 1;
u = (u * u) % mod;
}
return res;
}
ll mod_inv(ll u, ll mod = MOD) {
u %= mod;
ll g = __gcd(u, mod);
if (g != 1) {
return -1;
}
return mod_pow(u, mod - 2, mod);
}
ll mod_div(ll u, ll v, ll mod = MOD) {
u %= mod, v %= mod;
return mod_mul(u, mod_inv(v), mod);
}
template<class T>
vector<T> operator+(vector<T> a, vector<T> b) {
a.insert(a.end(), b.begin(), b.end());
return a;
}
pll operator+(pll a, pll b) {
pll ans = {a.first + b.first, a.second + b.second};
return ans;
}
template<class A, class B>
ostream &operator<<(ostream &os,
const pair<A, B> &p) {
os << p.first << " " << p.second;
return os;
}
template<class A, class B>
istream &operator>>(istream &is, pair<A, B> &p) {
is >> p.first >> p.second;
return is;
}
template<class T>
ostream &operator<<(ostream &os,
const vector<T> &vec) {
for (auto &x: vec) {
os << x << " ";
}
return os;
}
template<class T>
istream &operator>>(istream &is, vector<T> &vec) {
for (auto &x: vec) {
is >> x;
}
return is;
}
template<class T>
ostream &operator<<(ostream &os,
const set<T> &vec) {
for (auto &x: vec) {
os << x << " ";
}
return os;
}
template<class A, class B>
ostream &operator<<(ostream &os,
const map<A, B> d) {
for (auto &x: d) {
os << "(" << x.first << " " << x.second << ") ";
}
return os;
}
template<class A>
void read_arr(A a[], ll from, ll to) {
for (ll i = from; i <= to; i++) {
cin >> a[i];
}
}
template<class A>
void print_arr(A a[], ll from, ll to) {
for (ll i = from; i <= to; i++) {
cout << a[i] << " ";
}
cout << "\n";
}
template<class A>
void print_arr(A a[], ll n) {
print_arr(a, 0, n - 1);
}
template<class A>
void set_arr(A a[], A val, ll from, ll to) {
for (ll i = from; i <= to; i++) {
a[i] = val;
}
}
template<class A>
void set_arr(A a[], A val, ll n) {
set_arr(a, val, 0, n - 1);
}
const ll N = 1e6 + 10;
ll n, k, q, m;
ll a[N];
string s, s1, s2, s3;
void init() {
}
ll get_ans() {
}
void single(ll t_id = 0) {
cin >> n >> m;
ll g = __gcd(m, n);
ll ans = (n + m - 1) / g - (n - 1) / g;
ll rem = m / g;
ll tmp = rem;
vll vec;
for (ll i = 2; i * i <= rem; i++) {
if (tmp % i == 0) {
vec.pb(i);
}
while (tmp % i == 0) {
tmp /= i;
}
}
// cout << vec << "\n";
if (tmp > 1) {
vec.pb(tmp);
}
// sll st;
// cout << ans << "\n";
for (ll mask = 1; mask < (1 << sz(vec)); mask++) {
ll fac = 1;
ll sign = __builtin_popcount(mask) & 1 ? -1 : 1;
for (ll i = 0; i < sz(vec); i++) {
if (mask >> i & 1) {
fac *= vec[i];
}
}
// if (st.count(fac)) {
// continue;
// }
ans += sign * ((n + m - 1) / (g * fac) - (n - 1) / (g *fac));
// cout << fac << "\n";
// cout << ans << "\n";
// st.is(fac);
}
cout << ans << "\n";
}
void multiple() {
ll t;
cin >> t;
for (ll i = 0; i < t; i++) {
single(i);
}
}
//#endif
#if 0
void multiple() {
while (cin >> n >> m) {
if (n == 0 && m == 0) {
break;
}
single();
}
#endif
int main(int argc, char *argv[]) {
// ios_base::sync_with_stdio(false);
// cin.tie(nullptr);
init();
// freopen("feast.in", "r", stdin);
// freopen("feast.out", "w", stdout);
// freopen("../input.txt", "r", stdin);
multiple();
// single();
return 0;
}
| cpp |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
| [
"constructive algorithms",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
long long s;
cin>>s;
while(s--)
{ long long l;
cin>>l;
long long s[l+2];
for(long long q=0;q<l;q++)
cin>>s[q];
sort(s,s+l,greater<long long>());
for(long long q=0;q<l;q++)
cout<<s[q]<<" ";
cout<<endl;
}
return 0;
}
| cpp |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.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.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
| [
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main() {
long long t,s;
cin>>t;
while(t--){
cin>>s;int sum=s;
while(s>9){
int k=s%10;
s=s/10;
sum=sum+s;
s=s+k;
}
cout<<sum<<endl;
}
return 0;
} | cpp |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS. | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] |
// Author : حسن
#include <bits/stdc++.h>
using namespace std;
#define TL ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define rall(s) s.rbegin(),s.rend()
#define all(s) s.begin(),s.end()
#define pb push_back
#define fi first
#define se second
#define ll long long
#define ld long double
#define YES cout<<"YES\n"
#define Yes cout<<"Yes\n"
#define yes cout<<"yes\n"
#define NO cout<<"NO\n"
#define No cout<<"No\n"
#define no cout<<"no\n"
const int N = 4e5 + 9 , mod = 1e9 + 7;
ll a[N] , us[N] = {} , d[N] = {} , dp[N] = {} , b[N] = {} , c[N] = {} , p[N] = {} ;
void solve(){
ll q , s = 0, n , f , l , r , i , j , mn = 1e9 + 20, mx = 0, x , y , m , k;
cin>>n;
string a;
cin>>a;
for(i = 1; i <= n; i++){
b[i] = i;
c[i] = n - i + 1;
}
l = 0;
l = 1e9;
for(i = 0; i < a.size(); i++){
if(a[i] == '>'){
l = min(l , i);
}else {
if(l != 1e9){
x = i + 1;
y = l + 1;
for(j = i + 1; j >= l + 1; j--){
if(x >= y){
swap(b[x] , b[y]);
}else {
break;
}
x--;
y++;
}
}
l = 1e9;
}
}
if(l != 1e9){
x = a.size() + 1;
y = l + 1;
for(j = a.size() + 1; j >= l + 1; j--){
if(x >= y){
swap(b[x] , b[y]);
}else {
break;
}
x--;
y++;
}
}
l = 1e9;
for(i = 0; i < a.size(); i++){
if(a[i] == '<'){
l = min(l , i);
}else {
if(l != 1e9){
x = i + 1;
y = l + 1;
for(j = i + 1; j >= l + 1; j--){
if(x >= y){
swap(c[x] , c[y]);
}else {
break;
}
x--;
y++;
}
}
l = 1e9;
}
}
if(l != 1e9){
x = a.size() + 1;
y = l + 1;
for(j = a.size() + 1; j >= l + 1; j--){
if(x >= y){
swap(c[x] , c[y]);
}else {
break;
}
x--;
y++;
}
}
for(i = 1; i <= n; i++)
cout<<c[i]<<" ";
cout<<"\n";
for(i = 1; i <= n; i++)
cout<<b[i]<<" ";
cout<<"\n";
}
int main(){
TL;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t = 1;
cin>>t;
while(t--)
{
solve();
}
}
// Author : حسن
| cpp |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c;
int n;
cin>>n;
while(n--){
int ans=0;
cin>>a>>b>>c;
if(a)a--,ans++;
if(b)b--,ans++;
if(c)c--,ans++;
if(a<c)swap(a,c);
if(a<b)swap(a,b);
if(a&&b)a--,b--,ans++;
if(a&&c)a--,c--,ans++;
if(b&&c)b--,c--,ans++;
if(a&&b&&c)ans++;
cout<<ans<<endl;}
}
| 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<iostream>
#include<iterator>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
#include "local_dbg.cpp"
#else
#define debug(...) 101;
#endif
typedef long long int ll;
typedef long double ld;
typedef std::vector<int> vi;
typedef std::vector<ll> vll;
typedef std::vector<ld> vld;
typedef std::vector<std::vector<ll> > vvll;
typedef std::vector<std::vector<ld> > vvld;
typedef std::vector<std::vector<std::vector<ll> > > vvvll;
typedef std::vector<string> vstr;
typedef std::vector<std::pair<ll,ll> > vpll;
typedef std::pair<ll,ll> pll;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb push_back
#define nl "\n"
#define all(c) (c).begin(),(c).end()
#define iotam1 cout<<-1<<nl
#define cty cout<<"YES"<<nl
#define ctn cout<<"NO"<<nl
#define lmax LLONG_MAX
#define lmin LLONG_MIN
#define sz(v) (v).size()
#define deci(n) fixed<<setprecision(n)
#define c(x) cout<<(x)
#define csp(x) cout<<(x)<<" "
#define c1(x) cout<<(x)<<nl
#define c2(x,y) cout<<(x)<<" "<<(y)<<nl
#define c3(x,y,z) cout<<(x)<<" "<<(y)<<" "<<(z)<<nl
#define c4(a,b,c,d) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<nl
#define c5(a,b,c,d,e) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<" "<<(e)<<nl
#define c6(a,b,c,d,e,f) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<" "<<(e)<<" "<<(f)<<nl
#define f(i_itr,a,n) for(ll i_itr=a; i_itr<n; i_itr++)
#define rev_f(i_itr,n,a) for(ll i_itr=n; i_itr>a; i_itr--)
#define arri(n, arr) for(ll i_itr=0; i_itr<n; i_itr++) cin>>arr[i_itr]
#define a_arri(n, m, arr) for(ll i_itr=0; i_itr<n; i_itr++) for (ll j_itr=0; j_itr<m; j_itr++) cin>>arr[i_itr][j_itr]
#define pb push_back
#define fi first
#define se second
#define print(vec,a,b) for(ll i_itr=a;i_itr<b;i_itr++) cout<<vec[i_itr]<<" ";cout<<"\n";
#define input(vec,a,b) for(ll i_itr = a;i_itr<b;i_itr++) cin>>vec[i_itr];
#define ms(a,val) memset(a,val,sizeof(a))
const ll mod = 1000000007;
const long double pi=3.14159265358979323846264338327950288419716939937510582097494459230;
ll pct(ll x) { return __builtin_popcount(x); } // #of set bits
ll poww(ll a, ll b) { ll res=1; while(b) { if(b&1) res=(res*a); a=(a*a); b>>=1; } return res; }
ll modI(ll a, ll m=mod) { ll m0=m,y=0,x=1; if(m==1) return 0; while(a>1) { ll q=a/m; ll t=m; m=a%m; a=t; t=y; y=x-q*y; x=t; } if(x<0) x+=m0; return x;}
ll powm(ll a, ll b,ll m=mod) {ll res=1; while(b) { if(b&1) res=(res*a)%m; a=(a*a)%m; b>>=1; } return res;}
void ipgraph(ll,ll);
void ipgraph(ll); ///for tree
void dfs(ll node,ll par);
//******************************************************************************************************************************************* /
const ll N=2e5+5;
// ll inp[N];
// vll adj[N]; ///for graph(or tree) use this !!-><-!!
void ok_boss()
{
ll n,m;
cin >> n>>m;
ll z=n-m;
ll parts=m+1;
ll mmin=z/parts;
ll vadh=z%parts;
ll ok=parts-vadh;
ll anss=ok*((mmin*(mmin+1))>>1ll);
mmin++;
anss+=vadh*((mmin*(mmin+1))>>1ll);
c1(((n*(n+1))>>1ll) - anss);
return;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
#endif
fast;
/// std::cout << fixed<<setprecision(15); ///activate it if the answers are in decimal.
ll qq_itr = 1;
cin >> qq_itr;
while (qq_itr--)
ok_boss();
return 0;
}
/*
void ipgraph(ll nodes_ipg,ll edgs_ipg)
{
f(i,0,nodes_ipg)
adj[i].clear();
ll fir,sec;
while(edgs_ipg--)
{
cin>>fir>>sec;
fir--,sec--; ///turn it off if it is 0-indexed
adj[fir].pb(sec);
adj[sec].pb(fir); ///remove this if directed !!!
}
return;
}
void ipgraph(ll nodes_ipg)
{
ipgraph(nodes_ipg,nodes_ipg-1);
}
void dfs(ll node,ll par=-1)
{
for(ll chd : adj[node])
{
if(chd==par)
continue;
dfs(chd,node);
}
return;
}
*/ | cpp |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"greedy"
] | #include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll mod = 1e9+7;
bool cmp(pair<ll,ll>a,pair<ll,ll>b)
{
return a.second < b.second;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll n;
cin >> n;
vector<ll>a(n+1),pref(n+1,0);
map<ll,vector<pair<ll,ll>>>M;
vector<pair<ll,ll>>R;
for(ll i=1;i<=n;i++)
{
cin >> a[i];
if(i) pref[i]+=pref[i-1];
pref[i]+=a[i];
}
for(ll i=1;i<=n;i++)
{
for(ll j=i;j<=n;j++)
{
M[pref[j]-pref[i-1]].push_back({i,j});
}
}
for(auto &x:M)
{
sort(x.second.begin(),x.second.end(),cmp);
ll r=0;
vector<pair<ll,ll>>tmp;
for(ll i=0;i<x.second.size();i++)
{
// cout << x.second[i].first << ' ' << x.second[i].second << endl;
if(x.second[i].first>r)
{
// cout << "usao\n";
tmp.push_back(x.second[i]);
r=x.second[i].second;
}
}
if(tmp.size()>R.size()) R=tmp;
}
cout << R.size() << endl;
for(auto x:R) cout << x.first << ' ' << x.second << endl;
return 0;
}
| cpp |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1e9 + 7
string a = "abcdefghijklmnopqrstuvwxyz";
void dfs(string& k, char x, map<char, vector<char>>& mp, map<char, bool>& visited){
if(x < 'a' || x > 'z') return;
k += x;
visited[x] = true;
// if(mp[x][0] == ' ') return;
for(char c: mp[x]){
if(!visited[c]) dfs(k, c, mp, visited);
}
}
void solve(){
string s;
cin >> s;
int n = s.size();
vector<bool> visited(26, false);
visited[s[0] - 'a'] = true;
string res(1, s[0]);
int pos = 0;
for(int i=1; i<n; ++i){
if(visited[s[i] - 'a']){
if(pos && res[pos - 1] == s[i]) pos--;
else if(pos < res.size() - 1 && res[pos + 1] == s[i]) pos++;
else{
cout << "NO\n";
return;
}
}
else{
visited[s[i] - 'a'] = true;
if(!pos) res = s[i] + res;
else if(pos == res.size() - 1){
res += s[i];
pos++;
}
else{
cout << "NO\n";
return;
}
}
}
cout << "YES\n" << res;
for(int i=0; i<26; ++i){
if(!visited[a[i] - 'a']) cout << a[i];
}
cout << "\n";
// map<char, vector<char>> mp;
// for(int i=1; i<n-1; ++i){
// vector<char> v = mp[s[i]];
// if(find(begin(v), end(v), s[i - 1]) == end(v)) mp[s[i]].push_back(s[i - 1]);
// if(find(begin(mp[s[i]]), end(mp[s[i]]), s[i + 1]) == end(mp[s[i]])) mp[s[i]].push_back(s[i + 1]);
// }
// if(find(begin(mp[s[0]]), end(mp[s[0]]), s[1]) == end(mp[s[0]])) mp[s[0]].push_back(s[1]);
// if(find(begin(mp[s[n - 1]]), end(mp[s[n - 1]]), s[n - 2]) == end(mp[s[n - 1]])) mp[s[n - 1]].push_back(s[n - 2]);
// int cnt = 0;
// char pos;
// for(auto x: mp){
// if(x.second.size() == 1){
// pos = x.first;
// cnt++;
// }
// }
// if(n > 1 && cnt != 2) cout << "NO\n";
// else{
// string res = "";
// map<char, bool> visited;
// dfs(res, pos, mp, visited);
// // for(auto x: mp){
// // if(!visited[x.first]) dfs(res, x.first, mp, visited);
// // }
// for(int i=0; i<26; ++i){
// if(mp[a[i]].empty()) res.push_back(a[i]);
// }
// cout << "YES\n" << res << "\n";
// }
// for(auto x: mp){
// cout << x.first << " ";
// for(int k=0; k<x.second.size(); ++k){
// cout << x.second[k] << " ";
// }
// cout << "\n";
// }
// cout << "\n";
}
int 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
ll t = 1;
cin >> t;
while(t--){
solve();
}
return 0;
}
| cpp |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | #include <iostream>
#include <string>
const int SIZE = 2000;
int main() {
int t, n, a, odd_count;
std::cin >> t;
std::string arr[SIZE];
std::string s;
bool has_even, has_odd;
int temp[300];
for (int i = 0; i < t; i++) {
std::cin >> n;
odd_count = 0;
bool has_even = false, has_odd = false;
arr[i] = "NO";
for (int j = 0; j < n; j++) {
std::cin >> a;
if (a % 2 == 0) {
has_even = true;
} else {
has_odd = true;
odd_count++;
}
}
if (has_even && has_odd) {
arr[i] = "YES";
continue;
}
if (odd_count % 2 == 1) {
arr[i] = "YES";
}
}
for (int i = 0; i < t; i++)
std::cout << arr[i] << "\n";
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>
using namespace std;
#define int long long
#define PII pair<int,int>
#define x first
#define y second
const int N=1e5+10;
void solve()
{
int n,x,y;
cin>>n>>x>>y;
int t=(x+y+1)-n;
int a=min(max(t,1ll),n);
int b=min(x+y-1,n);
cout<<a<<' '<<b<<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 |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | /* Code by Poojan Patel (poojanpatel2712) */
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define tt ll testcase; cin>>testcase; while(testcase--)
#define ic(n) ll n; cin>>n
#define arr(a,n) ll a[n]; for(ll i=0; i<n; i++) cin>>a[i]
#define is(s) string s; cin>>s
#define floi(xi,xn,xs) for(ll i=xi; i<xn; i+=xs)
#define vll vector<ll>
#define vpll vector<pair<ll,ll>>
#define iv(vi,n) vll vi(n); for(ll i=0; i<n; i++) cin>>vi[i]
#define all(vi) (vi).begin(),(vi).end()
#define pv(vi) for(auto x : vi) cout<<x<<' '; cout<<endl;
#define pm(mp) for(auto x:mp) cout<<mp.first<<' '<<mp.second<<endl;
#define pa(a,n) for(ll i=0; i<n; i++){cout<<a[i]<<' ';} cout<<endl;
#define mll map<ll,ll>
#define ff first
#define ss second
#define setbit(x) __builtin_popcountll(x)
#define ctzll(x) __builtin_ctzll(x)
#define clzll(x) __builtin_clzll(x)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
const ll N=1e9+7;
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll lcm(ll a,ll b){return (a*1ll*b)/__gcd(a,b);}
ll power(ll a,ll b){ll ans=1;while(b){if(b&1) ans=(ans*a)%N; b>>=1;a=(a*a)%N;}return ans;}
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;}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
void solve(){
ic(n);
iv(a,n);
iv(b,n);
vll ai(n);
for(ll i=0; i<n; i++){
ai[i]=a[i]-b[i];
}
sort(all(ai));
ll ans=0;
for(ll i=0; i<n; i++){
if(ai[i]<=0) continue;
ll lower=lower_bound(all(ai),-1*ai[i]+1)-ai.begin();
ans+=i-lower;
}
cout<<ans<<endl;
}
int main ()
{
ios_base::sync_with_stdio(false); // for fast inputs and outputs....
cin.tie(NULL); // this flushes cout....
// tt{
solve();
// }
// cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;
return 0;
}
| cpp |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"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 = 0;
void solver();
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()
{
string s; cin >> s;
string ans = ""; char cur = '$';
set<char> adj[125]; vector<bool> vis(125, false);
if(s.size() == 1) {
cout << "YES\n";
for(int i = 'a'; i <= 'z'; i++) {
if(!vis[i]) ans += i;
}
cout << ans << endl;
return;
}
for(int i = 0; i < s.size()-1; i++) {
adj[s[i]].insert(s[i+1]);
adj[s[i+1]].insert(s[i]);
}
for(int i = 'a'; i <= 'z'; i++) {
if(adj[i].size() > 2) {
cout << "NO\n";
return;
}
else if(adj[i].size() == 1) cur = i;
}
if(cur == '$') {
cout << "NO\n";
return;
}
cout << "YES\n";
queue<char> q; q.push(cur);
while(!q.empty()) {
cur = q.front(); q.pop();
vis[cur] = true; ans += cur;
for(char ch: adj[cur]) {
if(!vis[ch]) q.push(ch);
}
}
for(int i = 'a'; i <= 'z'; i++) {
if(!vis[i]) ans += i;
}
cout << ans << endl;
} | 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"
] | //llllljy
#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
int t,n,vis[maxn],czc;
void solve1(){
int x,y;
memset(vis,0,sizeof(vis));
printf("? CH\n");fflush(stdout);scanf("%d",&x);
for(int i=1;i<=x;i++)scanf("%d",&y),vis[y]=1,vis[y+1]=3;
printf("? CC\n");fflush(stdout);scanf("%d",&x);
for(int i=1;i<=x;i++)scanf("%d",&y),vis[y]=1,vis[y+1]=1;
printf("? CO\n");fflush(stdout);scanf("%d",&x);
for(int i=1;i<=x;i++)scanf("%d",&y),vis[y]=1,vis[y+1]=2;
printf("? OO\n");fflush(stdout);scanf("%d",&x);
for(int i=1;i<=x;i++)scanf("%d",&y),vis[y]=2,vis[y+1]=2;
printf("? HO\n");fflush(stdout);scanf("%d",&x);
for(int i=1;i<=x;i++)scanf("%d",&y),vis[y]=3,vis[y+1]=2;
for(int i=2;i<n;i++)if(vis[i]==0)vis[i]=3;
int flag1=1,flagn=1;
if(vis[1]==0)flag1=0;
if(vis[n]==0)flagn=0;
if(!flag1)vis[1]=3;
if(!flagn)vis[n]=1;//H C
printf("? ");
fflush(stdout);
for(int i=1;i<=n;i++){
if(vis[i]==1)printf("C");
if(vis[i]==2)printf("O");
if(vis[i]==3)printf("H");
fflush(stdout);
}
printf("\n");
fflush(stdout);scanf("%d",&y);
for(int i=1;i<=y;i++)scanf("%d",&x);
if(y!=0)return ;
if(!flag1)vis[1]=3;
if(!flagn)vis[n]=3;//H H
printf("? ");
fflush(stdout);
for(int i=1;i<=n;i++){
if(vis[i]==1)printf("C");
if(vis[i]==2)printf("O");
if(vis[i]==3)printf("H");
fflush(stdout);
}
printf("\n");
fflush(stdout);scanf("%d",&y);
for(int i=1;i<=y;i++)scanf("%d",&x);
if(y!=0)return ;
if(!flag1)vis[1]=2;
if(!flagn)vis[n]=1;//O C
printf("? ");
fflush(stdout);
for(int i=1;i<=n;i++){
if(vis[i]==1)printf("C");
if(vis[i]==2)printf("O");
if(vis[i]==3)printf("H");
fflush(stdout);
}
printf("\n");
fflush(stdout);scanf("%d",&y);
for(int i=1;i<=y;i++)scanf("%d",&x);
if(y!=0)return ;
if(!flag1)vis[1]=2;
if(!flagn)vis[n]=3;//O H
}
int check(){
int y,x;
printf("? ");
fflush(stdout);
for(int i=1;i<=n;i++){
if(vis[i]==1)printf("C");
if(vis[i]==2)printf("O");
if(vis[i]==3)printf("H");
}
printf("\n");
fflush(stdout);scanf("%d",&y);
for(int i=1;i<=y;i++)scanf("%d",&x);
if(y!=0)return 1;
return 0;
}
void solve2(){//牛马啊
int x,y;
memset(vis,0,sizeof(vis));
int num=0;
printf("? CO\n");fflush(stdout);scanf("%d",&x),num+=x;
for(int i=1;i<=x;i++)scanf("%d",&y),vis[y]=1,vis[y+1]=2;
printf("? CC\n");fflush(stdout);scanf("%d",&x),num+=x;
for(int i=1;i<=x;i++)scanf("%d",&y),vis[y]=1,vis[y+1]=1;
printf("? CH\n");fflush(stdout);scanf("%d",&x),num+=x;
for(int i=1;i<=x;i++)scanf("%d",&y),vis[y]=1,vis[y+1]=3;
if(num!=0){//出现了!牛马czc
int flag1=0,flagn=0;
if(vis[1]==1){//3,4不确定 (3不可能为C)
if(vis[3]==0)flag1=1;
if(vis[4]==0)flagn=1;
for(int i=2;i<=3;i++){
for(int j=1;j<=3;j++){
if(flag1)vis[3]=i;
if(flagn)vis[4]=j;
if(check())return ;
}
}
}
else if(vis[2]==1){//二次出现牛马
if(vis[1]==0)flag1=1;
if(vis[4]==0)flagn=1;
for(int i=2;i<=3;i++){
for(int j=1;j<=3;j++){
if(flag1)vis[1]=i;
if(flagn)vis[4]=j;
if(check())return;
}
}
}else{//第三只(也是最后一只牛马)
if(vis[1]==0)flag1=1;
if(vis[2]==0)flagn=1;
for(int i=2;i<=3;i++){
for(int j=1;j<=3;j++){
if(flag1)vis[1]=i;
if(flagn)vis[2]=j;
if(check())return ;
}
}
}
return ;
}
// 牛马预处理
printf("? HO\n");fflush(stdout);scanf("%d",&x);
if(x!=0){
if(x==2){
scanf("%d%d",&y,&y);
vis[1]=3,vis[2]=2,vis[3]=3,vis[4]=2;
return ;
}
scanf("%d",&y);
vis[y]=3,vis[y+1]=2;
int lid,rid;
if(y==1)lid=3,rid=4;
if(y==2)lid=1,rid=4;
if(y==3)lid=1,rid=2;
int flag1=0,flagn=0;
if(vis[lid]==0)flag1=1;
if(vis[rid]==0)flagn=1;
for(int i=2;i<=3;i++){
for(int j=1;j<=3;j++){
if(flag1)vis[lid]=i;
if(flagn)vis[rid]=j;
if(check())return ;
}
}
}
//最后一步! OO
printf("? OO\n");fflush(stdout);scanf("%d",&x);
if(x==0){
vis[2]=vis[3]=3;
printf("? HHH\n");fflush(stdout);scanf("%d",&x);
if(x==0){
vis[1]=2,vis[4]=1;
return ;
}
if(x==2){
scanf("%d%d",&y,&y);
vis[1]=vis[4]=3;
return ;
}
scanf("%d",&y);
if(y==1)vis[1]=3,vis[4]=1;
else vis[4]=3,vis[1]=2;
}
else{
if(x==1){
scanf("%d",&y);
vis[1]=vis[2]=2,vis[3]=3;
int flag1=0;
if(vis[4]==0)flag1=1;
for(int i=1;i<=3;i+=2){
if(flag1)vis[4]=i;
if(check())return ;
}
}
else if(x==2){
scanf("%d%d",&y,&y);
vis[1]=vis[2]=vis[3]=2;
int flag1=0;
if(vis[4]==0)flag1=1;
for(int i=1;i<=3;i+=2){
if(flag1)vis[4]=i;
if(check())return ;
}
}else{
scanf("%d%d%d",&y,&y,&y);
vis[1]=vis[2]=vis[3]=vis[4]=2;
return ;
}
}
}
int main(){
cin>>t;
while(t--){
scanf("%d",&n);
if(n!=4)solve1();
else solve2();
printf("! ");
fflush(stdout);
for(int i=1;i<=n;i++){
if(vis[i]==1)printf("C");
if(vis[i]==2)printf("O");
if(vis[i]==3)printf("H");
}
printf("\n");
fflush(stdout);
scanf("%d",&czc);
if(czc==0)break;
}
return 0;
}
//2
//5
//CHHHH
//8
//HHHCCOOH | cpp |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
//#define int long long
//#define endl '\n'
const int N=200009;
const int INF=0x3f3f3f3f;
const int mod=998244353;
inline int read(){
int s=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
while(ch>='0'&&ch<='9'){s=(s<<1)+(s<<3)+(ch^48); ch=getchar();}
return s*=f;
}
inline void write(int x){
if(x>9)write(x/10);
putchar(x%10+48);
}
inline void print(int x){
if(x<0){putchar('-'); x=-x;}
write(x);
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T> T rnd(T l,T r){return uniform_int_distribution<T>(l,r)(rng);}
inline void file(){
freopen(".in","r",stdin);
freopen(".out","w",stdout);
}
int n,m,B,b[N],k[N],f[N],nxt[N];
inline void update(int id){
int l=(b[id]-1)*B+1;
int r=min(b[id]*B,n);
for(int i=id;i>=l;i--){
int pos=i+k[i];
if(pos>r){
f[i]=1;
nxt[i]=pos;
}
else{
f[i]=f[pos]+1;
nxt[i]=nxt[pos];
}
}
}
signed main(){
n=read(); m=read(); B=sqrt(n);
for(int i=1;i<=n;i++)k[i]=read();
for(int i=1;i<=n;i++)b[i]=(i-1)/B+1;
for(int i=n;i>=1;i--){
int pos=i+k[i];
int r=min(b[i]*B,n);
if(pos>r){
f[i]=1;
nxt[i]=pos;
}
else{
f[i]=f[pos]+1;
nxt[i]=nxt[pos];
}
}
for(int i=1;i<=m;i++){
int op=read(),id=read();
if(op==0){
k[id]=read();
update(id);
continue;
}
int ans=0;
while(nxt[id]<=n){
ans+=f[id];
id=nxt[id];
}
while(id+k[id]<=n)id+=k[id],ans++;
cout<<id<<' '<<ans+1<<'\n';
}
return 0;
} | cpp |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
#define ll long long
const ll MM = 998244353, N = 1e5 + 10, MAX = 1e15;
using namespace std;
vector<ll>v[200], v1[200];
int solve() {
int n; cin >> n;
string s, t; cin >> s >> t;
for (int i = 0; i < n; i++) {
v[s[i]].emplace_back(i + 1);
v1[t[i]].emplace_back(i + 1);
}
vector<pair<ll, ll>>res;
for (char c = 'a'; c <= 'z'; c++) {
while (v[c].size() && v1[c].size()) {
res.emplace_back(v[c].back(), v1[c].back());
v[c].pop_back();
v1[c].pop_back();
}
while (v[c].size()) {
v[0].emplace_back(v[c].back());
v[c].pop_back();
}
while (v1[c].size()) {
v1[0].emplace_back(v1[c].back());
v1[c].pop_back();
}
}
while (v['?'].size() && v1[0].size()) {
res.emplace_back(v['?'].back(), v1[0].back());
v['?'].pop_back();
v1[0].pop_back();
}
while (v1['?'].size() && v[0].size()) {
res.emplace_back(v[0].back(), v1['?'].back());
v1['?'].pop_back();
v[0].pop_back();
}
while (v['?'].size() && v1['?'].size()) {
res.emplace_back(v['?'].back(), v1['?'].back());
v['?'].pop_back();
v1['?'].pop_back();
}
cout << res.size() << '\n';
for (auto x : res) {
cout << x.first << " " << x.second << '\n';
}
return 0;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
std::cout.tie(0);
int t = 1;//cin >> t;
int i = 1;
while (t--) {
//cout << "Case #" << i++ << ": ";
solve();
}
}
/*
*/ | 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"
] | #include <bits/stdc++.h>
using namespace std;
#define rep(i, s, e) for (int i = s; i <= e; ++i)
#define drep(i, s, e) for (int i = s; i >= e; --i)
#define file(a) freopen(#a".in", "r", stdin), freopen(#a".out", "w", stdout)
#define pv(a) cout << #a << " = " << a << endl
#define pa(a, l, r) cout << #a " : "; rep(_, l, r) cout << a[_] << ' '; cout << endl
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 10;
int read() {
int x = 0, f = 1; char c = getchar();
for (; c < '0' || c > '9'; c = getchar()) if (c == '-') f = -1;
for (; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - 48;
return x * f;
}
int s, t, head[N], tot, d[N], pre[N], mc, mf;
bool tag[N];
struct node {
int nxt, to, f, w;
node(int _nxt = 0, int _to = 0, int _f = 0, int _w = 0) {
nxt = _nxt, to = _to, f = _f, w = _w;
}
} e[N];
void adde(int u, int v, int f, int w) {
e[++ tot] = node(head[u], v, f, w), head[u] = tot;
e[++ tot] = node(head[v], u, 0, -w), head[v] = tot;
}
bool spfa() {
rep(u, s, t) d[u] = INF, pre[u] = 0;
queue <int> q;
d[s] = 0, q.push(s), tag[s] = true;
while (q.size()) {
int u = q.front(); q.pop(), tag[u] = false;
for (int i = head[u], v; i; i = e[i].nxt) {
if (!e[i].f || d[v = e[i].to] <= d[u] + e[i].w) continue;
pre[v] = i, d[v] = d[u] + e[i].w;
if (!tag[v]) q.push(v), tag[v] = true;
}
}
return d[t] < INF;
}
int n, m, q;
int main() {
n = read(), m = read(), s = 1, t = n, tot = 1;
rep(i, 1, m) {
int u = read(), v = read(), w = read();
adde(u, v, 1, w);
}
vector <pair <int, int> > ver;
while (spfa()) {
int flow = INF;
for (int i = pre[t]; i; i = pre[e[i ^ 1].to]) flow = min(flow, e[i].f);
mf += flow;
for (int i = pre[t]; i; i = pre[e[i ^ 1].to]) e[i].f -= flow, e[i ^ 1].f += flow, mc += flow * e[i].w;
ver.emplace_back(make_pair(mf, mc));
}
for (int q = read(); q; -- q) {
int x = read(); double ans = 1e18;
for (auto it : ver) ans = min(ans, (double) (it.second + x) / it.first);
printf("%.10lf\n", ans);
}
return 0;
} | cpp |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | // LUOGU_RID: 99754622
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int mod=998244353;
const int N=2e5+5;
ll x[N], y[N];
void solve(){
cin>>x[0]>>y[0];
ll ax,ay,bx,by;
cin>>ax>>ay>>bx>>by;
int tot;
for(int i=1;;i++){
__int128_t xx=(__int128_t)ax*x[i-1]+bx;
__int128_t yy=(__int128_t)ay*y[i-1]+by;
if(xx<=1e18 && yy<=1e18) x[i]=xx, y[i]=yy;
else{
tot=i-1;
break;
}
}
ll xs,ys,t;
cin>>xs>>ys>>t;
int ans=0;
for(int i=0;i<=tot;i++){
for(int j=i;j<=tot;j++){
ll sum=abs(x[i]-xs)+abs(x[i]-x[j]);
sum+=abs(y[i]-ys)+abs(y[i]-y[j]);
if(sum<=t) ans=max(ans, j-i+1);
sum=abs(x[j]-xs)+abs(x[i]-x[j]);
sum+=abs(y[j]-ys)+abs(y[i]-y[j]);
if(sum<=t) ans=max(ans, j-i+1);
}
}
cout<<ans<<endl;
}
void init(){
}
signed main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
init();
solve();
return 0;
} | cpp |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | #include <bits/stdc++.h>
#define sys ios_base::sync_with_stdio(0);cin.tie(0);
#define mod 1000000007
using namespace std;
//#pragma comment(linker, "/STACK:268435456");
#define count_setbits(n) __builtin_popcount(n)
#define fixed cout<<fixed<<setprecision(16)
#define count_bits(n) ((ll)log2(n))+1
#define no_of_digits(n) ((ll)log10(n))+1
#define str string
#define c(itretor) cout<<itretor
#define cp(itretor) cout<<setprecision(itretor)
#define cys cout<<"YES"<<endl
#define cno cout<<"NO"<<endl
#define endl "\n"
#define imx INT_MAX
#define imn INT_MIN
#define lmx LLONG_MAX
#define lmn LLONG_MIN
#define ll long long
#define f(i,l,r) for(long long i=l;i<r;++i)
#define fr(i,r,l) for(long long i=r-1;i>=l;--i)
#define vi vector<int>
#define vs vector<string>
#define vll vector <long long>
#define mii map<int,int>
#define mll map<long long,long long>
#define pll pair<ll,ll>
#define tsolve long long t;cin>>t; while(t--) solve();
#define inp(x) for(auto &i:x) cin>>i;
#define all(x) x.begin(),x.end()
#define pb push_back
#define ff first
#define ss second
#define print(x) for(auto i:x) cout<<i<<" ";
#define pprint(x) for(auto [i,j]:x) cout<<i<<" "<<j
#define dbg1(x) cout << #x << "= " << x << endl;
#define dbg2(x,y) cout << #x << "= " << x << " " << #y << "= " << y <<endl;
#define dbg3(x,y,z) cout << #x << "= " << x << " " << #y << "= " << y << " " << #z << "= " << z << endl;
#define dbg4(x,y,z,w) cout << #x << "= " << x << " " << #y << "= " << y << " " << #z << "= " << z << " " << #w << "= " << w << endl;
//const ll N=2e5;
//vector<bool> isprime(N+1,1);
//inline void sieve(){ isprime[0]=isprime[1]=1; for(int i=2;i<=N;i++) if(isprime[i]) for(int j=i*i;j<=N;j+=i) isprime[j]=false;}
inline vector<ll> get_factors(ll n) { vector<ll> factors; if(n==0) return factors; for(ll i=1;i*i<=n;++i){ if(n%i==0){factors.push_back(i);
if(i!=n/i) factors.push_back(n/i);}} return factors;}
inline ll modpower(ll a, ll b, ll m = mod)
{ ll ans = 1; while (b) { if (b & 1) ans = (ans * a) % m; a = (a * a) % m; b >>= 1; } return ans; }
inline ll mod_inverse(ll x,ll y) { return modpower(x,y-2,y); }
inline ll max_ele(ll * arr ,ll n) { ll max=*max_element(arr,arr+n); return max;}
inline ll max_i(ll * arr,ll n){ return max_element(arr,arr+n)-arr+1; }
pll get_lowvalues(set<ll> s,ll value){
auto it=s.lower_bound(value);
pll a;--it;
a.ff=*it;--it;
a.ss=*it;
return a;
}
inline void solve()
{
ll n,ti; cin>>n>>ti;
bool c=0;
ll k=0,li=ti,ri=ti;
vector<vector<ll>> a(n,vector<ll> (3));
for(auto &i:a) for(auto &j:i) cin>>j;
sort(all(a));
f(i,0,n){
li=(li- (a[i][0] - k));ri=(ri + (a[i][0] - k));
if(li>a[i][2] or ri<a[i][1]) c=1;
if(li>ri) c=1;
li=max(li,a[i][1]);ri=min(ri,a[i][2]);k=a[i][0];
}
if(c) cno;
else cys;
}
int main()
{
sys;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
tsolve;
return 0;
} | 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;
typedef long long ll;
#define deb(...) logger(#__VA_ARGS__, __VA_ARGS__)
template<typename ...Args>
void logger(string vars, Args&&... values) {
cout << vars << " = ";
string delim = "";
(..., (cout << delim << values, delim = ", "));
cout << '\n';
}
const int N = 1000;
const int K = 100;
int dp[N][3];
int d[3];
int cyc = -1;
void pre() {
for (int i = 0; i < N; ++i) for (int j = 0; j < 3; ++j) dp[i][j] = 0;
for (int i = 1; i < N; ++i) {
for (int j = 0; j < 3; ++j) {
set<int> st;
for (int k = 0; k < 3; ++k) {
if (j == k && j != 0) continue;
int to = max(0, i - d[k]);
st.insert(dp[to][k]);
}
int mex = 0;
while (st.count(mex)) ++mex;
dp[i][j] = mex;
}
}
for (int len = 1; len * 2 < N; ++len) {
bool ok = true;
for (int i = K; ok && i + len < N; ++i) {
for (int j = 0; j < 3; ++j) {
if (dp[i][j] != dp[i + len][j]) ok = false;
}
}
if (ok) {
cyc = len;
break;
}
}
// cout << cyc << '\n';
// cout << '\n';
// for (int i = 1; i <= N; ++i) {
// for (int j = 0; j < 3; ++j) {
// cout << dp[i][j] << ' ';
// }
// cout << '\n';
// }
}
int grundy(ll n, int at) {
if (n < N) return dp[n][at];
int len = (n - K) % cyc;
// deb("Hi");
return dp[K + len][at];
}
void solve() {
int n;
cin >> n;
for (int j = 0; j < 3; ++j) cin >> d[j];
cyc = -1;
pre();
assert(cyc != -1);
int ans = 0;
vector<ll> a(n);
for (ll &x : a) {
cin >> x;
ans ^= grundy(x, 0);
}
int cnt = 0;
for (ll x : a) {
ans ^= grundy(x, 0);
for (int j = 0; j < 3; ++j) {
ll to = max(0ll, x - d[j]);
if ((ans ^ grundy(to, j)) == 0) ++cnt;
}
ans ^= grundy(x, 0);
}
cout << cnt << '\n';
}
int main() {
// freopen("out.txt", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
cin >> t;
while (t--) solve();
} | 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"
] | // LUOGU_RID: 98466313
#include <bits/stdc++.h>
#include <utility>
namespace atcoder {
namespace internal {
// @param m `1 <= m`
// @return x mod m
constexpr long long safe_mod(long long x, long long m) {
x %= m;
if (x < 0) x += m;
return x;
}
// Fast modular multiplication by barrett reduction
// Reference: https://en.wikipedia.org/wiki/Barrett_reduction
// NOTE: reconsider after Ice Lake
struct barrett {
unsigned int _m;
unsigned long long im;
// @param m `1 <= m < 2^31`
barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}
// @return m
unsigned int umod() const { return _m; }
// @param a `0 <= a < m`
// @param b `0 <= b < m`
// @return `a * b % m`
unsigned int mul(unsigned int a, unsigned int b) const {
// [1] m = 1
// a = b = im = 0, so okay
// [2] m >= 2
// im = ceil(2^64 / m)
// -> im * m = 2^64 + r (0 <= r < m)
// let z = a*b = c*m + d (0 <= c, d < m)
// a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im
// c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1) < 2^64 * 2
// ((ab * im) >> 64) == c or c + 1
unsigned long long z = a;
z *= b;
#ifdef _MSC_VER
unsigned long long x;
_umul128(z, im, &x);
#else
unsigned long long x =
(unsigned long long)(((unsigned __int128)(z)*im) >> 64);
#endif
unsigned int v = (unsigned int)(z - x * _m);
if (_m <= v) v += _m;
return v;
}
};
// @param n `0 <= n`
// @param m `1 <= m`
// @return `(x ** n) % m`
constexpr long long pow_mod_constexpr(long long x, long long n, int m) {
if (m == 1) return 0;
unsigned int _m = (unsigned int)(m);
unsigned long long r = 1;
unsigned long long y = safe_mod(x, m);
while (n) {
if (n & 1) r = (r * y) % _m;
y = (y * y) % _m;
n >>= 1;
}
return r;
}
// Reference:
// M. Forisek and J. Jancina,
// Fast Primality Testing for Integers That Fit into a Machine Word
// @param n `0 <= n`
constexpr bool is_prime_constexpr(int n) {
if (n <= 1) return false;
if (n == 2 || n == 7 || n == 61) return true;
if (n % 2 == 0) return false;
long long d = n - 1;
while (d % 2 == 0) d /= 2;
constexpr long long bases[3] = {2, 7, 61};
for (long long a : bases) {
long long t = d;
long long y = pow_mod_constexpr(a, t, n);
while (t != n - 1 && y != 1 && y != n - 1) {
y = y * y % n;
t <<= 1;
}
if (y != n - 1 && t % 2 == 0) {
return false;
}
}
return true;
}
template <int n> constexpr bool is_prime = is_prime_constexpr(n);
// @param b `1 <= b`
// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g
constexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {
a = safe_mod(a, b);
if (a == 0) return {b, 0};
// Contracts:
// [1] s - m0 * a = 0 (mod b)
// [2] t - m1 * a = 0 (mod b)
// [3] s * |m1| + t * |m0| <= b
long long s = b, t = a;
long long m0 = 0, m1 = 1;
while (t) {
long long u = s / t;
s -= t * u;
m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b
// [3]:
// (s - t * u) * |m1| + t * |m0 - m1 * u|
// <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)
// = s * |m1| + t * |m0| <= b
auto tmp = s;
s = t;
t = tmp;
tmp = m0;
m0 = m1;
m1 = tmp;
}
// by [3]: |m0| <= b/g
// by g != b: |m0| < b/g
if (m0 < 0) m0 += b / s;
return {s, m0};
}
// Compile time primitive root
// @param m must be prime
// @return primitive root (and minimum in now)
constexpr int primitive_root_constexpr(int m) {
if (m == 2) return 1;
if (m == 167772161) return 3;
if (m == 469762049) return 3;
if (m == 754974721) return 11;
if (m == 998244353) return 3;
int divs[20] = {};
divs[0] = 2;
int cnt = 1;
int x = (m - 1) / 2;
while (x % 2 == 0) x /= 2;
for (int i = 3; (long long)(i)*i <= x; i += 2) {
if (x % i == 0) {
divs[cnt++] = i;
while (x % i == 0) {
x /= i;
}
}
}
if (x > 1) {
divs[cnt++] = x;
}
for (int g = 2;; g++) {
bool ok = true;
for (int i = 0; i < cnt; i++) {
if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {
ok = false;
break;
}
}
if (ok) return g;
}
}
template <int m> constexpr int primitive_root = primitive_root_constexpr(m);
} // namespace internal
} // namespace atcoder
#include <cassert>
#include <numeric>
#include <type_traits>
namespace atcoder {
namespace internal {
#ifndef _MSC_VER
template <class T>
using is_signed_int128 =
typename std::conditional<std::is_same<T, __int128_t>::value ||
std::is_same<T, __int128>::value,
std::true_type,
std::false_type>::type;
template <class T>
using is_unsigned_int128 =
typename std::conditional<std::is_same<T, __uint128_t>::value ||
std::is_same<T, unsigned __int128>::value,
std::true_type,
std::false_type>::type;
template <class T>
using make_unsigned_int128 =
typename std::conditional<std::is_same<T, __int128_t>::value,
__uint128_t,
unsigned __int128>;
template <class T>
using is_integral = typename std::conditional<std::is_integral<T>::value ||
is_signed_int128<T>::value ||
is_unsigned_int128<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using is_signed_int = typename std::conditional<(is_integral<T>::value &&
std::is_signed<T>::value) ||
is_signed_int128<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using is_unsigned_int =
typename std::conditional<(is_integral<T>::value &&
std::is_unsigned<T>::value) ||
is_unsigned_int128<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using to_unsigned = typename std::conditional<
is_signed_int128<T>::value,
make_unsigned_int128<T>,
typename std::conditional<std::is_signed<T>::value,
std::make_unsigned<T>,
std::common_type<T>>::type>::type;
#else
template <class T> using is_integral = typename std::is_integral<T>;
template <class T>
using is_signed_int =
typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using is_unsigned_int =
typename std::conditional<is_integral<T>::value &&
std::is_unsigned<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using to_unsigned = typename std::conditional<is_signed_int<T>::value,
std::make_unsigned<T>,
std::common_type<T>>::type;
#endif
template <class T>
using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;
template <class T>
using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;
template <class T> using to_unsigned_t = typename to_unsigned<T>::type;
} // namespace internal
} // namespace atcoder
#include <cassert>
#include <numeric>
#include <type_traits>
#ifdef _MSC_VER
#include <intrin.h>
#endif
namespace atcoder {
namespace internal {
struct modint_base {};
struct static_modint_base : modint_base {};
template <class T> using is_modint = std::is_base_of<modint_base, T>;
template <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;
} // namespace internal
template <int m, std::enable_if_t<(1 <= m)>* = nullptr>
struct static_modint : internal::static_modint_base {
using mint = static_modint;
public:
static constexpr int mod() { return m; }
static mint raw(int v) {
mint x;
x._v = v;
return x;
}
static_modint() : _v(0) {}
template <class T, internal::is_signed_int_t<T>* = nullptr>
static_modint(T v) {
long long x = (long long)(v % (long long)(umod()));
if (x < 0) x += umod();
_v = (unsigned int)(x);
}
template <class T, internal::is_unsigned_int_t<T>* = nullptr>
static_modint(T v) {
_v = (unsigned int)(v % umod());
}
static_modint(bool v) { _v = ((unsigned int)(v) % umod()); }
unsigned int val() const { return _v; }
mint& operator++() {
_v++;
if (_v == umod()) _v = 0;
return *this;
}
mint& operator--() {
if (_v == 0) _v = umod();
_v--;
return *this;
}
mint operator++(int) {
mint result = *this;
++*this;
return result;
}
mint operator--(int) {
mint result = *this;
--*this;
return result;
}
mint& operator+=(const mint& rhs) {
_v += rhs._v;
if (_v >= umod()) _v -= umod();
return *this;
}
mint& operator-=(const mint& rhs) {
_v -= rhs._v;
if (_v >= umod()) _v += umod();
return *this;
}
mint& operator*=(const mint& rhs) {
unsigned long long z = _v;
z *= rhs._v;
_v = z % m;
return *this;
}
mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }
mint operator+() const { return *this; }
mint operator-() const { return mint() - *this; }
mint pow(long long n) const {
assert(0 <= n);
mint x = *this, r = 1;
while (n) {
if (n & 1) r *= x;
x *= x;
n >>= 1;
}
return r;
}
mint inv() const {
if (prime) {
assert(_v);
return pow(umod() - 2);
} else {
auto eg = internal::inv_gcd(_v, m);
assert(eg.first == 1);
return eg.second;
}
}
friend mint operator+(const mint& lhs, const mint& rhs) {
return mint(lhs) += rhs;
}
friend mint operator-(const mint& lhs, const mint& rhs) {
return mint(lhs) -= rhs;
}
friend mint operator*(const mint& lhs, const mint& rhs) {
return mint(lhs) *= rhs;
}
friend mint operator/(const mint& lhs, const mint& rhs) {
return mint(lhs) /= rhs;
}
friend bool operator==(const mint& lhs, const mint& rhs) {
return lhs._v == rhs._v;
}
friend bool operator!=(const mint& lhs, const mint& rhs) {
return lhs._v != rhs._v;
}
private:
unsigned int _v;
static constexpr unsigned int umod() { return m; }
static constexpr bool prime = internal::is_prime<m>;
};
template <int id> struct dynamic_modint : internal::modint_base {
using mint = dynamic_modint;
public:
static int mod() { return (int)(bt.umod()); }
static void set_mod(int m) {
assert(1 <= m);
bt = internal::barrett(m);
}
static mint raw(int v) {
mint x;
x._v = v;
return x;
}
dynamic_modint() : _v(0) {}
template <class T, internal::is_signed_int_t<T>* = nullptr>
dynamic_modint(T v) {
long long x = (long long)(v % (long long)(mod()));
if (x < 0) x += mod();
_v = (unsigned int)(x);
}
template <class T, internal::is_unsigned_int_t<T>* = nullptr>
dynamic_modint(T v) {
_v = (unsigned int)(v % mod());
}
dynamic_modint(bool v) { _v = ((unsigned int)(v) % mod()); }
unsigned int val() const { return _v; }
mint& operator++() {
_v++;
if (_v == umod()) _v = 0;
return *this;
}
mint& operator--() {
if (_v == 0) _v = umod();
_v--;
return *this;
}
mint operator++(int) {
mint result = *this;
++*this;
return result;
}
mint operator--(int) {
mint result = *this;
--*this;
return result;
}
mint& operator+=(const mint& rhs) {
_v += rhs._v;
if (_v >= umod()) _v -= umod();
return *this;
}
mint& operator-=(const mint& rhs) {
_v += mod() - rhs._v;
if (_v >= umod()) _v -= umod();
return *this;
}
mint& operator*=(const mint& rhs) {
_v = bt.mul(_v, rhs._v);
return *this;
}
mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }
mint operator+() const { return *this; }
mint operator-() const { return mint() - *this; }
mint pow(long long n) const {
assert(0 <= n);
mint x = *this, r = 1;
while (n) {
if (n & 1) r *= x;
x *= x;
n >>= 1;
}
return r;
}
mint inv() const {
auto eg = internal::inv_gcd(_v, mod());
assert(eg.first == 1);
return eg.second;
}
friend mint operator+(const mint& lhs, const mint& rhs) {
return mint(lhs) += rhs;
}
friend mint operator-(const mint& lhs, const mint& rhs) {
return mint(lhs) -= rhs;
}
friend mint operator*(const mint& lhs, const mint& rhs) {
return mint(lhs) *= rhs;
}
friend mint operator/(const mint& lhs, const mint& rhs) {
return mint(lhs) /= rhs;
}
friend bool operator==(const mint& lhs, const mint& rhs) {
return lhs._v == rhs._v;
}
friend bool operator!=(const mint& lhs, const mint& rhs) {
return lhs._v != rhs._v;
}
private:
unsigned int _v;
static internal::barrett bt;
static unsigned int umod() { return bt.umod(); }
};
template <int id> internal::barrett dynamic_modint<id>::bt = 998244353;
using modint998244353 = static_modint<998244353>;
using modint1000000007 = static_modint<1000000007>;
using modint = dynamic_modint<-1>;
namespace internal {
template <class T>
using is_static_modint = std::is_base_of<internal::static_modint_base, T>;
template <class T>
using is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;
template <class> struct is_dynamic_modint : public std::false_type {};
template <int id>
struct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};
template <class T>
using is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;
} // namespace internal
} // namespace atcoder
using namespace std;
typedef atcoder::static_modint<754974721> mint;
constexpr int N = 2e5 + 9, p = 469762049;
string s;
int n, m, cnt[N];
mint pw[N], hsh[2][N];
mint ghsh(int l, int len) {
return hsh[~l & 1][l + len] - hsh[~l & 1][l] * pw[cnt[l + len] - cnt[l]];
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> s, pw[0] = 1;
for (int i = 1; i <= n; ++i) {
cnt[i] = cnt[i - 1], pw[i] = pw[i - 1] * p;
hsh[0][i] = hsh[0][i - 1], hsh[1][i] = hsh[1][i - 1];
if (~s[i - 1] & 1) {
++cnt[i];
(hsh[0][i] *= p) += (i & 1) + 1;
(hsh[1][i] *= p) += (~i & 1) + 1;
}
}
cin >> m;
for (int l1, l2, len; m; --m) {
cin >> l1 >> l2 >> len, --l1, --l2;
cout << (ghsh(l1, len) == ghsh(l2, len) ? "Yes" : "No") << '\n';
}
return cout << flush, 0;
}
| cpp |
1290 | D | D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 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 3n22k3n22k 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 3n22k≤15 0003n22k≤15 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 3n22k3n22k 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 3n22k≤15 0003n22k≤15 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. | [
"constructive algorithms",
"graphs",
"interactive"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e3 + 42, INF = 1e18 + 42;
bool eq[N];
int n, k, nb = 0;
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
if(k == 1)
k = 2;
for(int i = 1; i < 2*n/k; i++) {
for(int r = 0; r < i && r + i < 2*n/k; r++) {
for(int j = r; j < 2*n/k; j += i) {
int deb = j*(k/2);
for(int id = 0; id < k/2; id++) {
cout << "? " << deb + id + 1 << '\n';
cout.flush();
char ans; cin >> ans;
if(ans == 'Y')
eq[deb + id] = true;
}
}
cout << "R\n";
cout.flush();
}
}
int ans = 0;
for(int i = 0; i < n; i++)
if(!eq[i])
ans++;
cout << "! " << ans;
} | 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 <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main()
{
int n;
cin >> n;
vector<int>a(n);
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
//pick max
vector<int> c(n);
int ans = 0;
for (int i = 0; i < n; i++)
{
//max is i
int sm = a[i];
int mn = a[i];
vector<int> b(n);
b[i] = a[i];
for (int j = i-1; j >= 0; j--)
{
mn = min(mn, a[j]);
b[j] = mn;
sm += mn;
}
mn = a[i];
for (int j = i + 1; j < n; j++)
{
mn = min(mn, a[j]);
b[j] = mn;
sm += mn;
}
if (sm > ans)
{
ans = sm;
c = b;
}
}
for (int i = 0; i < n; i++)
{
cout << c[i] << " ";
}
cout << "\n";
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"
] | #include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;
const int _=100,inf=1e9;
int S,T,n,m,Q,head[_],ne[_*_],to[_*_],w[_*_],c[_*_],tot=1,x;
int dis[_],vis[_],p[_];
vector<pair<int,int>>ans;
void add(int x,int y,int z,int a){
ne[++tot]=head[x],head[x]=tot,to[tot]=y,w[tot]=z,c[tot]=a;
}
void ad(int x,int y,int z){
add(x,y,1,z),add(y,x,0,-z);
}
bool bfs(){
for(int i=1;i<=n;i++)dis[i]=inf,vis[i]=0;
queue<int>q;q.push(S),vis[S]=1,dis[S]=0;
while(q.size()){
int u=q.front();q.pop(),vis[u]=0;
for(int i=head[u];i;i=ne[i])
if(w[i]&&dis[to[i]]>dis[u]+c[i]){
dis[to[i]]=dis[u]+c[i],p[to[i]]=i;
if(!vis[to[i]])vis[to[i]]=1,q.push(to[i]);
}
}
return dis[T]!=inf;
}
void EK(){
int flow=0,cost=0;
while(bfs()){
int f=inf;
for(int i=T;i!=S;i=to[p[i]^1])f=min(f,w[p[i]]);
flow+=f,cost+=dis[T]*f;
for(int i=T;i!=S;i=to[p[i]^1])w[p[i]]-=f,w[p[i]^1]+=f;
ans.push_back({flow,cost});
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1,y,z;i<=m;i++)
scanf("%d%d%d",&x,&y,&z),ad(x,y,z);
S=1,T=n;EK();
scanf("%d",&Q);
while(Q--){
scanf("%d",&x);
long double Min=inf;
for(auto v:ans)Min=min(Min,(long double)(v.se+x)/v.fi);
printf("%.10Lf\n",Min);
}
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"
] | #pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#ifndef ATCODER_INTERNAL_BITOP_HPP
#define ATCODER_INTERNAL_BITOP_HPP 1
#ifdef _MSC_VER
#include <intrin.h>
#include<cassert>
#endif
namespace atcoder {
namespace internal {
int ceil_pow2(int n) {
int x = 0;
while ((1U << x) < (unsigned int)(n)) x++;
return x;
}
int bsf(unsigned int n) {
#ifdef _MSC_VER
unsigned long index;
_BitScanForward(&index, n);
return index;
#else
return __builtin_ctz(n);
#endif
}
}
}
#endif
#ifndef ATCODER_INTERNAL_MATH_HPP
#define ATCODER_INTERNAL_MATH_HPP 1
#include <utility>
namespace atcoder {
namespace internal {
constexpr long long safe_mod(long long x, long long m) {
x %= m;
if (x < 0) x += m;
return x;
}
struct barrett {
unsigned int _m;
unsigned long long im;
barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}
unsigned int umod() const { return _m; }
unsigned int mul(unsigned int a, unsigned int b) const {
unsigned long long z = a;
z *= b;
#ifdef _MSC_VER
unsigned long long x;
_umul128(z, im, &x);
#else
unsigned long long x =
(unsigned long long)(((unsigned __int128)(z)*im) >> 64);
#endif
unsigned int v = (unsigned int)(z - x * _m);
if (_m <= v) v += _m;
return v;
}
};
constexpr long long pow_mod_constexpr(long long x, long long n, int m) {
if (m == 1) return 0;
unsigned int _m = (unsigned int)(m);
unsigned long long r = 1;
unsigned long long y = safe_mod(x, m);
while (n) {
if (n & 1) r = (r * y) % _m;
y = (y * y) % _m;
n >>= 1;
}
return r;
}
constexpr bool is_prime_constexpr(int n) {
if (n <= 1) return false;
if (n == 2 || n == 7 || n == 61) return true;
if (n % 2 == 0) return false;
long long d = n - 1;
while (d % 2 == 0) d /= 2;
int v[] = { 2,7,61 };
for (long long a : v) {
long long t = d;
long long y = pow_mod_constexpr(a, t, n);
while (t != n - 1 && y != 1 && y != n - 1) {
y = y * y % n;
t <<= 1;
}
if (y != n - 1 && t % 2 == 0) {
return false;
}
}
return true;
}
template <int n> constexpr bool is_prime = is_prime_constexpr(n);
constexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {
a = safe_mod(a, b);
if (a == 0) return { b, 0 };
long long s = b, t = a;
long long m0 = 0, m1 = 1;
while (t) {
long long u = s / t;
s -= t * u;
m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b
auto tmp = s;
s = t;
t = tmp;
tmp = m0;
m0 = m1;
m1 = tmp;
}
if (m0 < 0) m0 += b / s;
return { s, m0 };
}
constexpr int primitive_root_constexpr(int m) {
if (m == 2) return 1;
if (m == 167772161) return 3;
if (m == 469762049) return 3;
if (m == 754974721) return 11;
if (m == 998244353) return 3;
int divs[20] = {};
divs[0] = 2;
int cnt = 1;
int x = (m - 1) / 2;
while (x % 2 == 0) x /= 2;
for (int i = 3; (long long)(i)*i <= x; i += 2) {
if (x % i == 0) {
divs[cnt++] = i;
while (x % i == 0) {
x /= i;
}
}
}
if (x > 1) {
divs[cnt++] = x;
}
for (int g = 2;; g++) {
bool ok = true;
for (int i = 0; i < cnt; i++) {
if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {
ok = false;
break;
}
}
if (ok) return g;
}
}
template <int m> constexpr int primitive_root = primitive_root_constexpr(m);
}
}
#endif
#ifndef ATCODER_INTERNAL_QUEUE_HPP
#define ATCODER_INTERNAL_QUEUE_HPP 1
#include <vector>
namespace atcoder {
namespace internal {
template <class T> struct simple_queue {
std::vector<T> payload;
int pos = 0;
void reserve(int n) { payload.reserve(n); }
int size() const { return int(payload.size()) - pos; }
bool empty() const { return pos == int(payload.size()); }
void push(const T& t) { payload.push_back(t); }
T& front() { return payload[pos]; }
void clear() {
payload.clear();
pos = 0;
}
void pop() { pos++; }
};
}
}
#endif
#ifndef ATCODER_INTERNAL_SCC_HPP
#define ATCODER_INTERNAL_SCC_HPP 1
#include <algorithm>
#include <utility>
#include <vector>
namespace atcoder {
namespace internal {
template <class E> struct csr {
std::vector<int> start;
std::vector<E> elist;
csr(int n, const std::vector<std::pair<int, E>>& edges)
: start(n + 1), elist(edges.size()) {
for (auto e : edges) {
start[e.first + 1]++;
}
for (int i = 1; i <= n; i++) {
start[i] += start[i - 1];
}
auto counter = start;
for (auto e : edges) {
elist[counter[e.first]++] = e.second;
}
}
};
struct scc_graph {
public:
scc_graph(int n) : _n(n) {}
int num_vertices() { return _n; }
void add_edge(int from, int to) { edges.push_back({ from, {to} }); }
std::pair<int, std::vector<int>> scc_ids() {
auto g = csr<edge>(_n, edges);
int now_ord = 0, group_num = 0;
std::vector<int> visited, low(_n), ord(_n, -1), ids(_n);
visited.reserve(_n);
auto dfs = [&](auto self, int v) -> void {
low[v] = ord[v] = now_ord++;
visited.push_back(v);
for (int i = g.start[v]; i < g.start[v + 1]; i++) {
auto to = g.elist[i].to;
if (ord[to] == -1) {
self(self, to);
low[v] = std::min(low[v], low[to]);
}
else {
low[v] = std::min(low[v], ord[to]);
}
}
if (low[v] == ord[v]) {
while (true) {
int u = visited.back();
visited.pop_back();
ord[u] = _n;
ids[u] = group_num;
if (u == v) break;
}
group_num++;
}
};
for (int i = 0; i < _n; i++) {
if (ord[i] == -1) dfs(dfs, i);
}
for (auto& x : ids) {
x = group_num - 1 - x;
}
return { group_num, ids };
}
std::vector<std::vector<int>> scc() {
auto ids = scc_ids();
int group_num = ids.first;
std::vector<int> counts(group_num);
for (auto x : ids.second) counts[x]++;
std::vector<std::vector<int>> groups(ids.first);
for (int i = 0; i < group_num; i++) {
groups[i].reserve(counts[i]);
}
for (int i = 0; i < _n; i++) {
groups[ids.second[i]].push_back(i);
}
return groups;
}
private:
int _n;
struct edge {
int to;
};
std::vector<std::pair<int, edge>> edges;
};
}
}
#endif
#ifndef ATCODER_INTERNAL_TYPE_TRAITS_HPP
#define ATCODER_INTERNAL_TYPE_TRAITS_HPP 1
#include <cassert>
#include <numeric>
#include <type_traits>
namespace atcoder {
namespace internal {
#ifndef _MSC_VER
template <class T>
using is_signed_int128 =
typename std::conditional<std::is_same<T, __int128_t>::value ||
std::is_same<T, __int128>::value,
std::true_type,
std::false_type>::type;
template <class T>
using is_unsigned_int128 =
typename std::conditional<std::is_same<T, __uint128_t>::value ||
std::is_same<T, unsigned __int128>::value,
std::true_type,
std::false_type>::type;
template <class T>
using make_unsigned_int128 =
typename std::conditional<std::is_same<T, __int128_t>::value,
__uint128_t,
unsigned __int128>;
template <class T>
using is_integral = typename std::conditional<std::is_integral<T>::value ||
is_signed_int128<T>::value ||
is_unsigned_int128<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using is_signed_int = typename std::conditional<(is_integral<T>::value&&
std::is_signed<T>::value) ||
is_signed_int128<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using is_unsigned_int =
typename std::conditional<(is_integral<T>::value&&
std::is_unsigned<T>::value) ||
is_unsigned_int128<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using to_unsigned = typename std::conditional<
is_signed_int128<T>::value,
make_unsigned_int128<T>,
typename std::conditional<std::is_signed<T>::value,
std::make_unsigned<T>,
std::common_type<T>>::type>::type;
#else
template <class T> using is_integral = typename std::is_integral<T>;
template <class T>
using is_signed_int =
typename std::conditional<is_integral<T>::value&& std::is_signed<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using is_unsigned_int =
typename std::conditional<is_integral<T>::value&&
std::is_unsigned<T>::value,
std::true_type,
std::false_type>::type;
template <class T>
using to_unsigned = typename std::conditional<is_signed_int<T>::value,
std::make_unsigned<T>,
std::common_type<T>>::type;
#endif
template <class T>
using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;
template <class T>
using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;
template <class T> using to_unsigned_t = typename to_unsigned<T>::type;
}
}
#endif
#ifndef ATCODER_MODINT_HPP
#define ATCODER_MODINT_HPP 1
#include <cassert>
#include <numeric>
#include <type_traits>
#ifdef _MSC_VER
#include <intrin.h>
#endif
namespace atcoder {
namespace internal {
struct modint_base {};
struct static_modint_base : modint_base {};
template <class T> using is_modint = std::is_base_of<modint_base, T>;
template <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;
}
template <int m, std::enable_if_t<(1 <= m)>* = nullptr>
struct static_modint : internal::static_modint_base {
using mint = static_modint;
public:
static constexpr int mod() { return m; }
static mint raw(int v) {
mint x;
x._v = v;
return x;
}
static_modint() : _v(0) {}
template <class T, internal::is_signed_int_t<T>* = nullptr>
static_modint(T v) {
long long x = (long long)(v % (long long)(umod()));
if (x < 0) x += umod();
_v = (unsigned int)(x);
}
template <class T, internal::is_unsigned_int_t<T>* = nullptr>
static_modint(T v) {
_v = (unsigned int)(v % umod());
}
static_modint(bool v) { _v = ((unsigned int)(v) % umod()); }
unsigned int val() const { return _v; }
mint& operator++() {
_v++;
if (_v == umod()) _v = 0;
return *this;
}
mint& operator--() {
if (_v == 0) _v = umod();
_v--;
return *this;
}
mint operator++(int) {
mint result = *this;
++* this;
return result;
}
mint operator--(int) {
mint result = *this;
--* this;
return result;
}
mint& operator+=(const mint& rhs) {
_v += rhs._v;
if (_v >= umod()) _v -= umod();
return *this;
}
mint& operator-=(const mint& rhs) {
_v -= rhs._v;
if (_v >= umod()) _v += umod();
return *this;
}
mint& operator*=(const mint& rhs) {
unsigned long long z = _v;
z *= rhs._v;
_v = (unsigned int)(z % umod());
return *this;
}
mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }
mint operator+() const { return *this; }
mint operator-() const { return mint() - *this; }
mint pow(long long n) const {
assert(0 <= n);
mint x = *this, r = 1;
while (n) {
if (n & 1) r *= x;
x *= x;
n >>= 1;
}
return r;
}
mint inv() const {
if (prime) {
assert(_v);
return pow(umod() - 2);
}
else {
auto eg = internal::inv_gcd(_v, m);
assert(eg.first == 1);
return eg.second;
}
}
friend mint operator+(const mint& lhs, const mint& rhs) {
return mint(lhs) += rhs;
}
friend mint operator-(const mint& lhs, const mint& rhs) {
return mint(lhs) -= rhs;
}
friend mint operator*(const mint& lhs, const mint& rhs) {
return mint(lhs) *= rhs;
}
friend mint operator/(const mint& lhs, const mint& rhs) {
return mint(lhs) /= rhs;
}
friend bool operator==(const mint& lhs, const mint& rhs) {
return lhs._v == rhs._v;
}
friend bool operator!=(const mint& lhs, const mint& rhs) {
return lhs._v != rhs._v;
}
private:
unsigned int _v;
static constexpr unsigned int umod() { return m; }
static constexpr bool prime = internal::is_prime<m>;
};
template <int id> struct dynamic_modint : internal::modint_base {
using mint = dynamic_modint;
public:
static int mod() { return (int)(bt.umod()); }
static void set_mod(int m) {
assert(1 <= m);
bt = internal::barrett(m);
}
static mint raw(int v) {
mint x;
x._v = v;
return x;
}
dynamic_modint() : _v(0) {}
template <class T, internal::is_signed_int_t<T>* = nullptr>
dynamic_modint(T v) {
long long x = (long long)(v % (long long)(mod()));
if (x < 0) x += mod();
_v = (unsigned int)(x);
}
template <class T, internal::is_unsigned_int_t<T>* = nullptr>
dynamic_modint(T v) {
_v = (unsigned int)(v % mod());
}
dynamic_modint(bool v) { _v = ((unsigned int)(v) % mod()); }
unsigned int val() const { return _v; }
mint& operator++() {
_v++;
if (_v == umod()) _v = 0;
return *this;
}
mint& operator--() {
if (_v == 0) _v = umod();
_v--;
return *this;
}
mint operator++(int) {
mint result = *this;
++* this;
return result;
}
mint operator--(int) {
mint result = *this;
--* this;
return result;
}
mint& operator+=(const mint& rhs) {
_v += rhs._v;
if (_v >= umod()) _v -= umod();
return *this;
}
mint& operator-=(const mint& rhs) {
_v += mod() - rhs._v;
if (_v >= umod()) _v -= umod();
return *this;
}
mint& operator*=(const mint& rhs) {
_v = bt.mul(_v, rhs._v);
return *this;
}
mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }
mint operator+() const { return *this; }
mint operator-() const { return mint() - *this; }
mint pow(long long n) const {
assert(0 <= n);
mint x = *this, r = 1;
while (n) {
if (n & 1) r *= x;
x *= x;
n >>= 1;
}
return r;
}
mint inv() const {
auto eg = internal::inv_gcd(_v, mod());
assert(eg.first == 1);
return eg.second;
}
friend mint operator+(const mint& lhs, const mint& rhs) {
return mint(lhs) += rhs;
}
friend mint operator-(const mint& lhs, const mint& rhs) {
return mint(lhs) -= rhs;
}
friend mint operator*(const mint& lhs, const mint& rhs) {
return mint(lhs) *= rhs;
}
friend mint operator/(const mint& lhs, const mint& rhs) {
return mint(lhs) /= rhs;
}
friend bool operator==(const mint& lhs, const mint& rhs) {
return lhs._v == rhs._v;
}
friend bool operator!=(const mint& lhs, const mint& rhs) {
return lhs._v != rhs._v;
}
private:
unsigned int _v;
static internal::barrett bt;
static unsigned int umod() { return bt.umod(); }
};
template <int id> internal::barrett dynamic_modint<id>::bt = 998244353;
using modint998244353 = static_modint<998244353>;
using modint1000000007 = static_modint<1000000007>;
using modint = dynamic_modint<-1>;
namespace internal {
template <class T>
using is_static_modint = std::is_base_of<internal::static_modint_base, T>;
template <class T>
using is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;
template <class> struct is_dynamic_modint : public std::false_type {};
template <int id>
struct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};
template <class T>
using is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;
}
}
#endif
#ifndef ATCODER_CONVOLUTION_HPP
#define ATCODER_CONVOLUTION_HPP 1
#include <algorithm>
#include <array>
#include <cassert>
#include <type_traits>
#include <vector>
namespace atcoder {
namespace internal {
template <class mint, internal::is_static_modint_t<mint>* = nullptr>
void butterfly(std::vector<mint>& a) {
static constexpr int g = internal::primitive_root<mint::mod()>;
int n = int(a.size());
int h = internal::ceil_pow2(n);
static bool first = true;
static mint sum_e[30];
if (first) {
first = false;
mint es[30], ies[30];
int cnt2 = bsf(mint::mod() - 1);
mint e = mint(g).pow((mint::mod() - 1) >> cnt2), ie = e.inv();
for (int i = cnt2; i >= 2; i--) {
// e^(2^i) == 1
es[i - 2] = e;
ies[i - 2] = ie;
e *= e;
ie *= ie;
}
mint now = 1;
for (int i = 0; i < cnt2 - 2; i++) {
sum_e[i] = es[i] * now;
now *= ies[i];
}
}
for (int ph = 1; ph <= h; ph++) {
int w = 1 << (ph - 1), p = 1 << (h - ph);
mint now = 1;
for (int s = 0; s < w; s++) {
int offset = s << (h - ph + 1);
for (int i = 0; i < p; i++) {
auto l = a[i + offset];
auto r = a[i + offset + p] * now;
a[i + offset] = l + r;
a[i + offset + p] = l - r;
}
now *= sum_e[bsf(~(unsigned int)(s))];
}
}
}
template <class mint, internal::is_static_modint_t<mint>* = nullptr>
void butterfly_inv(std::vector<mint>& a) {
static constexpr int g = internal::primitive_root<mint::mod()>;
int n = int(a.size());
int h = internal::ceil_pow2(n);
static bool first = true;
static mint sum_ie[30];
if (first) {
first = false;
mint es[30], ies[30];
int cnt2 = bsf(mint::mod() - 1);
mint e = mint(g).pow((mint::mod() - 1) >> cnt2), ie = e.inv();
for (int i = cnt2; i >= 2; i--) {
// e^(2^i) == 1
es[i - 2] = e;
ies[i - 2] = ie;
e *= e;
ie *= ie;
}
mint now = 1;
for (int i = 0; i < cnt2 - 2; i++) {
sum_ie[i] = ies[i] * now;
now *= es[i];
}
}
for (int ph = h; ph >= 1; ph--) {
int w = 1 << (ph - 1), p = 1 << (h - ph);
mint inow = 1;
for (int s = 0; s < w; s++) {
int offset = s << (h - ph + 1);
for (int i = 0; i < p; i++) {
auto l = a[i + offset];
auto r = a[i + offset + p];
a[i + offset] = l + r;
a[i + offset + p] =
(unsigned long long)(mint::mod() + l.val() - r.val()) *
inow.val();
}
inow *= sum_ie[bsf(~(unsigned int)(s))];
}
}
}
}
template <class mint, internal::is_static_modint_t<mint>* = nullptr>
std::vector<mint> convolution(std::vector<mint> a, std::vector<mint> b) {
int n = int(a.size()), m = int(b.size());
if (!n || !m) return {};
if (std::min(n, m) <= 60) {
if (n < m) {
std::swap(n, m);
std::swap(a, b);
}
std::vector<mint> ans(n + m - 1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ans[i + j] += a[i] * b[j];
}
}
return ans;
}
int z = 1 << internal::ceil_pow2(n + m - 1);
a.resize(z);
internal::butterfly(a);
b.resize(z);
internal::butterfly(b);
for (int i = 0; i < z; i++) {
a[i] *= b[i];
}
internal::butterfly_inv(a);
a.resize(n + m - 1);
mint iz = mint(z).inv();
for (int i = 0; i < n + m - 1; i++) a[i] *= iz;
return a;
}
template <unsigned int mod = 998244353,
class T,
std::enable_if_t<internal::is_integral<T>::value>* = nullptr>
std::vector<T> convolution(const std::vector<T>& a, const std::vector<T>& b) {
int n = int(a.size()), m = int(b.size());
if (!n || !m) return {};
using mint = static_modint<mod>;
std::vector<mint> a2(n), b2(m);
for (int i = 0; i < n; i++) {
a2[i] = mint(a[i]);
}
for (int i = 0; i < m; i++) {
b2[i] = mint(b[i]);
}
auto c2 = convolution(move(a2), move(b2));
std::vector<T> c(n + m - 1);
for (int i = 0; i < n + m - 1; i++) {
c[i] = c2[i].val();
}
return c;
}
std::vector<long long> convolution_ll(const std::vector<long long>& a,
const std::vector<long long>& b) {
int n = int(a.size()), m = int(b.size());
if (!n || !m) return {};
static constexpr unsigned long long MOD1 = 754974721;
static constexpr unsigned long long MOD2 = 167772161;
static constexpr unsigned long long MOD3 = 469762049;
static constexpr unsigned long long M2M3 = MOD2 * MOD3;
static constexpr unsigned long long M1M3 = MOD1 * MOD3;
static constexpr unsigned long long M1M2 = MOD1 * MOD2;
static constexpr unsigned long long M1M2M3 = MOD1 * MOD2 * MOD3;
static constexpr unsigned long long i1 =
internal::inv_gcd(MOD2 * MOD3, MOD1).second;
static constexpr unsigned long long i2 =
internal::inv_gcd(MOD1 * MOD3, MOD2).second;
static constexpr unsigned long long i3 =
internal::inv_gcd(MOD1 * MOD2, MOD3).second;
auto c1 = convolution<MOD1>(a, b);
auto c2 = convolution<MOD2>(a, b);
auto c3 = convolution<MOD3>(a, b);
std::vector<long long> c(n + m - 1);
for (int i = 0; i < n + m - 1; i++) {
unsigned long long x = 0;
x += (c1[i] * i1) % MOD1 * M2M3;
x += (c2[i] * i2) % MOD2 * M1M3;
x += (c3[i] * i3) % MOD3 * M1M2;
long long diff =
c1[i] - internal::safe_mod((long long)(x), (long long)(MOD1));
if (diff < 0) diff += MOD1;
static constexpr unsigned long long offset[5] = {
0, 0, M1M2M3, 2 * M1M2M3, 3 * M1M2M3 };
x -= offset[diff % 5];
c[i] = x;
}
return c;
}
}
#endif
#ifndef ATCODER_DSU_HPP
#define ATCODER_DSU_HPP 1
#include <algorithm>
#include <cassert>
#include <vector>
namespace atcoder {
struct dsu {
public:
dsu() : _n(0) {}
dsu(int n) : _n(n), parent_or_size(n, -1) {}
int merge(int a, int b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
int x = leader(a), y = leader(b);
if (x == y) return x;
if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y);
parent_or_size[x] += parent_or_size[y];
parent_or_size[y] = x;
return x;
}
bool same(int a, int b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
return leader(a) == leader(b);
}
int leader(int a) {
assert(0 <= a && a < _n);
if (parent_or_size[a] < 0) return a;
return parent_or_size[a] = leader(parent_or_size[a]);
}
int size(int a) {
assert(0 <= a && a < _n);
return -parent_or_size[leader(a)];
}
std::vector<std::vector<int>> groups() {
std::vector<int> leader_buf(_n), group_size(_n);
for (int i = 0; i < _n; i++) {
leader_buf[i] = leader(i);
group_size[leader_buf[i]]++;
}
std::vector<std::vector<int>> result(_n);
for (int i = 0; i < _n; i++) {
result[i].reserve(group_size[i]);
}
for (int i = 0; i < _n; i++) {
result[leader_buf[i]].push_back(i);
}
result.erase(
std::remove_if(result.begin(), result.end(),
[&](const std::vector<int>& v) { return v.empty(); }),
result.end());
return result;
}
private:
int _n;
std::vector<int> parent_or_size;
};
}
#endif
#ifndef ATCODER_FENWICKTREE_HPP
#define ATCODER_FENWICKTREE_HPP 1
#include <cassert>
#include <vector>
namespace atcoder {
template <class T> struct fenwick_tree {
using U = internal::to_unsigned_t<T>;
public:
fenwick_tree() : _n(0) {}
fenwick_tree(int n) : _n(n), data(n) {}
void add(int p, T x) {
assert(0 <= p && p < _n);
p++;
while (p <= _n) {
data[p - 1] += U(x);
p += p & -p;
}
}
T sum(int l, int r) {
assert(0 <= l && l <= r && r <= _n);
return sum(r) - sum(l);
}
private:
int _n;
std::vector<U> data;
U sum(int r) {
U s = 0;
while (r > 0) {
s += data[r - 1];
r -= r & -r;
}
return s;
}
};
}
#endif
#ifndef ATCODER_LAZYSEGTREE_HPP
#define ATCODER_LAZYSEGTREE_HPP 1
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
namespace atcoder {
template <class S,
S(*op)(S, S),
S(*e)(),
class F,
S(*mapping)(F, S),
F(*composition)(F, F),
F(*id)()>
struct lazy_segtree {
public:
lazy_segtree() : lazy_segtree(0) {}
lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) {
log = internal::ceil_pow2(_n);
size = 1 << log;
d = std::vector<S>(2 * size, e());
lz = std::vector<F>(size, id());
for (int i = 0; i < _n; i++) d[size + i] = v[i];
for (int i = size - 1; i >= 1; i--) {
update(i);
}
}
void set(int p, S x) {
assert(0 <= p && p < _n);
p += size;
for (int i = log; i >= 1; i--) push(p >> i);
d[p] = x;
for (int i = 1; i <= log; i++) update(p >> i);
}
S get(int p) {
assert(0 <= p && p < _n);
p += size;
for (int i = log; i >= 1; i--) push(p >> i);
return d[p];
}
S prod(int l, int r) {
assert(0 <= l && l <= r && r <= _n);
if (l == r) return e();
l += size;
r += size;
for (int i = log; i >= 1; i--) {
if (((l >> i) << i) != l) push(l >> i);
if (((r >> i) << i) != r) push(r >> i);
}
S sml = e(), smr = e();
while (l < r) {
if (l & 1) sml = op(sml, d[l++]);
if (r & 1) smr = op(d[--r], smr);
l >>= 1;
r >>= 1;
}
return op(sml, smr);
}
S all_prod() { return d[1]; }
void apply(int p, F f) {
assert(0 <= p && p < _n);
p += size;
for (int i = log; i >= 1; i--) push(p >> i);
d[p] = mapping(f, d[p]);
for (int i = 1; i <= log; i++) update(p >> i);
}
void apply(int l, int r, F f) {
assert(0 <= l && l <= r && r <= _n);
if (l == r) return;
l += size;
r += size;
for (int i = log; i >= 1; i--) {
if (((l >> i) << i) != l) push(l >> i);
if (((r >> i) << i) != r) push((r - 1) >> i);
}
{
int l2 = l, r2 = r;
while (l < r) {
if (l & 1) all_apply(l++, f);
if (r & 1) all_apply(--r, f);
l >>= 1;
r >>= 1;
}
l = l2;
r = r2;
}
for (int i = 1; i <= log; i++) {
if (((l >> i) << i) != l) update(l >> i);
if (((r >> i) << i) != r) update((r - 1) >> i);
}
}
template <bool (*g)(S)> int max_right(int l) {
return max_right(l, [](S x) { return g(x); });
}
template <class G> int max_right(int l, G g) {
assert(0 <= l && l <= _n);
assert(g(e()));
if (l == _n) return _n;
l += size;
for (int i = log; i >= 1; i--) push(l >> i);
S sm = e();
do {
while (l % 2 == 0) l >>= 1;
if (!g(op(sm, d[l]))) {
while (l < size) {
push(l);
l = (2 * l);
if (g(op(sm, d[l]))) {
sm = op(sm, d[l]);
l++;
}
}
return l - size;
}
sm = op(sm, d[l]);
l++;
} while ((l & -l) != l);
return _n;
}
template <bool (*g)(S)> int min_left(int r) {
return min_left(r, [](S x) { return g(x); });
}
template <class G> int min_left(int r, G g) {
assert(0 <= r && r <= _n);
assert(g(e()));
if (r == 0) return 0;
r += size;
for (int i = log; i >= 1; i--) push((r - 1) >> i);
S sm = e();
do {
r--;
while (r > 1 && (r % 2)) r >>= 1;
if (!g(op(d[r], sm))) {
while (r < size) {
push(r);
r = (2 * r + 1);
if (g(op(d[r], sm))) {
sm = op(d[r], sm);
r--;
}
}
return r + 1 - size;
}
sm = op(d[r], sm);
} while ((r & -r) != r);
return 0;
}
private:
int _n, size, log;
std::vector<S> d;
std::vector<F> lz;
void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
void all_apply(int k, F f) {
d[k] = mapping(f, d[k]);
if (k < size) lz[k] = composition(f, lz[k]);
}
void push(int k) {
all_apply(2 * k, lz[k]);
all_apply(2 * k + 1, lz[k]);
lz[k] = id();
}
};
}
#endif
#ifndef ATCODER_MATH_HPP
#define ATCODER_MATH_HPP 1
#include <algorithm>
#include <cassert>
#include <tuple>
#include <vector>
namespace atcoder {
long long pow_mod(long long x, long long n, int m) {
assert(0 <= n && 1 <= m);
if (m == 1) return 0;
internal::barrett bt((unsigned int)(m));
unsigned int r = 1, y = (unsigned int)(internal::safe_mod(x, m));
while (n) {
if (n & 1) r = bt.mul(r, y);
y = bt.mul(y, y);
n >>= 1;
}
return r;
}
long long inv_mod(long long x, long long m) {
assert(1 <= m);
auto z = internal::inv_gcd(x, m);
assert(z.first == 1);
return z.second;
}
std::pair<long long, long long> crt(const std::vector<long long>& r,
const std::vector<long long>& m) {
assert(r.size() == m.size());
int n = int(r.size());
long long r0 = 0, m0 = 1;
for (int i = 0; i < n; i++) {
assert(1 <= m[i]);
long long r1 = internal::safe_mod(r[i], m[i]), m1 = m[i];
if (m0 < m1) {
std::swap(r0, r1);
std::swap(m0, m1);
}
if (m0 % m1 == 0) {
if (r0 % m1 != r1) return { 0, 0 };
continue;
}
long long g, im;
std::tie(g, im) = internal::inv_gcd(m0, m1);
long long u1 = (m1 / g);
if ((r1 - r0) % g) return { 0, 0 };
long long x = (r1 - r0) / g % u1 * im % u1;
r0 += x * m0;
m0 *= u1;
if (r0 < 0) r0 += m0;
}
return { r0, m0 };
}
long long floor_sum(long long n, long long m, long long a, long long b) {
long long ans = 0;
if (a >= m) {
ans += (n - 1) * n * (a / m) / 2;
a %= m;
}
if (b >= m) {
ans += n * (b / m);
b %= m;
}
long long y_max = (a * n + b) / m, x_max = (y_max * m - b);
if (y_max == 0) return ans;
ans += (n - (x_max + a - 1) / a) * y_max;
ans += floor_sum(y_max, a, m, (a - x_max % a) % a);
return ans;
}
}
#endif
#ifndef ATCODER_MAXFLOW_HPP
#define ATCODER_MAXFLOW_HPP 1
#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <vector>
namespace atcoder {
template <class Cap> struct mf_graph {
public:
mf_graph() : _n(0) {}
mf_graph(int n) : _n(n), g(n) {}
int add_edge(int from, int to, Cap cap) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
assert(0 <= cap);
int m = int(pos.size());
pos.push_back({ from, int(g[from].size()) });
g[from].push_back(_edge{ to, int(g[to].size()), cap });
g[to].push_back(_edge{ from, int(g[from].size()) - 1, 0 });
return m;
}
struct edge {
int from, to;
Cap cap, flow;
};
edge get_edge(int i) {
int m = int(pos.size());
assert(0 <= i && i < m);
auto _e = g[pos[i].first][pos[i].second];
auto _re = g[_e.to][_e.rev];
return edge{ pos[i].first, _e.to, _e.cap + _re.cap, _re.cap };
}
std::vector<edge> edges() {
int m = int(pos.size());
std::vector<edge> result;
for (int i = 0; i < m; i++) {
result.push_back(get_edge(i));
}
return result;
}
void change_edge(int i, Cap new_cap, Cap new_flow) {
int m = int(pos.size());
assert(0 <= i && i < m);
assert(0 <= new_flow && new_flow <= new_cap);
auto& _e = g[pos[i].first][pos[i].second];
auto& _re = g[_e.to][_e.rev];
_e.cap = new_cap - new_flow;
_re.cap = new_flow;
}
Cap flow(int s, int t) {
return flow(s, t, std::numeric_limits<Cap>::max());
}
Cap flow(int s, int t, Cap flow_limit) {
assert(0 <= s && s < _n);
assert(0 <= t && t < _n);
std::vector<int> level(_n), iter(_n);
internal::simple_queue<int> que;
auto bfs = [&]() {
std::fill(level.begin(), level.end(), -1);
level[s] = 0;
que.clear();
que.push(s);
while (!que.empty()) {
int v = que.front();
que.pop();
for (auto e : g[v]) {
if (e.cap == 0 || level[e.to] >= 0) continue;
level[e.to] = level[v] + 1;
if (e.to == t) return;
que.push(e.to);
}
}
};
auto dfs = [&](auto self, int v, Cap up) {
if (v == s) return up;
Cap res = 0;
int level_v = level[v];
for (int& i = iter[v]; i < int(g[v].size()); i++) {
_edge& e = g[v][i];
if (level_v <= level[e.to] || g[e.to][e.rev].cap == 0) continue;
Cap d =
self(self, e.to, std::min(up - res, g[e.to][e.rev].cap));
if (d <= 0) continue;
g[v][i].cap += d;
g[e.to][e.rev].cap -= d;
res += d;
if (res == up) break;
}
return res;
};
Cap flow = 0;
while (flow < flow_limit) {
bfs();
if (level[t] == -1) break;
std::fill(iter.begin(), iter.end(), 0);
while (flow < flow_limit) {
Cap f = dfs(dfs, t, flow_limit - flow);
if (!f) break;
flow += f;
}
}
return flow;
}
std::vector<bool> min_cut(int s) {
std::vector<bool> visited(_n);
internal::simple_queue<int> que;
que.push(s);
while (!que.empty()) {
int p = que.front();
que.pop();
visited[p] = true;
for (auto e : g[p]) {
if (e.cap && !visited[e.to]) {
visited[e.to] = true;
que.push(e.to);
}
}
}
return visited;
}
private:
int _n;
struct _edge {
int to, rev;
Cap cap;
};
std::vector<std::pair<int, int>> pos;
std::vector<std::vector<_edge>> g;
};
}
#endif
#ifndef ATCODER_MINCOSTFLOW_HPP
#define ATCODER_MINCOSTFLOW_HPP 1
#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <vector>
namespace atcoder {
template <class Cap, class Cost> struct mcf_graph {
public:
mcf_graph() {}
mcf_graph(int n) : _n(n), g(n) {}
int add_edge(int from, int to, Cap cap, Cost cost) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int m = int(pos.size());
pos.push_back({ from, int(g[from].size()) });
g[from].push_back(_edge{ to, int(g[to].size()), cap, cost });
g[to].push_back(_edge{ from, int(g[from].size()) - 1, 0, -cost });
return m;
}
struct edge {
int from, to;
Cap cap, flow;
Cost cost;
};
edge get_edge(int i) {
int m = int(pos.size());
assert(0 <= i && i < m);
auto _e = g[pos[i].first][pos[i].second];
auto _re = g[_e.to][_e.rev];
return edge{
pos[i].first, _e.to, _e.cap + _re.cap, _re.cap, _e.cost,
};
}
std::vector<edge> edges() {
int m = int(pos.size());
std::vector<edge> result(m);
for (int i = 0; i < m; i++) {
result[i] = get_edge(i);
}
return result;
}
std::pair<Cap, Cost> flow(int s, int t) {
return flow(s, t, std::numeric_limits<Cap>::max());
}
std::pair<Cap, Cost> flow(int s, int t, Cap flow_limit) {
return slope(s, t, flow_limit).back();
}
std::vector<std::pair<Cap, Cost>> slope(int s, int t) {
return slope(s, t, std::numeric_limits<Cap>::max());
}
std::vector<std::pair<Cap, Cost>> slope(int s, int t, Cap flow_limit) {
assert(0 <= s && s < _n);
assert(0 <= t && t < _n);
assert(s != t);
std::vector<Cost> dual(_n, 0), dist(_n);
std::vector<int> pv(_n), pe(_n);
std::vector<bool> vis(_n);
auto dual_ref = [&]() {
std::fill(dist.begin(), dist.end(),
std::numeric_limits<Cost>::max());
std::fill(pv.begin(), pv.end(), -1);
std::fill(pe.begin(), pe.end(), -1);
std::fill(vis.begin(), vis.end(), false);
struct Q {
Cost key;
int to;
bool operator<(Q r) const { return key > r.key; }
};
std::priority_queue<Q> que;
dist[s] = 0;
que.push(Q{ 0, s });
while (!que.empty()) {
int v = que.top().to;
que.pop();
if (vis[v]) continue;
vis[v] = true;
if (v == t) break;
for (int i = 0; i < int(g[v].size()); i++) {
auto e = g[v][i];
if (vis[e.to] || !e.cap) continue;
Cost cost = e.cost - dual[e.to] + dual[v];
if (dist[e.to] - dist[v] > cost) {
dist[e.to] = dist[v] + cost;
pv[e.to] = v;
pe[e.to] = i;
que.push(Q{ dist[e.to], e.to });
}
}
}
if (!vis[t]) {
return false;
}
for (int v = 0; v < _n; v++) {
if (!vis[v]) continue;
dual[v] -= dist[t] - dist[v];
}
return true;
};
Cap flow = 0;
Cost cost = 0, prev_cost = -1;
std::vector<std::pair<Cap, Cost>> result;
result.push_back({ flow, cost });
while (flow < flow_limit) {
if (!dual_ref()) break;
Cap c = flow_limit - flow;
for (int v = t; v != s; v = pv[v]) {
c = std::min(c, g[pv[v]][pe[v]].cap);
}
for (int v = t; v != s; v = pv[v]) {
auto& e = g[pv[v]][pe[v]];
e.cap -= c;
g[v][e.rev].cap += c;
}
Cost d = -dual[s];
flow += c;
cost += c * d;
if (prev_cost == d) {
result.pop_back();
}
result.push_back({ flow, cost });
prev_cost = cost;
}
return result;
}
private:
int _n;
struct _edge {
int to, rev;
Cap cap;
Cost cost;
};
std::vector<std::pair<int, int>> pos;
std::vector<std::vector<_edge>> g;
};
}
#endif
#ifndef ATCODER_SCC_HPP
#define ATCODER_SCC_HPP 1
#include <algorithm>
#include <cassert>
#include <vector>
namespace atcoder {
struct scc_graph {
public:
scc_graph() : internal(0) {}
scc_graph(int n) : internal(n) {}
void add_edge(int from, int to) {
int n = internal.num_vertices();
assert(0 <= from && from < n);
assert(0 <= to && to < n);
internal.add_edge(from, to);
}
std::vector<std::vector<int>> scc() { return internal.scc(); }
private:
internal::scc_graph internal;
};
}
#endif
#ifndef ATCODER_SEGTREE_HPP
#define ATCODER_SEGTREE_HPP 1
#include <algorithm>
#include <cassert>
#include <vector>
namespace atcoder {
template <class S, S(*op)(S, S), S(*e)()> struct segtree {
public:
segtree() : segtree(0) {}
segtree(int n) : segtree(std::vector<S>(n, e())) {}
segtree(const std::vector<S>& v) : _n(int(v.size())) {
log = internal::ceil_pow2(_n);
size = 1 << log;
d = std::vector<S>(2 * size, e());
for (int i = 0; i < _n; i++) d[size + i] = v[i];
for (int i = size - 1; i >= 1; i--) {
update(i);
}
}
void set(int p, S x) {
assert(0 <= p && p < _n);
p += size;
d[p] = x;
for (int i = 1; i <= log; i++) update(p >> i);
}
S get(int p) {
assert(0 <= p && p < _n);
return d[p + size];
}
S prod(int l, int r) {
assert(0 <= l && l <= r && r <= _n);
S sml = e(), smr = e();
l += size;
r += size;
while (l < r) {
if (l & 1) sml = op(sml, d[l++]);
if (r & 1) smr = op(d[--r], smr);
l >>= 1;
r >>= 1;
}
return op(sml, smr);
}
S all_prod() { return d[1]; }
template <bool (*f)(S)> int max_right(int l) {
return max_right(l, [](S x) { return f(x); });
}
template <class F> int max_right(int l, F f) {
assert(0 <= l && l <= _n);
assert(f(e()));
if (l == _n) return _n;
l += size;
S sm = e();
do {
while (l % 2 == 0) l >>= 1;
if (!f(op(sm, d[l]))) {
while (l < size) {
l = (2 * l);
if (f(op(sm, d[l]))) {
sm = op(sm, d[l]);
l++;
}
}
return l - size;
}
sm = op(sm, d[l]);
l++;
} while ((l & -l) != l);
return _n;
}
template <bool (*f)(S)> int min_left(int r) {
return min_left(r, [](S x) { return f(x); });
}
template <class F> int min_left(int r, F f) {
assert(0 <= r && r <= _n);
assert(f(e()));
if (r == 0) return 0;
r += size;
S sm = e();
do {
r--;
while (r > 1 && (r % 2)) r >>= 1;
if (!f(op(d[r], sm))) {
while (r < size) {
r = (2 * r + 1);
if (f(op(d[r], sm))) {
sm = op(d[r], sm);
r--;
}
}
return r + 1 - size;
}
sm = op(d[r], sm);
} while ((r & -r) != r);
return 0;
}
private:
int _n, size, log;
std::vector<S> d;
void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
};
}
#endif
#ifndef ATCODER_STRING_HPP
#define ATCODER_STRING_HPP 1
#include <algorithm>
#include <cassert>
#include <numeric>
#include <string>
#include <vector>
namespace atcoder {
namespace internal {
std::vector<int> sa_naive(const std::vector<int>& s) {
int n = int(s.size());
std::vector<int> sa(n);
std::iota(sa.begin(), sa.end(), 0);
std::sort(sa.begin(), sa.end(), [&](int l, int r) {
if (l == r) return false;
while (l < n && r < n) {
if (s[l] != s[r]) return s[l] < s[r];
l++;
r++;
}
return l == n;
});
return sa;
}
std::vector<int> sa_doubling(const std::vector<int>& s) {
int n = int(s.size());
std::vector<int> sa(n), rnk = s, tmp(n);
std::iota(sa.begin(), sa.end(), 0);
for (int k = 1; k < n; k *= 2) {
auto cmp = [&](int x, int y) {
if (rnk[x] != rnk[y]) return rnk[x] < rnk[y];
int rx = x + k < n ? rnk[x + k] : -1;
int ry = y + k < n ? rnk[y + k] : -1;
return rx < ry;
};
std::sort(sa.begin(), sa.end(), cmp);
tmp[sa[0]] = 0;
for (int i = 1; i < n; i++) {
tmp[sa[i]] = tmp[sa[i - 1]] + (cmp(sa[i - 1], sa[i]) ? 1 : 0);
}
std::swap(tmp, rnk);
}
return sa;
}
template <int THRESHOLD_NAIVE = 10, int THRESHOLD_DOUBLING = 40>
std::vector<int> sa_is(const std::vector<int>& s, int upper) {
int n = int(s.size());
if (n == 0) return {};
if (n == 1) return { 0 };
if (n == 2) {
if (s[0] < s[1]) {
return { 0, 1 };
}
else {
return { 1, 0 };
}
}
if (n < THRESHOLD_NAIVE) {
return sa_naive(s);
}
if (n < THRESHOLD_DOUBLING) {
return sa_doubling(s);
}
std::vector<int> sa(n);
std::vector<bool> ls(n);
for (int i = n - 2; i >= 0; i--) {
ls[i] = (s[i] == s[i + 1]) ? ls[i + 1] : (s[i] < s[i + 1]);
}
std::vector<int> sum_l(upper + 1), sum_s(upper + 1);
for (int i = 0; i < n; i++) {
if (!ls[i]) {
sum_s[s[i]]++;
}
else {
sum_l[s[i] + 1]++;
}
}
for (int i = 0; i <= upper; i++) {
sum_s[i] += sum_l[i];
if (i < upper) sum_l[i + 1] += sum_s[i];
}
auto induce = [&](const std::vector<int>& lms) {
std::fill(sa.begin(), sa.end(), -1);
std::vector<int> buf(upper + 1);
std::copy(sum_s.begin(), sum_s.end(), buf.begin());
for (auto d : lms) {
if (d == n) continue;
sa[buf[s[d]]++] = d;
}
std::copy(sum_l.begin(), sum_l.end(), buf.begin());
sa[buf[s[n - 1]]++] = n - 1;
for (int i = 0; i < n; i++) {
int v = sa[i];
if (v >= 1 && !ls[v - 1]) {
sa[buf[s[v - 1]]++] = v - 1;
}
}
std::copy(sum_l.begin(), sum_l.end(), buf.begin());
for (int i = n - 1; i >= 0; i--) {
int v = sa[i];
if (v >= 1 && ls[v - 1]) {
sa[--buf[s[v - 1] + 1]] = v - 1;
}
}
};
std::vector<int> lms_map(n + 1, -1);
int m = 0;
for (int i = 1; i < n; i++) {
if (!ls[i - 1] && ls[i]) {
lms_map[i] = m++;
}
}
std::vector<int> lms;
lms.reserve(m);
for (int i = 1; i < n; i++) {
if (!ls[i - 1] && ls[i]) {
lms.push_back(i);
}
}
induce(lms);
if (m) {
std::vector<int> sorted_lms;
sorted_lms.reserve(m);
for (int v : sa) {
if (lms_map[v] != -1) sorted_lms.push_back(v);
}
std::vector<int> rec_s(m);
int rec_upper = 0;
rec_s[lms_map[sorted_lms[0]]] = 0;
for (int i = 1; i < m; i++) {
int l = sorted_lms[i - 1], r = sorted_lms[i];
int end_l = (lms_map[l] + 1 < m) ? lms[lms_map[l] + 1] : n;
int end_r = (lms_map[r] + 1 < m) ? lms[lms_map[r] + 1] : n;
bool same = true;
if (end_l - l != end_r - r) {
same = false;
}
else {
while (l < end_l) {
if (s[l] != s[r]) {
break;
}
l++;
r++;
}
if (l == n || s[l] != s[r]) same = false;
}
if (!same) rec_upper++;
rec_s[lms_map[sorted_lms[i]]] = rec_upper;
}
auto rec_sa =
sa_is<THRESHOLD_NAIVE, THRESHOLD_DOUBLING>(rec_s, rec_upper);
for (int i = 0; i < m; i++) {
sorted_lms[i] = lms[rec_sa[i]];
}
induce(sorted_lms);
}
return sa;
}
}
std::vector<int> suffix_array(const std::vector<int>& s, int upper) {
assert(0 <= upper);
for (int d : s) {
assert(0 <= d && d <= upper);
}
auto sa = internal::sa_is(s, upper);
return sa;
}
template <class T> std::vector<int> suffix_array(const std::vector<T>& s) {
int n = int(s.size());
std::vector<int> idx(n);
iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(), [&](int l, int r) { return s[l] < s[r]; });
std::vector<int> s2(n);
int now = 0;
for (int i = 0; i < n; i++) {
if (i && s[idx[i - 1]] != s[idx[i]]) now++;
s2[idx[i]] = now;
}
return internal::sa_is(s2, now);
}
std::vector<int> suffix_array(const std::string& s) {
int n = int(s.size());
std::vector<int> s2(n);
for (int i = 0; i < n; i++) {
s2[i] = s[i];
}
return internal::sa_is(s2, 255);
}
template <class T>
std::vector<int> lcp_array(const std::vector<T>& s,
const std::vector<int>& sa) {
int n = int(s.size());
assert(n >= 1);
std::vector<int> rnk(n);
for (int i = 0; i < n; i++) {
rnk[sa[i]] = i;
}
std::vector<int> lcp(n - 1);
int h = 0;
for (int i = 0; i < n; i++) {
if (h > 0) h--;
if (rnk[i] == 0) continue;
int j = sa[rnk[i] - 1];
for (; j + h < n && i + h < n; h++) {
if (s[j + h] != s[i + h]) break;
}
lcp[rnk[i] - 1] = h;
}
return lcp;
}
std::vector<int> lcp_array(const std::string& s, const std::vector<int>& sa) {
int n = int(s.size());
std::vector<int> s2(n);
for (int i = 0; i < n; i++) {
s2[i] = s[i];
}
return lcp_array(s2, sa);
}
template <class T> std::vector<int> z_algorithm(const std::vector<T>& s) {
int n = int(s.size());
if (n == 0) return {};
std::vector<int> z(n);
z[0] = 0;
for (int i = 1, j = 0; i < n; i++) {
int& k = z[i];
k = (j + z[j] <= i) ? 0 : std::min(j + z[j] - i, z[i - j]);
while (i + k < n && s[k] == s[i + k]) k++;
if (j + z[j] < i + z[i]) j = i;
}
z[0] = n;
return z;
}
std::vector<int> z_algorithm(const std::string& s) {
int n = int(s.size());
std::vector<int> s2(n);
for (int i = 0; i < n; i++) {
s2[i] = s[i];
}
return z_algorithm(s2);
}
}
#endif
#ifndef ATCODER_TWOSAT_HPP
#define ATCODER_TWOSAT_HPP 1
#include <cassert>
#include <vector>
namespace atcoder {
struct two_sat {
public:
two_sat() : _n(0), scc(0) {}
two_sat(int n) : _n(n), _answer(n), scc(2 * n) {}
void add_clause(int i, bool f, int j, bool g) {
assert(0 <= i && i < _n);
assert(0 <= j && j < _n);
scc.add_edge(2 * i + (f ? 0 : 1), 2 * j + (g ? 1 : 0));
scc.add_edge(2 * j + (g ? 0 : 1), 2 * i + (f ? 1 : 0));
}
bool satisfiable() {
auto id = scc.scc_ids().second;
for (int i = 0; i < _n; i++) {
if (id[2 * i] == id[2 * i + 1]) return false;
_answer[i] = id[2 * i] < id[2 * i + 1];
}
return true;
}
std::vector<bool> answer() { return _answer; }
private:
int _n;
std::vector<bool> _answer;
internal::scc_graph scc;
};
}
#endif
#include <iostream>
#include <string>
#include <cmath>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<iomanip>
#include<bitset>
#define _USE_MATH_DEFINES
#include <math.h>
#include <functional>
#include<complex>
#include<cassert>
#include<random>
using namespace std;
using namespace atcoder;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repi(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
typedef long long ll;
typedef unsigned long long ull;
const ll inf=1e18;
using graph = vector<vector<int> > ;
using P= pair<ll,ll>;
using vi=vector<int>;
using vvi=vector<vi>;
using vll=vector<ll>;
using vvll=vector<vll>;
using vp=vector<P>;
using vpp=vector<vp>;
using mint=modint1000000007;
using vm=vector<mint>;
using vvm=vector<vm>;
//string T="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//string S="abcdefghijklmnopqrstuvwxyz";
//cout << fixed << setprecision(10);
//cin.tie(0); ios::sync_with_stdio(false);
const double PI = acos(-1);
template<class T> bool chmin(T& a, T b) {
if (a > b) {
a = b;
return true;
}
else return false;
}
template<class T> bool chmax(T& a, T b) {
if (a < b) {
a = b;
return true;
}
else return false;
}
struct edge{
int to; int w;
edge(int to,int w) : to(to),w(w){}
};
//g++ cf.cpp -std=c++17 -I .
int main(){cin.tie(0);ios::sync_with_stdio(false);
int n; cin >> n;
vi a(n);rep(i,n)cin >> a[i];
vvi dp(n,vi(n,-1));
rep(i,n)dp[i][i]=a[i];
repi(wid,1,n){
rep(l,n){
int r=l+wid;
if(r>=n)break;
for(int i=l; i<r; i++){
if(dp[l][i]==dp[i+1][r] && dp[l][i]!=-1)dp[l][r]=dp[l][i]+1;
}
}
}
vll dp2(n+1,inf);
dp2[0]=0;
for(int i=0; i<=n; i++){
ll now=dp2[i];
if(now==inf)continue;
for(int j=i+1; j<=n; j++){
ll cost=j-i;
if(dp[i][j-1]!=-1)cost=1;
chmin(dp2[j],now+cost);
}
}
cout << dp2[n] << endl;
}
| 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 <bits/stdc++.h>
using namespace std;
#define ll long long
ll a[40001],b[40001],n,m,i,j,k,ans=0;
int main()
{
cin>>n>>m>>k;
for(i=0;i<n;i++){cin>>a[i];if(a[i]) a[i]+=a[i-1];}
for(i=0;i<m;i++){cin>>b[i];if(b[i]) b[i]+=b[i-1];}
for(i=1;i<=n;i++)
if(k%i==0){
ll u=i,v=k/i,x=0,y=0l;
for(j=0;j<n;j++) if(a[j]>=u) x++;
for(j=0;j<m;j++) if(b[j]>=v) y++;
ans+=x*y;
}
cout<<ans;
}
| 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>
#pragma GCC optimize("Ofast")
#define debug(x) cerr << #x << " " << x << "\n"
#define debugs(x) cerr << #x << " " << x << " "
using namespace std;
typedef long long ll;
typedef pair <short, short> pii;
const ll NMAX = 1002;
const ll VMAX = 41;
const ll INF = (1LL << 59);
const ll MOD = 1000000009;
const ll BLOCK = 318;
const ll base = 31;
const ll nrbits = 21;
short dist[NMAX][NMAX][41];
short mat[NMAX][NMAX];
vector <pii> v[41];
struct ura {
short pf, ps;
int cost;
};
vector <ura> muchii;
short dx[] = {0, 1, -1, 0};
short dy[] = {1, 0, 0, -1};
short n, m;
bool OK(short i, short j) {
if(i > 0 && i <= n && j > 0 && j <= m)
return 1;
return 0;
}
int main() {
#ifdef HOME
ifstream cin(".in");
ofstream cout(".out");
#endif // HOME
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
short k, i, j;
cin >> n >> m >> k;
for(i = 1; i <= n; i++) {
for(j = 1; j <= m; j++) {
cin >> mat[i][j];
v[mat[i][j]].push_back({i, j});
}
}
for(int col = 1; col <= k; col++) {
for(i = 1; i <= n + 1; i++) {
for(j = 1; j <= max(m, k); j++) {
dist[i][j][col] = 32767;
}
}
deque <pii> q;
for(auto x : v[col]) {
dist[x.first][x.second][col] = 0;
q.push_back({x.first, x.second});
}
while(q.size()) {
pii x = q.front();
q.pop_front();
if(x.first != n + 1) {
for(int d = 0; d < 4; d++) {
pii care = {x.first + dx[d], x.second + dy[d]};
if(!OK(care.first, care.second)) continue;
if(dist[care.first][care.second][col] == 32767) { /// Hmm...
dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1;
q.push_back({care.first, care.second});
}
}
pii care = {n + 1, mat[x.first][x.second]};
if(dist[care.first][care.second][col] == 32767) { /// Hmm...
dist[care.first][care.second][col] = dist[x.first][x.second][col];
q.push_front({care.first, care.second});
}
} else {
for(auto y : v[x.second]) {
pii care = y;
if(dist[care.first][care.second][col] == 32767) { /// Hmm...
dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1;
q.push_back({care.first, care.second});
}
}
}
}
}
int q;
cin >> q;
while(q--) {
int a, b, c, d;
cin >> a >> b >> c >> d;
int minim = abs(c - a) + abs(d - b);
for(int col = 1; col <= k; col++) {
minim = min(minim, (int)dist[a][b][col] + (int)dist[c][d][col] + 1);
}
cout << minim << "\n";
}
return 0;
}
| 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"
] | /// What are you doing now? Just go f*cking code now dude?
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define TASK "codin"
//#define int long long
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long llu;
#define IO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define is insert
#define eb emplace_back
#define FOR(x,a,b) for (ll x=a;x<=b;x++)
#define FOD(x,a,b) for (ll x=a;x>=b;x--)
#define FER(x,a,b) for (ll x=a;x<b;x++)
#define FED(x,a,b) for (ll x=a;x>b;x--)
#define EL "\n"
#define ALL(v) v.begin(),v.end()
#define vi vector<ll>
#define vii vector<pii>
#define pii pair<int,int>
///---------- TEMPLATE ABOUT BIT ----------///
ll getbit(ll val, ll num){
return ((val >> (num)) & 1LL);
}
ll offbit(ll val, ll num){
return ((val ^ (1LL << (num - 1))));
}
ll setbit(ll k, ll s) {
return (k &~ (1 << s));
}
///---------- TEMPLATE ABOUT MATH ----------///
ll lcm(ll a, ll b){
return a * b/__gcd(a, b);
}
ll bmul(ll a, ll b, ll mod){
if(b == 0){return 0;}
if(b == 1){return a;}
ll t = bmul(a, b/2, mod);t = (t + t)%mod;
if(b%2 == 1){t = (t + a) % mod;}return t;
}
ll bpow(ll n, ll m, ll mod){
ll res = 1; while (m) {
if (m & 1) res = res * n % mod; n = n * n % mod; m >>= 1;
} return res;
}
///----------------------------------------///
const int S = 5e5 + 5, M = 2e3 + 4;
const ll mod = 1e9 + 7, hashmod = 1e9 + 9, inf = 1e18;
const int base = 311, BLOCK_SIZE = 420;
const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
const int dxx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, dyy[8]={0, 1, 1, 1, 0, -1, -1, -1};
///------ The main code starts here ------///
int n, d, h[S], cnt[S];
void solve(){
cin >> n >> d;
int mini = 0, maxi = (n - 1) * n / 2;
memset(cnt, 0, sizeof cnt); memset(h, 0, sizeof h);
h[1] = 0, cnt[0] = 1;
FOR(i, 2, n){
h[i] = h[i / 2] + 1;
mini += h[i];
cnt[h[i]]++;
}
//cout << mini << EL;
if(d < mini || d > maxi){
cout << "NO" << EL;
return;
}
int dist = d - mini;
//cout << dist << EL;
int height = n - 1;
while(cnt[height] == 0){
height--;
}
int tmp = height++;
while(dist > 0){
while(cnt[tmp] == 1){
tmp--;
}
int k = tmp;
while(k < height && dist > 0){
cnt[k]--;
cnt[k + 1]++;
k++;
dist--;
}
if(k == height){
height++;
}
}
cout << "YES" << EL;
int x = 0, y = 1;
FOR(i, 1, n - 1){
FOR(j, 0, cnt[i] - 1){
cout << x + j / 2 + 1 << " ";
}
x = y;
y += cnt[i];
}
cout << EL;
}
signed main(){
IO
if(fopen(TASK".inp","r")){
freopen(TASK".inp","r",stdin);
freopen(TASK".out","w",stdout);
}
int t = 1;
cin >> t;
while(t--){
solve();
}
}
| cpp |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0); cin.tie(0)
#define ff first
#define ss second
#define pb push_back
#define pf push_front
#define all(s) s.begin(),s.end()
typedef long long ll;
const double pi = acos(-1),ef=1e-9;
const ll N=100+5,M=1e9+7;
ll n,a[N],mm[N][N][N][2];
ll rec(ll i,ll one,ll zero,ll lst)
{
if(i>n){
return 0;
}
ll &ans=mm[i][one][zero][lst];
if(ans!=-1)return ans;
ans=1e15;
if(a[i]==-1){
if(one>0){
ans=min(ans,(lst!=1)+rec(i+1,one-1,zero,1));
}
if(zero>0){
ans=min(ans,(lst!=0)+rec(i+1,one,zero-1,0));
}
}
else{
ans=min(ans,(lst!=a[i])+rec(i+1,one,zero,a[i]));
}
return ans;
}
void solve()
{
memset(mm,-1,sizeof mm);
ll c[2]={0};
cin>>n;
set<ll>st;
for(ll i=1;i<=n;i++){
cin>>a[i];
if(a[i]==0){
a[i]=-1;
//cout<<a[i]<<' ';
continue;
}
st.insert(a[i]);
a[i]%=2;
}
for(ll i=1;i<=n;i++){
if(st.count(i))continue;
c[i%2]++;
}
//for(auto p:st)cout<<p<<' ';
//cout<<c[0]<<' '<<c[1]<<"\n";
ll ans=1e18;
ans=min(ans,rec(1,c[1],c[0],0));
ans=min(ans,rec(1,c[1],c[0],1));
cout<<ans<<"\n";
}
int main()
{
fast;
ll t=1,tc=1;
// cin>>tc;
while(tc--){
solve();
}
} | 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<bits/stdc++.h>
using namespace std;
void count(vector<int> &src, vector<long long> &dest){
int i = 0;
int n = src.size();
while (i < n){
int j = i;
while (j < n && src[j] == 1){
j++;
}
int len_ones = (j - i);
int cnt = 1;
while (len_ones > 0){
dest[len_ones] += cnt;
len_ones--;
cnt++;
}
i = j + 1;
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m, k;
cin >> n >> m >> k;
vector<int> a(n);
vector<int> b(m);
for (int i = 0; i < n ;i++){
cin >> a[i];
}
for (int i = 0; i < m; i++){
cin >> b[i];
}
vector<long long> a_cnt(n + 1, 0);
vector<long long> b_cnt(m + 1, 0);
count(a, a_cnt);
count(b, b_cnt);
long long cnt = 0;
for (int i = 1; i <= n; i++){
int idx = k / i;
int mod = k % i;
if (idx <= m && mod == 0){
cnt += (a_cnt[i] * b_cnt[idx]);
}
}
cout<<cnt<<"\n";
return 0;
} | cpp |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.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.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | #include<iostream>
using namespace std; int t,a,b,c,n; main(){for(cin>>t;t--;puts((a+b+c+n)%3||(a+b+c+n)/3<max(a,max(b,c))?"NO":"YES")) cin>>a>>b>>c>>n;} | cpp |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
//#include <atcoder/all>
#define f first
#define s second
# define FAST() ios_base::sync_with_stdio(false); cin.tie(NULL);
#define IN() freopen("collectingofficer.in", "r", stdin);
#define OUT() freopen("output.txt", "w", stdout) ;
/*
وَمَا تَوْفِيقِي إِلَّا بِاللَّهِ
*/
using namespace std;
using ll = long long ;
using ld = long double ;
const int N = 2e5+7 , M = 998244353;
const double ES = 1e-6;
using vi = deque<int>;
template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
int dx[] = {0, 0, 1, -1, 1, -1, 1, -1}, dx4[] = {1, 0 , 0 , -1};
int dy[] = {1, -1, 0, 0, 1, -1, -1, 1}, dy4[] = {0, 1, -1 ,0 };
/*Remind pleaseeeee
* can brute force ? can brute force for specific size ? pleasee ?
* sum or mult over flow????????
*
*
*/
void solve() {
vector<vi>a(27),b(27);
string in;
int n;
cin>>n>>in;
vector<pair<int,int>>res;
for (int i = 0; i <in.size() ; ++i) {
if(in[i]=='?')a[26].push_back(i+1);
else a[in[i]-'a'].push_back(i+1);
}
cin>>in;
for (int i = 0; i <in.size() ; ++i) {
if(in[i]=='?')b[26].push_back(i+1);
else b[in[i]-'a'].push_back(i+1);
}
for (int i = 0; i <=26 ; ++i) {
while (!a[i].empty() and !b[i].empty()){
res.emplace_back(a[i].front(),b[i].front());
a[i].pop_front();
b[i].pop_front();
}
while (!a[i].empty() and !b[26].empty()){
res.emplace_back(a[i].front(),b[26].front());
a[i].pop_front();
b[26].pop_front();
}
while (!a[26].empty() and !b[i].empty()){
res.emplace_back(a[26].front(),b[i].front());
b[i].pop_front();
a[26].pop_front();
}
}
cout<<res.size()<<"\n";
for (int i = 0; i <res.size() ; ++i) {
cout<<res[i].f<<" "<<res[i].s<<"\n";
}
}
int main(){
// IN();
// FAST()
int t=1;
// cin>>t;
while (t--){
solve();
// cout<<"\n";
}
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;
#define int long long
#define double long long
struct Point{
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
};
typedef Point Vector;
Vector operator - (Point A, Point B){return Vector(A.x - B.x, A.y - B.y);}
Vector operator * (Vector A, double p){return Vector(A.x * p, A.y * p);}
Vector operator + (Vector A, Vector B){return Vector(A.x + B.x, A.y + B.y);}
struct Line{
Vector v;
Point p;
Line(){};
Line(Vector v,Point p):v(v),p(p){}
Point get_point_in_line(double t)
{
return v+(p-v)*t;
}
};
/* double eps=1e-30;
int sgn(double x)
{
if(fabs(x)<eps)
{
return 0;
}
if(x<0)
return -1;
return 1;
} */
const double pi=acos(-1);
double Dot(Vector A, Vector B){return A.x * B.x + A.y * B.y;}
inline double R_to_D(double rad)// 弧度转角度
{ return 180/pi*rad; }
double Length(Vector A){return sqrt(Dot(A, A));}
double Angle(Vector A, Vector B){return acos(fabs((Dot(A, B) / Length(A) / Length(B))));}
double Cross(Vector A, Vector B){return A.x * B.y - B.x * A.y;}
bool OnSegment(Point p, Point a1, Point a2){
/* cout<<"judge "<<endl;
cout<<p.x<<" "<<p.y<<endl;
cout<<a1.x<<" "<<a1.y<<endl;
cout<<a2.x<<" "<<a2.y<<endl;
cout<<Cross(a1-p, a2-p)<<" "<<Dot(a1-p,a2-p)<<endl; */
return (Cross(a1-p, a2-p) ==0)&&(Dot(a1-p,a2-p)<0);
}
double dis(Point p1,Point p2)
{
return (p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y);
}
bool judge(Point p,Line L)
{
if(OnSegment(p,L.p,L.v+L.p))
{
/* cout<<p.x<<" "<<p.y<<"-----"<<L.p.x<<" "<<L.p.y<<"---"<<(L.v+L.p).x<<" "<<(L.v+L.p).y<<endl; */
double xx1=dis(p,L.p);
double xx2=dis(p,(L.v+L.p));
if(xx1-xx2>0) swap(xx1,xx2);
/* cout<<"-----"<<xx1<<" "<<xx2<<endl; */
if(16*xx1-xx2>=0)
{
return 1;
}else
{
return 0;
}
}else
{
/* cout<<"pp"<<endl; */
return 0;
}
}
signed main()
{
int t;
cin>>t;
while(t--)
{
int n=3;
map<pair<int,int>,vector<int>>mp;
Line l[4];
set<pair<int,int>>se;
for(int i=1;i<=n;i++)
{
int a1,b1,a2,b2;
cin>>a1>>b1>>a2>>b2;
l[i]=Line({a2-a1,b2-b1},{a1,b1});
mp[{a1,b1}].push_back(i);
mp[{a2,b2}].push_back(i);
se.insert({a1,b1});
se.insert({a2,b2});
}
Point aa;
Line new_l[4];
int cnt=0;
if(se.size()!=5)
{
cout<<"NO"<<endl;
continue;
}else
{
for(auto it:se)
{
if(mp[it].size()==2)
{
aa.x=it.first,aa.y=it.second;
new_l[1]=l[mp[it][0]];
new_l[2]=l[mp[it][1]];
/* if(mp[it][0]==mp[it][1])
{
cout<<"NO"<<endl;
return 0;
} */
new_l[3]=l[6-mp[it][0]-mp[it][1]];
break;
}
}
}
Point bb,cc;
if(new_l[1].p.x==aa.x&&new_l[1].p.y==aa.y)
{
bb={(new_l[1].p+new_l[1].v).x,(new_l[1].p+new_l[1].v).y};
}else
{
bb={(new_l[1].p).x,(new_l[1].p).y};
}
if(new_l[2].p.x==aa.x&&new_l[2].p.y==aa.y)
{
cc={(new_l[2].p+new_l[2].v).x,(new_l[2].p+new_l[2].v).y};
}else
{
cc={(new_l[2].p).x,(new_l[2].p).y};
}
if(dis(aa,bb)+dis(aa,cc)<dis(bb,cc))
{
cout<<"NO"<<endl;
continue;
}
/* for(int i=1;i<=3;i++)
{
cout<<new_l[i].p.x<<" "<<new_l[i].p.y<<endl;
}
cout<<new_l[1].v.x<<" "<<new_l[1].v.y<<endl;
cout<<new_l[2].v.x<<" "<<new_l[2].v.y<<endl; */
/* double alpha=Angle(new_l[1].v,new_l[2].v); */
if((judge(new_l[3].p,new_l[1])&&judge(new_l[3].p+new_l[3].v,new_l[2]))||(judge(new_l[3].p,new_l[2])&&judge(new_l[3].p+new_l[3].v,new_l[1])))
{
cout<<"YES"<<endl;
}else
{
cout<<"NO"<<endl;
}
}
} | cpp |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"data structures",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class t> using vc=vector<t>;
template<class t> using vvc=vc<vc<t>>;
using vi = vc<int>;
using vl = vc<ll>;
using vvi = vc<vi>;
using vvl = vc<vl>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define inf 0x3f3f3f3f
#define llinf 0x3f3f3f3f3f3f3f3f
#define ALL(x) (x).begin(),(x).end()
#define rALL(x) (x).rbegin(),(x).rend()
#define rev(x) reverse(ALL(x))
#define srt(x) sort(ALL(x))
#define rsrt(x) sort(rALL(x))
#define rb(_, l, r) for(int _= l; _ <= r; ++_)
#define rep(_, l, r) for(int _ = l; _ < r; ++_)
#define br(_, r, l) for(int _ = r; _ >= l; _--)
#define sz(x) (int)(x.size())
template<class t,class u> bool chmax(t&a,u b){if(a<b){a=b;return true;}else return false;}
template<class t,class u> bool chmin(t&a,u b){if(b<a){a=b;return true;}else return false;}
template<typename T> void in(vector<T>&a) {for(auto& e: a) cin>> e;}
mt19937_64 rng((unsigned int) chrono::steady_clock::now().time_since_epoch().count());
void p(int x) { if (x) cout << "YES" << '\n'; else cout << "NO" << '\n'; }
template<class t> void printv(t x, char delimiter = ',', bool needBrace = true) {
needBrace && cout << "{";
for(auto it = x.begin(); it != x.end(); ) {
cout << *it;
it = next(it);
if (it != x.end()) {
cout << delimiter;
} else {
needBrace && cout << "}";
}
}
cout << "\n";
}
#define TEST
#ifdef TEST
#define pr(...) printf(__VA_ARGS__);
#define db(x, ...) debug##x(__VA_ARGS__)
#define ldb(parm...) do {cout << "Line:" << __LINE__ << " "; db(parm);} while(0)
#define debugv(v...) do {printv(v);} while(0)
#define debug1(a) cout << #a << " = " << a << ' ';
#define debug2(a,b) do {debug1(a); debug1(b); cout << '\n';} while(0)
#define debug3(a,b,c) do {debug1(a); debug2(b, c);} while(0)
#define debug4(a,b,c,d) do {debug1(a); debug3(b, c, d);} while(0)
#else
#define db(...) "Your attitude towards suffering is the melody of life.";
#endif
/*
str -> str.c_str()
db(v, a) -> printv()
db(1, x) -> print x
db(2, x, y) -> print x, y
*/
const char nl = '\n';
#define SINGLE
void solve() {
int n;
cin >> n;
vi a(n);
in(a);
map<int, vc<pii>> mp;
rep (i, 0, n) {
int cur = 0;
br (j, i, 0) {
cur += a[j];
mp[cur].push_back({j + 1, i + 1});
}
}
int mxv = -1, mx = 0;
for (auto&[k, v]: mp) {
int m = sz(v), cur = 1, pre = v[0].second;
rep (i, 1, m) {
if (v[i].first > pre) {
cur ++;
pre = v[i].second;
}
}
if (chmax(mx, cur)) mxv = k;
}
auto v = mp[mxv];
cout << mx << nl;
auto [l, r] = v.front();
cout << l << ' ' << r << nl;
int m = sz(v), cur = 1, pre = v[0].second;
rep (i, 1, m) {
if (v[i].first > pre) {
cout << v[i].first << ' ' << v[i].second << nl;
pre = v[i].second;
}
}
}
int main() {
ios::sync_with_stdio(0);cin.tie(0);
#ifdef SINGLE
solve();
#else
int T; cin >> T; while (T--) solve();
#endif
return 0;
} | cpp |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105) — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | /**
* author: tourist
* created: 02.02.2020 17:12:43
**/
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string s;
cin >> s;
int len = (int) s.size();
vector<int> nxt(len + 1);
for (int i = len - 2; i >= 0; i--) {
if (s[i] != s[i + 1]) {
nxt[i] = i + 1;
} else {
nxt[i] = nxt[i + 1];
}
}
vector<vector<int>> txn(len + 1, vector<int>(26, len));
for (int i = len - 1; i >= 0; i--) {
txn[i] = txn[i + 1];
txn[i][(char) (s[i] - 'a')] = i;
}
int tt;
cin >> tt;
while (tt--) {
int from, to;
cin >> from >> to;
--from; --to;
if (to - from + 1 == 1) {
cout << "Yes" << '\n';
continue;
}
if (nxt[from] > to) {
cout << "No" << '\n';
continue;
}
if (s[from] != s[to]) {
cout << "Yes" << '\n';
continue;
}
int cnt = 0;
for (int c = 0; c < 26; c++) {
cnt += (txn[from][c] <= to);
}
if (cnt >= 3) {
cout << "Yes" << '\n';
continue;
}
cout << "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"
] | #line 1 "library/my_template.hpp"
#if defined(LOCAL)
#include <my_template_compiled.hpp>
#else
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) \
vector<vector<vector<type>>> name( \
h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name( \
a, vector<vector<vector<type>>>( \
b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c))
#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)
#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) \
overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)
#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define stoi stoll
template <typename T, typename U>
T SUM(const vector<U> &A) {
T sum = 0;
for (auto &&a: A) sum += a;
return sum;
}
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#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 UNIQUE(x) \
sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
template <typename T>
T pick(deque<T> &que) {
T a = que.front();
que.pop_front();
return a;
}
template <typename T>
T pick(pq<T> &que) {
T a = que.top();
que.pop();
return a;
}
template <typename T>
T pick(pqg<T> &que) {
assert(que.size());
T a = que.top();
que.pop();
return a;
}
template <typename T>
T pick(vc<T> &que) {
assert(que.size());
T a = que.back();
que.pop_back();
return a;
}
template <typename T, typename U>
T ceil(T x, U y) {
return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U>
T floor(T x, U y) {
return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
T q = floor(x, y);
return {q, x - q * y};
}
template <typename F>
ll binary_search(F check, ll ok, ll ng) {
assert(check(ok));
while (abs(ok - ng) > 1) {
auto x = (ng + ok) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return ok;
}
template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
FOR(iter) {
double x = (ok + ng) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return (ok + ng) / 2;
}
template <class T, class S>
inline bool chmax(T &a, const S &b) {
return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
return (a > b ? a = b, 1 : 0);
}
vc<int> s_to_vi(const string &S, char first_char) {
vc<int> A(S.size());
FOR(i, S.size()) { A[i] = S[i] - first_char; }
return A;
}
template <typename T, typename U>
vector<T> cumsum(vector<U> &A, int off = 1) {
int N = A.size();
vector<T> B(N + 1);
FOR(i, N) { B[i + 1] = B[i] + A[i]; }
if (off == 0) B.erase(B.begin());
return B;
}
template <typename CNT, typename T>
vc<CNT> bincount(const vc<T> &A, int size) {
vc<CNT> C(size);
for (auto &&x: A) { ++C[x]; }
return C;
}
// stable
template <typename T>
vector<int> argsort(const vector<T> &A) {
vector<int> ids(A.size());
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
return ids;
}
// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
int n = len(I);
vc<T> B(n);
FOR(i, n) B[i] = A[I[i]];
return B;
}
#endif
#line 1 "library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace fastio {
// クラスが read(), print() を持っているかを判定するメタ関数
struct has_write_impl {
template <class T>
static auto check(T &&x) -> decltype(x.write(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_write : public decltype(has_write_impl::check<T>(std::declval<T>())) {
};
struct has_read_impl {
template <class T>
static auto check(T &&x) -> decltype(x.read(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_read : public decltype(has_read_impl::check<T>(std::declval<T>())) {};
struct Scanner {
FILE *fp;
char line[(1 << 15) + 1];
size_t st = 0, ed = 0;
void reread() {
memmove(line, line + st, ed - st);
ed -= st;
st = 0;
ed += fread(line + ed, 1, (1 << 15) - ed, fp);
line[ed] = '\0';
}
bool succ() {
while (true) {
if (st == ed) {
reread();
if (st == ed) return false;
}
while (st != ed && isspace(line[st])) st++;
if (st != ed) break;
}
if (ed - st <= 50) {
bool sep = false;
for (size_t i = st; i < ed; i++) {
if (isspace(line[i])) {
sep = true;
break;
}
}
if (!sep) reread();
}
return true;
}
template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
while (true) {
size_t sz = 0;
while (st + sz < ed && !isspace(line[st + sz])) sz++;
ref.append(line + st, sz);
st += sz;
if (!sz || st != ed) break;
reread();
}
return true;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
bool neg = false;
if (line[st] == '-') {
neg = true;
st++;
}
ref = T(0);
while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
if (neg) ref = -ref;
return true;
}
template <typename T,
typename enable_if<has_read<T>::value>::type * = nullptr>
inline bool read_single(T &x) {
x.read();
return true;
}
bool read_single(double &ref) {
string s;
if (!read_single(s)) return false;
ref = std::stod(s);
return true;
}
bool read_single(char &ref) {
string s;
if (!read_single(s) || s.size() != 1) return false;
ref = s[0];
return true;
}
template <class T>
bool read_single(vector<T> &ref) {
for (auto &d: ref) {
if (!read_single(d)) return false;
}
return true;
}
template <class T, class U>
bool read_single(pair<T, U> &p) {
return (read_single(p.first) && read_single(p.second));
}
template <size_t N = 0, typename T>
void read_single_tuple(T &t) {
if constexpr (N < std::tuple_size<T>::value) {
auto &x = std::get<N>(t);
read_single(x);
read_single_tuple<N + 1>(t);
}
}
template <class... T>
bool read_single(tuple<T...> &tpl) {
read_single_tuple(tpl);
return true;
}
void read() {}
template <class H, class... T>
void read(H &h, T &... t) {
bool f = read_single(h);
assert(f);
read(t...);
}
Scanner(FILE *fp) : fp(fp) {}
};
struct Printer {
Printer(FILE *_fp) : fp(_fp) {}
~Printer() { flush(); }
static constexpr size_t SIZE = 1 << 15;
FILE *fp;
char line[SIZE], small[50];
size_t pos = 0;
void flush() {
fwrite(line, 1, pos, fp);
pos = 0;
}
void write(const char val) {
if (pos == SIZE) flush();
line[pos++] = val;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
void write(T val) {
if (pos > (1 << 15) - 50) flush();
if (val == 0) {
write('0');
return;
}
if (val < 0) {
write('-');
val = -val; // todo min
}
size_t len = 0;
while (val) {
small[len++] = char(0x30 | (val % 10));
val /= 10;
}
for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
pos += len;
}
void write(const string s) {
for (char c: s) write(c);
}
void write(const char *s) {
size_t len = strlen(s);
for (size_t i = 0; i < len; i++) write(s[i]);
}
void write(const double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
void write(const long double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
template <typename T,
typename enable_if<has_write<T>::value>::type * = nullptr>
inline void write(T x) {
x.write();
}
template <class T>
void write(const vector<T> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
template <class T, class U>
void write(const pair<T, U> val) {
write(val.first);
write(' ');
write(val.second);
}
template <size_t N = 0, typename T>
void write_tuple(const T t) {
if constexpr (N < std::tuple_size<T>::value) {
if constexpr (N > 0) { write(' '); }
const auto x = std::get<N>(t);
write(x);
write_tuple<N + 1>(t);
}
}
template <class... T>
bool write(tuple<T...> tpl) {
write_tuple(tpl);
return true;
}
template <class T, size_t S>
void write(const array<T, S> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
void write(i128 val) {
string s;
bool negative = 0;
if (val < 0) {
negative = 1;
val = -val;
}
while (val) {
s += '0' + int(val % 10);
val /= 10;
}
if (negative) s += "-";
reverse(all(s));
if (len(s) == 0) s = "0";
write(s);
}
};
Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);
void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
printer.write(head);
if (sizeof...(Tail)) printer.write(' ');
print(forward<Tail>(tail)...);
}
void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
scanner.read(head);
read(tail...);
}
} // namespace fastio
using fastio::print;
using fastio::flush;
using fastio::read;
#define INT(...) \
int __VA_ARGS__; \
read(__VA_ARGS__)
#define LL(...) \
ll __VA_ARGS__; \
read(__VA_ARGS__)
#define STR(...) \
string __VA_ARGS__; \
read(__VA_ARGS__)
#define CHAR(...) \
char __VA_ARGS__; \
read(__VA_ARGS__)
#define DBL(...) \
double __VA_ARGS__; \
read(__VA_ARGS__)
#define VEC(type, name, size) \
vector<type> name(size); \
read(name)
#define VV(type, name, h, w) \
vector<vector<type>> name(h, vector<type>(w)); \
read(name)
void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 2 "library/graph/base.hpp"
template <typename T>
struct Edge {
int frm, to;
T cost;
int id;
};
template <typename T = int, bool directed = false>
struct Graph {
int N, M;
using cost_type = T;
using edge_type = Edge<T>;
vector<edge_type> edges;
vector<int> indptr;
vector<edge_type> csr_edges;
vc<int> vc_deg, vc_indeg, vc_outdeg;
bool prepared;
class OutgoingEdges {
public:
OutgoingEdges(const Graph* G, int l, int r) : G(G), l(l), r(r) {}
const edge_type* begin() const {
if (l == r) { return 0; }
return &G->csr_edges[l];
}
const edge_type* end() const {
if (l == r) { return 0; }
return &G->csr_edges[r];
}
private:
const Graph* G;
int l, r;
};
bool is_prepared() { return prepared; }
constexpr bool is_directed() { return directed; }
Graph() : N(0), M(0), prepared(0) {}
Graph(int N) : N(N), M(0), prepared(0) {}
void resize(int n) { N = n; }
void add(int frm, int to, T cost = 1, int i = -1) {
assert(!prepared);
assert(0 <= frm && 0 <= to && to < N);
if (i == -1) i = M;
auto e = edge_type({frm, to, cost, i});
edges.eb(e);
++M;
}
// wt, off
void read_tree(bool wt = false, int off = 1) { read_graph(N - 1, wt, off); }
void read_graph(int M, bool wt = false, int off = 1) {
for (int m = 0; m < M; ++m) {
INT(a, b);
a -= off, b -= off;
if (!wt) {
add(a, b);
} else {
T c;
read(c);
add(a, b, c);
}
}
build();
}
void read_parent(int off = 1) {
for (int v = 1; v < N; ++v) {
INT(p);
p -= off;
add(p, v);
}
build();
}
void build() {
assert(!prepared);
prepared = true;
indptr.assign(N + 1, 0);
for (auto&& e: edges) {
indptr[e.frm + 1]++;
if (!directed) indptr[e.to + 1]++;
}
for (int v = 0; v < N; ++v) { indptr[v + 1] += indptr[v]; }
auto counter = indptr;
csr_edges.resize(indptr.back() + 1);
for (auto&& e: edges) {
csr_edges[counter[e.frm]++] = e;
if (!directed)
csr_edges[counter[e.to]++] = edge_type({e.to, e.frm, e.cost, e.id});
}
}
OutgoingEdges operator[](int v) const {
assert(prepared);
return {this, indptr[v], indptr[v + 1]};
}
vc<int> deg_array() {
if (vc_deg.empty()) calc_deg();
return vc_deg;
}
pair<vc<int>, vc<int>> deg_array_inout() {
if (vc_indeg.empty()) calc_deg_inout();
return {vc_indeg, vc_outdeg};
}
int deg(int v) {
if (vc_deg.empty()) calc_deg();
return vc_deg[v];
}
int in_deg(int v) {
if (vc_indeg.empty()) calc_deg_inout();
return vc_indeg[v];
}
int out_deg(int v) {
if (vc_outdeg.empty()) calc_deg_inout();
return vc_outdeg[v];
}
void debug() {
print("Graph");
if (!prepared) {
print("frm to cost id");
for (auto&& e: edges) print(e.frm, e.to, e.cost, e.id);
} else {
print("indptr", indptr);
print("frm to cost id");
FOR(v, N) for (auto&& e: (*this)[v]) print(e.frm, e.to, e.cost, e.id);
}
}
private:
void calc_deg() {
assert(vc_deg.empty());
vc_deg.resize(N);
for (auto&& e: edges) vc_deg[e.frm]++, vc_deg[e.to]++;
}
void calc_deg_inout() {
assert(vc_indeg.empty());
vc_indeg.resize(N);
vc_outdeg.resize(N);
for (auto&& e: edges) { vc_indeg[e.to]++, vc_outdeg[e.frm]++; }
}
};
#line 2 "library/graph/centroid.hpp"
template <typename GT>
vc<int> find_centroids(GT& G) {
int N = G.N;
vc<int> par(N, -1);
vc<int> V(N);
vc<int> sz(N);
int l = 0, r = 0;
V[r++] = 0;
while (l < r) {
int v = V[l++];
for (auto&& e: G[v])
if (e.to != par[v]) {
par[e.to] = v;
V[r++] = e.to;
}
}
FOR_R(i, N) {
int v = V[i];
sz[v] += 1;
int p = par[v];
if (p != -1) sz[p] += sz[v];
}
int M = N / 2;
auto check = [&](int v) -> bool {
if (N - sz[v] > M) return false;
for (auto&& e: G[v]) {
if (e.to != par[v] && sz[e.to] > M) return false;
}
return true;
};
vc<int> ANS;
FOR(v, N) if (check(v)) ANS.eb(v);
return ANS;
}
template <typename GT>
struct Centroid_Decomposition {
using edge_type = typename GT::edge_type;
GT& G;
int N;
vc<int> sz;
vc<int> par;
vector<int> cdep; // depth in centroid tree
bool calculated;
Centroid_Decomposition(GT& G)
: G(G), N(G.N), sz(G.N), par(G.N), cdep(G.N, -1) {
calculated = 0;
build();
}
private:
int find(int v) {
vc<int> V = {v};
par[v] = -1;
int p = 0;
while (p < len(V)) {
int v = V[p++];
sz[v] = 0;
for (auto&& e: G[v]) {
if (e.to == par[v] || cdep[e.to] != -1) continue;
par[e.to] = v;
V.eb(e.to);
}
}
while (len(V)) {
int v = V.back();
V.pop_back();
sz[v] += 1;
if (p - sz[v] <= p / 2) return v;
sz[par[v]] += sz[v];
}
return -1;
}
void build() {
assert(G.is_prepared());
assert(!G.is_directed());
assert(!calculated);
calculated = 1;
vc<pair<int, int>> st;
st.eb(0, 0);
while (!st.empty()) {
auto [lv, v] = st.back();
st.pop_back();
auto c = find(v);
cdep[c] = lv;
for (auto&& e: G[c]) {
if (cdep[e.to] == -1) { st.eb(lv + 1, e.to); }
}
}
}
public:
/*
root を重心とする木において、(v, path data v) の vector
を、方向ごとに集めて返す ・0 番目:root からのパスすべて(root を含む)
・i番目:i 番目の方向
f: E x edge -> E
*/
template <typename E, typename F>
vc<vc<pair<int, E>>> collect(int root, E root_val, F f) {
vc<vc<pair<int, E>>> res = {{{root, root_val}}};
for (auto&& e: G[root]) {
int nxt = e.to;
if (cdep[nxt] < cdep[root]) continue;
vc<pair<int, E>> dat;
int p = 0;
dat.eb(nxt, f(root_val, e));
par[nxt] = root;
while (p < len(dat)) {
auto [v, val] = dat[p++];
for (auto&& e: G[v]) {
if (e.to == par[v]) continue;
if (cdep[e.to] < cdep[root]) continue;
par[e.to] = v;
dat.eb(e.to, f(val, e));
}
}
res.eb(dat);
res[0].insert(res[0].end(), all(dat));
}
return res;
}
vc<vc<pair<int, int>>> collect_dist(int root) {
auto f = [&](int x, auto e) -> int { return x + 1; };
return collect(root, 0, f);
}
// (V, H), V[i] は、H における頂点 i の G における番号
// 頂点は EulerTour 順に並ぶ
pair<vc<int>, Graph<typename GT::cost_type, true>> get_subgraph(int root) {
static vc<int> conv;
while (len(conv) < N) conv.eb(-1);
vc<int> V;
using cost_type = typename GT::cost_type;
vc<tuple<int, int, cost_type>> edges;
auto dfs = [&](auto& dfs, int v, int p) -> void {
conv[v] = len(V);
V.eb(v);
for (auto&& e: G[v]) {
int to = e.to;
if (to == p) continue;
if (cdep[to] < cdep[root]) continue;
dfs(dfs, to, v);
edges.eb(conv[v], conv[to], e.cost);
}
};
dfs(dfs, root, -1);
int n = len(V);
Graph<typename GT::cost_type, true> H(n);
for (auto&& [a, b, c]: edges) H.add(a, b, c);
H.build();
for (auto&& v: V) conv[v] = -1;
return {V, H};
}
};
#line 1 "library/convex/cht.hpp"
template <typename T>
struct Line {
mutable T k, m, p;
bool operator<(const Line& o) const { return k < o.k; }
bool operator<(T x) const { return p < x; }
};
template <typename T>
T lc_inf() {
return numeric_limits<T>::max();
}
template <>
long double lc_inf<long double>() {
return 1 / .0;
}
template <typename T>
T lc_div(T a, T b) {
return a / b - ((a ^ b) < 0 and a % b);
}
template <>
long double lc_div(long double a, long double b) {
return a / b;
};
template <>
double lc_div(double a, double b) {
return a / b;
};
template <typename T, bool MINIMIZE = true>
struct LineContainer : multiset<Line<T>, less<>> {
using super = multiset<Line<T>, less<>>;
using super::begin, super::end, super::insert, super::erase;
using super::empty, super::lower_bound;
const T inf = lc_inf<T>();
bool insect(typename super::iterator x, typename super::iterator y) {
if (y == end()) return x->p = inf, false;
if (x->k == y->k)
x->p = (x->m > y->m ? inf : -inf);
else
x->p = lc_div(y->m - x->m, x->k - y->k);
return x->p >= y->p;
}
void add(T k, T m) {
if (MINIMIZE) { k = -k, m = -m; }
auto z = insert({k, m, 0}), y = z++, x = y;
while (insect(y, z)) z = erase(z);
if (x != begin() and insect(--x, y)) insect(x, y = erase(y));
while ((y = x) != begin() and (--x)->p >= y->p) insect(x, erase(y));
}
T query(T x) {
assert(!empty());
auto l = *lower_bound(x);
T v = (l.k * x + l.m);
return (MINIMIZE ? -v : v);
}
};
template <typename T>
using CHT_min = LineContainer<T, true>;
template <typename T>
using CHT_max = LineContainer<T, false>;
/*
long long / double で動くと思う。クエリあたり O(log N)
・add(a, b):ax + by の追加
・get_max(x,y):max_{a,b} (ax + by)
・get_min(x,y):max_{a,b} (ax + by)
*/
template <typename T>
struct CHT_xy {
using ld = long double;
CHT_min<ld> cht_min;
CHT_max<ld> cht_max;
T amax = -1e18, amin = 1e18, bmax = -1e18, bmin = 1e18;
void add(T a, T b) {
cht_min.add(b, a);
cht_max.add(b, a);
chmax(amax, a), chmin(amin, a), chmax(bmax, b), chmin(bmin, b);
}
T get_max(T x, T y) {
if (x == 0) { return max(bmax * y, bmin * y); }
ld z = ld(y) / x;
if (x > 0) {
auto l = cht_max.lower_bound(z);
ll a = l->m, b = l->k;
return a * x + b * y;
}
auto l = cht_min.lower_bound(z);
ll a = -(l->m), b = -(l->k);
return a * x + b * y;
}
T get_min(T x, T y) { return -get_max(-x, -y); }
};
#line 5 "main.cpp"
void solve() {
LL(N);
Graph<bool, 0> G(N);
G.read_tree();
VEC(ll, A, N);
Centroid_Decomposition<decltype(G)> X(G);
ll ANS = 0;
auto solve = [&](Graph<bool, 1> G, vi A) -> void {
/*
各頂点について、根を含むものについて
・根からの距離 D[v]
・A[v] の和
・A[v]D[v] の和
*/
const int N = len(A);
vi D(N), dp(N), dp1(N);
{
auto dfs = [&](auto& dfs, int d, int v, int p) -> void {
D[v] = d;
dp[v] = (v == 0 ? 0 : dp[p]) + A[v];
dp1[v] = (v == 0 ? 0 : dp1[p]) + A[v] * D[v];
for (auto&& e: G[v]) dfs(dfs, d + 1, e.to, v);
};
dfs(dfs, 0, 0, -1);
}
// 根を含むパスに対する答の計算
FOR(v, N) {
// 根から
chmax(ANS, dp1[v] + dp[v]);
// 根に向かって
chmax(ANS, (D[v] + 1) * dp[v] - dp1[v]);
}
// 方向ごとに頂点を集める
vvc<int> vs;
for (auto&& e: G[0]) {
vc<int> V;
auto dfs = [&](auto& dfs, int v) -> void {
V.eb(v);
for (auto&& e: G[v]) dfs(dfs, e.to);
};
dfs(dfs, e.to);
vs.eb(V);
}
// (D[u]+1)dp[u] - dp1[u] - (D[u]+1)A[0] + (D[u]+1)dp[v] + dp1[v]
// u を固定すると、a[u] dp[v] + b[u] + dp1[v] の形
FOR(2) {
reverse(all(vs));
CHT_max<ll> cht;
for (auto&& V: vs) {
// 計算
for (auto&& v: V) {
if (cht.empty()) break;
ll y = cht.query(dp[v]) + dp1[v];
chmax(ANS, y);
}
// 直線追加
for (auto&& u: V) {
ll a = D[u] + 1;
ll b = (D[u] + 1) * dp[u] - dp1[u] - (D[u] + 1) * A[0];
cht.add(a, b);
}
}
}
};
FOR(v, N) {
auto [V, H] = X.get_subgraph(v);
vi B(len(V));
FOR(i, len(V)) B[i] = A[V[i]];
solve(H, B);
}
print(ANS);
}
signed main() {
solve();
return 0;
}
| cpp |
1307 | F | F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n) — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105) — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi) — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
OutputCopyYES
YES
NO
InputCopy8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
OutputCopyYES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below. | [
"dfs and similar",
"dsu",
"trees"
] | #include<bits/stdc++.h>
#define Mx 18
using namespace std;
int n,k,r,tot,edge_t=0,Q;
int la[400002],rt[400002],col[400002],dep[400002];
int fa[400002][22];
vector<int> vec[200002];
typedef pair<int,int> P;P p;
queue<P> q;
struct aaa
{
int to,nx;
}edge[800002];
inline void add_edge(int x,int y)
{
edge[++edge_t]=(aaa){y,la[x]},la[x]=edge_t;
edge[++edge_t]=(aaa){x,la[y]},la[y]=edge_t;
}
inline void getroot(int x)
{
if(rt[x]==x)return ;
getroot(rt[x]),rt[x]=rt[rt[x]];
}
inline void dfs(int x,int f)
{
for(int i=0,v;i<vec[x].size();++i)if((v=vec[x][i])!=f)add_edge(x,++tot),add_edge(tot,v),dep[v]=(dep[tot]=dep[fa[fa[v][0]=tot][0]=x]+1)+1,dfs(v,x);
}
inline void get_LCA()
{
for(int i=1;i<=Mx;++i)
for(int j=1;j<=tot;++j)
fa[j][i]=fa[fa[j][i-1]][i-1];
}
inline int LCA(int x,int y)
{
if(dep[x]<dep[y])swap(x,y);
for(int i=Mx;~i;--i)
if(dep[fa[x][i]]>=dep[y])
x=fa[x][i];
if(x==y)return x;
for(int i=Mx;~i;--i)
if(fa[x][i]!=fa[y][i])
x=fa[x][i],y=fa[y][i];
return fa[x][0];
}
int main()
{
scanf("%d%d%d",&n,&k,&r),tot=n;
for(int i=1,x,y;i<n;++i)scanf("%d%d",&x,&y),vec[x].push_back(y),vec[y].push_back(x);
dfs(dep[1]=1,0),get_LCA();
for(int i=1,x;i<=r;++i)scanf("%d",&x),q.push(P(rt[x]=col[x]=x,0));
for(;!q.empty();)
{
p=q.front(),q.pop(),getroot(col[p.first]);
for(int i=la[p.first],v;i;i=edge[i].nx)
{
if(!col[v=edge[i].to])
{
col[v]=col[p.first];
if(p.second+1<k)q.push(P(v,p.second+1));
}
else getroot(col[v]),rt[rt[col[v]]]=rt[col[p.first]];
}
}
for(int i=1;i<=n;++i)if(rt[i])getroot(i);
for(int i=1;i<=tot;++i)if(col[i] && rt[col[i]]!=col[i])col[i]=rt[col[i]];
scanf("%d",&Q);
for(int x,y,z;Q--;)
{
scanf("%d%d",&x,&y);
if(dep[x]+dep[y]-2*dep[z=LCA(x,y)]<=2*k)
{
puts("YES");
continue;
}
if(dep[x]-dep[z]<k)swap(x,y);
for(int i=Mx;~i;--i)if((k>>i)&1)x=fa[x][i];
if(dep[y]-dep[z]<k)z=dep[x]+dep[y]-2*dep[z]-k,y=x;
else z=k;
for(int i=Mx;~i;--i)if((z>>i)&1)y=fa[y][i];
puts((col[x] && col[x]==col[y])? "YES":"NO");
}
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;
typedef long long ll;
typedef vector <int> vi;
typedef vector <string> vs;
typedef pair <int, int> pii;
typedef vector<pii > vpii;
#define MP make_pair
#define F first
#define S second
#define REVERSE(a) reverse (a.begin(), a.end())
#define ALL(a) a.begin(), a.end()
#define ms(x,y) memset (x, y, sizeof (x))
#define pb push_back
#define debug(a,b) cout<<a<<": "<<b<<endl
#define Debug cout<<"Reached here"<<endl
#define prnt(a) cout<<a<<"\n"
#define VecPrnt(v) for(auto i: v) cout<<i<<" "; cout<<endl
#define endl "\n"
#define PrintPair(x) cout<<x.first<<" "<<x.second<<endl
#define ArrPrint(a,st,en) for(int J=st; J<=en; J++) cout<<a[J]<<" "; cout<<endl;
/* Direction Array */
// int fx[]={1,-1,0,0};
// int fy[]={0,0,1,-1};
// int fx[]={0,0,1,-1,-1,1,-1,1};
// int fy[]={-1,1,0,0,1,1,-1,-1};
const int maxn = 2e5+10;
int n, maxh, maxh2, l, mx[2], mark[maxn], hi[maxn];
vi adj[maxn];
vi p;
vi path;
queue<int> q;
void dfs(int v, int par, int h, int t, int en)
{
p.pb(v);
if(v == en)
path = p;
if(h > maxh)
mx[t] = v, maxh = h;
for(int u: adj[v])
if(u!=par)
dfs(u, v, h+1, t, en);
p.pop_back();
}
void bfs()
{
for(int i: path)
{
q.push(i);
mark[i] = 1 , hi[i] = 0;
}
while(q.size()>0)
{
int v = q.front();
q.pop();
for(int u: adj[v])
{
if(!mark[u])
{
mark[u] = 1;
q.push(u);
hi[u] = hi[v] + 1;
if(hi[u]>maxh2)
{
maxh2 = hi[u];
l = u;
}
}
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL); cout.tie(NULL);
cin >> n;
for(int u, v, i = 1; i < n; i++)
{
cin >> u >> v;
adj[v].pb(u);
adj[u].pb(v);
}
maxh = 0;
dfs(1, -1, 0, 0, n+1);
maxh = 0;
dfs(mx[0], -1, 0, 1, n+1);
if(maxh == n-1)
for(int i = 1; i <= n; i++)
if(i != mx[0] && i != mx[1])
{
prnt(maxh);
cout << mx[0] << " " << mx[1] << " " << i;
return 0;
}
p.clear();
path.clear();
// debug(mx[0], mx[1]);
dfs(mx[0], -1, 0, 2, mx[1]);
maxh2 = 0;
bfs();
prnt(maxh + maxh2);
cout << mx[0] << " " << mx[1] << " " << l << endl;
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"
] | #include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
typedef long long ll;
#define vi vector<int>
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
double a=0;
int n;
cin>>n;
for(int i=1;i<=n;i++) a=a+(double)1/i;
cout << fixed << setprecision(12) << a << endl;
return 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"
] | //NEWBIE CONTESTANT
// copy right © 12/2/2022 to ESLAM SAYED (ESLAM 7215) Educational DIV2--> 143
#include <bits/stdc++.h>
using namespace std ;
#define clo cout << "Time execute: " << clock() / (double)CLOCKS_PER_SEC << " sec" << endl;
#define NB iostream::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
#define OUT cout << setprecision(6) << fixed ;
#define ul unsigned long long
#define yes cout << "YES\n" ;
#define PI 3.14159265358979323846264338327
#define no cout << "NO\n" ;
#define all(ans) ans.begin() , ans.end()
#define allr(ans) ans.rbegin() , ans.rend()
#define N <<"\n" ;
#define S(c) string (1 , c)
const int MAX = 1e8 ;
typedef long long ll ;
typedef double long dll ;
using namespace std ;
const ll MOD = 1073741824 ;
template <typename t>
istream & operator >> (istream & in, vector<t> & es){
for (auto & i : es){
in >> i ;
}
return in ;
}
template<typename t>
istream & operator >> (vector<t> & es , int n){
t rr ;
for (int i = 0 ; i < n ; i++){
cin >> rr ;
es.push_back(rr) ;
}
}
ll gcd(ll a , ll b){
if (b == 0)
return a ;
return gcd(b , a % b ) ;
}
int lcm (long long a , long long b){
return a / gcd(a , b) * b ;
}
bool pal (string w ){
string ss = w;
reverse(ss.begin() , ss.end()) ;
if (w == ss)
return true;
else
return false;
}
bool isprime (ll a){
if (a == 1 || a == 0)
return false ;
if (a == 2)
return true ;
for (int i = 2 ; i <= sqrt(a) ; i++){
if (a % i == 0)
return false ;
}
return true ;
}
template <typename t>
ostream & operator << (ostream & out , vector<t> es){
for (auto i : es){
out << i << " ";
}
out N
return out ;
}
ll fact (ll num){
ll sum = 1 ;
for (ll i = 2 ; i <= num ; i++){
sum *= i ;
}
return sum ;
}
bool check (map<char , ll>mp , ll k){
bool r = true ;
ll ch = 0;
ll e = 0 ;
for (auto i : mp){
e ++ ;
if (r) {
ch = i.second;
r = false ;
}else if (i.second != ch){
return false ;
}
}
if (e == k) {
return true;
}else {
return false ;
}
}
bool is (int n){
string r = to_string(n) ;
int e = r.size() ;
for (int i = 0 ; i < e ; i++){
if (r[i] != '7' && r[i] != '4'){
return false ;
}
}
return true;
}
string binary (int n , int k){
string w ;
while (n > 0){
if (n % 2 == 0){
w += '0' ;
}else {
w += '1' ;
}
n /= 2 ;
}
while (w.size() < k){
w += '0' ;
}
reverse(all(w)) ;
return w ;
}
/*to isolate the primes from 1 to n*/
//for (ll i = 2 ; i * i < 1000001 ; i++){
// if (!es[i]){
// for (ll j = i + i ; j < 1000001 ; j += i)
// es[j] = true ;
// }
//}
//for (int i = 2 ; i < es.size() ; i++){
// if (!es[i]){
// cout << i << " " ;
// }
//}
vector<string>ww ;
void sol (string w , int i ){
if (i == 1){
string qq , q;
for (int j = 0 ; j < w.length() ; j++){
if (w[j] == 'A'){
qq += '(' ;
q += ')' ;
}else {
qq += w[j] ;
q += w[j];
}
}
sol(qq , i + 1) ;
sol (q , i + 1) ;
}
else if (i == 2){
string qq , q;
for (int j = 0 ; j < w.length() ; j++){
if (w[j] == 'B'){
qq += '(' ;
q += ')' ;
}else {
qq += w[j] ;
q += w[j];
}
}
sol(qq , i + 1) ;
sol (q , i + 1) ;
}
else if (i == 3){
string qq , q;
for (int j = 0 ; j < w.length() ; j++){
if (w[j] == 'C'){
qq += '(' ;
q += ')' ;
}else {
qq += w[j] ;
q += w[j];
}
}
if (qq[0] != qq[qq.length() - 1 ]) {
ww.push_back(qq);
}
if (q[0] != q[q.length() - 1] ) {
ww.push_back(q);
}
sol(qq , i + 1) ;
sol (q , i + 1) ;
}else
return;
}
vector<ll> taken (10000) ;
ll fib (ll n , int a){
if (a == n + 1 ){
return taken[n ] ;
}
if (a == 0) {
taken[a] = 0;
return fib(n, a + 1);
}
else if (a == 1) {
taken[a] = 1;
return fib(n, a + 1);
}else {
taken[a] = taken[a - 1] + taken[a - 2] ;
return fib(n , a + 1) ;
}
}
//vector<int>os {1 , 2 , 3};
//vector<int>ans ;
//int y = 0 ;
//void sol (string w){
// if (w.length() == 5){
// cout << w N
// y ++ ;
// return;
// }
// sol(w + "R") ;
// sol(w + "G") ;
// sol(w + "Y") ;
// sol(w + "E") ;
//}
ll div (ll n){
double tt = sqrt(n) ;
set<ll>st ;
for (int i = 1 ; i <= tt ; i++){
if (n % i == 0){
st.insert(i) ;
st.insert(n / i) ;
}
}
return st.size() ;
}
//bool fun (ll n , vector<ll>es , vector<ll>os ){
// ll st = 1e9 , sr = 0 ;
// for (auto i : os){
// ll tt = i + n , ttt = i - n ;
// ll l = -1 , r = es.size() ;
// ll fs , sn;
// while (l < r - 1){
// ll mm = (l + r ) / 2 ;
// if (es[mm] <= tt){
// l = mm ;
// }else {
// r = mm ;
// }
// }
// fs = l ;
// l = -1 ; r = es.size() ;
// while (l < r - 1){
// ll mm = (l + r ) / 2 ;
// if (es[mm] < ttt){
// l = mm ;
// }else {
// r = mm ;
// }
// }
// sn = r ;
// if (min(sn , fs) > sr){
// if (abs(min(fs , sn) - sr) == 1){
// }else {
// return false ;
// }
// }
// st = min(st , sn) ;
// sr = max(sr , fs) ;
// }
// if (st == 0 && sr >= es.size() - 1)
// return true ;
// else
// return false ;
//}
//void sol (){
// ll n , m ;
// cin >> n >> m ;
// unordered_map<ll , ll> aa , rr;
// vector<ll>es , os;
// for (int i = 0 ; i < n ; i++){
// ll y ;
// cin >> y;
// if (aa[y] == 0){
// es.push_back(y) ;
// aa[y] = 1 ;
// }
// }
// ll minss = 4e9 ;
// for (int i = 0 ; i < m ; i++){
// ll y ;
// cin >> y;
// if (rr[y] == 0){
// os.push_back(y) ;
// rr[y] = 1 ;
// if (n == 1){
// minss = min(minss , abs(y - es[0])) ;
// }
// }
// }
// if (n == 1) {
// cout << minss ;
// return ;
// }
// ll l = -1e9 , r = 4e9 + 10 ;
// while (l < r - 1){
// ll mm = (l + r) / 2 ;
// if (fun(mm , es , os)){
// r = mm ;
// }else {
// l = mm ;
// }
// }
// cout << abs(r) ;
//}
int main () {
NB
OUT
int t = 1 ;
cin >> t ;
while (t--){
ll n , d ;
cin >> n >> d ;
bool fl = true ;
if (n >= d)
yes
else {
for (ll i = 1; i < 100000; i++) {
ll aaa = i + d / (i + 1);
if (d % (i + 1) != 0) {
aaa++;
}
// cout << aaa N
if (aaa <= n) {
// cout << i N
fl = false;
yes
break;
}
}
if (fl)
no
}
// if (y <= n || rr <= n || rrr <= n || r <= n || a <= n){
// yes
// }else if (n >= d){
// yes
// }else
// no
}
}
| cpp |
1303 | F | F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10
2 1 1
1 2 1
2 2 1
1 1 2
3 1 2
1 2 2
2 2 2
2 1 2
3 2 4
2 1 5
OutputCopy2
4
3
3
4
4
4
2
2
4
| [
"dsu",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int n, m, q;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, -1, 0, 1};
vector <int> p, rk;
vector <vector <int> > A;
int get(int a)
{
if(p[a] == a)
{
return a;
}
else
{
return p[a] = get(p[a]);
}
}
bool unite(int a, int b)
{
a = get(a);
b = get(b);
if(a == b)
{
return false;
}
if(rk[a] < rk[b])
{
swap(a, b);
}
p[b] = a;
rk[a] += rk[b];
return true;
}
vector <vector <pair <int, int> > > add(2000010), del(2000010);
vector <int> dif(2e6 + 13);
void recalc(vector <pair <int, int> > &ev, int coeff)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
A[i][j] = 0;
}
}
for(int i = 0; i < n * m; i++)
{
p[i] = i;
rk[i] = 1;
}
for(int i = 0; i < ev.size(); i++)
{
int cur = 1;
int x = ev[i].first / m;
int y = ev[i].first % m;
A[x][y] = 1;
for(int k = 0; k < 4; k++)
{
int nx = dx[k] + x;
int ny = y + dy[k];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && A[nx][ny] == 1)
{
cur -= unite(nx * m + ny, x * m + y);
}
}
dif[ev[i].second] += cur * coeff;
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m >> q;
int colors = 1;
p.resize(n * m);
rk.resize(n * m);
A.resize(n, vector <int> (m));
for(int i = 0; i < q; i++)
{
int x, y, c;
cin >> x >> y >> c;
x--;
y--;
if(A[x][y] == c)
{
continue;
}
colors = c + 1;
add[c].push_back({x * m + y, i});
del[A[x][y]].push_back({x * m + y, i});
A[x][y] = c;
}
for(int x = 0; x < n; x++){
for(int y = 0; y < m; y++)
{
del[A[x][y]].push_back({x * m + y, q});
}
}
for(int i = 0; i < colors; i++)
{
reverse(del[i].begin(), del[i].end());
}
for(int i = 0; i < colors; i++)
{
recalc(add[i], 1);
}
for(int i = 0; i < colors; i++)
{
recalc(del[i], -1);
}
int cur = 1;
for(int i = 0; i < q; i++)
{
cur += dif[i];
cout << cur << "\n";
}
return 0;
} | cpp |
1299 | D | D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept. | [
"bitmasks",
"combinatorics",
"dfs and similar",
"dp",
"graphs",
"graphs",
"math",
"trees"
] | // LUOGU_RID: 100367685
#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<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int MX = 100005, mod = 1000000007;
#define s sum[x][y] = sum[y][x] =
int n, m, acu[MX], cn, vis[MX], sz, sum[400][400], b1[MX], b2[MX];
vii adj[MX];
vi base[MX], base2[MX];
bitset<MX> c1, valid, valid2;
int mem[MX][400], hsh[(1 << 25) + 5];
vector<vi> v;
bool add (vi &base, int x) {
forn(i, 5)
if (x & (1 << i))
x ^= base[i];
if (!x) return 0;
forn(i, 5)
if (!base[i] && (x & (1 << i))) {
base[i] = x;
forn(j, i)
if (base[j] & (1 << i))
base[j] ^= x;
break;
}
return 1;
}
void dfs (int u, int p, int w) {
acu[u] = w;
vis[u] = 1;
for (ii &v : adj[u]) {
if (v.fi == p) continue;
if (vis[v.fi] == 1) {
if (v.fi == 1) c1[cn] = 1;
else valid2[cn] = valid2[cn] & add(base2[cn], w ^ v.se ^ acu[v.fi]);
valid[cn] = valid[cn] & add(base[cn], w ^ v.se ^ acu[v.fi]);
} else if (!vis[v.fi]) {
dfs(v.fi, u, w ^ v.se);
}
}
vis[u] = 2;
}
int get (vi b) {
int pos = 0;
for (int y : b)
pos = 32 * pos + y;
if (hsh[pos] == -1) {
v.pb(b);
hsh[pos] = sz++;
}
return hsh[pos];
}
int dp (int i, int h) {
if (h == -1) return 0;
if (i == cn) return 1;
if (mem[i][h] != -1) return mem[i][h];
ll res = dp(i + 1, h);
if (valid[i])
res += dp(i + 1, sum[h][b1[i]]);
if (c1[i] && valid2[i])
res += 2 * dp(i + 1, sum[h][b2[i]]);
return mem[i][h] = res % mod;
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
memset(hsh, -1, sizeof(hsh));
memset(mem, -1, sizeof(mem));
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, w;
cin >> a >> b >> w;
adj[a].emplace_back(b, w);
adj[b].emplace_back(a, w);
}
get({0, 0, 0, 0, 0});
valid.set(), valid2.set();
vis[1] = 1;
for (ii &v : adj[1])
if (!vis[v.fi]) {
base[cn] = base2[cn] = vi(5);
dfs(v.fi, 1, v.se);
if (valid[cn])
b1[cn] = get(base[cn]);
if (c1[cn] && valid2[cn])
b2[cn] = get(base2[cn]);
cn++;
}
for (int i = 0; i < v.size(); i++) {
int x = get(v[i]);
for (int j = 0; j < v.size(); j++) {
int y = get(v[j]);
vi aux = v[i];
int f = 1;
for (int k : v[j])
if (k)
f &= add(aux, k);
if (f) s get(aux);
else s -1;
}
}
cout << dp(0, 0) << endl;
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 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);
string s;cin>>s;
vi v[26];
int n=s.length();
for(int i=0;i<n;i++){
v[s[i]-'a'].pb(i);
}
for(int i=0;i<26;i++){
if(v[i].size()!=0) sort(all(v[i]));
}
debug(v[1])
ll ans=1;
for(int i=0;i<26;i++){
if(v[i].size()==0) continue;
ans=max(ans,(ll)v[i].size());
for(int j=0;j<26;j++){
if(v[j].size()==0) continue;
ll temp=0;
for(int k=0;k<v[i].size();k++){
int ind=upper_bound(all(v[j]),v[i][k])-v[j].begin();
if(ind==v[j].size()) continue;
temp+=(v[j].size()-ind);
}
ans=max(ans,temp);
}
}
cout<<ans;
return 0;
}
| cpp |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — 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≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int n;
cin >> n;
int b[n];
for (int j = 0; j < 2; j++) {
for (int i=0; i<n; i++) cin>>b[i];
sort(b, b + n);
for (int k = 0; k < n; k++) cout<<b[k]<<" ";
printf("\n");
}
}
return 0;
}
| cpp |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | #include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
#include <functional>
#include <cassert>
using namespace std;
#define int long long
int gauss(int x)
{
return x*(x+1)/2;
}
void solve()
{
int n;
cin>>n;
vector<pair<int,int>>a(n);
for(auto &c:a)cin>>c.first;
for(auto &c:a)cin>>c.second;
sort(a.begin(),a.end());
int sum=0,rez=0;
priority_queue<int>q;
int acm=-1;
a.push_back({1e18,-1});
for(int i=0;i<=n;)
{
while(acm!=a[i].first && q.size())
{
sum-=q.top();
q.pop();
rez+=sum;
acm++;
}
acm=a[i].first;
while(a[i].first==acm)
{
sum+=a[i].second;
q.push(a[i].second);
i++;
}
}
cout<<rez;
}
main()
{
auto sol=[](bool x)->string
{
if(x)return "YES";
return "NO";
};
int tt=1;
//cin>>tt;
while(tt--)
{
solve();
cout<<'\n';
}
}
| cpp |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll euler_phi(ll n) {
ll ans = n;
for (ll i = 2; i * i <= n; i++)
if (n % i == 0) {
ans = ans / i * (i - 1);
while (n % i == 0)
n /= i;
}
if (n > 1)
ans = ans / n * (n - 1);
return ans;
}
auto solve() {
ll a, m;
cin >> a >> m;
ll x = gcd(a, m);
m /= x;
cout << euler_phi(m) << "\n";
}
auto main() -> int {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int _ = 1;
cin >> _;
while (_--) {
solve();
}
} | cpp |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences. | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | #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=2e5+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;
struct Node{
int fi,se;
bool flag;
bool operator < (const Node &k) const {
if(fi!=k.fi) return fi<k.fi;
else return se<k.se;
}
};
Node w[N];
int sum[N];
void solve() {
n=read();
int res=0;
for(int i=1;i<=n;i++) {
m=read();
int maxn=-1,minn=INF;
bool flag=false;
int last;
for(int j=1;j<=m;j++) {
int c=read();
if(j==1) last=c;
else if(j>=2) {
if(c>last) flag=true;
last=min(last,c);
}
maxn=max(maxn,c);
minn=min(minn,c);
}
if(flag) res++;
w[i]={minn,maxn,flag};
}
sort(w+1,w+1+n);
for(int i=1;i<=n;i++) {
if(w[i].flag) sum[i]=sum[i-1]+1;
else sum[i]=sum[i-1];
}
ll ans=0;
for(int i=1;i<=n;i++) {
if(w[i].flag) {
ans+=(ll)n;
continue;
}
int l=0,r=n;
while(l<r) {
int mid=l+r+1>>1;
if(w[mid].fi<w[i].se) l=mid;
else r=mid-1;
}
ans+=(ll)l-sum[l]+res;
}
printf("%lld\n",ans);
}
int main() {
// init();
// stin();
// scanf("%d",&T);
T=1;
while(T--) solve();
return 0;
}
| 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<bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define all(v) ((v).begin()), ((v).end())
#define rall(v) ((v).rbegin()), ((v).rend())
#define Py cout<<"YES"<<endl;
#define Pn cout<<"NO"<<endl;
#define oo 1e18+5
#define MOD ll(1e9+7)
//#define endl '\n'
#define fvec(i,vec) for(auto i:vec)
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
# define M_PI 3.14159265358979323846
#define int long long
#define foor(i,a,b) for (ll i = a; i < b; i++)
typedef long long ll;
typedef map<ll,ll> mapi;
typedef vector<ll> vi;
typedef vector<vi> vii;
typedef pair<ll,ll> pi;
typedef vector<pi> vip;
typedef vector<vip> viip;
typedef tree< pi, null_type, less<pi>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
ll gcd(ll a, ll b) { return ((b == 0) ? a : gcd(b, a % b)); }
ll lcm(ll a,ll b) {return (a * b) / gcd(a, b);}
void solve( ll h) {
ll n, m, k;
cin >> n >> m >> k;
vi freq(n + 10, 0);
vi freq2(m + 10, 0);
vi a, b;
ll con = 0;
vi div;
ll ans = 0;
for (int i = 0; i < n; ++i) {
ll x;
cin >> x;
if (x == 0) {
if (con != 0) {
freq[con]++;
if (freq[con] == 1)
a.push_back(con);
}
con = 0;
} else {
con++;
}
}
if (con != 0) {
freq[con]++;
if (freq[con] == 1)
a.push_back(con);
}
con = 0;
for (int i = 0; i < m; ++i) {
ll x;
cin >> x;
if (x == 0) {
if (con != 0) {
freq2[con]++;
if (freq2[con] == 1)
b.push_back(con);
}
con = 0;
} else {
con++;
}
}
if (con != 0) {
freq2[con]++;
if (freq2[con] == 1)
b.push_back(con);
}
for (int i = 1; i * i <= k; ++i) {
if (k % i == 0)div.push_back(i);
}
for (int i = 0; i < a.size(); ++i) {
for (int j = 0; j < b.size(); ++j) {
ll mul = freq[a[i]] * freq2[b[j]];
ll has = 0;
for (int l = 0; l < div.size(); ++l) {
ll fir = div[l];
ll sec = (k / div[l]);
if (fir <= a[i] && sec <= b[j]) {
has += (a[i] - fir + 1) * (b[j] - sec + 1);
}
if (fir <= b[j] && sec <= a[i] && (fir != sec)) {
has += (b[j] - fir + 1) * (a[i] - sec + 1);
}
}
ans += has * mul;
}
}
cout << ans << endl;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll t = 1;
//cin >> t;
cout << fixed << setprecision(9);
ll h = 1;
while (t--) {
solve(h++);
}
} | cpp |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS. | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] | #ifdef LOCAL
#define _GLIBCXX_DEBUG
#define _GLIBCXX_DEBUG_PEDANTIC
#endif
//#define NOGNU
#ifndef LOCAL
#pragma GCC optimize("Ofast")
#pragma GCC optimize("no-stack-protector")
#endif
#pragma GCC target("avx2")
// #pragma GCC target("sse4")
// #pragma GCC target("sse2")
#pragma GCC target("bmi2")
#pragma GCC target("popcnt")
#include <bits/stdc++.h>
#include <immintrin.h>
#ifdef IACA
#include <iacaMarks.h>
#else
#define IACA_START
#define IACA_END
#endif
// #define FILENAME "delivery"
#ifndef NOGNU
#include <ext/rope>
#include <ext/pb_ds/assoc_container.hpp>
#endif // NOGNU
#define lambda(body, ...) [&][[gnu::always_inline]](__VA_ARGS__) { return body; }
#define vlambda(body, ...) lambda(body, __VA_ARGS__ __VA_OPT__(,) auto&&...)
#define trans(...) views::transform(lambda(__VA_ARGS__))
#define vtrans(...) views::transform(vlambda(__VA_ARGS__))
#define all(x) (x).begin(), (x).end()
#define F first
#define S second
#define eb emplace_back
#define pb push_back
#define unires(x) x.resize(unique(all(x)) - x.begin())
#define ll long long
#define yesno(x) ((x) ? "YES" : "NO")
#ifdef LOCAL
#define assume assert
#define unreachable() abort()
#else
#ifdef NOGNU
#define assume(...)
#define unreachable()
#else
#define unreachable() __builtin_unreachable()
#define assume(...) if (!(__VA_ARGS__)) unreachable()
#endif
#endif
#define XCAT(x, y) x##y
#define CAT(x, y) XCAT(x, y)
#define MAKE_INT_TYPE_SHORTCUT(bits) \
using CAT(i, bits) = CAT(int, CAT(bits, _t)); \
using CAT(u, bits) = CAT(uint, CAT(bits, _t));
MAKE_INT_TYPE_SHORTCUT(8)
MAKE_INT_TYPE_SHORTCUT(16)
MAKE_INT_TYPE_SHORTCUT(32)
MAKE_INT_TYPE_SHORTCUT(64)
#undef MAKE_INT_TYPE_SHORTCUT
#ifndef NOGNU
using u128 = unsigned __int128;
using i128 = __int128;
using i_max = i128;
using u_max = u128;
#else
using i_max = i64;
using u_max = u64;
#endif
using ld = long double;
using pii = std::pair<int, int>;
using pll = std::pair<ll, ll>;
using puu = std::pair<u32, u32>;
using puu64 = std::pair<u64, u64>;
const unsigned ll M1 = 4294967291, M2 = 4294967279, M = 998244353;
#ifndef M_PI
const ld M_PI = acos(-1);
#endif // M_PI
using namespace std;
namespace rng = std::ranges;
#ifndef NOGNU
using namespace __gnu_cxx;
using namespace __gnu_pbds;
template<class K, class T, class Cmp = less<K>>
using ordered_map = tree<K, T, Cmp, rb_tree_tag, tree_order_statistics_node_update>;
template<class T, class Cmp = less<T>>
using ordered_set = ordered_map<T, null_type, Cmp>;
#endif
void run();
template<bool neg>
struct Inf {
constexpr Inf() {}
template<class T>
[[nodiscard, gnu::pure]] constexpr operator T() const requires(std::integral<T> || std::floating_point<T>) {
// No infinity for fast-math
if constexpr (neg) {
static_assert(is_signed_v<T>);
return numeric_limits<T>::min() / 2;
} else {
return numeric_limits<T>::max() / 2;
}
}
template<class T>
[[nodiscard, gnu::pure]] constexpr auto operator<=>(const T &x) const {
return (T) *this <=> x;
}
template<class T>
[[nodiscard, gnu::pure]] constexpr auto operator==(const T &x) const {
return (T) *this == x;
}
Inf &operator=(const Inf&) = delete;
Inf &operator=(Inf&&) = delete;
Inf(const Inf&) = delete;
Inf(Inf&&) = delete;
[[nodiscard]] Inf<!neg> operator-() const {
return {};
}
};
static Inf<0> inf;
template<class T1, class T2>
[[gnu::always_inline]] inline bool mini(T1 &&a, T2 &&b) {
if (a > b) {
a = b;
return 1;
}
return 0;
}
template<class T1, class T2>
[[gnu::always_inline]] inline bool maxi(T1 &&a, T2 &&b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
static mt19937 rnd(0);
signed main() {
#if defined FILENAME && !defined STDIO && !defined LOCAL
freopen(FILENAME".in", "r", stdin);
freopen(FILENAME".out", "w", stdout);
#endif // FILENAME
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef LOCAL
_mm_setcsr(_mm_getcsr() & ~(0x0080 | 0x0200));
#else
rnd.seed(random_device{}());
#endif
cout << setprecision(11) << fixed;
#ifdef PRINTTIME
auto start = clock();
#endif
run();
#ifdef PRINTTIME
cout << "\ntime = " << (double)(clock() - start) / CLOCKS_PER_SEC << "\n";
#endif
return 0;
}
#define rand rnd
template<class T>
struct is_tuple_like {
private:
static void detect(...);
template<class U>
static enable_if_t<(bool) tuple_size<U>::value, int> detect(const U&);
public:
static constexpr bool value = !is_same_v<decltype(detect(declval<remove_reference_t<T>>())), void>;
};
template<class T>
inline constexpr bool is_tuple_like_v = is_tuple_like<T>::value;
template<class T>
concept tuple_like = is_tuple_like_v<T>;
template<class Stream>
struct StreamWrapper {
Stream &stream;
[[gnu::always_inline]] StreamWrapper(Stream &stream): stream(stream) {}
[[gnu::always_inline]] operator Stream&() const {
return stream;
}
};
namespace std {
template<std::ranges::range T>
[[gnu::always_inline]] inline ostream &operator<<(StreamWrapper<ostream> wout, const T &arr) {
auto &out = wout.stream;
bool first = 1;
for (auto &&x : arr) {
if (!first) {
if constexpr (
(std::ranges::range<decltype(x)> &&
!is_same_v<decltype(x), string>)
|| is_tuple_like_v<decltype(x)>) {
out << '\n';
} else {
out << ' ';
}
} else {
first = 0;
}
out << x;
}
return out;
}
template<std::ranges::range T>
[[gnu::always_inline]] inline istream &operator>>(StreamWrapper<istream> win, T &arr) {
auto &in = win.stream;
for (auto &x : arr)
in >> x;
return in;
}
};
template<class T, size_t pos>
[[gnu::always_inline]] inline void read_tuple(istream &in, T &x) {
if constexpr (pos == tuple_size_v<T>)
return;
else {
in >> get<pos>(x);
read_tuple<T, pos + 1>(in, x);
}
}
template<class T, size_t pos>
[[gnu::always_inline]] inline void write_tuple(ostream &out, const T &x) {
if constexpr (pos == tuple_size_v<T>)
return;
else {
if constexpr (pos != 0)
out << " ";
out << get<pos>(x);
write_tuple<T, pos + 1>(out, x);
}
}
namespace std {
template<tuple_like T>
requires(!std::ranges::range<T>)
[[gnu::always_inline]] inline istream &operator>>(StreamWrapper<istream> in, T &x) {
read_tuple<T, 0>(in, x);
return in;
}
template<tuple_like T>
requires(!std::ranges::range<T>)
[[gnu::always_inline]] inline ostream &operator<<(StreamWrapper<ostream> out, const T &x) {
write_tuple<T, 0>(out, x);
return out;
}
};
template<std::integral Int>
[[gnu::always_inline]] inline auto range(Int n) {
return views::iota(static_cast<Int>(0), n);
}
template<std::integral Int1, std::integral Int2>
[[gnu::always_inline]] inline auto range(Int1 from, Int2 to) {
using T = std::common_type_t<Int1, Int2>;
return views::iota(static_cast<T>(from), static_cast<T>(to));
}
template<class T, class... Ts, class... Args>
[[gnu::always_inline]] inline auto input(Args&&... args) {
if constexpr (sizeof...(Ts) == 0) {
T x(forward<Args>(args)...);
cin >> x;
return x;
} else {
return input<tuple<T, Ts...>>(forward<Args>(args)...);
}
}
namespace segtree {
#ifdef LOCAL
#pragma GCC diagnostic ignored "-Winaccessible-base"
#endif
struct DoNothingFunc {
template<class... Args>
[[gnu::always_inline]] void operator()(Args&&... args) const {}
};
struct AssignFunc {
template<class T, class U, class... Args>
[[gnu::always_inline]] void operator()(T &x, U &&y, Args&&...) const {
x = forward<U>(y);
}
};
template<class F, class Res, class... Args>
[[gnu::always_inline]] inline
typename enable_if<
is_void_v<decltype(declval<F>()(declval<Res&>(), declval<Args>()...))>,
void
>::type
assign_or_call(F &f, Res &res, Args&&... args) {
f(res, forward<Args>(args)...);
}
template<class F, class Res, class... Args>
[[gnu::always_inline]] inline
typename enable_if<
!is_void_v<decltype(declval<F>()(declval<Args>()...))>,
void
>::type
assign_or_call(F &f, Res &res, Args&&... args) {
res = f(forward<Args>(args)...);
}
template<int priority, class calc_t, class recalc_t, class join_t, class Self>
struct PointUpdatePolicyType {
static constexpr int update_priority = priority;
static constexpr int init_priority = numeric_limits<int>::min();
[[no_unique_address]] calc_t calc;
[[no_unique_address]] recalc_t recalc;
[[no_unique_address]] join_t join;
template<class F, class Policy>
[[gnu::always_inline]] static auto select(Policy policy) {
if constexpr (is_default_constructible_v<F>)
return F();
else
return policy.template get<F>();
}
template<class Policy>
PointUpdatePolicyType(Policy policy)
: calc(select<calc_t>(policy))
, recalc(select<recalc_t>(policy))
, join(select<join_t>(policy)) {}
PointUpdatePolicyType(const PointUpdatePolicyType &) = default;
PointUpdatePolicyType(PointUpdatePolicyType &&) = default;
template<class... Args>
void upd_impl(size_t p, size_t v, size_t l, size_t r, Args&&... args) {
auto self = static_cast<Self *>(this);
self->push(v, l, r);
assign_or_call(recalc, self->get_val(self->a[v]), forward<Args>(args)..., l, r);
if (r - l == 1) {
assign_or_call(calc, self->get_val(self->a[v]), forward<Args>(args)..., l, r);
return;
}
size_t c = (l + r) / 2;
size_t left = self->get_left(v, l, r);
size_t right = self->get_right(v, l, r);
if (p < c)
upd_impl(p, left, l, c, forward<Args>(args)...);
else
upd_impl(p, right, c, r, forward<Args>(args)...);
assign_or_call(
join,
self->get_val(self->a[v]),
self->get_val(self->a[left]),
self->get_val(self->a[right]),
forward<Args>(args)...,
l, r);
}
template<class... Args>
[[gnu::always_inline]] void upd(size_t p, Args&&... args) {
auto self = static_cast<Self *>(this);
upd_impl(p, self->get_root(), 0, self->n, forward<Args>(args)...);
}
[[gnu::always_inline]] void push(size_t, size_t, size_t) {}
};
template<class recalc_t, int priority = 0>
struct PathUpdatePolicy {
[[no_unique_address]] recalc_t recalc;
template<class T>
[[gnu::always_inline]] T get() {
return recalc;
}
PathUpdatePolicy(recalc_t recalc): recalc(recalc) {}
template<class Self>
using type = PointUpdatePolicyType<
priority,
DoNothingFunc,
recalc_t,
DoNothingFunc,
Self
>;
};
template<class join_t, class convert_t, int priority = 0>
struct JoinUpdatePolicy {
[[no_unique_address]] join_t join;
[[no_unique_address]] convert_t convert;
template<class T>
[[gnu::always_inline]] T get() {
if constexpr (is_same_v<T, join_t>)
return T(join);
else
return T(convert);
}
JoinUpdatePolicy(join_t join, convert_t convert): join(join), convert(convert) {}
template<class Self>
using type = PointUpdatePolicyType<
priority,
convert_t,
DoNothingFunc,
join_t,
Self
>;
};
template<int priority, class gen_t, class Self>
struct SegTreeInitType {
static constexpr int init_priority = priority;
static constexpr int update_priority = numeric_limits<int>::min();
[[gnu::always_inline]] void push(size_t, size_t, size_t) {}
[[no_unique_address]] gen_t gen;
template<class Policy>
SegTreeInitType(Policy policy): gen(policy.template get<gen_t>()) {}
void build(size_t v, size_t l, size_t r) {
auto self = static_cast<Self *>(this);
if (r - l == 1) {
if constexpr (!is_invocable_v<gen_t, size_t, size_t>)
self->get_val(self->a[v]) = gen(l);
} else {
size_t c = (l + r) / 2;
auto left = self->get_left(v, l, r);
auto right = self->get_right(v, l, r);
build(left, l, c);
build(right, c, r);
if constexpr (!is_invocable_v<gen_t, size_t, size_t>)
self->join(
self->get_val(self->a[v]),
self->get_val(self->a[left]),
self->get_val(self->a[right]));
}
if constexpr (is_invocable_v<gen_t, size_t, size_t>) {
self->get_val(self->a[v]) = init(l, r);
}
}
[[gnu::always_inline]] void init() {
auto self = static_cast<Self *>(this);
build(self->get_root(), 0, self->n);
}
[[gnu::always_inline]] auto init(size_t l, size_t r) {
if constexpr (is_invocable_v<gen_t, size_t, size_t>)
return gen(l, r);
else
return gen();
}
};
template<class gen_t>
struct InitPolicy {
[[no_unique_address]] gen_t gen;
InitPolicy(gen_t gen): gen(gen) {}
template<class T>
[[gnu::always_inline]] T get() {
return gen;
}
template<class Self>
using type = SegTreeInitType<0, gen_t, Self>;
};
struct IdentityFunc {
template<class T, class... Args>
[[gnu::always_inline, gnu::const]] const T &operator()(const T &x, Args&&...) {
return x;
}
};
template<class join_t, class identity_t, class convert_t = IdentityFunc>
struct GetPolicy {
[[no_unique_address]] join_t join;
[[no_unique_address]] identity_t identity;
[[no_unique_address]] convert_t convert;
template<class T>
[[gnu::always_inline]] T get() {
if constexpr (is_same_v<T, join_t>)
return join;
else if constexpr (is_same_v<T, identity_t>)
return identity;
}
[[gnu::always_inline]]
GetPolicy(join_t join, identity_t identity, convert_t convert = convert_t()):
join(join),
identity(identity),
convert(convert) {}
template<class Self>
struct type
: public PointUpdatePolicyType<
-1,
AssignFunc,
DoNothingFunc,
join_t,
Self
>
, public SegTreeInitType<-1, identity_t, Self>
{
static constexpr int init_priority = -1;
static constexpr int update_priority = -1;
[[no_unique_address]] GetPolicy policy;
type(GetPolicy policy)
: PointUpdatePolicyType<
-1,
AssignFunc,
DoNothingFunc,
join_t,
Self
>(policy)
, SegTreeInitType<-1, identity_t, Self>(policy)
, policy(policy) {}
template<class... Args>
auto get_impl(size_t ql, size_t qr, size_t v, size_t l, size_t r, Args&&... args) {
auto self = static_cast<Self *>(this);
if (qr <= l || r <= ql) {
return static_cast<
decltype(policy.convert(self->get_val(self->a[v]), forward<Args>(args)..., l, r))
>(policy.identity(forward<Args>(args)..., l, r));
}
self->push(v, l, r);
if (ql <= l && r <= qr)
return policy.convert(self->get_val(self->a[v]), forward<Args>(args)..., l, r);
size_t c = (l + r) / 2;
return policy.join(
get_impl(ql, qr, self->get_left(v, l, r), l, c, forward<Args>(args)...),
get_impl(ql, qr, self->get_right(v, l, r), c, r, forward<Args>(args)...),
forward<Args>(args)..., l, r);
}
template<class... Args>
[[gnu::always_inline]] auto get(size_t ql, size_t qr, Args&&... args) {
auto self = static_cast<Self *>(this);
return get_impl(ql, qr, self->get_root(), 0, self->n, forward<Args>(args)...);
}
[[gnu::always_inline]] void push(size_t, size_t, size_t) {}
};
};
template<class push_t, class balance_t, class calc_t>
struct MassUpdatePolicy {
[[no_unique_address]] push_t push;
[[no_unique_address]] balance_t balance;
[[no_unique_address]] calc_t calc;
MassUpdatePolicy(push_t push, balance_t balance, calc_t calc):
push(push),
balance(balance),
calc(calc) {}
template<class Self>
struct type {
static const int init_priority = numeric_limits<int>::min();
static const int update_priority = numeric_limits<int>::min();
[[no_unique_address]] MassUpdatePolicy policy;
type(MassUpdatePolicy policy): policy(policy) {}
[[gnu::always_inline]] void push(size_t v, size_t l, size_t r) {
auto self = static_cast<Self *>(this);
if (r - l != 1) {
auto left = self->get_left(v, l, r);
auto right = self->get_right(v, l, r);
size_t c = (l + r) / 2;
policy.push(self->get_val(self->a[left]), l, c, self->get_val(self->a[v]), l, r);
policy.push(self->get_val(self->a[right]), c, r, self->get_val(self->a[v]), l, r);
}
policy.balance(self->get_val(self->a[v]), l, r);
}
template<class... Args>
void mass_upd_impl(size_t ql, size_t qr, size_t v, size_t l, size_t r, Args&&... args) {
auto self = static_cast<Self *>(this);
if (qr <= l || r <= ql)
return;
self->push(v, l, r);
if (ql <= l && r <= qr) {
policy.calc(self->get_val(self->a[v]), forward<Args>(args)..., l, r);
return;
}
size_t c = (l + r) / 2;
mass_upd_impl(ql, qr, self->get_left(v, l, r), l, c, forward<Args>(args)...);
mass_upd_impl(ql, qr, self->get_right(v, l, r), c, r, forward<Args>(args)...);
auto left = self->get_left(v, l, r);
auto right = self->get_right(v, l, r);
self->join(self->get_val(self->a[v]), self->get_val(self->a[left]), self->get_val(self->a[right]));
}
template<class... Args>
[[gnu::always_inline]] void mass_upd(size_t ql, size_t qr, Args&&... args) {
auto self = static_cast<Self *>(this);
mass_upd_impl(ql, qr, self->get_root(), 0, self->n, forward<Args>(args)...);
}
};
};
struct BaseSegTree {
[[gnu::always_inline]] void init() {}
template<class... Args>
[[gnu::always_inline]] void upd(Args&&...) {}
[[no_unique_address]] DoNothingFunc join;
};
#define SEG_TREE_HELPERS(SegTree) \
[[gnu::always_inline]] void push(size_t v, size_t l, size_t r) { \
(Policies<SegTree<T, Policies...>>::push(v, l, r), ...); \
} \
template<class... Args> \
[[gnu::always_inline]] void upd(size_t p, Args&&... args) { \
constexpr int max_prior = max({Policies<SegTree<T, Policies...>>::update_priority...}); \
auto select = []<class X>(X x) { \
if constexpr (X::update_priority >= max_prior) { \
return x; \
} else { \
return BaseSegTree(); \
} \
}; \
(decltype(select(declval<Policies<SegTree<T, Policies...>>>()))::upd(p, forward<Args>(args)...), ...); \
} \
template<class P> \
typename P::template type<SegTree<T, Policies...>> &as(const P&) { \
return static_cast<typename P::template type<SegTree<T, Policies...>> &>(*this); \
} \
template<class... Args> \
[[gnu::always_inline]] void join(T &res, const T &a, const T &b) { \
constexpr auto max_prior = max({Policies<SegTree<T, Policies...>>::update_priority...}); \
auto select = []<class X>(X x) { \
if constexpr (X::update_priority >= max_prior) { \
return x; \
} else { \
return BaseSegTree(); \
} \
}; \
(assign_or_call( \
static_cast<decltype(select(declval<Policies<SegTree<T, Policies...>>>())) *>(this)->join, \
res, a, b), ...); \
} \
[[gnu::always_inline]] auto init(size_t l, size_t r) { \
constexpr int max_prior = max({Policies<SegTree<T, Policies...>>::init_priority...}); \
auto select = []<class X, class... Args>(auto select, X x, Args... args) { \
if constexpr (X::init_priority >= max_prior) { \
return x; \
} else { \
return select(select, forward<Args>(args)...); \
} \
}; \
return decltype(select(select, declval<Policies<SegTree<T, Policies...>>>()...))::init(l, r); \
} \
template<class T, template<class> class... Policies>
struct SegTree: BaseSegTree, public Policies<SegTree<T, Policies...>>... {
size_t n;
vector<T> a;
SegTree(size_t n, Policies<SegTree<T, Policies...>>... policies)
: Policies<SegTree<T, Policies...>>(policies)...
, n(n)
{
size_t sz = 1;
while (sz < n)
sz <<= 1;
a.resize(sz * 2 - 1);
constexpr int max_prior = max({Policies<SegTree<T, Policies...>>::init_priority...});
auto select = []<class X>(X x) {
if constexpr (X::init_priority >= max_prior) {
return x;
} else {
return BaseSegTree();
}
};
(decltype(select(policies))::init(), ...);
}
[[gnu::always_inline, gnu::const]] T &get_val(T &x) {
return x;
}
[[gnu::always_inline, gnu::const]] size_t get_left(size_t v, size_t, size_t) const {
return v * 2 + 1;
}
[[gnu::always_inline, gnu::const]] size_t get_right(size_t v, size_t, size_t) const {
return v * 2 + 2;
}
[[gnu::always_inline, gnu::const]] size_t get_root() const {
return 0;
}
SEG_TREE_HELPERS(SegTree)
};
template<class T, class... Policies>
SegTree<T, Policies::template type...> make_segtree(size_t n, Policies... policies) {
return SegTree<T, Policies::template type...>(
n,
typename Policies::template type<SegTree<T, Policies::template type...>>(policies)...);
}
template<class T, template<class> class... Policies>
struct LazySegTree: BaseSegTree, public Policies<LazySegTree<T, Policies...>>... {
struct Node {
constexpr static unsigned null = numeric_limits<unsigned>::max();
unsigned left = null, right = null;
T val;
Node(T &&val): val(val) {}
};
size_t n;
vector<Node> a;
LazySegTree(size_t n, Policies<LazySegTree<T, Policies...>>... policies)
: Policies<LazySegTree<T, Policies...>>(policies)...
, n(n)
{}
[[gnu::always_inline, gnu::const]] T &get_val(Node &node) {
return node.val;
}
[[gnu::always_inline]] size_t get_left(size_t v, size_t l, size_t r) {
if (a[v].left == Node::null) {
a[v].left = a.size();
a.eb(init(l, r));
}
return a[v].left;
}
[[gnu::always_inline]] size_t get_right(size_t v, size_t l, size_t r) {
if (a[v].right == Node::null) {
a[v].right = a.size();
a.eb(init(l, r));
}
return a[v].right;
}
[[gnu::always_inline]] size_t get_root() {
if (a.empty())
a.eb(init(0, n));
return 0;
}
SEG_TREE_HELPERS(LazySegTree)
};
template<class T, class... Policies>
LazySegTree<T, Policies::template type...> make_lazy_segtree(size_t n, Policies... policies) {
return LazySegTree<T, Policies::template type...>(
n,
typename Policies::template type<LazySegTree<T, Policies::template type...>>(policies)...);
}
#undef SEG_TREE_HELPERS
#ifdef LOCAL
#pragma GCC diagnostic pop
#endif
}; // namespace segtree
#if !defined NOGNU && __x86_64__
namespace std {
template<>
struct make_unsigned<__int128> {
using type = unsigned __int128;
};
template<>
struct make_unsigned<unsigned __int128> {
using type = unsigned __int128;
};
}; // namespace std
#endif
template<class T, auto c>
constexpr T const_in_type = c;
template<class T_ = int, auto &mod = const_in_type<make_unsigned_t<T_>, M>, class U_ = ll>
struct ModInt {
using T = make_unsigned_t<T_>;
using U = make_unsigned_t<U_>;
static_assert(sizeof(U) > sizeof(T));
T x{};
[[gnu::always_inline]] constexpr ModInt() {}
[[gnu::always_inline]] constexpr ModInt(T x): x(x) {}
template<
class T2_,
class U2_,
class = enable_if_t<sizeof(T) == sizeof(T2_), void>
>
[[gnu::always_inline]] constexpr ModInt(ModInt<T2_, mod, U2_> other): x(other.x) {}
[[nodiscard, gnu::always_inline, gnu::pure]]
[[gnu::always_inline]] constexpr auto operator<=>(const ModInt&) const = default;
[[nodiscard, gnu::always_inline, gnu::pure]] constexpr ModInt operator+(ModInt other) const {
auto selector = []() {
if constexpr (__builtin_constant_p(mod))
return conditional_t<U(mod) + U(mod) == U(mod + mod), T, U>{};
else
return U{};
};
using imm_type = decltype(selector());
auto res = imm_type(x) + imm_type(other.x);
res -= res >= mod ? mod : 0;
return ModInt(res);
}
[[gnu::always_inline]] constexpr ModInt &operator+=(ModInt other) {
return *this = *this + other;
}
[[nodiscard, gnu::always_inline, gnu::pure]] constexpr ModInt operator-() const {
return ModInt(x ? mod - x : 0);
}
[[nodiscard, gnu::always_inline, gnu::pure]] constexpr ModInt operator-(ModInt other) const {
return *this + -other;
}
[[gnu::always_inline]] constexpr ModInt &operator-=(ModInt other) {
return *this = *this - other;
}
[[nodiscard, gnu::always_inline, gnu::pure]] constexpr ModInt operator*(ModInt other) const {
auto selector = []() {
if constexpr (__builtin_constant_p(mod))
return conditional_t<U(mod) * U(mod) == U(mod * mod), T, U>{};
else
return U{};
};
using imm_type = decltype(selector());
auto res = imm_type(x) * imm_type(other.x);
return ModInt(res % mod);
}
[[gnu::always_inline]] constexpr ModInt &operator*=(ModInt other) {
return *this = *this * other;
}
template<class Int>
[[nodiscard, gnu::pure, gnu::always_inline]] constexpr ModInt pow(Int p) const {
#ifdef NOGNU
if constexpr (1)
#else
if (is_constant_evaluated())
#endif
{
ModInt x = *this;
ModInt ans = 1;
while (p) {
if (p & 1)
ans *= x;
x *= x;
p >>= 1;
}
return ans;
} else {
return __gnu_cxx::power(*this, p);
}
}
template<auto p>
[[nodiscard, gnu::pure, gnu::always_inline]] constexpr ModInt pow() const {
static_assert(is_integral_v<decltype(p)> && p >= 0);
if constexpr (p == 0) {
return {1};
} else if constexpr (p % 2) {
return *this * pow<p - 1>();
} else {
auto t = pow<p / 2>();
return t * t;
}
}
[[nodiscard, gnu::always_inline, gnu::pure]] constexpr ModInt inv() const {
if constexpr (__builtin_constant_p(mod))
return pow<mod - 2>();
else
return pow(mod - 2);
}
[[nodiscard, gnu::always_inline, gnu::pure]] constexpr ModInt operator/(ModInt other) const {
return *this * other.inv();
}
[[gnu::always_inline]] constexpr ModInt &operator/=(ModInt other) {
return *this = *this / other;
}
};
struct fictive {};
template<class F>
[[gnu::always_inline]] inline auto cond_cmp(F &&f) {
return [f]<class A, class B>[[gnu::always_inline]](const A &a, const B &b)->bool {
if constexpr (is_same_v<A, fictive>) {
return 0;
} else if constexpr (is_same_v<B, fictive>) {
return !f(a);
} else {
return f(a) < f(b);
}
};
}
template<class F, class T1, class T2, size_t... i>
[[gnu::always_inline]] inline enable_if_t<tuple_size<T1>::value == tuple_size<T2>::value, void>
elementwise_apply(F f, T1 &x, const T2 &y, index_sequence<i...>) {
(((void) f(get<i>(x), get<i>(y))), ...);
}
template<class F, class T1, class T2, size_t... i>
[[gnu::always_inline]] inline auto
elementwise_operaton(F f, T1 x, const T2 &y, index_sequence<i...>)
requires(tuple_size<T1>::value == tuple_size<T2>::value)
{
if constexpr (tuple_size<T1>::value == 2)
return pair(f(get<i>(x), get<i>(y))...);
else
return tuple(f(get<i>(x), get<i>(y))...);
}
template<class F, class T1, class T2, size_t... i>
[[gnu::always_inline]] inline enable_if_t<is_tuple_like_v<T1> && !is_tuple_like_v<T2>, void>
elementwise_apply(F f, T1 &x, const T2 &y, index_sequence<i...>) {
(((void) f(get<i>(x), y)), ...);
}
template<class F, class T1, class T2, size_t... i>
[[gnu::always_inline]] inline auto
elementwise_operaton(F f, T1 x, const T2 &y, index_sequence<i...>)
requires(is_tuple_like_v<T1> && !is_tuple_like_v<T2>)
{
if constexpr (tuple_size<T1>::value == 2)
return pair(f(get<i>(x), y)...);
else
return tuple(f(get<i>(x), y)...);
}
namespace std {
template<tuple_like T1, class T2>
[[gnu::always_inline]] inline T1 &operator+=(T1 &&x, T2 &&y) {
elementwise_apply(
lambda(x += y, auto &x, auto &y),
forward<T1>(x), forward<T2>(y),
make_index_sequence<tuple_size_v<remove_reference_t<T1>>>{}
);
return x;
}
template<tuple_like T1, class T2>
[[gnu::always_inline, nodiscard]] inline auto operator+(T1 &&x, T2 &&y) {
return elementwise_operaton(
lambda(x + y, auto &&x, auto &&y),
std::forward<T1>(x), std::forward<T2>(y),
make_index_sequence<tuple_size_v<remove_reference_t<T1>>>{}
);
}
template<class T1, class T2>
[[gnu::always_inline, nodiscard]] inline enable_if_t<is_tuple_like_v<T1> && !is_tuple_like_v<T2>, T1>
operator+(const T2 &y, T1 x) {
x += y;
return x;
}
template<tuple_like T1, class T2>
[[gnu::always_inline]] inline T1 &operator-=(T1 &&x, T2 &&y) {
elementwise_apply(
lambda(x -= y, auto &x, auto &y),
forward<T1>(x), forward<T2>(y),
make_index_sequence<tuple_size_v<remove_reference_t<T1>>>{}
);
return x;
}
template<tuple_like T1, class T2>
[[gnu::always_inline, nodiscard]] inline auto operator-(T1 &&x, T2 &&y) {
return elementwise_operaton(
lambda(x - y, auto &&x, auto &&y),
std::forward<T1>(x), std::forward<T2>(y),
make_index_sequence<tuple_size_v<remove_reference_t<T1>>>{}
);
}
template<class T1, class T2>
[[gnu::always_inline, nodiscard]] inline enable_if_t<is_tuple_like_v<T1> && !is_tuple_like_v<T2>, T1>
operator-(const T2 &y, T1 x) {
x -= y;
return x;
}
template<tuple_like T1, class T2>
[[gnu::always_inline]] inline T1 &operator*=(T1 &&x, T2 &&y) {
elementwise_apply(
lambda(x *= y, auto &x, auto &y),
forward<T1>(x), forward<T2>(y),
make_index_sequence<tuple_size_v<remove_reference_t<T1>>>{}
);
return x;
}
template<tuple_like T1, class T2>
[[gnu::always_inline, nodiscard]] inline auto operator*(T1 &&x, T2 &&y) {
return elementwise_operaton(
lambda(x * y, auto &&x, auto &&y),
std::forward<T1>(x), std::forward<T2>(y),
make_index_sequence<tuple_size_v<remove_reference_t<T1>>>{}
);
}
template<class T1, class T2>
[[gnu::always_inline, nodiscard]] inline enable_if_t<is_tuple_like_v<T1> && !is_tuple_like_v<T2>, T1>
operator*(const T2 &y, T1 x) {
x *= y;
return x;
}
template<tuple_like T1, class T2>
[[gnu::always_inline]] inline T1 &operator/=(T1 &&x, T2 &&y) {
elementwise_apply(
lambda(x /= y, auto &x, auto &y),
forward<T1>(x), forward<T2>(y),
make_index_sequence<tuple_size_v<remove_reference_t<T1>>>{}
);
return x;
}
template<tuple_like T1, class T2>
[[gnu::always_inline, nodiscard]] inline auto operator/(T1 &&x, T2 &&y) {
return elementwise_operaton(
lambda(x / y, auto &&x, auto &&y),
std::forward<T1>(x), std::forward<T2>(y),
make_index_sequence<tuple_size_v<remove_reference_t<T1>>>{}
);
}
template<class T1, class T2>
[[gnu::always_inline, nodiscard]] inline enable_if_t<is_tuple_like_v<T1> && !is_tuple_like_v<T2>, T1>
operator/(const T2 &y, T1 x) {
x /= y;
return x;
}
template<class T, auto &mod, class U>
ostream &operator<<(ostream &out, ModInt<T, mod, U> v) {
return out << v.x;
}
template<class T, auto &mod, class U>
istream &operator>>(istream &in, ModInt<T, mod, U> &v) {
return in >> v.x;
}
};
namespace geometry {
template<class T1, class T2, class T3>
[[nodiscard, gnu::always_inline, gnu::const]] inline bool near(T1 x, T2 y, T3 eps) {
return abs(x - y) <= eps;
}
template <class T>
struct Point {
T x, y;
template <class U, std::enable_if_t<!std::is_same_v<U, std::common_type_t<T, U>>, bool> = true>
[[gnu::always_inline]] explicit operator Point<U>() const noexcept {
return Point<U>{static_cast<U>(x), static_cast<U>(y)};
}
template <class U, std::enable_if_t<std::is_same_v<U, std::common_type_t<T, U>>, bool> = true>
[[gnu::always_inline]] operator Point<U>() const noexcept {
return Point<U>{static_cast<U>(x), static_cast<U>(y)};
}
[[gnu::always_inline]] Point() = default;
[[gnu::always_inline]] Point(T x, T y) : x(x), y(y) {}
[[gnu::always_inline]] explicit Point(double radians): x(std::cos(radians)), y(std::sin(radians)) {}
template <class V>
[[gnu::always_inline]] explicit Point(const V& v) noexcept : x(v.x), y(v.y) {}
[[gnu::always_inline]] Point& operator+=(const Point& other) {
x += other.x;
y += other.y;
return *this;
}
[[gnu::always_inline]] Point& operator-=(const Point& other) {
x -= other.x;
y -= other.y;
return *this;
}
template <class U>
[[gnu::always_inline, nodiscard, gnu::pure]] Point<std::common_type_t<T, U>> operator+(
const Point<U>& other) const noexcept {
return {x + other.x, y + other.y};
}
template <class U>
[[gnu::always_inline, nodiscard, gnu::pure]] Point<std::common_type_t<T, U>> operator-(
const Point<U>& other) const noexcept {
return {x - other.x, y - other.y};
}
[[gnu::always_inline, nodiscard, gnu::pure]] T lenSq() const noexcept { return x * x + y * y; }
[[gnu::always_inline, nodiscard, gnu::pure]] auto len() const noexcept {
return std::sqrt(lenSq());
}
[[gnu::always_inline, nodiscard, gnu::pure]] Point operator-() const noexcept {
return Point{-x, -y};
}
[[gnu::always_inline]] Point& operator*=(T c) {
x *= c;
y *= c;
return *this;
}
template <class Dummy = T, std::enable_if_t<std::is_floating_point_v<Dummy>, bool> = true>
[[gnu::always_inline]] Point& operator/=(T c) {
x /= c;
y /= c;
return *this;
}
template <class U>
[[gnu::always_inline, nodiscard, gnu::pure]] auto rotate(U radians) const {
using Ret = std::conditional_t<std::is_floating_point_v<T>, T, double>;
using Ang = std::common_type_t<Ret, U>;
auto sn = std::sin(static_cast<Ang>(radians));
auto cs = std::cos(static_cast<Ang>(radians));
return Point<Ret>{x * cs - y * sn, x * sn + y * cs};
}
[[gnu::always_inline, nodiscard, gnu::pure]] Point left() const noexcept {
Point ans = *this;
std::swap(ans.x, ans.y);
ans.x = -ans.x;
return ans;
}
[[gnu::always_inline, nodiscard, gnu::pure]] Point right() const noexcept {
Point ans = *this;
std::swap(ans.x, ans.y);
ans.y = -ans.y;
return ans;
}
[[gnu::always_inline, nodiscard, gnu::pure]] auto radians() const { return std::atan2(y, x); }
[[gnu::always_inline, nodiscard, gnu::pure]] bool operator==(const Point& other) const noexcept {
return x == other.x && y == other.y;
}
};
template <class T1, class T2>
[[gnu::always_inline, nodiscard, gnu::pure]] inline Point<std::common_type_t<T1, T2>> operator*(
const Point<T1>& v, T2 c) noexcept {
return {v.x * c, v.y * c};
}
template <class T1, class T2>
[[gnu::always_inline, nodiscard, gnu::pure]] inline auto operator*(T2 c,
const Point<T1>& v) noexcept {
return v * c;
}
template <class T1, class T2>
[[gnu::always_inline, nodiscard, gnu::pure]] inline auto operator/(const Point<T1>& v,
T2 c) noexcept {
using Ret = std::conditional_t<std::is_integral_v<T1> && std::is_integral_v<T2>,
double,
std::common_type_t<T1, T2>>;
return Point<Ret>{static_cast<Ret>(v.x) / c, static_cast<Ret>(v.y) / c};
}
template <class T1, class T2, class T3>
[[gnu::always_inline, nodiscard, gnu::pure]] inline bool near(const Point<T1>& a, const Point<T2>& b,
T3 eps) noexcept {
return near(a.x, b.x, eps) && near(a.y, b.y, eps);
}
template <class T1, class T2>
[[gnu::always_inline, nodiscard, gnu::pure]] inline auto operator*(const Point<T1>& a,
const Point<T2>& b) noexcept {
return a.x * b.x + a.y * b.y;
}
template <class T1, class T2>
[[gnu::always_inline, nodiscard, gnu::pure]] inline auto operator^(const Point<T1>& a,
const Point<T2>& b) noexcept {
return a.x * b.y - a.y * b.x;
}
template <class T1, class T2>
[[gnu::always_inline, nodiscard, gnu::pure]] inline auto distSq(const Point<T1> &a,
const Point<T2> &b) noexcept {
return (a - b).lenSq();
}
template <std::floating_point Ret = double, class T1 = void, class T2 = void>
[[gnu::always_inline, nodiscard, gnu::pure]] inline auto dist(const T1 &a, const T2 &b) {
return std::sqrt((Ret) distSq(a, b));
}
template <class T>
[[gnu::always_inline]] inline std::ostream& operator<<(std::ostream& out, const Point<T>& v) {
return out << v.x << " " << v.y;
}
template<class T>
[[gnu::always_inline]] inline istream &operator>>(istream &in, Point<T> &p) {
return in >> p.x >> p.y;
}
template <class T>
struct Line {
union {
struct {
T a, b;
};
Point<T> normal;
};
T c;
[[gnu::always_inline]] Line(T a = 1, T b = 0, T c = 0) : a(a), b(b), c(c) {}
[[gnu::always_inline]] Line(const Point<T> &norm, T c) : normal(norm), c(c) {}
template<class U>
Line(const Line<U> &other): normal(other.normal), c(other.c) {}
[[gnu::always_inline, nodiscard, gnu::pure]] static Line fromTwoPoints(
const Point<T>& p1, const Point<T>& p2) noexcept {
Point<T> norm{p2.y - p1.y, p1.x - p2.x};
return Line(norm, -(p1 * norm));
}
[[gnu::always_inline, nodiscard, gnu::pure]] static Line fromPointAndNormal(
const Point<T>& p1, const Point<T>& norm) noexcept {
return Line(norm, -(p1 * norm));
}
[[gnu::always_inline, nodiscard, gnu::pure]] static Line fromPointAndCollinear(
const Point<T>& p1, const Point<T>& coll) noexcept {
Point<T> norm{coll.y, -coll.x};
return Line(norm, -(p1 * norm));
}
[[gnu::always_inline, nodiscard, gnu::pure]] bool operator==(const Line& other) const noexcept {
return normal * other.c == other.normal * c;
}
};
template <class T1, class T2, class T3>
[[gnu::always_inline, nodiscard, gnu::pure]] inline bool near(const Line<T1>& a, const Line<T2>& b,
T3 eps) noexcept {
return near(a.normal * b.c, b.normal * a.c, eps);
}
template<floating_point Ret = double, class T = void>
[[gnu::always_inline, nodiscard, gnu::pure]] Ret dist(const Line<T> &l, const Point<T> &p) {
return abs((Ret) (l.normal * p + l.c) / sqrt((Ret) l.normal.sqrlen()));
}
template<class T1, class T2>
[[gnu::always_inline, nodiscard, gnu::pure]] inline std::common_type_t<T1, T2> distDenomalized(const Line<T1> &l, const Point<T2> &p) {
return (l.normal * p + l.c);
}
template<class T>
[[gnu::always_inline]] inline ostream &operator<<(ostream &out, const Line<T> &l) {
return out << l.a << " " << l.b << " " << l.c;
}
template<class T>
[[gnu::always_inline]] inline istream &operator>>(istream &in, Line<T> &l) {
return in >> l.a >> l.b >> l.c;
}
template<std::floating_point Ret = double, class T1 = void, class T2 = void, class T3 = int>
[[gnu::always_inline, nodiscard, gnu::pure]]
inline optional<vector<Point<Ret>>> intersect(const Line<T1> &l1, const Line<T2> &l2, T3 eps = 0) noexcept {
if (near(l1.normal ^ l2.normal, 0, eps)) {
if (l1 == l2) {
return nullopt;
}
return vector<Point<Ret>>{};
}
if (near(l2.a, 0, eps)) {
return intersect<Ret>(l2, l1, eps);
}
if (near(l1.a, 0, eps)) {
Ret y = (Ret) -l1.c / l1.b;
Ret x = (Ret) (-l2.b * y - l2.c) / l2.a;
return vector{Point(x, y)};
} else {
Ret nb = l2.b - (Ret) l1.b * l2.a / l1.a;
Ret nc = l2.c - (Ret) l1.c * l2.a / l1.a;
Ret y = -nc / nb;
Ret x = (Ret) (-l2.b * y - l2.c) / l2.a;
return vector{Point(x, y)};
}
}
template<class T>
struct Circle {
Point<T> c;
T r;
[[gnu::always_inline, nodiscard, gnu::pure]] bool operator==(const Circle &other) const {
return c == other.c && r == other.r;
}
};
template<std::floating_point Ret = double, class T1 = void, class T2 = void, class T3 = int>
[[gnu::always_inline, nodiscard, gnu::pure]]
inline optional<vector<Point<Ret>>> intersect(const Circle<T1> &c, const Line<T2> &l, T3 eps = 0) noexcept {
Ret d = dist<Ret>(l, c.c);
if (d > c.r) {
return vector<Point<Ret>>{};
} else {
Point<Ret> dn = l.normal;
if (dist_denomalized(l, c.c) > 0)
dn = -dn;
dn /= sqrt((Ret) dn.sqrlen());
dn *= d;
Point<Ret> p = c.c;
p += dn;
dn = l.normal.left();
dn /= sqrt(dn.sqrlen());
dn *= sqrt(c.r * c.r - d * d);
if (near(p + dn, p - dn, eps)) {
return vector{p + dn};
} else {
return vector{p + dn, p - dn};
}
}
}
template<std::floating_point Ret = double, class T1 = void, class T2 = void, class T3 = int>
[[gnu::always_inline, nodiscard, gnu::pure]]
inline optional<vector<Point<Ret>>> intersect(Circle<T1> c1, const Circle<T2> &c2, T3 eps = 0) noexcept {
if (c1 == c2) {
return nullopt;
}
c2.c -= c1.c;
auto ans = intersect<Ret>(c2, Line<T2>(-2 * c2.c.x, -2 * c2.c.y,
c2.c.x * c2.c.x + c2.c.y * c2.c.y + c1.r * c1.r - c2.r * c2.r));
for (auto &p : ans)
p += c1.c;
return ans;
}
template<class T>
[[gnu::always_inline]] inline ostream &operator<<(ostream &out, const Circle<T> &c) {
return out << c.c << " " << c.r;
}
template<class T>
[[gnu::always_inline]] inline istream &operator>>(istream &in, Circle<T> &c) {
return in >> c.c >> c.r;
}
template<class T, class T2 = int>
[[gnu::always_inline, nodiscard]] inline bool is_inside(const Point<T> &p, const vector<Point<T>> &polygon, T2 eps = 0) {
double sum = 0;
for (int i = 0; i < (int) polygon.size(); ++i) {
auto a = polygon[i] - p;
auto b = polygon[(i + 1 == (int) polygon.size()) ? 0 : i + 1] - p;
if (a * b <= 0 && near(a ^ b, 0, eps)) {
return 1;
}
sum += atan2(a ^ b, a * b);
}
return abs(sum) > 1;
}
template<class T>
[[gnu::always_inline, nodiscard]] inline T sqr2(const vector<Point<T>> &polygon) {
T sum = 0;
for (int i = 0; i < (int) polygon.size(); ++i) {
sum += polygon[i] ^ polygon[(i + 1 == (int) polygon.size()) ? 0 : i + 1];
}
if (sum < 0)
sum = -sum;
return sum;
}
}; // geometry
template<class T, class V>
[[gnu::always_inline, nodiscard, gnu::const]] inline auto &as_array(V &v) {
using Arr = array<T, sizeof(V) / sizeof(T)>;
return *reinterpret_cast<conditional_t<is_const_v<V>, const Arr, Arr> *>(&v);
}
template<class V, bool allgined = false, class T = int>
[[gnu::always_inline, nodiscard]] inline V load_vec(T *ptr) {
if constexpr (sizeof(V) == 32) {
auto vptr = reinterpret_cast<__m256i *>(ptr);
if constexpr (allgined) {
return reinterpret_cast<V>(_mm256_load_si256(vptr));
} else {
return reinterpret_cast<V>(_mm256_lddqu_si256(vptr));
}
} else if constexpr (sizeof(V) == 16) {
auto vptr = reinterpret_cast<__m128i *>(ptr);
if constexpr (allgined) {
return reinterpret_cast<V>(_mm_load_si128(vptr));
} else {
return reinterpret_cast<V>(_mm_loadu_si128(vptr));
}
} else {
static_assert(is_void_v<V>);
}
}
template<bool flush = false>
void print() {
if constexpr (flush)
cout << endl;
else
cout << '\n';
}
template<bool flush = false, class T>
void print(const T &x) {
cout << x;
print<flush>();
}
template<bool flush = false, class T, class... Args>
void print(const T &x, const Args & ...args) {
cout << x << " ";
print<flush>(args...);
}
template<class T>
void prints(const T &x) {
cout << x << " ";
}
template<class T, class... Args>
void prints(const T &x, const Args & ...args) {
cout << x << " ";
prints(args...);
}
#define named(x) #x, "=", x
// #define FAST_ALLOC_MEM_SIZE 500e6
#ifdef FAST_ALLOC_MEM_SIZE
constexpr size_t TOTAL_MEM = FAST_ALLOC_MEM_SIZE;
alignas(__STDCPP_DEFAULT_NEW_ALIGNMENT__) static char buf[TOTAL_MEM];
static char *ptr = buf;
[[nodiscard]] inline void *my_alloc(size_t x, size_t alignment = __STDCPP_DEFAULT_NEW_ALIGNMENT__) noexcept {
ptr += (alignment - (reinterpret_cast<uintptr_t>(ptr) & (alignment - 1))) & (alignment - 1);
auto ret = reinterpret_cast<void *>(ptr);
ptr += x;
return ret;
}
[[nodiscard]] inline void *operator new(size_t x) {
return my_alloc(x);
}
[[nodiscard]] inline void *operator new(size_t x, align_val_t alignment) {
return my_alloc(x, static_cast<size_t>(alignment));
}
[[nodiscard]] inline void *operator new(size_t x, const nothrow_t&) {
return my_alloc(x);
}
[[nodiscard]] inline void *operator new(size_t x, align_val_t alignment, const nothrow_t&) {
return my_alloc(x, static_cast<size_t>(alignment));
}
[[nodiscard]] inline void *operator new[](size_t x) {
return my_alloc(x);
}
[[nodiscard]] inline void *operator new[](size_t x, align_val_t alignment) {
return my_alloc(x, static_cast<size_t>(alignment));
}
[[nodiscard]] inline void *operator new[](size_t x, const nothrow_t&) {
return my_alloc(x);
}
[[nodiscard]] inline void *operator new[](size_t x, align_val_t alignment, const nothrow_t&) {
return my_alloc(x, static_cast<size_t>(alignment));
}
inline void operator delete(void *) noexcept {}
inline void operator delete(void *, size_t) noexcept {}
inline void operator delete(void *, align_val_t) noexcept {}
inline void operator delete(void *, size_t, align_val_t) noexcept {}
inline void operator delete[](void *) noexcept {}
inline void operator delete[](void *, size_t) noexcept {}
inline void operator delete[](void *, align_val_t) noexcept {}
inline void operator delete[](void *, size_t, align_val_t) noexcept {}
#endif
// #define NODEBUG
#if defined NODEBUG || !defined LOCAL
#define debug(...)
#define debugs(...)
#else
#define debug print<true>
#define debugs prints
#endif
// ---SOLUTION--- //
// using namespace segtree;
// using namespace geometry;
void run() {
int t = 1;
cin >> t;
while (t--) {
auto [n, s] = input<int, string>();
rope<int> pos;
pos.pb(0);
int cur = 0;
for (int i = 0; i < n - 1; ++i) {
auto x = s[i];
if (x == '<') {
pos.insert(cur + 1, i + 1);
++cur;
} else {
pos.push_front(i + 1);
cur = 0;
}
}
// debug(pos);
vector<int> ans(n);
for (int i = 0; auto x : pos) {
ans[x] = ++i;
}
print(ans);
pos.clear();
pos.pb(0);
cur = 0;
for (int i = 0; i < n - 1; ++i) {
auto x = s[i];
if (x == '<') {
pos.pb(i + 1);
cur = i + 1;
} else {
pos.insert(cur, i + 1);
cur = 0;
}
}
for (int i = 0; auto x : pos) {
ans[x] = ++i;
}
print(ans);
}
}
| cpp |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample: | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | // LUOGU_RID: 102246479
#include <bits/stdc++.h>
using namespace std;
namespace vbzIO {
char ibuf[(1 << 20) + 1], *iS, *iT;
#if ONLINE_JUDGE
#define gh() (iS == iT ? iT = (iS = ibuf) + fread(ibuf, 1, (1 << 20) + 1, stdin), (iS == iT ? EOF : *iS++) : *iS++)
#else
#define gh() getchar()
#endif
#define pi pair<int, int>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define ins insert
#define era erase
inline int read () {
char ch = gh();
int x = 0;
bool t = 0;
while (ch < '0' || ch > '9') t |= ch == '-', ch = gh();
while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = gh();
return t ? ~(x - 1) : x;
}
inline void write(int x) {
if (x < 0) {
x = ~(x - 1);
putchar('-');
}
if (x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
}
using vbzIO::read;
using vbzIO::write;
const int maxn = 4e5 + 400;
int n, m, b, top, st[maxn], vis[maxn], dep[maxn];
vector<int> ans, g[maxn];
void dfs(int u, int fa) {
dep[u] = dep[fa] + 1, st[++top] = u;
for (int v : g[u]) {
if (dep[v]) {
if (dep[v] > dep[u] - b + 1) continue;
write(2), puts("");
vector<int> tp;
while (st[top] != v) {
tp.pb(st[top]);
top--;
}
write(tp.size() + 1), puts("");
for (int i : tp) write(i), putchar(' ');
write(v);
exit(0);
} else dfs(v, u);
}
if (!vis[u]) {
ans.pb(u);
for (int v : g[u]) vis[v] = 1;
}
top--;
}
int main() {
n = read(), m = read(), b = sqrt(n - 1) + 1;
for (int i = 1, u, v; i <= m; i++) {
u = read(), v = read();
g[u].pb(v), g[v].pb(u);
}
dfs(1, 0);
write(1), puts("");
for (int i = 0; i < b; i++) write(ans[i]), putchar(' ');
return 0;
} | cpp |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | #include<bits/stdc++.h>
using namespace std;
#define fio ios_base::sync_with_stdio(0); cin.tie(0);
#define int long long
#define vt vector
#define pb push_back
#define eb emplace_back
#define INF 0x3f3f3f3f3f3f3f3f
#define PI pair<int, int>
#define rep(i, from, to) for (int i = from; i <= to; ++i)
#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")
#pragma GCC target("avx,avx2,fma")
const int mxn = 2e5 + 5, MOD = 998244353;
//枚舉最大的數
//最大的數為i 有Ci - 1取n - 2
//每種會有n - 2種
//1 1 2 3 => 1231 1321 n - 2?
//1 2 2 3 4 => 12342 12432 24321 13421
int n, m, fac[mxn];
int fast_power(int a, int b, int MOD = MOD){
if (b < 0) return 0;
int res = 1;
while (b){
if (b & 1) res = res * a % MOD;
a = a * a % MOD;
b >>= 1;
}
return res;
}
void init() {
fac[0] = 1;
rep(i, 1, 2e5) fac[i] = fac[i - 1] * i % MOD;
}
int C(int n, int r) {
if (n < r) return 0;
return fac[n] * fast_power(fac[r], MOD - 2) % MOD * fast_power(fac[n - r], MOD - 2) % MOD;
}
signed main(void){
#ifndef ONLINE_JUDGE
freopen("C:\\Code\\C\\input.txt","r",stdin);
freopen("C:\\Code\\C\\output.txt","w",stdout);
#endif
fio
cin >> n >> m;
init();
int ans = 0;
rep(i, 1, m) {
ans = (ans + C(i - 1, n - 2) * fast_power(2, n - 3) % MOD * (n - 2) % MOD) % MOD;
}
cout << ans % MOD << '\n';
} | 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"
] | //#pragma GCC optomize ("Ofast")
//#pragma GCC optomize ("unroll-loops")
//#pragma GCC target ("avx,avx2,fma")
#include <bits/stdc++.h>
#define F first
#define S second
#define ll long long
#define all(x) (x.begin(), x.end());
#define uint unsigned int
#define pb push_back
#define ios ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int ll
using namespace std;
const ll N=3e5+7 ,INF = 1e18, inf = 1e9 , mod = 1e9+7;
int n,m;
int a[N];
int mn[N];
int mx[N];
int cur[N];
int pred[N];
bool ok[N];
int t[N*4];
int x[N*4];
void upd_x(int pos,int val,int u=1,int ul=1,int ur=n){
if(ul==ur){
x[u]=val;
return;
}
int um=(ul+ur)/2;
if(pos<=um)upd_x(pos,val,u*2,ul,um);
else upd_x(pos,val,u*2+1,um+1,ur);
x[u]=x[u*2]+x[u*2+1];
}
int get_x(int l,int r,int u=1,int ul=1,int ur=n){
if(l<=ul&&ur<=r)return x[u];
if(ur<l||r<ul)return 0;
int um=(ul+ur)/2;
return get_x(l,r,u*2,ul,um)+get_x(l,r,u*2+1,um+1,ur);
}
void upd(int pos,int val,int u=1,int ul=1,int ur=m){
if(ul==ur){
t[u]=val;
return;
}
int um=(ul+ur)/2;
if(pos<=um)upd(pos,val,u*2,ul,um);
else upd(pos,val,u*2+1,um+1,ur);
t[u]=t[u*2]+t[u*2+1];
}
int get(int l,int r,int u=1,int ul=1,int ur=m){
if(l<=ul&&ur<=r)return t[u];
if(ur<l||r<ul)return 0;
int um=(ul+ur)/2;
return get(l,r,u*2,ul,um)+get(l,r,u*2+1,um+1,ur);
}
signed main(){
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
ios;
int tt=1;
// cin>>tt;
while(tt--){
cin>>n>>m;
for(int i=1;i<=n;i++){
mn[i]=i;
mx[i]=i;
cur[i]=i;
}
for(int i=1;i<=m;i++){
cin>>a[i];
mn[a[i]]=1;
ok[a[i]]=1;
upd_x(a[i],1);
if(pred[a[i]]!=0)upd(pred[a[i]],0);
upd(i,1);
if(pred[a[i]]==0&&a[i]!=n){
int val=get_x(a[i]+1,n);
mx[a[i]]=max(mx[a[i]],min(cur[a[i]]+val,n));
}
else{
int val=get(pred[a[i]],i);
mx[a[i]]=max(mx[a[i]],min(cur[a[i]]+val-1,n));
}
pred[a[i]]=i;
cur[a[i]]=1;
}
for(int i=1;i<=n;i++){
if(ok[i]){
int val=get(pred[i]+1,m);
mx[i]=max(mx[i],min(val+1,n));
}
}
vector<int>v;
for(int i=1;i<=n;i++)if(!ok[i])v.pb(i);
int cnt=n;
for(int i=v.size()-1;i>=0;i--)mx[v[i]]=cnt--;
for(int i=1;i<=n;i++)cout<<mn[i]<<" "<<mx[i]<<'\n';
}
} | cpp |
1304 | F2 | F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp",
"greedy"
] | #include <bits/stdc++.h>
// v.erase( unique(all(v)) , v.end() ) -----> removes duplicates and resizes the vector as so
using namespace std;
#define ll long long
#define lld long double
const lld pi = 3.14159265358979323846;
#define pb push_back
#define pf push_front
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define getunique(v) {sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end());}
constexpr int mod = (int)(1e9+7);
#define log(x) (31^__builtin_clz(x)) // Easily calculate log2 on GNU G++ compilers
#define left p<<1 , l , (l+r)>>1
#define right p<<1|1 , ((l+r)>>1)+1 , r
const int N=4e4+7;
const int M=52;
vector<int> seg[2],lazy[2];
void push(int t,int p){
if(!lazy[t][p]) return;
seg[t][p<<1] += lazy[t][p]; seg[t][p<<1|1] += lazy[t][p];
lazy[t][p<<1] += lazy[t][p]; lazy[t][p<<1|1] +=lazy[t][p];
lazy[t][p] = 0;
}
void upd(int t,int i , int j , int inc , int p , int l , int r){
if(j<l || r<i) return;
if(i<=l && r<=j){
lazy[t][p] += inc;
seg[t][p] += inc;
return;
}
push(t,p);
upd(t,i,j,inc,left); upd(t,i,j,inc,right);
seg[t][p]=max(seg[t][p<<1],seg[t][p<<1|1]);
}
int a[M][N];
int main()
{ios_base::sync_with_stdio(0),cin.tie(0);
int n,m;cin>>n>>m;int k;cin>>k;
for(int i=0;i<2;i++){
seg[i].resize(4*m);lazy[i].resize(4*m);
}
for(int i=0;i<n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];a[i][j]+=a[i][j-1];
}
}
if(n==1){
int ans=0;
for(int i=k;i<=m;i++)ans=max(ans,a[0][i]-a[0][i-k]);
cout<<ans<<'\n';return 0;
}
for(int i=1;i<=m;i++){
int sum=a[1][i]-a[1][max(i-k,0)]+a[0][i]-a[0][max(i-k,0)];
upd(0,i,i,sum,1,1,m);
}
for(int c=2;c<=n;c++){
for(int i=0;i<4*m;i++)seg[1][i]=lazy[1][i]=0;
for(int i=1;i<=m;i++){
int sum=a[c][i]-a[c][max(i-k,0)]+a[c-1][i]-a[c-1][max(i-k,0)];
int minus=a[c-1][i]-a[c-1][i-1];
upd(0,i,min(i+k-1,m),-minus,1,1,m);
upd(1,i,i,sum+seg[0][1],1,1,m);
if(i>=k)upd(0,i-k+1,i,(a[c-1][i-k+1]-a[c-1][i-k]),1,1,m);
}
swap(seg[0],seg[1]); swap(lazy[0],lazy[1]);
}
cout<<seg[0][1]<<'\n';
return 0;
}
/*
*/ | 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>
#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 pre[N], suf[N], n, a[N];
signed main() {
// freopen("1.in", "r", stdin);
n = read();
int pl = 0, ans = -1;
rep(i, 1, n) a[i] = read(), pre[i] = pre[i - 1] | a[i];
irep(i, n, 1) suf[i] = suf[i + 1] | a[i];
rep(i, 1, n) {
int x = a[i] - (a[i] & (pre[i - 1] | suf[i + 1]));
if(x > ans) ans = x, pl = i;
}
cout << a[pl] << ' ';
rep(i ,1, n) if(i != pl) cout << a[i] << ' ';
cout << '\n';
return 0;
}
| cpp |
1311 | C | C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.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.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11. | [
"brute force"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
#define rep(i, a, b) for(ll i = a; i < b; i++)
#define rrep(i, a, b) for(ll i = a; i >= b; i--)
const ll inf = 4e18;
int main(void) {
cin.tie(0);
ios::sync_with_stdio(0);
ll t;
cin >> t;
while(t--) {
ll n, m;
cin >> n >> m;
string s;
cin >> s;
vector<ll> p(m);
rep(i, 0, m) {
cin >> p[i];
p[i]--;
}
sort(p.begin(), p.end());
vector<ll> cnt(26);
rep(i, 0, n) {
ll idx = lower_bound(p.begin(), p.end(), i) - p.begin();
cnt[s[i] - 'a'] += (m - idx + 1);
}
rep(i, 0, 26) {
cout << cnt[i] << " \n"[i == 25];
}
}
} | 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>
using namespace std;
int main(){
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin >> n;
const int F = 3;
vector<int> a(n+F+F, 0);
for(int i = F; i < n+F; i++) cin >> a[i];
for(int i = 2; i < F; i++) a[i] = a[F];
for(int i = n+F; i < n+F+F-2; i++) a[i] = a[n+F-1];
n = (int)a.size();
map<int, vector<int> > where;
for(int i = 0; i < (int)a.size(); i++){
if(a[i]) where[-a[i]].push_back(i);
}
multiset<int> diffs;
vector<int> ans(n, 0);
vector<bool> big(n, false);
vector<int> z(n);
for(int i = F; i < n-F; i++) z[i-F] = i;
vector<int> zz(n-1);
for(int i = 0; i < n-1; i++) zz[i] = i;
set<int> not_yet(z.begin(), z.end());
set<int> stuff(zz.begin(), zz.end());
diffs.insert(1);
int curval;
auto set_interval = [&](int s, int e){
while(true){
auto r = not_yet.lower_bound(s);
if(r == not_yet.end() || (*r >= e)) break;
ans[*r] = -curval;
not_yet.erase(r);
}
};
auto rem = [&](int idx){
// remove 00
auto s = stuff.find(idx);
int f = *prev(s);
int g = *s;
int h = *next(s);
int rp = big[f];
int tp = big[h];
stuff.erase(s);
if(g-f > 2) diffs.erase(diffs.find(g-f));
if(h-g > 2) diffs.erase(diffs.find(h-g));
if(h-f > 2) diffs.insert(h-f);
if(rp && !tp) set_interval(f, (f + h) / 2 + 1);
if(!rp && tp) set_interval((f + h + 1) / 2 + 1, h + 2);
if(rp && tp) set_interval(f, h+2);
};
auto ins = [&](int idx){
// insert 11
stuff.insert(idx);
auto s = stuff.find(idx);
int f = *prev(s);
int g = *s;
int h = *next(s);
int rp = big[f];
int tp = big[h];
if(h-f > 2) diffs.erase(diffs.find(h-f));
if(h-g > 2) diffs.insert(h-g);
if(g-f > 2) diffs.insert(g-f);
if(!rp) set_interval((f + g + 1) / 2 + 1, g + 2);
if(!tp) set_interval(g, (g + h) / 2 + 1);
if(rp) set_interval(f, g + 2);
if(tp) set_interval(g, h + 2);
};
auto add = [&](int idx) {
if(!big[idx-1]) rem(idx-1);
if(!big[idx+1]) rem(idx);
big[idx] = true;
if(big[idx-1]) ins(idx-1);
if(big[idx+1]) ins(idx);
};
int c = 0;
for(auto p : where){
curval = p.first;
vector<int> locs = p.second;
for(int v : locs) add(v);
c = max(c, (*diffs.rbegin() - 1) / 2);
}
cout << c << '\n';
for(int i = F; i < n-F; i++){
cout << ans[i] << ' ';
}
cout << '\n';
// int on = n-F-F;
// vector<int> b(on);
// for(int i = 0; i < on; i++) b[i] = a[i+F];
// int realc = 0;
// while(true){
// vector<int> newb = b;
// for(int i = 1; i + 1 < on; i++){
// newb[i] = b[i] + b[i+1] + b[i-1] -
// min(b[i], min(b[i+1], b[i-1])) - max(b[i], max(b[i+1], b[i-1]));
// }
// if(b == newb) break;
// realc++;
// b = newb;
// }
// cout << c << ' ' << realc << '\n';
// for(int i = 0; i < on; i++){
// cout << b[i] << ' ';
// }
// cout << '\n';
// assert(c == realc);
// for(int i = 0; i < on; i++){
// if(ans[i+F] != b[i]) cerr << i << ' ' << ans[i+F] << ' ' << b[i] << '\n';
// assert(ans[i+F] == b[i]);
// }
} | cpp |
1301 | E | E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105) — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray. | [
"binary search",
"data structures",
"dp",
"implementation"
] | #include<iostream>
#include<cstring>
using namespace std;
using LL = long long;
const int maxn = 505;
int s1[4][maxn][maxn], a[maxn][maxn];
int s2[255][maxn][maxn];
int sum(int s[maxn][maxn], int l1, int r1, int l2, int r2){
return s[l2][r2] - s[l2][r1 - 1] - s[l1 - 1][r2] + s[l1 - 1][r1 - 1];
}
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);
auto get = [](char c){
if (c == 'R') return 0;
if (c == 'G') return 1;
if (c == 'Y') return 2;
return 3;
};
int n, m, q;
cin >> n >> m >> q;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++){
char c;
cin >> c;
a[i][j] = get(c);
}
for(int x = 0; x < 4; x++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
s1[x][i][j] = (a[i][j] == x) + s1[x][i - 1][j] + s1[x][i][j - 1] - s1[x][i - 1][j - 1];
int up = min(n, m) / 2;
for(int len = 1; len <= up; len++){
for(int i = 1; i + 2 * len - 1 <= n; i++){
for(int j = 1; j + 2 * len - 1 <= m; j++){
int t = 0;
if (sum(s1[0], i, j, i + len - 1, j + len - 1) == len * len &&
sum(s1[1], i, j + len, i + len - 1, j + 2 * len - 1) == len * len &&
sum(s1[2], i + len, j, i + 2 * len - 1, j + len - 1) == len * len &&
sum(s1[3], i + len, j + len, i + 2 * len - 1, j + 2 * len - 1) == len * len)
t = 1;
s2[len][i][j] = t + s2[len][i - 1][j] + s2[len][i][j - 1] - s2[len][i - 1][j - 1];
}
}
}
while(q--){
int l1, r1, l2, r2;
cin >> l1 >> r1 >> l2 >> r2;
int mx = min(l2 - l1 + 1, r2 - r1 + 1) / 2;
while(mx && !sum(s2[mx], l1, r1, l2 - 2 * mx + 1, r2 - 2 * mx + 1)) mx--;
cout << 4 * mx * mx << '\n';
}
} | cpp |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int t,n,x,s,A;
int main()
{
cin>>t;
while(t--&&cin>>n)
{
A=s=0;
for(int i=1;i<=n;i++)
{
cin>>x;
if(x==0)
A++,s++;
s+=x;
}
cout<<A+(s==0)<<'\n';
}
return 0;
} | cpp |
1313 | D | D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third. | [
"bitmasks",
"dp",
"implementation"
] | // Problem: Happy New Year
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF1313D
// Memory Limit: 500 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
//不回家了,我们去鸟巢!
#include<bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
using namespace std;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
pair<int,int> a[100003];
int f[100003][1<<8],g[100003][13],tr[13],arr[13];
signed main()
{
int n=read(),m=read(),w=read(),N=1<<w;
for(int i=1; i<=n; ++i)
a[i].first=read(),a[i].second=read();
sort(a+1,a+n+1),
memset(f,0xc0,sizeof(f)),
f[0][0]=0;
a[n+1].first=m+1;
for(int i=0; i<w; ++i) g[0][i]=0;
for(int i=1; i<=n; ++i)
{
for(int j=0; j<w; ++j) tr[j]=1<<j;
int o=0;
while(o<w&&a[i].second>g[i-1][o]) ++o;
assert(o!=0);
for(int j=o; j<w; ++j) g[i][j]=g[i-1][j];
for(int j=0; j+1<o; ++j) g[i][j]=g[i-1][j+1];
g[i][o-1]=a[i].second;
int O=(1<<o)-1;
for(int j=0; j<N; ++j)
f[i][j-(j&O)+((j&O)>>1)]=
max(f[i][j-(j&O)+((j&O)>>1)],f[i-1][j]),
f[i][j-(j&O)+((j&O)>>1)+(1<<(o-1))]=
max(f[i][j-(j&O)+((j&O)>>1)+(1<<(o-1))],f[i-1][j]);
for(int j=0; j<N; ++j) if(f[i][j]>=0)
{
int cnt=0;
arr[0]=a[i].first-1;
for(int k=0; k<w; ++k)
if(((j>>k)&1))
arr[++cnt]=max(a[i].first-1,
min(a[i+1].first-1,g[i][k]));
for(int k=cnt; k>=1; k-=2)
f[i][j]+=arr[k]-arr[k-1];
}
}
int ans=0;
for(int i=0; i<N; ++i) ans=max(ans,f[n][i]);
printf("%d\n",ans);
return 0;
} | cpp |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | #include<bits/stdc++.h>
#define maxn 1001
using namespace std;
int ans[maxn],tot;
char s[maxn];
int main(){
int l,r,len,i;
scanf("%s",s+1);
len=strlen(s+1);
l=1,r=len;
while(1){
while(l<=len&&s[l]==')')l++;
while(1<=r&&s[r]=='(')r--;
if(l>r)break;
ans[++tot]=l,ans[++tot]=r;
l++,r--;
}
if(!tot)printf("0\n");
else{
printf("1\n");
printf("%d\n",tot);
sort(ans+1,ans+1+tot);
for(i=1;i<tot;i++)printf("%d ",ans[i]);
printf("%d\n",ans[tot]);
}
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 int long long
#define fir first
#define sec second
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);
int32_t main(){
int n,ans=0;
cin >> n;
priority_queue<int> pq;
for(int i=0;i<n;i++){
int x;
cin >> x;
pq.push(x);
if(i!=0){
if(x<pq.top()){
ans+=pq.top()-x;
pq.pop();
pq.push(x);
}
}
}
cout << ans;
return 0;
}
| cpp |
1290 | D | D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 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 3n22k3n22k 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 3n22k≤15 0003n22k≤15 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 3n22k3n22k 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 3n22k≤15 0003n22k≤15 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. | [
"constructive algorithms",
"graphs",
"interactive"
] | #include <bits/stdc++.h>
//#pragma GCC target("sse,sse2,avx2")
//#pragma GCC optimize("unroll-loops,O3")
#define rep(i,l,r) for (int i = l; i < r; i++)
#define repr(i,r,l) for (int i = r; i >= l; i--)
#define X first
#define Y second
#define all(x) (x).begin() , (x).end()
#define pb push_back
#define endl '\n'
#define debug(x) cerr << #x << " : " << x << endl;
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
constexpr int N = 1e6+10,mod = 1e9+7,maxm = 1026;
constexpr ll inf = 1e18+10;
inline int mkay(int a,int b){
if (a+b >= mod) return a+b-mod;
if (a+b < 0) return a+b+mod;
return a+b;
}
inline int poww(int a,int k){
if (k < 0) return 0;
int z = 1;
while (k){
if (k&1) z = 1ll*z*a%mod;
a = 1ll*a*a%mod;
k >>= 1;
}
return z;
}
int n,k,t;
int m;
int p[maxm];
bool vis[N],mark[N];
vector<pll> adj[maxm];
bool good[maxm];
vector<int> ve;
char ask(int i){
char c;
cout << "? " << i << endl;
cin >> c;
return c;
}
void rst(){
cout << "R\n";
}
void dfs(int v){
mark[v] = 1;
ve.pb(v);
while (p[v] < (int)adj[v].size()){
int u = adj[v][p[v]].X;
int i = adj[v][p[v]].Y;
p[v]++;
if (vis[i] || mark[u]) continue;
vis[i] = 1;
dfs(u);
return;
if (p[v] == (int) adj[v].size()) break;
}
}
int main(){
//ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> k;
rep(i,1,n+1) if (ask(i) == 'N') good[i] = 1;
rst();
if (k == 1){
rep(i,1,n+1){
if (!good[i]) continue;
rep(j,i+1,n+1){
if (!good[j]) continue;
ask(i);
if (ask(j) == 'Y') good[j] = 0;
rst();
}
}
int ans = 0;
rep(i,1,n+1) ans += good[i];
cout << "! " << ans << endl;
return 0;
}
k /= 2;
t = n/k;
rep(i,1,t+1) rep(j,i+2,t+1){
adj[i].pb({j,m});
// adj[j].pb({i,m});
m++;
}
int cur = 1;
while (cur <= t){
dfs(cur);
if (ve.size() == 1){
mark[cur] = 0;
ve.clear();
cur++;
continue;
}
rst();
for (int v : ve){
mark[v] = 0;
int l = (v-1)*k+1,r = v*k;
rep(i,l,r+1) if (good[i]){
char c = ask(i);
if (c == 'Y') good[i] = 0;
}
}
ve.clear();
}
int ans = 0;
rep(i,1,n+1) ans += good[i];
cout << "! " << ans << endl;
}
| 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;
typedef long long ll;
typedef vector<ll> v;
ll n, d;
int main()
{
long long t;
cin >> t;
while (t--)
{
cin >> n >> d;
if (n >= d)
{
cout << "YES" << endl;
}
else
{
if(2*sqrt(d)-1<=n) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
} | cpp |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/detail/standard_policies.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define FIO ios::sync_with_stdio(false); cin.tie(nullptr)
#define TC(t) int t; cin >> t; for(int i = 1; i <= t; i++)
#define ll long long int
#define ull unsigned long long int
#define lll __int128
#define lld long double
#define loop(i, a, b) for(ll i = a; i <= b; i++)
#define loop2(i, b, a) for(ll i = b; i >= a; i--)
#define ini(x, y) memset(x, y, sizeof(x))
#define all(x) x.begin(), x.end()
#define all2(x) x.rbegin(), x.rend()
#define sz(x) (ll)x.size()
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define M 1000000007
#define endl '\n'
#define bits(x) __builtin_popcountll(x)
#define zrbits(x) __builtin_ctzll(x)
#define vl vector<ll>
#define pll pair<ll,ll>
#define vpll vector<pll>
#define uni(x) x.erase(unique(all(x)), x.end())
#define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define multi_ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define mxheap priority_queue<ll>
#define mnheap priority_queue<ll, vector<ll>, greater<ll>>
#define mxheap2 priority_queue<pair<ll,ll>>
#define mnheap2 priority_queue<pair<ll,ll>, vector<pair<ll,ll>>, greater<pair<ll,ll>>>
const int N = 1e6 + 5;
const int L = 20;
const int MX = 1e9 + 10;
const ll INF = 1e18;
const int dx[] = {0, -1, 0, 1, -1, -1, 1, 1};
const int dy[] = {1, 0, -1, 0, 1, -1, -1, 1};
using namespace std;
using namespace __gnu_pbds;
inline ll uceil(ll a,ll b) {return (a % b ? a / b + 1 : a / b);}
inline ll mod(ll x) {return ( (x % M + M) % M );}
ll ulog(ll val, ll base) {ll cnt = 0; val /= base; while(val) {cnt++; val /= base;} return cnt;}
ll power(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a; a = a * a; b >>= 1;} return res;}
ll modpow(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a % M; a = a * a % M; b >>= 1;} return res;}
#ifdef FARHAN
#define deb(x) cerr << #x << " = " << x << endl;
#define deb2(x, y) cerr << #x << " = " << x << ", " << #y << " = " << y << endl;
#define deb3(x, y, z) cerr << #x << " = " << x << ", " << #y << " = " << y << ", " << #z << " = " << z << endl;
#define deb4() cerr << endl;
#define done cerr << "Line " << __LINE__ << " is done" << endl;
#else
#define deb(x)
#define deb2(x, y)
#define deb3(x, y, z)
#define deb4()
#define done
#endif
template<typename T> ostream& operator<<(ostream& os, const vector<T>& v) {for(auto& x : v) os << x << " "; return os;}
template<typename T> ostream& operator<<(ostream& os, const set<T>& v) {for(auto& x : v) os << x << " "; return os;}
template<typename T, typename S> ostream& operator<<(ostream& os, const pair<T, S>& p) {os << p.first << ' ' << p.second; return os;}
template<typename... T> void in(T&... args) {((cin >> args), ...);}
template<typename... T> void out(T&&... args) {((cout << args << endl), ...);}
template<typename... T> void out2(T&&... args) {((cout << args << " "), ...);}
template<typename... T> void out3(T&&... args) {((cout << args << " "), ...); cout << endl;}
struct grp {
ll def, att, coin;
};
bool comp(grp x, grp y) {
return (x.def < y.def);
}
ll seg[4*N], lazy[4*N];
void update(ll node, ll start, ll end, ll l, ll r, ll val) {
if(lazy[node] != 0) {
seg[node] += lazy[node];
if(start != end) {
lazy[2 * node + 1] += lazy[node];
lazy[2 * node + 2] += lazy[node];
}
lazy[node] = 0;
}
if(start > end || start > r || end < l) return;
if(start >= l && end <= r) {
seg[node] += val;
if(start != end) {
lazy[2 * node + 1] += val;
lazy[2 * node + 2] += val;
}
return;
}
ll mid = (start + end) >> 1;
update(2 * node + 1, start, mid, l, r, val);
update(2 * node + 2, mid + 1, end, l, r, val);
seg[node] = max(seg[2 * node + 1], seg[2 * node + 2]);
}
ll query(ll node, ll start, ll end, ll l, ll r) {
if(start > end || start > r || end < l) return -INF;
if(lazy[node] != 0) {
seg[node] += lazy[node];
if(start != end) {
lazy[2 * node + 1] += lazy[node];
lazy[2 * node + 2] += lazy[node];
}
lazy[node] = 0;
}
if(start >= l && end <= r) return seg[node];
ll mid = (start + end) >> 1;
ll left = query(2 * node + 1, start, mid, l, r);
ll right = query(2 * node + 2, mid + 1, end, l, r);
return max(left, right);
}
void solve() {
ll n, m, p;
cin >> n >> m >> p;
vector<pll> a(n);
for(ll i = 0; i < n; i++) {
cin >> a[i].ff >> a[i].ss;
}
vector<pll> b(m);
for(ll i = 0; i < m; i++) {
cin >> b[i].ff >> b[i].ss;
}
vector<grp> d(p);
for(ll i = 0; i < p; i++) {
cin >> d[i].def >> d[i].att >> d[i].coin;
}
vector<ll> mna(N, INF);
for(auto e : a) {
mna[e.ff] = min(mna[e.ff], e.ss);
}
for(ll i = N - 2; i >= 0; i--) {
mna[i] = min(mna[i + 1], mna[i]);
}
vector<ll> mnb(N, INF);
for(auto e : b) {
mnb[e.ff] = min(mnb[e.ff], e.ss);
}
for(ll i = N - 2; i >= 0; i--) {
mnb[i] = min(mnb[i + 1], mnb[i]);
}
ll ans = -INF;
ans = max(ans, -mna[0] - mnb[0]);
sort(all(d), comp);
for(ll i = 0; i < N; i++) {
update(0, 0, N - 1, i, i, -mnb[i]);
}
for(auto e : d) {
update(0, 0, N - 1, e.att + 1, N - 1, e.coin);
ans = max(ans, -mna[e.def + 1] + query(0, 0, N - 1, 0, N - 1));
}
cout << ans << endl;
}
signed main () {
#ifdef FARHAN
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
FIO;
// TC(t)
solve();
return 0;
} | cpp |
1312 | G | G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier. | [
"data structures",
"dfs and similar",
"dp"
] | #include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int st[N];
int rs[N],dp[N];
int e[N][27];
vector<pair<int,int>> stk;
int Rank;
void dfs(int u)
{
Rank+=st[u];
if(stk.size()&&st[u])
dp[u]=min(dp[u],stk.back().second+Rank);
//if(u==1)cout<<stk.size()<<endl;
//if(u)
// if(u!=5)
if(stk.empty()||stk.back().second>=dp[u]-Rank+st[u])
stk.push_back({u,dp[u]-Rank+st[u]});
//if(u==7){cout<<stk.back().second<<" "<<stk.back().second+Rank+1<<" "<<dp[u]<<endl;}
//cout<<stk.size()<<endl;
for(int i=0;i<26;++i)
{
if(!e[u][i])continue;
int v=e[u][i];
dp[v]=dp[u]+1;
dfs(v);
}
if(stk.size()&&stk.back().first==u)stk.pop_back();
}
int main()
{
int n,m;scanf("%d",&n);
char op[3];
for(int i=1,fa;i<=n;++i)
{
scanf("%d%s",&fa,op);e[fa][op[0]-'a']=i;
}
scanf("%d",&m);
for(int i=1;i<=m;++i)scanf("%d",&rs[i]),st[rs[i]]=1;
dfs(0);
for(int i=1;i<=m;++i)printf("%d%c",dp[rs[i]]," \n"[i==m]);
// cout<<stk.size();
} | 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 <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
#define int long long
typedef long long ll;
typedef pair<int, int> pii;
const ll mod = 1e9 + 7;
const ll inf = 2e9 + 7;
const ll maxn = 2e5 + 5;
#define pb push_back
#define fi first
#define se second
#define endl '\n'
#define all(x) (x).begin(), (x).end()
#define floral \
ios_base::sync_with_stdio(0); \
cin.tie(0); cout.tie(0)
int n, m, k;
void solve(){
cin >> n >> m >> k;
vector<int> a(n+2), b(m+2);
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= m; i++) cin >> b[i];
int mx = max(m, n);
vector<int> ca(mx+1), cb(mx+1);
int l = 1, r = 1;
while(l <= n){
if(a[l] == 0){
l++;
continue;
}
r = l;
while(a[r] == 1 and r <= n) r++;
int len = r - l;
for(int i = 1; i <= len; i++){
ca[i] += len - i + 1;
}
l = r;
}
l = 1, r = 1;
while(l <= m){
if(b[l] == 0){
l++;
continue;
}
r = l;
while(b[r] == 1 and r <= m) r++;
int len = r - l;
for(int i = 1; i <= len; i++){
cb[i] += len - i + 1;
}
l = r;
}
int ans = 0;
for(int i = 1; i <= mx; i++){
if(k % i == 0 and k / i <= mx){
ans += ca[i] * cb[k / i];
}
}
cout << ans << endl;
}
signed main(){
floral;
solve();
} | cpp |
1324 | A | A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.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 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process. | [
"implementation",
"number theory"
] | #include <bits/stdc++.h>
typedef long long ll;
#define endl '\n'
const int N = 234234;
ll n, T;
ll nums[N];
void solve()
{
std::cin >> n;
ll odd = 0, even = 0;
for (int i = 0; i < n; i++) {
int a;
std::cin >> a;
if (a & 1) {
odd ++;
} else even ++;
}
std::cout << (odd && even ? "NO" : "YES") << endl;
}
int main()
{
std::ios::sync_with_stdio(0);
std::cin.tie(0);
std::cout.tie(0);
std::cin >> T;
while (T--)
{
solve();
}
return 0;
} | cpp |
1305 | G | G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105) — the ages of the people.OutputOutput exactly one integer — the maximum possible combined gainings of all nn people.ExampleInputCopy3
1 2 3
OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it. | [
"bitmasks",
"brute force",
"dp",
"dsu",
"graphs"
] | // LUOGU_RID: 97972407
#include<stdio.h>
#include<bits/stdc++.h>
#define fir first
#define sec second
#define all(x) begin(x),end(x)
using namespace std;
typedef long long ll;
typedef unsigned uint;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef __int128 int128;
typedef __uint128_t uint128;
typedef pair<int,int> pii;
template<typename type>
inline void chmin(type &x,const type &y)
{
if(x>y)
x=y;
}
template<typename type>
inline void chmax(type &x,const type &y)
{
if(x<y)
x=y;
}
constexpr int Max=262144+100,Log=18,Lim=262144;
int n,a[Max],b[Max],fa[Max];
int find(int i)
{
return i==fa[i]?i:fa[i]=find(fa[i]);
}
inline bool unite(int x,int y)
{
x=find(x),y=find(y);
if(x!=y)
{
fa[x]=y;
return true;
}
return false;
}
struct node
{
int x1,y1,x2,y2;
inline node(const int &x,const int &y)
{
x1=x,y1=y,x2=0,y2=0;
}
inline node()
{
x1=y1=x2=y2=0;
}
};
node f[Max];
inline void clear()
{
for(int i=0;i<Lim;++i)
f[i]=node();
}
inline void update(node &a,const node &b)
{
if(b.x1>a.x1)
{
if(a.y1!=b.y1)
a.x2=a.x1,a.y2=a.y1;
a.x1=b.x1,a.y1=b.y1;
}
if(b.x1>a.x2&&b.y1!=a.y1)
a.x2=b.x1,a.y2=b.y1;
if(b.x2>a.x2&&b.y2!=a.y1)
a.x2=b.x2,a.y2=b.y2;
}
inline void solve()
{
for(int j=0;j<Log;++j)
for(int i=0;i<Lim;++i)
if(!(i>>j&1))
update(f[i],f[i|1<<j]);
}
int val[Max],pos[Max];
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
cin>>n;
for(int i=1;i<=n;++i)
cin>>a[i],b[i]=a[i]^(Lim-1);
for(int i=0;i<=n;++i)
fa[i]=i;
ll ans=0;
int cnt=n+1;
while(cnt>1)
{
clear();
for(int i=0;i<=n;++i)
update(f[b[i]],node(a[i],find(i)));
solve();
for(int i=0;i<=n;++i)
val[i]=-1,pos[i]=0;
for(int i=0;i<=n;++i)
{
const int x=find(i),k=a[i];
int u,v;
if(f[k].y1==x)
u=f[k].x2,v=f[k].y2;
else
u=f[k].x1,v=f[k].y1;
u+=a[i];
if(val[x]<u)
val[x]=u,pos[x]=v;
}
for(int i=0;i<=n;++i)
if(find(i)==i&&unite(i,pos[i]))
ans+=val[i],--cnt;
}
for(int i=1;i<=n;++i)
ans-=a[i];
cout<<ans<<"\n";
return 0;
} | cpp |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | #include<bits/stdc++.h>
#include<unordered_set>
using namespace std;
typedef long long ll;
vector<ll> bulbs;
unordered_map<string,int> mp;
ll min(ll a,ll b)
{
if(a<b) return a;
return b;
}
// odd--->0
int util(ll odd,ll even,ll i,ll prev)
{
string temp=to_string(odd)+"_"+to_string(even)+"_"+to_string(i)+"_"+to_string(prev);
if(mp.find(temp)!=mp.end()) return mp[temp];
if(i==bulbs.size()) return 0;
ll res=INT_MAX;
if(bulbs[i]!=0)
{
ll tp;
if(bulbs[i]%2==1) tp=0;
else tp=1;
if(i==0)
{
return mp[temp]=util(odd,even,i+1,tp);
}
if(prev==0&&bulbs[i]%2==0)
{
return mp[temp]= 1+util(odd,even,i+1,1);
}
else if(prev==1&&bulbs[i]%2==1)
{
return mp[temp]= 1+util(odd,even,i+1,0);
}
else
{
return mp[temp]= util(odd,even,i+1,tp);
}
}
else
{
if(i==0)
{
if(odd>0)
{
res=min(res,util(odd-1,even,i+1,0));
}
if(even>0)
{
res=min(res,util(odd,even-1,i+1,1));
}
return mp[temp]= res;
}
else
{
if(prev==0)
{
if(odd>0)
{
res=min(res,util(odd-1,even,i+1,0));
}
if(even>0)
{
res=min(res,1+util(odd,even-1,i+1,1));
}
return mp[temp]= res;
}
else
{
if(odd>0)
{
res=min(res,1+util(odd-1,even,i+1,0));
}
if(even>0)
{
res=min(res,util(odd,even-1,i+1,1));
}
return mp[temp]= res;
}
}
}
}
void solve(vector<ll> &bulbs)
{
ll odd=0;
ll even=0;
ll n=bulbs.size();
unordered_set<ll> us;
for(auto x:bulbs)
{
us.insert(x);
}
for(ll i=1;i<=n;i++)
{
if(us.find(i)==us.end())
{
if(i%2==0) even++;
else odd++;
}
}
ll res=util(odd,even,0,-1);
cout<<res<<"\n";
return ;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
ll n;
cin>>n;
bulbs.resize(n);
for(ll i=0;i<n;i++)
{
cin>>bulbs[i];
}
solve(bulbs);
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"
] | // LUOGU_RID: 92581424
#include <bits/stdc++.h>
using namespace std;
const int N = 4e5 + 6;
int T, n, m, ans, cnt[N], mx;
pair<int, int> q[N];
set<int> st;
inline void solve()
{
scanf("%d", &n);
ans = m = 0;
st.clear();
mx = -1;
for (int i = 1; i <= n; i++)
{
int l, r;
scanf("%d%d", &l, &r);
q[++m] = make_pair(l, -i);
q[++m] = make_pair(r, i);
}
sort(q + 1, q + m + 1);
for (int i = 1; i <= m; i++)
{
int j = q[i].second;
if (j > 0)
{
if (st.size() == 1)
cnt[j]--;
st.erase(j);
}
else
{
if (st.empty())
cnt[-j]--;
st.insert(-j);
}
if (st.empty())
ans++;
else if (st.size() == 1)
cnt[*st.begin()]++;
}
for (int i = 1; i <= n; i++)
mx = max(mx, cnt[i]), cnt[i] = 0;
printf("%d\n", mx + ans);
}
int main()
{
scanf("%d", &T);
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;
const int MAXN=200010;
int n,ans,dp[MAXN],mx[27];
char c[MAXN];
int main () {
scanf("%d%s",&n,c+1);
for (int i=n;i>=1;i--) {
dp[i]=mx[c[i]-'a']+1;
for (int j=c[i]-'a'+1;j<=25;j++) {mx[j]=max(mx[j],dp[i]);}
ans=max(ans,dp[i]);
}
printf("%d\n",ans);
for (int i=1;i<n;i++) {printf("%d ",dp[i]);}
printf("%d\n",dp[n]);
return 0;
} | cpp |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define mod 998244353
int check(int a[],int p,int n)
{
int ans=0;
for(int i=0;i<n;i++)
{
if(a[i]<p){ans+=(p-a[i]);continue;}
int x=a[i];
ans+=min(x%p,p-x%p);
}
return ans;
}
vector<int> primes(int x)
{
vector<int> v;
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
v.push_back(i);
while(x%i==0){x=x/i;}
}
}
if(x>1){v.push_back(x);}
return v;
}
std::mt19937 rng((unsigned int) std::chrono::steady_clock::now().time_since_epoch().count());
int32_t main()
{
// ios::sync_with_stdio(0);
// cin.tie(0);
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){cin>>a[i];}
int ans=1e15;
for(int i=0;i<25;i++)
{
int ind=rng()%n;
vector<int> v;
for(int x=a[ind]-1;x<=a[ind]+1;x++)
{
for(auto y:primes(x)){v.push_back(y);}
}
/* for(auto x:v)
{
if(check(a,x,n)==3){cout<<x<<"P\n";}
}*/
for(auto x:v){ans=min(ans,check(a,x,n));}
}
cout<<ans;
}
| cpp |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "debug.h"
#else
#define debug(...) 42
#endif
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, m, p;
cin >> n >> m >> p;
vector<int> a(n), b(m);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0; i < m; ++i) {
cin >> b[i];
}
int ans = 0;
for (int i = i = 0; i < n; ++i) {
if (a[i] % p) {
ans += i;
break;
}
}
for (int i = 0; i < m; ++i) {
if (b[i] % p) {
ans += i;
break;
}
}
cout << ans << '\n';
return 0;
} | 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>
#include <fstream>
#include <ext/rope> //header with rope
using namespace __gnu_cxx;
#define pb push_back
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#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 std;
const int N = 200001;
#define endl '\n'
#define int long long
#define ll long long
///int cnt[N+1]={0};
////vector<int>v[N+1];
/*int df(int x)
{
//// cout<<x<<" "<<dp[x]<<endl;
if(dp[x]!=-1)
{
/// cout<<x<<" "<<dp[x]<<endl;
return dp[x];
}
/// cout<<"ppp"<<endl;
int f=value[x];
dp[x]=n-x+df(f);
/// cout<<f<< " "<<dp[f]<<endl;
return dp[x];
}
*/
int func( int i, int j, vector<int>a, int k)
{
// Base condition.
if(i==0)
{
return 0;
}
// Initialize 'ans'= '0'.
int ans = 0;
// If no operation is applied on the 'i'th index.
if(j==0)
{
// Apply no operation the 'i-1'th index.
ans = max(ans, abs(a[i] - a[i-1]) + func(i-1, 0, a, k));
// Apply operation the 'i-1'th index.
ans = max(ans, abs(a[i] - (a[i-1]^k)) + func(i-1, 1, a, k));
}
// If operation is applied on the 'i' the index.
else
{
// Apply no operation the 'i-1'th index.
ans = max(ans, abs((a[i]^k) - a[i-1]) + func(i-1, 0, a, k));
// Apply operation the 'i-1'th index.
ans = max(ans, abs((a[i]^k) - (a[i-1]^k)) + func(i-1, 1, a, k));
}
return ans;
}
int xorOrNot(int n, int k, vector<int>a)
{
// If operation is not applied on the 'n-1'th index.
int ans1 = func(n-1,0,a,k);
// If operation is applied on the 'n-1'th index.
int ans2 = func(n-1,1,a,k);
// Return max of the 'ans1' and 'ans2' as the final answer.
return max(ans1,ans2);
}
class DSU
{
int* parent;
int* rank;
public:
DSU(int n)
{
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++)
{
parent[i] = -1;
rank[i] = 1;
}
}
// Find function
int find(int i)
{
if (parent[i] == -1)
return i;
return parent[i] = find(parent[i]);
}
// Union function
void unite(int x, int y)
{
int s1 = find(x);
int s2 = find(y);
if (s1 != s2)
{
if (rank[s1] < rank[s2])
{
parent[s1] = s2;
}
else if (rank[s1] > rank[s2])
{
parent[s2] = s1;
}
else
{
parent[s2] = s1;
rank[s1] += 1;
}
}
}
};
class Graph
{
vector<vector<int> > edgelist;
int V;
public:
Graph(int V)
{
this->V = V;
}
void addEdge(int x, int y, int w)
{
edgelist.push_back({ w, x, y });
}
void kruskals_mst()
{
// 1. Sort all edges
sort(edgelist.begin(), edgelist.end());
// Initialize the DSU
DSU s(V);
int ans = 0;
for (auto edge : edgelist)
{
int w = edge[0];
int x = edge[1];
int y = edge[2];
// Take this edge in MST if it does
// not forms a cycle
if (s.find(x) != s.find(y))
{
s.unite(x, y);
ans += w;
}
}
cout <<-ans;
}
};
int powe(int x, int y, int p)
{
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0) return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res%p;
}
void solve()
{
int n;
cin>>n;
// int a[n];
int m,k;
cin>>m>>k;
int ma=0;
map<int,int>p;
for( int i=0; i<m; i++)
{
int x;
cin>>x;
p[x]++;
ma=max(ma,x);
}
int u=(n+k-1)/k;
int ava=1+(n-1)%k;
if(ma>u ||( ma==u && p[ma]>ava))
{
cout<<"NO"<<endl;
}
else
{
cout<<"YES"<<endl;
}
}
long long calculate(long long p,
long long q,long long mod)
{
long long expo;
expo = mod - 2;
// Loop to find the value
// until the expo is not zero
while (expo)
{
// Multiply p with q
// if expo is odd
if (expo & 1)
{
p = (p * q) % mod;
}
q = (q * q) % mod;
// Reduce the value of
// expo by 2
expo >>= 1;
}
return p%mod;
}
int vis[N+1];
// array to store inverse of 1 to N
int factorialNumInverse[N + 1];
// array to precompute inverse of 1! to N!
int naturalNumInverse[N + 1];
// array to store factorial of first N numbers
int fact[N + 1];
// Function to precompute inverse of numbers
void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for (int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] * (p - p / i) % p;
}
// Function to precompute inverse of factorials
void InverseofFactorial(int p)
{
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// precompute inverse of natural numbers
for (int i = 2; i <= N; i++)
factorialNumInverse[i] = (calculate(1ll,i,p)* factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to N
void factorial(int p)
{
fact[0] = 1;
// precompute factorials
for (int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * i) % p;
}
}
// Function to return nCr % p in O(1) time
int Binomial(int N, int R, int p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
int ans = ((fact[N] * factorialNumInverse[R])
% p * factorialNumInverse[N - R])
% p;
return ans;
}
int seg[4*N+100],seg1[4*N+100],seg2[4*N+100],seg3[4*N+100];
void build(int node, int st, int en)
{
if (st == en)
{
// left node ,string the single array element
seg[node] = 1e9;
return;
}
int mid = (st + en) / 2;
// recursively call for left child
build(2 * node, st, mid);
// recursively call for the right child
build(2 * node + 1, mid + 1, en);
// Updating the parent with the values of the left and right child.
seg[node] = min(seg[2 * node],seg[2 * node + 1]);
}
void update(int node, int st, int en, int l, int r, int val)
{
if ((en < l) || (st > r)) // case 1
{
return;
}
if (st >= l && en <= r) // case 2
{
seg[node] = val;
return;
}
// case 3
int mid = (st + en) / 2;
// recursively call for updating left child
update(2 * node, st, mid, l, r, val);
// recursively call for updating right child
update(2 * node + 1, mid + 1, en, l, r, val);
// Updating the parent with the values of the left and right child.
seg[node] =min(seg[2 * node],seg[2 * node + 1]);
}
int query(int node, int st, int en, int l, int r)
{
// case 1
if (en < l || st > r)
{
return 1e9;
}
// case 2
if ((l <= st) && (en <= r))
{
return seg[node];
}
int mid = (st + en) / 2;
//query left child
ll q1 = query(2 * node, st, mid, l, r);
// query right child
ll q2 = query(2 * node + 1, mid + 1, en, l, r);
return min(q1,q2);
}
void build1(int node, int st, int en)
{
if (st == en)
{
// left node ,string the single array element
seg1[node] = 1e9;
return;
}
int mid = (st + en) / 2;
// recursively call for left child
build1(2 * node, st, mid);
// recursively call for the right child
build1(2 * node + 1, mid + 1, en);
// Updating the parent with the values of the left and right child.
seg1[node] = min(seg1[2 * node],seg1[2 * node + 1]);
}
void update1(int node, int st, int en, int l, int r, int val)
{
if ((en < l) || (st > r)) // case 1
{
return;
}
if (st >= l && en <= r) // case 2
{
seg1[node] = val;
return;
}
// case 3
int mid = (st + en) / 2;
// recursively call for updating left child
update1(2 * node, st, mid, l, r, val);
// recursively call for updating right child
update1(2 * node + 1, mid + 1, en, l, r, val);
// Updating the parent with the values of the left and right child.
seg1[node] =min(seg1[2 * node],seg1[2 * node + 1]);
}
int query1(int node, int st, int en, int l, int r)
{
// case 1
if (en < l || st > r)
{
return 1e9;
}
// case 2
if ((l <= st) && (en <= r))
{
return seg1[node];
}
int mid = (st + en) / 2;
//query left child
ll q1 = query1(2 * node, st, mid, l, r);
// query right child
ll q2 = query1(2 * node + 1, mid + 1, en, l, r);
return min(q1,q2);
}
void build2(int node, int st, int en)
{
if (st == en)
{
// left node ,string the single array element
seg2[node] = 1e9;
return;
}
int mid = (st + en) / 2;
// recursively call for left child
build2(2 * node, st, mid);
// recursively call for the right child
build2(2 * node + 1, mid + 1, en);
// Updating the parent with the values of the left and right child.
seg2[node] = min(seg2[2 * node],seg2[2 * node + 1]);
}
void update2(int node, int st, int en, int l, int r, int val)
{
if ((en < l) || (st > r)) // case 1
{
return;
}
if (st >= l && en <= r) // case 2
{
seg2[node] = val;
return;
}
// case 3
int mid = (st + en) / 2;
// recursively call for updating left child
update2(2 * node, st, mid, l, r, val);
// recursively call for updating right child
update2(2 * node + 1, mid + 1, en, l, r, val);
// Updating the parent with the values of the left and right child.
seg2[node] =min(seg2[2 * node],seg2[2 * node + 1]);
}
int query2(int node, int st, int en, int l, int r)
{
// case 1
if (en < l || st > r)
{
return 1e9;
}
// case 2
if ((l <= st) && (en <= r))
{
return seg2[node];
}
int mid = (st + en) / 2;
//query left child
ll q1 = query2(2 * node, st, mid, l, r);
// query right child
ll q2 = query2(2 * node + 1, mid + 1, en, l, r);
return min(q1,q2);
}
void build3(int node, int st, int en)
{
if (st == en)
{
// left node ,string the single array element
seg3[node] = 1e9;
return;
}
int mid = (st + en) / 2;
// recursively call for left child
build3(2 * node, st, mid);
// recursively call for the right child
build3(2 * node + 1, mid + 1, en);
// Updating the parent with the values of the left and right child.
seg3[node] = min(seg3[2 * node],seg3[2 * node + 1]);
}
void update3(int node, int st, int en, int l, int r, int val)
{
if ((en < l) || (st > r)) // case 1
{
return;
}
if (st >= l && en <= r) // case 2
{
seg3[node] = val;
return;
}
// case 3
int mid = (st + en) / 2;
// recursively call for updating left child
update3(2 * node, st, mid, l, r, val);
// recursively call for updating right child
update3(2 * node + 1, mid + 1, en, l, r, val);
// Updating the parent with the values of the left and right child.
seg3[node] =min(seg3[2 * node],seg3[2 * node + 1]);
}
int query3(int node, int st, int en, int l, int r)
{
// case 1
if (en < l || st > r)
{
return 1e9;
}
// case 2
if ((l <= st) && (en <= r))
{
return seg3[node];
}
int mid = (st + en) / 2;
//query left child
ll q1 = query3(2 * node, st, mid, l, r);
// query right child
ll q2 = query3(2 * node + 1, mid + 1, en, l, r);
return min(q1,q2);
}
int mi[5001],ma[5001];
int parent[6001];
int c1[N],c2[N];
int g=0;
void binarytree(int n,int depth,int pa)
{
if( n==0)
{
return ;
}
g++;
parent[g]=pa;
int h=depth-(n-1);
for( int i=0; i<=n-1; i++)
{
if( ma[i]+ma[n-1-i]>=h && h>=mi[i]+mi[n-1-i])
{
}
}
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int t = 1;
int nj=5000;
for( int i=1; i<=nj; i++)
{
ma[i]=(i*(i-1))/2;
int y=i;
int de=0;
int u=1;
while( y>0)
{
mi[i]+=min(u,y)*de;
de++;
y-=min(u,y);
u=u*2ll;
}
}
cin >> t;
for (int tc = 0; tc < t; tc++)
{
int n,d;
cin>>n>>d;
///cout<<mi[n]<<endl;
if( d<mi[n] || d>ma[n] ){
cout<<"NO"<<endl;
continue;
}
cout<<"YES"<<endl;
int tot[110]={0};
int u=1;
int h=n;
for( int i=0;i<=109;i++){
if( h==0)break;
tot[i]=min(h,u);
h-=tot[i];
u*=2;
}
for( int i=0;i<d-mi[n];i++){
for( int i=108;i>=0;i--){
if( tot[i]>1){
tot[i]--;
tot[i+1]++;
break;
}
}
}
int g=1;
int ans[n+100]={0};
vector<int>v[110];
for( int i=0;i<=109;i++){
for( int j=0;j<tot[i];j++){
v[i].pb(g++);
}
}
for( int i=1;i<=109;i++){
for( int j=0;j<tot[i];j++){
ans[v[i][j]]=v[i-1][j/2];
}
}
for( int i=2;i<=n;i++){
cout<<ans[i]<<" ";
}
cout<<endl;
}
return 0;
}
| 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;
#define pb emplace_back
const int MN=8e4;
int N, at=170, dist[MN], ans = MN; bool pvis[1001], vis[MN];
set<int> start; vector<int> prime, vals, adj[MN];
unordered_map<int, int> ind; // (value, index it maps to)
queue<pair<int, pair<int, int> > > next1; // (distance, (node, parent))
void bfs(int j){ memset(vis, 0, sizeof(vis)); next1.push({0, {j, j}});
while (!next1.empty()) { int d = next1.front().first;
int x = next1.front().second.first; int p = next1.front().second.second;
next1.pop(); if(adj[x].size()<=1 || vis[x]) continue;
vis[x]=1; dist[x] = d; bool skip=0;
for (int i: adj[x])
if (i != p || skip)
{ if (vis[i]) ans = min(ans, dist[i] + dist[x] + 1);
else next1.push({d + 1, {i, x}}); }
else skip = 1;
}
adj[j].clear();
}
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
prime.reserve(170); 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=1; 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) bfs(j);
cout << (ans == MN ? -1 : 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 <bits/stdc++.h>
#pragma GCC optimize("O3,Ofast,fast-math")
using namespace std;
#define int long long
vector <int> a, b;
int ac(int x) {
int ans = 0;
int now = 0;
for (int i = 0; i < a.size(); i++) {
if (a[i]) now++;
else now = 0;
if (now >= x) ans++;
}
return ans;
}
int bc(int x) {
int ans = 0;
int now = 0;
for (int i = 0; i < b.size(); i++) {
if (b[i]) now++;
else now = 0;
if (now >= x) ans++;
}
return ans;
}
signed main() {
int n, m;
cin >> n >> m;
a.resize(n), b.resize(m);
int k; cin >> k;
for (int i = 0; i < n; i++) cin >> a[i];
for (int j = 0; j < m; j++) cin >> b[j];
long long answer = 0;
for (int i = 1; i * i <= k; i++) {
if (k % i != 0) continue;
answer += ac(i) * bc(k / i);
if (i * i != k) answer += ac(k / i) * bc(i);
}
cout << answer;
} | cpp |
1304 | F2 | F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp",
"greedy"
] | // LUOGU_RID: 101625819
#pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define int long long
int read()
{
int s=0; char c=getchar();
while(c<'0' || c>'9') c=getchar();
while(c>='0' && c<='9') s=s*10+c-'0',c=getchar();
return s;
}
int n,m,k; int a[55][20010],b[55][20010];
int sum[55][20010];
int dp[55][20010];
struct Tree
{
int ax1,ax2,ax3,ax4;
} tree[80010];
Tree merge(Tree x,Tree y)
{
return {max(x.ax1,y.ax1),max(x.ax2,y.ax2),max(x.ax3,y.ax3),max(x.ax4,y.ax4)};
}
void build(int now,int qx,int l,int r)
{
if(l==r)
{
tree[now]={dp[qx][l]+sum[qx][l+k-1]-sum[qx][l-1],dp[qx][l]-sum[qx][l-1],
dp[qx][l]+sum[qx][l+k-1],dp[qx][l]+sum[qx][l+k-1]-sum[qx][l-1]};
return;
}
int mid=(l+r)>>1;
build(now<<1,qx,l,mid),build(now<<1|1,qx,mid+1,r);
tree[now]=merge(tree[now<<1],tree[now<<1|1]);
}
int query(int now,int ql,int qr,int l,int r,int op)
{
ql=max(ql,1ll),qr=min(qr,m-k+1);
if(ql>qr) return -1e9;
if(ql<=l && r<=qr) return op==1?tree[now].ax1:op==2?tree[now].ax2:op==3?tree[now].ax3:tree[now].ax4;
int mid=(l+r)>>1,ans=-1e9;
if(ql<=mid) ans=max(ans,query(now<<1,ql,qr,l,mid,op));
if(qr>mid) ans=max(ans,query(now<<1|1,ql,qr,mid+1,r,op));
return ans;
}
signed main()
{
n=read(),m=read(),k=read();
for(int i=1; i<=n; ++i)
{
for(int j=1; j<=m; ++j)
{
a[i][j]=read();
}
}
for(int i=1; i<=n; ++i)
{
for(int j=1; j<=m; ++j)
{
sum[i][j]=sum[i][j-1]+a[n-i+1][j];
}
}
build(1,1,1,m-k+1);
for(int i=2; i<=n; ++i)
{
for(int j=1; j<=m-k+1; ++j)
{
dp[i][j]=max(dp[i][j],query(1,1,j-k,1,m-k+1,1)+sum[i-1][j+k-1]-sum[i-1][j-1]);
dp[i][j]=max(dp[i][j],query(1,j-k+1,j,1,m-k+1,2)+sum[i-1][j+k-1]);
dp[i][j]=max(dp[i][j],query(1,j,j+k-1,1,m-k+1,3)-sum[i-1][j-1]);
dp[i][j]=max(dp[i][j],query(1,j+k,m-k+1,1,m-k+1,4)+sum[i-1][j+k-1]-sum[i-1][j-1]);
}
build(1,i,1,m-k+1);
}
int ans=0;
for(int i=1; i<=m-k+1; ++i) ans=max(ans,dp[n][i]+sum[n][i+k-1]-sum[n][i-1]);
cout<<ans;
return 0;
} | cpp |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"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;
vi vec(n);
for (int i = 0; i < n; ++i) {
cin >> vec[i];
}
int ans = 0;
vb seen(n);
for (int l = 0; l < n; l++) {
if (vec[l] == 0) continue;
if (seen[l]) continue;
seen[l] = 1;
int count = 1;
int r = (l + 1) % n;
for (; r != l; r = (r + 1) % n) {
if (vec[r] == 0) break;
seen[r] = 1;
count++;
}
l = r;
ans = max(ans, count);
}
cout << ans;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
//ifstream cin ("puzzle_name.in");
//ofstream cout ("puzzle_name.out");
solve();
return 0;
}
| cpp |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | #include <bits/stdc++.h>
#define fi first
#define se second
#define faster ios_base::sync_with_stdio(0); cin.tie(0);
#define pb push_back
using namespace std;
using ll = long long;
using pii = pair <int, int>;
mt19937_64 Rand(chrono::steady_clock::now().time_since_epoch().count());
const int maxN = 2e5 + 1;
const int inf = 0x3f3f3f3f;
const int Mod = 1e9 + 7;
ll a[maxN];
int n;
bool in[maxN * 5];
vector <int> P;
inline int rd(int l, int r){
return l + Rand() % (r - l + 1);
}
void Sieve(){
for (int i = 2; i <= 1e6; ++i){
if (!in[i]){
P.pb(i);
for (int j = i * 2; j <= 1e6; j += i)
in[j] = 1;
}
}
}
int check(ll x){
if (x == 0) return n;
vector <ll> S;
for (int i: P){
if (x % i == 0){
S.pb(i);
while (x % i == 0) x /= i;
}
}
if (x != 1) S.pb(x);
ll res = n;
for (ll i: S){
ll cnt = 0;
for (int j = 1; j <= n; ++j){
cnt += min(a[j] < i ? n : a[j] % i, i - (a[j] % i));
}
res = min(res, cnt);
}
return res;
}
void Init(){
cin >> n;
Sieve();
for (int i = 1; i <= n; ++i){
cin >> a[i];
}
vector <int> b;
for (int i = 0; i < 50; ++i) b.pb(rd(1, n));
int ans = n;
for (int i: b){
ans = min(ans, check(a[i]));
ans = min(ans, check(a[i] - 1));
ans = min(ans, check(a[i] + 1));
}
cout << ans;
}
#define taskname "test"
signed main(){
faster
if (fopen(taskname ".inp", "r")){
freopen(taskname ".inp", "r", stdin);
freopen(taskname ".out", "w", stdout);
}
int tt = 1;
//cin >> tt;
while (tt--){
Init();
}
if (fopen("timeout.txt", "r")){
ofstream timeout("timeout.txt");
cerr << "Time elapsed: " << signed(double(clock()) / CLOCKS_PER_SEC * 1000) << "ms\n";
timeout << signed(double(clock()) / CLOCKS_PER_SEC * 1000);
timeout.close();
}
}
| cpp |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
const int N = 1505;
int sums[N];
void solve() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> sums[i];
sums[i] += sums[i - 1];
}
unordered_map<int, vector<pair<int, int>>> pos;
for (int i = 1; i <= n; ++i) {
for (int j = i; j <= n; ++j) {
pos[sums[j] - sums[i - 1]].emplace_back(i, j);
}
}
int cnt = 0, val = 0;
for (auto &[v, vec] : pos) {
if (vec.size() < cnt) continue;
sort(vec.begin(), vec.end(), [](auto &x, auto &y) { // se越靠前越好
return x.second < y.second;
});
int last = -1, cur = 0;
for (auto &[fi, se] : vec) {
if (fi <= last) continue;
++cur;
last = se;
}
if (cur > cnt) {
cnt = cur;
val = v;
}
}
cout << cnt << '\n';
int last = -1;
for (auto &[fi, se] : pos[val]) {
if (fi <= last) continue;
cout << fi << ' ' << se << '\n';
last = se;
}
}
int main() {
cin.tie(0)->sync_with_stdio(0);
solve();
return 0;
} | 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;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define fi first
#define se second
#define n_l '\n'
using ll = long long;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
using ld = long double;
using ull = uint64_t;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
using vvl = vector<vector<ll>>;
#define gg(...) [](const auto&...x){ char c='='; cerr<<#__VA_ARGS__<<" "; ((cerr<<exchange(c,',')<<" "<<x),...); cerr<<endl; }(__VA_ARGS__);
int nxt() { int x; cin >> x; return x; }
// const uint64_t mod = (1ULL << 61) - 1;
// const uint64_t seed = chrono::system_clock::now().time_since_epoch().count();
// const uint64_t base = mt19937_64(seed)() % (mod / 3) + (mod / 3);
// #include <atcoder/dsu>
// #include <atcoder/lazysegtree>
// #include <atcoder/segtree>
// #include <atcoder/modint>
// using namespace atcoder;
// using mint = modint998244353;
const ll INF = 1e18;
ll tests;
ll n, m;
void solve() {
cin >> n;
vl a(n); rep(i, 0, n) cin >> a[i];
vl aor(n+1);
for (int i = n-1; i >= 0; i--) {
aor[i] = aor[i+1] | a[i];
}
ll bor = 0;
vl v;
rep(i, 0, n) v.pb(a[i]);
ll ans = 0;
rep(i, 0, n) {
ll fullor = aor[i+1] | bor;
ll cres = a[i] & (~fullor);
if (cres > ans) {
ans = cres;
swap(v[0], v[i]);
}
bor |= a[i];
}
// gg(ans);
for(ll x: v) cout << x << ' '; cout << endl;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
// tests = nxt();
// while(tests--) {
solve();
// }
}
// 6 - 5 - 4 - 3 - 2 - 1 - 6
// 1 - 2 - 3 - 6 - 5 - 4 - 1 | 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 namespace std;
#define ll long long
#define ull unsigned long long
#define mk make_pair
#define lowbit(x) (x&(-x))
#define pb emplace_back
#define pr pair<int,int>
#define let const auto
const int N=1e6+5;
int read(){
int x=0,f=1; char c=getchar();
while(('0'>c||c>'9')&&c!='-') c=getchar();
if(c=='-') f=0,c=getchar();
while('0'<=c&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return f?x:-x;
}
int n,a[N],nxt[N],fa[N];
ll pre[N];
struct node{
ll v;int l,r;
int len(){return r-l+1;}
bool operator<(node b)const{return 1ll*v*b.len()>1ll*b.v*(r-l+1);}
};
int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}
int main(){
n=read();
for(int i=1; i<=n; i++) a[i]=read(),pre[i]=pre[i-1]+a[i];
priority_queue <node> q;
for(int i=1; i<=n; i++) nxt[i]=i,q.push({a[i],i,i}),fa[i]=i;
while(!q.empty()){
auto [v,l,r]=q.top(); q.pop();
if(nxt[l]!=r) continue;
if(l==1) continue;
int las=find(l-1);
if(1ll*(pre[l-1]-pre[las-1])*(r-l+1)>=1ll*v*(l-las)){
fa[l]=las; nxt[las]=r;
q.push({pre[r]-pre[las-1],las,r});
}
}
for(int i=1; i<=n; i=nxt[i]+1){
double res=1.0*(pre[nxt[i]]-pre[i-1])/(nxt[i]-i+1);
for(int j=i; j<=nxt[i]; j++) printf("%.10lf\n",res);
}
return 0;
}
| cpp |
1310 | D | D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
OutputCopy2
InputCopy3 2
0 1 1
2 0 1
2 2 0
OutputCopy3
| [
"dp",
"graphs",
"probabilities"
] | #include <bits/stdc++.h>
#define For(i, a, b) for (int i = a, i##end = b; i <= i##end; ++i)
#define rFor(i, b, a) for (int i = b, i##end = a; i >= i##end; --i)
#define eFor(i, u, v) for (int i = head[u], v = e[i].to; i; i = e[i].next, v = e[i].to)
typedef long long ll;
using std::cin;
using std::cout;
using std::endl;
typedef std::pair<int, int> pii;
#define fi first
#define se second
std::mt19937 rnd(std::chrono::steady_clock::now().time_since_epoch().count());
template<typename T> T myrand(T l, T r) {
return std::uniform_int_distribution<T>(l, r)(rnd);
}
void close_stdio() {
std::ios::sync_with_stdio(false);
std::cerr << "DO NOT use scanf/printf!\n";
}
const int kN = 85;
const int kK = 15;
int n, k, e[kN][kN], d[kN][kK], c[kN];
int main() {
scanf("%d%d", &n, &k);
For(i, 1, n) For(j, 1, n) scanf("%d", &e[i][j]);
int T = 5000, ans = 0x3f3f3f3f;
while (T--) {
memset(d, 0x3f, sizeof(d));
For(i, 1, n) c[i] = myrand(0, 1);
d[1][0] = 0;
For(i, 0, k - 1) For(u, 1, n) if (d[u][i] < 0x3f3f3f3f) {
For(v, 1, n) if (c[u] != c[v])
d[v][i + 1] = std::min(d[v][i + 1], d[u][i] + e[u][v]);
}
ans = std::min(ans, d[1][k]);
}
printf("%d", ans);
return 0;
}
/* PAY ATTENTION TO: */
/* 1. Memory Limit, Array Size */
/* 2. Integer Overflow */
/* 3. Multi-test */
/* 4. Potential Constant-speedup */
/* Stay organized and write things down. */
| cpp |
1295 | E | E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
| [
"data structures",
"divide and conquer"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
typedef long long ll;
const double PI = acos(-1.0);
const int maxn = 2e5 + 7;
int n,m, a[maxn], b[maxn], pos[maxn], val[maxn];
struct segment_tree {
struct tree {
int l, r, lazy, mi;
}tr[maxn * 4];
inline void build(int p, int l, int r) {
tr[p].l = l, tr[p].r = r;
if (l == r) {
tr[p].mi = a[l];
tr[p].lazy = 0;
return;
}
int mid = (l + r) >> 1;
build(p * 2, l, mid);
build(p * 2 + 1, mid + 1, r);
tr[p].mi = min(tr[p * 2].mi, tr[p * 2 + 1].mi);
return;
}
inline void push_down(int p) {
if (tr[p].lazy != 0) { //如果父节点lazy标记不为0,既让lazy标记下传
tr[p * 2].lazy += tr[p].lazy;
tr[p * 2 + 1].lazy += tr[p].lazy;
int mid = (tr[p].l + tr[p].r) >> 1;
tr[p * 2].mi += tr[p].lazy;//改变两个子节点的maxv
tr[p * 2 + 1].mi += tr[p].lazy;
tr[p].lazy = 0;//下传后自己的lazy标记变为0
}
}
inline void add(int p, int l, int r, int k) {
if (tr[p].l >= l && tr[p].r <= r) {
tr[p].mi += k;
tr[p].lazy += k; //完全包含就将lazy标记加上k用来之后传给子节点
return;
}
push_down(p); //如果没有完全找到就往下找,同时下传lazy和子节点的maxv;
if (tr[p * 2].r >= l) add(p * 2, l, r, k); //哪边有交集就往哪边走;
if (tr[p * 2 + 1].l <= r) add(p * 2 + 1, l, r, k);
tr[p].mi = min(tr[p * 2].mi , tr[p * 2 + 1].mi);//自下向上更新maxv
return;
}
inline int search(int p, int l, int r) {
if (tr[p].l >= l && tr[p].r <= r) { //如果完全包含就返回maxv,并加在s上
return tr[p].mi;
}
if (tr[p].l > r || tr[p].r < l) return 0;
push_down(p);////如果没有完全找到就往下找,同时下传lazy和子节点的maxv;
int s = 0;
if (tr[p * 2].r >= l) s = min(s, search(p * 2, l, r));
if (tr[p * 2 + 1].l <= r) s = min(s, search(p * 2 + 1, l, r));
return s;
}
}ST;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n;
for(int i = 1; i <= n; i++){
cin >> b[i];
pos[b[i]] = i;
}
for(int i = 1, x; i <= n; i++){
cin >> x;
val[b[i]] = x;
a[i] = a[i - 1] + x;
}
ST.build(1, 1, n - 1);
ll ans = ST.tr[1].mi;
for(int i = 1; i <= n; i++){
// cout << ST.tr[1].mi << '\n';
if(1 <= pos[i] - 1)ST.add(1, 1, pos[i] - 1, val[i]);
if(pos[i] <= n - 1)ST.add(1, pos[i], n - 1, -val[i]);
ans = min(ans, ST.tr[1].mi);
}
cout << ans << '\n';
} | cpp |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"data structures",
"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);
for (int i = 0; i < n; i++) {
std::cin >> a[i];
}
std::vector<int> s(n + 1);
for (int i = 0; i < n; i++) {
s[i + 1] = s[i] + a[i];
}
std::map<int, std::vector<std::pair<int, int>>> rag;
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
rag[s[j] - s[i - 1]].emplace_back(j, i);
}
}
std::vector<std::pair<int, int>> ans;
for (auto [x, v] : rag) {
std::sort(v.begin(), v.end());
int l = 0, r = 0;
std::vector<std::pair<int, int>> res;
for (auto p : v) {
if (res.empty() || p.second > res.back().first) {
res.emplace_back(p);
}
}
if (res.size() > ans.size()) ans = res;
}
std::cout << ans.size() << "\n";
for (auto [r, l] : ans) {
std::cout << l << " " << r << "\n";
}
return 0;
} | cpp |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] | #include <bits/stdc++.h>
using namespace std;
vector<int> distances (int s, int n ,vector<vector<int>> & adj) {
vector<bool> visited(n, false);
vector<int> dist(n, -1);
queue<int> Q;
dist[s] = 0;
visited[s] = true;
Q.push(s);
while(!Q.empty()) {
int v = Q.front();
Q.pop();
for (auto i: adj[v])
if (!visited[i]) {
visited[i] = true;
dist[i] = dist[v] + 1;
Q.push(i);
}
}
return dist;
}
pair<int, int> route_rebuild(int v, vector<vector<int>> &adj, vector<int> & dist, int next) {
int rebuilds_min = 0;
int rebuilds_max = 0;
if (dist[v] <= dist[next]) {
rebuilds_min++;
rebuilds_max++;
return {rebuilds_min, rebuilds_max};
}
int cont = 0;
for(int i: adj[v]) {
if (dist[i] == dist[next])
cont++;
if(cont == 2) {
rebuilds_max++;
break;
}
}
return {rebuilds_min, rebuilds_max};
}
int main() {
int n, m, a, b, k, x;
ios::sync_with_stdio(0); cin.tie(0);
cin >> n >> m;
vector<vector<int>> adj(n);
vector<vector<int>> adj_reverse(n);
for(int i=0; i < m; i++) {
cin >> a >> b;
a--; b--;
adj[a].push_back(b);
adj_reverse[b].push_back(a);
}
cin >> k;
vector<int> route(k);
for(int i=0; i < k; i++) {
cin >> x;
route[i] = x - 1;
}
int s = route.front(); int f = route.back();
vector<int> dist = distances(f, n, adj_reverse);
pair<int, int> rebuild = {0, 0};
pair<int, int> aux;
for (int i=0; i < k-1; i++) {
aux = route_rebuild(route[i], adj, dist, route[i+1]);
rebuild.first += aux.first;
rebuild.second += aux.second;
}
cout << rebuild.first << " " << rebuild.second;
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<iostream>
#include <bits/stdc++.h>
using namespace std;
template<class container> void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;}
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define nd "\n"
#define all(x) (x).begin(), (x).end()
#define popcount(x) __builtin_popcount(x)
const ll N = 2e5+50 , LOG = 22 , inf = 1e8 , SQ= 550 , mod = 1e9+7;
#define py cout <<"YES"<<endl;
#define pn cout <<"NO"<<endl;
#define pp cout <<"ppppppppppppppppp"<<nd;
#define lol cout <<"i am here"<<nd;
const double PI = acos(-1.0);
const int MX = 1000+10;
template <typename T> using min_heap = priority_queue<T , vector <T > , greater <T > >;
vector< vector <int > > g(N);
ll n;
vector <int > get(){
auto bfs =[&](int src)->pair<int , vector <int > > {
vector <int > par(n+5 , -1);
deque<int > q;
q.emplace_back(src);
vector <int > dist(n+5 , inf);
dist[src] = 0;
int cur = src;
while (!q.empty()){
int sz = (int)q.size();
while (sz--){
int node = q.front(); q.pop_front();
for (auto &ch : g[node]){
if (dist[ch] > dist[node]+1){
dist[ch] = 1+ dist[node];
q.emplace_back(ch);
par[ch] = node;
}
}
cur = node;
}
}
return {cur , par};
};
auto p1 = bfs(1);
auto p2 = bfs(p1.first);
int node = p2.first;
vector <int > ans;
while (node != -1) {
ans.emplace_back(node);
node = p2.second[node];
}
return ans;
}
void hi(){
cin >> n;
for (int i = 1; i < n; ++i){ ll u , v;
cin >> u >> v;
g[u].emplace_back(v);
g[v].emplace_back(u);
}
vector <int >path = get();
if ((int)path.size() == n){
cout << n -1<< nd;
cout << path.front() <<" "<< path[1] <<" "<< path.back() <<nd;
return;
}
//print(path);
//pp;
vector <int > mark(n+5);
for (auto &u : path) mark[u] = 1;
vector<int > dist(n+5 , inf);
deque<int > q;
for (auto &u : path){
q.emplace_back(u);
dist[u] = 0;
}
int last = -1;
while (!q.empty()){
int sz = (int)q.size();
while (sz--){
int node = q.front(); q.pop_front();
for (auto &ch : g[node]){
if (dist[ch] > dist[node]+1){
dist[ch] = 1 + dist[node];
q.emplace_back(ch);
}
}
last = node;
}
}
assert(~last);
cout << (int)path.size()+ dist[last]-1 <<nd;
cout << path.front() <<" "<< last <<" "<< path.back() <<nd;
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
int tt = 1 , tc = 0;
// cin >> tt;
while(tt--) hi();
return 0;
}
| cpp |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
#define sp ' '
#define pb push_back
#define assert(x,a) if(x){cout << a << endl;return;}
#define sortv(x)sort(x.begin(),x.end())
#define revev(x)reverse(x.begin(),x.end())
const ll mod = 1000000007;
vector<vector<int>>graph;
map<int,int>mapping;
int id = 1;
inline void fast(){
std::ios_base::sync_with_stdio(0);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
}
using namespace std;
ll gcd(ll a,ll b)
{
if ( b == 0 ) return a;
return gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return (a * b) / gcd(a,b);
}
void debug(vector<int>&l)
{
for(auto &it : l)cout << it << sp;
cout << endl;
}
void solve()
{
int a,b;cin >>a >> b;
vector<int>l(a);for(int &e : l)cin >> e;
vector<int>pairs(b);for(int &e : pairs)cin >> e;
sortv(pairs);
map<int,int>w;
int last_one = -2;
for(int i = 0;i < pairs.size();i++)
{
if(pairs[i] != a)
{
w[l[pairs[i] - 1]]++;
if(last_one == -2)
{
last_one = pairs[i] - 1;
}
}
if(i + 1 != pairs.size() && pairs[i + 1] - 1== pairs[i])
{
continue;
}
else
{
w[l[pairs[i]]]++;
auto it = w.begin();
for (int j = last_one; j<= pairs[i]; j++)
{
if (it->second != 0)
l[j] = it->first;
it->second--;
while (it != w.end() && it->second == 0)
it++;
}
last_one = -2;
w.clear();
}
}
if(is_sorted(l.begin(),l.end()))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
int main()
{
fast();
ll t{ 1 };cin >> t;
// cin.ignore();
while (t--)
{
solve();
}
}
| 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 <bits/stdc++.h>
using namespace std;
const int N = 505;
int a[N];
int f[N][N];
int dp[N];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
f[i][i] = a[i];
}
for (int len = 2; len <= n; len++) {
for (int l = 1; l + len - 1 <= n; l++) {
int r = l + len - 1;
for (int j = l; j < r; j++) {
if (f[l][j] && f[l][j] == f[j + 1][r])
f[l][r] = f[l][j] + 1;
}
}
}
for (int i = 1; i <= n; i++) {
dp[i] = 1e7;
for (int j = 0; j < i; j++)
if (f[j + 1][i]) dp[i] = min(dp[i], dp[j] + 1);
}
cout << dp[n] << endl;
} | cpp |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | #include<bits/stdc++.h>
int i,j,k,n,m,a[100];int main(){
for(scanf("%*d");~scanf("%d%d",&n,&m);i=j=0){std::set<int>p;
for(;i<n;i++)scanf("%d",a+i);while(m--)scanf("%d",&i),p.insert(i);
for(k=1;k<=n;k++)if(!p.count(k))std::sort(a+j,a+k),j=k;
puts(std::is_sorted(a,a+n)?"YES":"NO");
}} | 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"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fr(i,a,b,k) for(int i=a;i<b;i+=k)
#define frrev(i,a,b,k) for(int i=a;i>b;i-=k)
#define NO cout<<"NO\n"
#define YES cout<<"YES\n"
#define V vector<ll int>
#define VP vector<pair<ll int,ll int>>
#define MP map<ll int,ll int>
#define pb push_back
#define ff first
#define ss second
#define input(A) for(auto &i:A)cin>>i
#define output(A) for(auto &i:A)cout<<i<<" "
void solve(int t)
{
int x,y,a,b;
cin>>x>>y>>a>>b;
if((y-x)%(a+b)!=0)
cout<<"-1\n";
else
cout<<(y-x)/(a+b)<<endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
for(int i=1;i<=t;i++)
{
solve(t);
}
return 0;
}
| cpp |
1141 | C | C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1
| [
"math"
] | #include<iostream>
#include<iterator>
#include<ranges>
#include<vector>
#include<algorithm>
void solve_test_case();
int main()
{
unsigned t{ 1 };
do
solve_test_case();
while (--t);
}
void solve_test_case()
{
unsigned length_of_permutation;
std::cin >> length_of_permutation;
std::vector<int> increments_of_permutation(length_of_permutation - 1);
int minimal_element_of_integral{ (int)length_of_permutation }; /* 1 - p0 or 1*/
for (int previous{};
auto & increment : increments_of_permutation) {
std::cin >> increment;
previous = increment += previous;
if (previous > (int)length_of_permutation) {
std::cout
<< "-1"
<< std::endl;
return;
}
minimal_element_of_integral -= (increment < minimal_element_of_integral) * (minimal_element_of_integral - increment);
}
std::vector<bool> sorted_permutation(length_of_permutation);
if (-minimal_element_of_integral >= (int)length_of_permutation) {
std::cout
<< "-1"
<< std::endl;
}
else {
if (minimal_element_of_integral == 1)
sorted_permutation[0] = true;
else
sorted_permutation[-minimal_element_of_integral] = true;
for (auto& increment : increments_of_permutation)
if (unsigned(increment -= minimal_element_of_integral - (minimal_element_of_integral == 1)) >= length_of_permutation)
break;
else
sorted_permutation[increment] = true;
if (std::ranges::find(sorted_permutation, false) != sorted_permutation.end()) {
std::cout
<< "-1"
<< std::endl;
}
else {
std::cout << -minimal_element_of_integral + (minimal_element_of_integral == 1) + 1;
for (auto increment : increments_of_permutation) {
std::cout
<< ' '
<< increment + 1;
}
std::cout << std::endl;
}
}
} | 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>
using namespace std;
typedef long long ll;
#define endo '\n'
#define fast ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
/*int isprime(int N){
if(N<2 || (!(N&1) && N!=2))
return 0;
for(int i=3; i*i<=N; i+=2){
if(!(N%i))
return 0;
}
return 1;
}*/
int main(){
fast
int t;cin>>t;
while(t--)
{
ll n,m;cin>>n>>m;
ll sum=0;
vector<int>v(n);
for(auto &i:v){
cin>>i;
sum+=i;
}cout<<min(m,sum)<<endo;
}
return 0;
}
| cpp |
1322 | F | F. Assigning Farestime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMayor of city M. decided to launch several new metro lines during 2020. Since the city has a very limited budget; it was decided not to dig new tunnels but to use the existing underground network.The tunnel system of the city M. consists of nn metro stations. The stations are connected with n−1n−1 bidirectional tunnels. Between every two stations vv and uu there is exactly one simple path. Each metro line the mayor wants to create is a simple path between stations aiai and bibi. Metro lines can intersects freely, that is, they can share common stations or even common tunnels. However, it's not yet decided which of two directions each line will go. More precisely, between the stations aiai and bibi the trains will go either from aiai to bibi, or from bibi to aiai, but not simultaneously.The city MM uses complicated faring rules. Each station is assigned with a positive integer cici — the fare zone of the station. The cost of travel from vv to uu is defined as cu−cvcu−cv roubles. Of course, such travel only allowed in case there is a metro line, the trains on which go from vv to uu. Mayor doesn't want to have any travels with a negative cost, so it was decided to assign directions of metro lines and station fare zones in such a way, that fare zones are strictly increasing during any travel on any metro line.Mayor wants firstly assign each station a fare zone and then choose a lines direction, such that all fare zones are increasing along any line. In connection with the approaching celebration of the day of the city, the mayor wants to assign fare zones so that the maximum cici will be as low as possible. Please help mayor to design a new assignment or determine if it's impossible to do. Please note that you only need to assign the fare zones optimally, you don't need to print lines' directions. This way, you solution will be considered correct if there will be a way to assign directions of every metro line, so that the fare zones will be strictly increasing along any movement of the trains.InputThe first line contains an integers nn, mm (2≤n,≤500000, 1≤m≤5000002≤n,≤500000, 1≤m≤500000) — the number of stations in the city and the number of metro lines.Each of the following n−1n−1 lines describes another metro tunnel. Each tunnel is described with integers vivi, uiui (1≤vi, ui≤n1≤vi, ui≤n, vi≠uivi≠ui). It's guaranteed, that there is exactly one simple path between any two stations.Each of the following mm lines describes another metro line. Each line is described with integers aiai, bibi (1≤ai, bi≤n1≤ai, bi≤n, ai≠biai≠bi).OutputIn the first line print integer kk — the maximum fare zone used.In the next line print integers c1,c2,…,cnc1,c2,…,cn (1≤ci≤k1≤ci≤k) — stations' fare zones. In case there are several possible answers, print any of them. In case it's impossible to assign fare zones, print "-1".ExamplesInputCopy3 1
1 2
2 3
1 3
OutputCopy3
1 2 3
InputCopy4 3
1 2
1 3
1 4
2 3
2 4
3 4
OutputCopy-1
InputCopy7 5
3 4
4 2
2 5
5 1
2 6
4 7
1 3
6 7
3 7
2 1
3 6
OutputCopy-1
NoteIn the first example; line 1→31→3 goes through the stations 1, 2, 3 in this order. In this order the fare zones of the stations are increasing. Since this line has 3 stations, at least three fare zones are needed. So the answer 1, 2, 3 is optimal.In the second example, it's impossible to assign fare zones to be consistent with a metro lines. | [
"dp",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
using pii = pair<int, int>;
void upd(pii &x, const pii &y) {
auto &[a, b] = x;
const auto &[c, d] = y;
x = {max(a, c), min(b, d)};
}
int n, m, val[N], repr[N], dis[N];
vector<int> G[N];
int fa[N][20], ord[N], dep[N];
int find(int x) {
if (repr[x] == x) {
return x;
} else {
int r = find(repr[x]);
dis[x] ^= dis[repr[x]];
repr[x] = r;
return r;
}
}
void merge(int u, int v, int d) {
int fu = find(u), fv = find(v);
if (fu != fv) {
repr[fu] = fv;
dis[fu] = (d ^ dis[u] ^ dis[v]);
} else if ((dis[u] ^ dis[v]) != d) {
cout << -1 << "\n";
exit(0);
}
}
void dfs(int u, int p) {
static int dfs_clock = 0;
if (p) {
G[u].erase(find(G[u].begin(), G[u].end(), p));
}
dep[u] = dep[p] + 1;
ord[++dfs_clock] = u;
fa[u][0] = p;
for (int i = 1; i < 20; i++) {
fa[u][i] = fa[fa[u][i - 1]][i - 1];
}
for (int v : G[u]) {
dfs(v, u);
}
}
int kfa(int u, int k) {
for (int i = 20; i--; ) {
if ((k >> i) & 1) {
u = fa[u][i];
}
}
return u;
}
int lca(int u, int v) {
if (dep[u] < dep[v]) {
swap(u, v);
}
u = kfa(u, dep[u] - dep[v]);
if (u == v) {
return u;
}
for (int i = 20; i--; ) {
if (fa[u][i] != fa[v][i]) {
u = fa[u][i], v = fa[v][i];
}
}
return fa[u][0];
}
int dp[N], type[N];
pii s[N];
bool solve(int u, int k) {
pii x(1, k);
for (int v : G[u]) {
pii &t = (find(v) == find(u) ? x : s[find(v)]);
if (dis[v] == dis[u]) {
type[v] = 0;
upd(t, { dp[v] + 1, k });
} else {
type[v] = 1;
upd(t, { 1, (k + 1 - dp[v]) - 1 });
}
}
pii y(1, k);
for (int v : G[u]) {
if (find(v) != find(u)) {
auto [l, r] = s[find(v)];
if (l > k + 1 - r) {
type[v] ^= 1;
tie(l, r) = pii(k + 1 - r, k + 1 - l);
}
upd(y, { l, r });
}
}
auto [a, b] = x;
auto [c, d] = y;
if (max(a, c) <= min(b, d)) {
dp[u] = max(a, c);
} else {
tie(c, d) = pii(k + 1 - d, k + 1 - c);
if (max(a, c) <= min(b, d)) {
dp[u] = max(a, c);
for (int v : G[u]) {
if (find(v) != find(u)) {
type[v] ^= 1;
}
}
} else {
return false;
}
}
return true;
}
bool check(int k) {
fill(s + 1, s + n + 1, pii(1, k));
for (int i = n; i; i--) {
if (!solve(ord[i], k)) {
return false;
}
}
return true;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
iota(repr + 1, repr + n + 1, 1);
for (int i = 1, u, v; i <= n - 1; i++) {
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1, 0);
while (m--) {
int u, v;
cin >> u >> v;
int l = lca(u, v);
if (u != l) {
val[u]++;
u = kfa(u, dep[u] - dep[l] - 1);
val[u]--;
}
if (v != l) {
val[v]++;
v = kfa(v, dep[v] - dep[l] - 1);
val[v]--;
}
if (u != l && v != l) {
merge(u, v, 1);
}
}
for (int i = n; i; i--) {
int u = ord[i];
val[fa[u][0]] += val[u];
if (val[u]) {
merge(u, fa[u][0], 0);
}
}
int l = 1, r = n, ans = 0;
while (l <= r) {
int mid = (l + r) / 2;
if (check(mid)) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
check(ans);
cout << ans << "\n";
for (int i = 1; i <= n; i++) {
int u = ord[i];
type[u] ^= type[fa[u][0]];
}
for (int i = 1; i <= n; i++) {
cout << (type[i] == 0 ? dp[i] : ans + 1 - dp[i]) << " ";
}
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>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const ll mod = 998244353;
const int mm = 3e5 + 10;
map<string,int>mp;
string a[1505];
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int n,k;
cin>>n>>k;
for(int i=1;i<=n;i++){
cin>>a[i];
mp[a[i]]++;
}
ll ans=0;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
string s;
for(int x=0;x<k;x++){
if(a[i][x]=='E'&&a[j][x]=='E')s.push_back('E');
else if(a[i][x]=='T'&&a[j][x]=='T')s.push_back('T');
else if(a[i][x]=='S'&&a[j][x]=='S')s.push_back('S');
else if(a[i][x]=='E'&&a[j][x]=='T')s.push_back('S');
else if(a[i][x]=='T'&&a[j][x]=='E')s.push_back('S');
else if(a[i][x]=='E'&&a[j][x]=='S')s.push_back('T');
else if(a[i][x]=='S'&&a[j][x]=='E')s.push_back('T');
else if(a[i][x]=='T'&&a[j][x]=='S')s.push_back('E');
else if(a[i][x]=='S'&&a[j][x]=='T')s.push_back('E');
}
if(s==a[i]&&s==a[j])ans+=mp[s]-2;
else ans+=mp[s];
}
}cout<<ans/3;
}
| cpp |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
int n,a[105],tag;
cin>>t;
while(t--)
{
tag=0;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
if(n==1&&a[1]%2==1)
cout<<-1<<endl;
else
{
if(a[1]%2==0)
{
cout<<1<<endl<<1<<endl;
}
else if(a[2]%2==0)
{
cout<<1<<endl<<2<<endl;
}
else
{
cout<<2<<endl<<1<<" "<<2<<endl;
}
}
}
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<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=2e5+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;
char str[N];
void solve() {
n=read();
scanf("%s",str+1);
int x=0,y=0;
int ansl,ansr;
int ans=INF;
map<int,map<int,int> > book;
book[x][y]=1;
for(int i=1;i<=n;i++) {
if(str[i]=='U') y++;
else if(str[i]=='D') y--;
else if(str[i]=='R') x++;
else if(str[i]=='L') x--;
if(book[x][y]!=0) {
if(i-book[x][y]<ans) {
ans=i-book[x][y];
ansl=book[x][y]+1,ansr=i+1;
}
}
book[x][y]=i+1;
}
if(ans==INF) printf("-1\n");
else printf("%d %d\n",ansl-1,ansr-1);
}
int main() {
// init();
// stin();
scanf("%d",&T);
// T=1;
while(T--) solve();
return 0;
}
| cpp |
1304 | B | B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string. | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fr(i,a,b,k) for(int i=a;i<b;i+=k)
#define frrev(i,a,b,k) for(int i=a;i>=b;i-=k)
#define NO cout<<"NO\n"
#define YES cout<<"YES\n"
#define V vector<ll int>
#define VP vector<pair<ll int,ll int>>
#define MP map<ll int,ll int>
#define pb push_back
#define ff first
#define ss second
#define input(A) for(auto &i:A)cin>>i
#define output(A) for(auto &i:A)cout<<i<<" "
string s[100];
void solve(int t)
{
set<string> d;
int n, m, i;
cin >> n >> m;
for (i = 0; i < n; i++)
{
cin >> s[i];
d.insert(s[i]);
}
vector<string> l, r;
string mid;
for (i = 0; i < n; i++)
{
string t = s[i];
reverse(t.begin(), t.end());
if (t == s[i])
mid = t;
else if (d.find(t) != d.end())
{
l.pb(s[i]);
r.push_back(t);
d.erase(s[i]);
d.erase(t);
}
}
string ans="";
for (string x : l)
ans+=x;
ans+=mid;
reverse(r.begin(), r.end());
for (string x : r)
ans+=x;
cout<<ans.size()<<endl;
cout<<ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
//cin>>t;
t=1;
for(int i=1;i<=t;i++)
{
solve(i);
}
return 0;
}
| cpp |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t,m,n;
int tag;
cin>>t;
while(t--)
{
tag=0;
cin>>n>>m;
if(n%m==0)
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
} | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.