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 |
---|---|---|---|---|---|
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 ll long long int
// nCr using inverse factorial
ll mod = 998244353;
ll power(ll a, ll b, ll m = mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
ll invmod(ll a, ll m = mod) {return power(a, m - 2, m);} //For prime mod
ll mAdd(ll a, ll b, ll m = mod) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mSub(ll a, ll b, ll m = mod) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
ll mMul(ll a, ll b, ll m = mod) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
ll mDiv(ll a, ll b, ll m = mod) {a = a % m; b = b % m; return mMul(a, invmod(b), m);}
ll N = 1e6 + 1;
vector<ll> factorial (N, 1);
vector<ll> invFactorial (N, 1);
//Call this in main function
void prenCr(){
for (ll i = 2; i < N; i++)
{
factorial[i] = mMul(i, factorial[i-1]);
invFactorial[i] = mDiv(1, factorial[i]);
}
}
ll nCr(ll n, ll r){
if(r > n || r < 0){
return 0;
}
return mMul(factorial[n], mMul(invFactorial[r], invFactorial[n-r]));
}
void solve(){
ll n, m;
cin >> n >> m;
if(n == 2){
cout << 0 << endl;
return;
}
ll ans = 0;
ll p = power(2, n-3);
ll invModNminus2 = invmod(1, n-1);
for (ll i = n-1; i <= m; i++)
{
ll sa = nCr(i-1, n-2);
sa *= p;
sa %= mod;
sa *= n-2;
sa %= mod;
sa = mMul(sa, invModNminus2);
ans += sa;
ans %= mod;
}
cout << ans << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
prenCr();
ll T = 1;
while (T--)
{
solve();
}
return 0;
} | cpp |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
using ll = long long int;
using pii = pair<int, int>;
#ifndef ONLINE_JUDGE
#define deb(...) logger(__LINE__, #__VA_ARGS__, __VA_ARGS__)
template <typename... Args>
void logger(int line, string vars, Args&&... values) {
cout << line << ": ";
cout << vars << " = ";
string delim = "";
(..., (cout << delim << values, delim = ", "));
cout << "\n";
}
#else
#define deb(...) 0
#endif
void solve() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int a, b, x, y;
cin >> a >> b >> x >> y;
int max_w = max(x, a - x - 1);
int max_h = max(y, b - y - 1);
cout << max(max_w * b, max_h * a) << "\n";
}
return;
}
int main() {
cin.tie(0)->sync_with_stdio(false);
solve();
cout.flush();
return 0;
} | cpp |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.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. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
//---------------------------------------------------------------------------------
#define ll long long
#define fixed(n) cout << fixed << setprecision(n)
#define sz(x) int(x.size())
#define TC int t; cin >> t; while(t--)
#define all(s) s.begin(), s.end()
#define rall(s) s.rbegin(), s.rend()
#define dl "\n"
#define Ceil(a, b) ((a / b) + (a % b ? 1 : 0))
#define pi 3.141592
#define OO 2'000'000'000
#define MOD 1'000'000'007
#define EPS 1e-10
using namespace std;
using namespace __gnu_pbds;
//---------------------------------------------------------------------------------
template <typename K, typename V, typename Comp = std::less<K>>
using ordered_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = std::greater<K>>
using ordered_set = ordered_map<K, null_type, Comp>;
template <typename K, typename V, typename Comp = std::less_equal<K>>
using ordered_multimap = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = std::less_equal<K>>
using ordered_multiset = ordered_multimap<K, null_type, Comp>;
// order_of_key(val) count elements smaller than val
// *s.find_by_order(idx) element with index idx
template<typename T = int > istream& operator >> (istream &in , vector < T > &v){
for(auto &i : v) in >> i ;
return in ;
}
template<typename T = int > ostream& operator << (ostream &out ,vector < T > &v){
for(auto &i : v) out << i << ' ' ;
return out ;
}
//-----------------------------------------------------------------------------------------
void ZEDAN() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin) ;
freopen("output.txt", "w", stdout) ;
#endif
}
//-----------------------------------------(notes)-----------------------------------------
/*
*/
//-----------------------------------------(function)--------------------------------------
//-----------------------------------------(code here)-------------------------------------
void solve(){
string s ; cin >> s ;
s.push_back('R') ;
ll ans=-OO , cnt = 0 ;
for(auto &i : s){
cnt++ ;
if(i=='R'){
ans = max(ans,cnt) ;
cnt = 0 ;
}
}
cout << ans ;
}
//-----------------------------------------------------------------------------------------
int main()
{
ZEDAN() ;
ll t = 1 ;
cin >> t ;
while(t--){
solve() ;
if(t) cout << dl ;
}
return 0;
} | cpp |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | #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;
template <typename T>
struct fenwick_tree {
int n;
vector<T> data;
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] += x;
p += p & -p;
}
}
T sum(int r) {
T s = 0;
while(r > 0) {
s += data[r - 1];
r -= r & -r;
}
return s;
}
T sum(int l, int r) {
assert(0 <= l && l <= r && r <= n);
return sum(r) - sum(l);
}
T operator[](int x) const {
assert(0 <= x && x < n);
return sum(x, x + 1);
}
};
int main(void) {
cin.tie(0);
ios::sync_with_stdio(0);
ll n;
cin >> n;
vector<ll> x(n), v(n);
rep(i, 0, n) {
cin >> x[i];
}
rep(i, 0, n) {
cin >> v[i];
}
vector<ll> res = v;
sort(res.begin(), res.end());
res.erase(unique(res.begin(), res.end()), res.end());
vector<P> p(n);
rep(i, 0, n) {
p[i].first = x[i];
p[i].second = lower_bound(res.begin(), res.end(), v[i]) - res.begin();
// cout << p[i].first << " " << p[i].second << '\n';
}
sort(p.begin(), p.end());
fenwick_tree<ll> fw1(n), fw2(n), fw3(n), fw4(n);
rep(i, 0, n) {
fw3.add(p[i].second, p[i].first);
fw4.add(p[i].second, 1);
}
ll ans = 0;
rep(i, 0, n) {
ll cnt = 0;
cnt = fw2.sum(0, p[i].second + 1);
ans += (cnt * p[i].first - fw1.sum(0, p[i].second + 1));
cnt = fw4.sum(p[i].second, n);
ans += (fw3.sum(p[i].second, n) - cnt * p[i].first);
fw1.add(p[i].second, p[i].first);
fw2.add(p[i].second, 1);
fw3.add(p[i].second, -p[i].first);
fw4.add(p[i].second, -1);
}
cout << ans / 2 << '\n';
} | cpp |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pi;
const int MN=8e4;
int N, at=170, ans = MN; bool pvis[1001], vis[MN]; pi dist[MN];
set<int> start; vector<int> prime, vals, adj[MN]; queue<pi> q;
unordered_map<int, int> ind; // (value, index it maps to)
void bfs(int r){ memset(dist, 0, sizeof(dist)); q.push({r,-1}); dist[r]={1,r};
while(!q.empty()){ pi t = q.front(); int x=t.first, p=t.second; q.pop();
for(int nx: adj[x]) if(nx!=p && nx>=r) if(adj[nx].size()>1) {
if(dist[nx].second==dist[x].second) ans=min(ans,dist[x].first+dist[nx].first-1);
else{ dist[nx]={dist[x].first + 1,r}; q.push({nx,x}); } } } }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
prime.reserve(170); prime.push_back(0); prime.push_back(1);
for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.push_back(i);
for(int j=i*i;j<=1e3;j+=i) pvis[j]=1; }
cin >> N; int x; for (int i=0; i<N; i++) { vals.clear(); cin >> x;
for (int j=2; j<prime.size() && prime[j] * prime[j] <= x; j++) { int cnt = 0;
while (x%prime[j] == 0) { x /= prime[j]; cnt++; }
if (cnt%2 == 1) vals.push_back(prime[j]); }
if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; }
vals.push_back(x); if (vals.size() == 1) vals.push_back(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]]].push_back(ind[vals[1]]);
adj[ind[vals[1]]].push_back(ind[vals[0]]);
}
for (int j: start) if(j && adj[j].size()>1) bfs(j);
cout << (ans == MN ? -1 : ans) <<'\n';
} | cpp |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | #include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2")
#include<unordered_set>
#define debug(x) cout<<#x<<" = "<<x<<endl;
#define fix(prec) cout << setprecision(prec) << fixed;
#define ms(arr, v) memset(arr, v, sizeof(arr))
#define pb push_back
#define lcm(a,b) (a*b)/(__gcd(a,b))
#define max3(a,b,c) max(max(a,b),c)
#define min3(a,b,c) min(min(a,b),c)
#define google(t) cout<<"Case #"<<t<<": ";
using namespace std;
//using namespace __gnu_pbds;
typedef long long ll;
typedef long double ld;
//typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
constexpr ll MAXX = 2e18;
constexpr ld EPS = 1e-9;
constexpr ll P = 1000000007;//998244853;
ll mod_add(ll a, ll b, ll m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
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;}
template <typename T> ostream& operator <<(ostream& output, const vector<T>& data)
{
for (const T& x : data)
output << x <<" ";
return output;
}
template <typename T> istream& operator>>(istream& input,vector<T>& data)
{
for (auto& item : data)
{
input >> item;
}
return input;
}
/************************************* SIEVE OF ERASTOSTHENES ***************************************************************/
vector<bool> seive(ll n)
{
vector<bool>arr(n+1, true);
for( int i=2; i*i <= n ; i++ )
{
if(arr[i])
{
for(int j=i*i; j<=n; j+=i)
{
arr[j] = false;
}
}
}
return arr;
}
vector<ll> lp;
vector<ll> prime;
void seive_op( ll n )
{
lp.assign(n+1,0);
ll m=0;
for(int i=2;i<=n;i++)
{
if(lp[i] == 0)
{
lp[i]=i;
prime.push_back(i);
m++;
}
for(int j=0 ; (j<m) && (prime[j]<=lp[i]) && (i*prime[j]<=n) ; j++)
{
lp[i*prime[j]] = prime[j];
}
}
}
/***********************************************************************************************************************************/
map<ll,ll> primefactorisation(ll n)
{
map<ll,ll>mp;
while(n!=1)
{
mp[lp[n]]++;
n/=(lp[n]);
}
return mp;
}
//Modular Exponetiation (2^k ary method)
ll mod_exp(ll x, ll y, ll p)
{
ll ans=1LL,r=1LL;
x%=p;
while(r>0&&r<=y)
{
if(r&y)
{
ans*=x;
ans%=p;
}
r = (r<<1LL);
x*=x;
x%=p;
}
return ans;
}
ll mod_inv(ll n, ll p)
{
/* This works because n and p are coprime as p is already prime in most questions
and n<p for most question (ie n is not a multiple of p) */
return mod_exp(n, p - 2LL, p);
}
ll mod_gp(ll a, ll n, ll p)
{
// this is for computing 1+(a^2)+(a^3)+(a^4)+...(a^n)
// total number of terms is n+1
if(n==0) return 1;
if(n==1) return (1+a);
ll ans=(1+a);
ll temp=1LL;
if(n%2==1)
{
temp=mod_gp(mod_mul(a,a,P),(n-1)/2,P);
return mod_mul(ans,temp,P);
}
else
{
temp=mod_gp(mod_mul(a,a,P),(n/2)-1,P);
ans=mod_mul(ans,temp,P);
ans=mod_mul(ans,a,P);
ans=mod_add(ans,1LL,P);
}
return ans;
}
bool isprime(ll x)
{
for (ll i=2; i*i<=x; i++)
{
if ( x%i==0 )
{
return 0;
}
}
return 1;
}
bool cmp(pair<ll,ll> p1, pair<ll,ll> p2)
{
return (p1.first > p2.first);
}
/***************************************** NCR MOD P ****************************************************************************/
vector<ll> fact;
vector<ll> mod_in;
void pre_fermat()
{
fact.assign( 1000001, 1);
mod_in.assign( 1000001,1);
fact[0]=1;
for(int i=1; i<= (1000000); i++)
{
fact[i] = mod_mul(fact[i-1], i, P);
mod_in[i]=mod_inv(fact[i],P);
}
}
ll ncr(ll n, ll r, ll p)
{
if (n < r)
{
return 0LL;
}
if (r == 0)
{
return 1LL;
}
ll ans=mod_mul(fact[n],mod_mul(mod_in[r],mod_in[n-r],P),P);
return ans;
}
/************************************************************************************************************************************/
vector<ll> bfs(vector<vector<ll>>&edge, ll start, ll n)
{
ll curr = start;
vector<bool> visited(n+1,0);
vector<ll> lvl(n+1);
lvl[curr]=0;
queue<ll> qq;
qq.push(curr);
visited[curr]=1;
while(!qq.empty())
{
curr=qq.front();
for( ll x : edge[curr] )
{
if(!visited[x])
{
lvl[x] = 1 + lvl[curr];
qq.push(x);
visited[x] = 1;
}
}
qq.pop();
}
return lvl;
}
void dfs(vector<vector<ll>>&edge, ll curr, ll prev)
{
for(ll x:edge[curr])
{
if(x!=prev)
{
dfs(edge,x,curr);
}
}
}
vector <string> bor = {"YES","NO"};
void solve()
{
ll n;
cin>>n;
ll m;
cin>>m;
vector<vector<ll>>arr(n,vector<ll>(m));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>arr[i][j];
}
}
ll ans=0;
vector<ll>brr((1LL<<m)+1,0);
for(int i=0;i<n;i++)
{
for(int j=0;j<(1LL<<m);j++)
{
ll temp=INT_MAX;
for(int k=0;k<m;k++)
{
if(j&(1LL<<k))
{
temp=min(temp,arr[i][k]);
}
}
brr[j]=max(brr[j],temp);
}
}
ll curr=0;
for(int i=0;i<n;i++)
{
ll low=0,high=1e9;
while(low<=high)
{
ll mid=(low+high)/2;
ll f=0;
for(int j=0;j<m;j++)
{
if(arr[i][j]<mid)
{
f|=(1LL<<j);
}
}
if(brr[f]>=mid)
{
if(mid>ans)
{
ans=mid;
curr=i;
}
low=mid+1;
}
else
{
high=mid-1;
}
}
}
// cout<<ans<<"\n";
for(int j=0;j<n;j++)
{
ll v=INT_MAX;
for(int i=0;i<m;i++)
{
v=min(v,max(arr[curr][i],arr[j][i]));
}
if(v==ans)
{
cout<<curr+1<<" "<<j+1<<"\n";
return;
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll t=1;
while (t--)
{
solve();
}
return 0;
}
| cpp |
1284 | F | F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4
1 2
2 3
4 3
1 3
2 4
1 4
OutputCopy3
3 2 4 2
2 1 1 3
4 3 1 4
InputCopy5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
OutputCopy4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
InputCopy9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
OutputCopy8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
| [
"data structures",
"graph matchings",
"graphs",
"math",
"trees"
] | #include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/trie_policy.hpp>
// #include <ext/rope>
using namespace std;
// using namespace __gnu_cxx;
// using namespace __gnu_pbds;
void Hollwo_Pelw();
signed main(){
#ifndef hollwo_pelw_local
if (fopen(".inp", "r"))
assert(freopen(".inp", "r", stdin)), assert(freopen(".out", "w", stdout));
#else
using namespace chrono;
auto start = steady_clock::now();
#endif
cin.tie(0), cout.tie(0) -> sync_with_stdio(0);
int testcases = 1;
// cin >> testcases;
for (int test = 1; test <= testcases; test++){
// cout << "Case #" << test << ": ";
Hollwo_Pelw();
}
#ifdef hollwo_pelw_local
auto end = steady_clock::now();
cout << "\nExecution time : " << duration_cast<milliseconds> (end - start).count() << "[ms]" << endl;
#endif
}
const int N = 2.5e5 + 5;
int n, h[N], par[18][N], fa[N];
vector<int> g1[N], g2[N];
void pre_dfs(int u, int p) {
h[u] = h[par[0][u] = p] + 1;
for (int i = 1; i < 18; i++)
par[i][u] = par[i - 1][par[i - 1][u]];
for (int v : g1[u]) if (v != p)
pre_dfs(v, u);
}
inline int lca(int u, int v) {
if (h[u] > h[v]) swap(u, v);
for (int i = 18; i --; )
if ((h[v] - h[u]) >> i & 1)
v = par[i][v];
if (u == v)
return u;
for (int i = 18; i --; )
if (par[i][u] ^ par[i][v])
u = par[i][u], v = par[i][v];
return par[0][u];
}
vector<tuple<int, int, int, int>> res;
inline int find(int u) { return fa[u] == u ? u : fa[u] = find(fa[u]); }
inline void merge(int v, int u) {
int fv = find(v), fu = find(u), w = find(lca(u, v));
// assert(fv != fu && "WTF is this");
if (find(fv) != w) {
fa[fv] = find(par[0][fv]);
res.emplace_back(fv, par[0][fv], v, u);
} else {
for (int i = 18; i --; )
if (h[find(par[i][fu])] > h[w])
fu = par[i][fu];
fa[fu] = find(par[0][fu]);
res.emplace_back(fu, par[0][fu], v, u);
}
}
void solve(int u, int p) {
for (int v : g2[u]) if (v != p) {
solve(v, u);
merge(v, u);
}
}
void Hollwo_Pelw(){
cin >> n;
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
g1[u].push_back(v);
g1[v].push_back(u);
}
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
g2[u].push_back(v);
g2[v].push_back(u);
}
pre_dfs(1, 0);
iota(fa + 1, fa + n + 1, 1);
solve(1, 0);
cout << res.size() << '\n';
for (auto [a, b, c, d] : res)
cout << a << ' ' << b << ' ' << c << ' ' << d << '\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>
using namespace std;
#define sz(s) (int)(s.size())
#define all(v) v.begin(),v.end()
#define clr(d, v) memset(d,v,sizeof(d))
#define ll long long
void file() {
std::ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
}
vector<pair<int, int>> ans;
void solve(set<pair<int, int>> &st1, set<pair<int, int>> &st2, bool ok = false) {
vector<pair<int, int>> temp;
for (auto it: st1)temp.push_back(it);
for (auto it: temp) {
auto it2 = st2.lower_bound({it.first, -1});
if (it2 != st2.end() && it2->first == it.first) {
if (ok)
ans.emplace_back(it.second + 1, it2->second + 1);
else ans.emplace_back(it2->second + 1, it.second + 1);
st1.erase(it);
st2.erase(it2);
}
}
}
int main() {
file();
int n;
string s, t;
cin >> n >> s >> t;
vector<int> q1, q2;
set<pair<int, int>> st1, st2;
for (int i = 0; i < n; i++) {
if (s[i] == '?')q1.push_back(i);
else st1.insert({s[i], i});
}
for (int i = 0; i < n; i++) {
if (t[i] == '?')q2.push_back(i);
else st2.insert({t[i], i});
}
solve(st1, st2, true);
solve(st2, st1, false);
vector<pair<int, int>> rem1, rem2;
for (auto it: st1)rem1.push_back(it);
for (auto it: st2)rem2.push_back(it);
for (int i = 0; i < rem1.size() && (!q2.empty()); i++) {
ans.emplace_back(rem1[i].second + 1, 1 + q2.back());
q2.pop_back();
}
for (int i = 0; i < rem2.size() && (!q1.empty()); i++) {
ans.emplace_back(q1.back() + 1, rem2[i].second + 1);
q1.pop_back();
}
for (int i = 0; i < min(q1.size(), q2.size()); i++) {
ans.emplace_back(q1[i] + 1, q2[i] + 1);
}
cout << ans.size() << "\n";
for (auto it: ans)cout << it.first << " " << it.second << "\n";
} | cpp |
13 | D | D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7 | [
"dp",
"geometry"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define foru(i, a, b) for (int i = a; i <= b; ++i)
#define ford(i, a, b) for (int i = a; i >= b; --i)
#define all(a) a.begin(), a.end()
#define pb push_back
#define ii pair <int, int>
#define sd second
#define ft first
#define bit(i) (i & (-i))
#define base 29
#define endl '\n'
#define mod 1000000007ll
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { 1, 0, -1, 0 };
string yno[2] = { "NO\n", "YES\n" };
const int maxn = 505;
int n, m, f[maxn][maxn];
ii a[maxn], b[maxn];
bool check(ii a, ii b, ii c){
if(c.sd <= a.sd || b.sd < c.sd) return false;
return ((a.sd+b.sd)*(a.ft-b.ft) + (b.sd+c.sd)*(b.ft-c.ft) + (c.sd+a.sd)*(c.ft-a.ft)) > 0;
}
void solve(){
cin>>n>>m;
foru(i,1,n){
cin>>a[i].ft>>a[i].sd;
}
foru(i,1,m){
cin>>b[i].ft>>b[i].sd;
}
sort(a+1, a+n+1, [](ii a, ii b){return a.sd < b.sd;});
foru(i,1,n){
foru(j,i+1,n){
foru(k,1,m){
f[i][j] += check(a[i], a[j], b[k]);
}
}
}
int ans = 0;
foru(i,1,n){
foru(j,i+1,n){
foru(k,j+1,n){
ans += (f[i][k] == f[i][j] + f[j][k]);
}
}
}
cout<<ans<<endl;
}
#undef int
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("Test.inp", "r", stdin);
// freopen("Test.out", "w", stdout);
#endif
int t = 1;
// cin >> t;
while (t--){
solve();
}
return 0;
}
| cpp |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | #include<iostream>
#include<cstdio>
#include<bitset>
#include<vector>
#include<math.h>
#include<algorithm>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<unordered_set>
#include <cstring>
#include <iomanip>
//#include <bits/stdc++.h>
#define BATSY ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define ld long double
#define endl '\n'
#define DEC(n) cout<<fixed;cout<<setprecision(n);
#define LENGTH(n) (floor(log10(max(abs(n),1LL)))+1)
#define log_n(number,n) log2(number)/log2(n)
#define OO (ll)1e18
#define F first
#define S second
using namespace std;
//_____________________ _____________________
//`-._ \ |\__/| / _.-'
// \ \ | | / /
// \ `-_______/ \_______-' /
// | '||''|. | |''||''| .|'''.| '||' '| ' |
// | || || ||| || ||.. ' || | |
// | ||'''|. | || || ''|||. || |
// / || || .''''|. || . '|| || \
// /________.||...|' .|. .||. .||. |'....|' .||.__________\
// `----._ _.----'
// `--. .--'
// `-. .-'
// \ /
// \ /
// \/
bool isPrime(ll n){
for(ll i=2;i*i<=n;i++){
if(n%i==0)return false;
}
return n>1;
}
ll get(ll n){
for(ll i=2;i*i<=n;i++){
if(n%i==0)return i;
}
return 1;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("in.in", "r", stdin);
//freopen("out.out", "w", stdout);
#endif
BATSY
int t;
cin>>t;
while(t--){
ll n;
cin>>n;
set<ll>st;
bool f=0;
for(ll i=2;i*i<=n;i++){
if(n%i==0){
ll tm[]={i,n/i};
for(ll j=0;j<2;j++){
st.clear();
st.insert(tm[j]);
ll tmp=get(tm[1-j]);
if(tmp!=1){
st.insert(tmp);
st.insert(tm[1-j]/tmp);
}
if(st.size()==3){
f=1;
break;
}
}
if(f)break;
}
}
if(f){
cout<<"YES\n";
for(auto it:st)cout<<it<<' ';
cout<<endl;
}
else{
cout<<"NO\n";
}
}
} | cpp |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | [
"greedy"
] | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
int n;
cin>>n;
int count=0,sumb=0,sumr=0;
int r[n],b[n];
for(int i=0;i<n;i++)
{
cin>>r[i];
}
for(int i=0;i<n;i++)
{
cin>>b[i];
if(r[i]==1&&b[i]==0)
count++;
else if(r[i]==1)
sumr++;
sumb=sumb+b[i];
}
if(count==0)
cout<<-1<<endl;
else
{
int i=1;
while(true)
{
if((i*count+sumr)>sumb)
{
cout<<i<<endl;
break;
}
i++;
}
}
return 0;
}
| cpp |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | #include<bits/stdc++.h>
#define x first
#define y second
#define endl '\n'
#define LL long long
#define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;
const int N=200010,MOD=1e9+7;
typedef pair<int,int> PII;
int e[N],ne[N],h[N],w[N],idx=0;
void add(int a,int b){
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
LL n,z,x,y,a,b,d[N];
queue<int> q;
int main(){
cin>>n;
memset(h,-1,sizeof h);
for(int i=1;i<n;i++){
cin>>a>>b;
add(a,b);
add(b,a);
d[a]++;
d[b]++;
}
for(int i=1;i<=n;i++){
if(d[i]==1) q.push(i);
}
while(q.size()>1){
int x=q.front();
q.pop();
int y=q.front();
q.pop();
for(int i=h[x];i!=-1;i=ne[i]){
int j=e[i];
d[j]--;
if(d[j]==1) q.push(j);
}
for(int i=h[y];i!=-1;i=ne[i]){
int j=e[i];
d[j]--;
if(d[j]==1) q.push(j);
}
cout<<"? "<<x<<" "<<y<<endl;
cin>>z;
if(x==z){
cout<<"! "<<x<<endl;
break;
}else if(y==z){
cout<<"! "<<y<<endl;
break;
}
}
if(q.size()==1) cout<<"! "<<q.front()<<endl;
}
| 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;
const int N=1e6+10;
using ull=unsigned long long;
using ll=long long;
const int inf=1e9;
using ld=long double;
const ld eps=1e-12;
int a[N];
void solve()
{
int n;scanf("%d",&n);
for(int i=1;i<=n;++i)scanf("%d",&a[i]);
vector<pair<ld,int>>vec;
vec.push_back({a[1],1});
for(int i=2;i<=n;++i)
{
vec.push_back({a[i],1});
while((int)vec.size()>=2)
{
auto [sum,cnt]=vec.back();
vec.pop_back();
int fg=1;
if((vec.back().first+sum)/(vec.back().second+cnt)<
vec.back().first/vec.back().second-eps)
{
fg=0;
sum+=vec.back().first;cnt+=vec.back().second;
vec.pop_back();
}
vec.push_back({sum,cnt});
if(fg)break;
}
}
for(auto [t,cnt]:vec)
{
ld val=t/cnt;
while(cnt--)printf("%.10Lf\n",val);
}
}
int main()
{
// init();
int T=1;//scanf("%d",&T);
while(T--)solve();
} | cpp |
1286 | C2 | C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"hashing",
"interactive",
"math"
] | // LUOGU_RID: 93741769
#include <bits/stdc++.h>
#define fo(i,a,b) for(int i=a;i<=b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
using namespace std;
char an[105];
struct cx{
int len,tn[26];
}sp[105];
int tn[105][26],tn1[26],tn2[26];
bool zqr(cx a1,cx a2)
{
return a1.len<a2.len;
}
void solve(int l)
{
if(l==1)
{
printf("? %d %d\n",1,1);fflush(stdout);
string s;cin>>s;
an[1]=s[0];
return;
}
multiset<vector<int> >aa;
printf("? %d %d\n",1,l);fflush(stdout);
fo(i,1,l*(l+1)>>1)
{
vector<int> tn(26,0);
string s;cin>>s;
for(auto xx:s)tn[xx-'a']++;
aa.insert(tn);
}
printf("? %d %d\n",1,l-1);fflush(stdout);
fo(i,1,l*(l-1)>>1)
{
vector<int> tn(26,0);
string s;cin>>s;
for(auto xx:s)tn[xx-'a']++;
aa.erase(aa.find(tn));
}
int tot=0;
for(auto xx:aa)
{
tot++;
fo(i,0,25)sp[tot].len+=xx[i],sp[tot].tn[i]=xx[i];
}
sort(sp+1,sp+tot+1,zqr);
fo(i,1,tot)
{
fo(j,0,25)if(sp[i].tn[j]-sp[i-1].tn[j])an[tot-i+1]=j+'a';
}
}
int main()
{
int n;scanf("%d",&n);
if(n==1)
{
printf("? %d %d\n",1,1);fflush(stdout);
string s;cin>>s;
printf("! %c",s[0]);fflush(stdout);
return 0;
}
solve(n>>1);
printf("? %d %d\n",1,n);
fo(i,1,n*(n+1)>>1)
{
string s;cin>>s;
int len=s.size();
for(auto xx:s)tn[len][xx-'a']++;
}
fo(i,1,n-(n>>1))
{
fo(j,0,25)tn1[j]=tn[i][j]-tn[i-1][j];
fo(j,0,25)tn2[j]=tn[i+1][j]-tn[i][j];
fo(j,0,25)if(tn1[j]-tn2[j])
{
if(tn1[j]-tn2[j]==2)an[n-i+1]=j+'a';
else if(j+'a'!=an[i])an[n-i+1]=j+'a';
}
}
printf("! ");fo(i,1,n)putchar(an[i]);
return 0;
}
//niceprob | 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;
int main()
{
long long int n;
cin>>n;
vector<int> s;
long long int l=0;
vector<int> q;
for(int i=0;i<n;i++)
{
long long int x;
cin>>x;
s.push_back(x);
}
long long int c=count(s.begin(),s.end(),0);
long long int y=0;
if(n==c)
cout<<"0"<<endl;
else if(s[0]==1&&s[n-1]==1)
{
long long int r=0,d=0;
for(auto w:s)
{
if(w==1)
r++;
else
break;
}
for(int i=n-1;i>=0;i--)
{
if(s[i]==1)
d++;
else
break;
}
y=d+r;
}
long long int mx=0;
if(c<n)
{
long long int sum=1;
for(int i=1;i<n;i++)
{
if(s[i]==1&&s[i-1]==1)
sum=sum+1;
else
{
mx=max(sum,mx);
sum=1;
}
mx=max(mx,sum);
}
cout<<max(mx,y)<<endl;
}
}
| cpp |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | #include <bits/stdc++.h>
#include<cmath>
#include <map>
using namespace std;
#define ll long long
#define lld long double
#define sst string
#define freeopen freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);
#define ios ios::sync_with_stdio(false);
#define pb push_back
#define foor(x,vec) for(auto x:vec ){cout<< x<<" ";};
#define fi first
#define se second
#define mod 1000000007
//
//int main(){
// ll m,n,b,k;
// cin>>m>>n>>b>>k;
// ll mk=-111111111111;
// ll x[169][169];
// for(ll i=1;i<=m;i++){
// for(ll j=1;j<=n;j++){
// cin>>x[i][j];
// }
// }
// ll sum=0,ans=0;
// for(ll i=b;i<=m;i++){
// for(ll j=k;(j<=n);j++){
// sum=0;
// for(ll h=i-b+1;h<=i;h++){
// for(ll w=j-k+1;w<=j;w++){
// sum+=x[h][w];
// }
// }
// mk=max(sum,mk);
// }
// }
//
// for(ll j=k;j<=n;j++){
// sum=0;
// for(ll w=j-k+1;w<=j;w++){
// sum+=x[m][w];
// sum+=x[1][w];
// }
// mk=max(sum,mk);
// }
// for(ll j=b;j<=m;j++){
// sum=0;
// for(ll w=j-b+1;w<=j;w++){
// sum+=x[w][n];
// sum+=x[w][1];
// }
// mk=max(mk,sum);
// }
//
//
//// for(ll i=)
// cout<<mk;
//}
//
//
//
//
////int main(){
//// ll m,n,x[100069];
//// set <ll> st;
//// cin>>n>>m;
//// ll mk=mod;
//// for(ll i=1;i<=n;i++){
//// cin>>x[i];
//// mk=min(mk,x[i]);
//// st.insert(x[i]);
//// }
////
//// if(st.size()==m){
//// cout<<"-1";
//// }
//// else if(n==1){
//// if(m-x[1]>x[1]-1){
//// cout<<m;
//// }
//// else{
//// cout<<n;
//// }
//// }
//// else{
//// for(auto x : st){
////
//// }
////
//// }
////
////
////}
int main(){
ll t;
cin>>t;
while(t--){
ll a,b,x,y;
cin>>a>>b>>x>>y;
ll ans=max(max(x*b,y*a),max((a-1-x)*b,(b-1-y)*a));
cout<<ans<<endl;
}
}
| 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 <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int a;
cin >> a;
int sum = 0, even = 0, odd = 0;
vector<int> arr(a);
for (int j = 0; j < a; j++)
{
cin >> arr[j];
sum += arr[j];
}
if(sum%2 == 1)
{
cout << "YES" << endl;
}
else
{
for (int j = 0; j < a; j++)
{
if(arr[j]%2 == 0)
{
even++;
}
else
{
odd++;
}
}
if(even != 0 && odd != 0){
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
}
} | 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"
] | /*
Author : Catalyst71
< While there is a code, there is a bug > ¯\_(ツ)_/¯
*/
#include<bits/stdc++.h>
//#include<C:\Users\itsar\OneDrive\Desktop\0\CODES\HEADERS\debug.cpp>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
#define FIO ios::sync_with_stdio(0); cin.tie(0);
#define pb push_back
#define eb emplace_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define nn endl
#define sp " "
#define ff(i,start,n) for(i=start;i<=n;i++)
#define fx(s) for(auto &x:s)
#define check(i) cout << i << endl
#define EPS 1e-10
#define frs first
#define sec second
#define mp make_pair
#define vl vector<ll>
#define vi vector<int>
#define dbp cout << " = Working = " << endl;
#define aff cout << "YES" << endl;
#define neg cout << "NO" <<endl;
#define inn(n) scanf("%d", &n);
#define innm(n,m) scanf("%d%d",&n,&m);
#define outnn(n) printf("%d\n",n);
#define outsn(n) printf("%d ",n);
#define R return;
#define ffin(n) for(int i=0;i<(n);i++)
#define ffjn(n) for(int j=0;j<(n);j++)
#define ffkn(n) for(int k=0;k<(n);k++)
#define FRW {freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);}
int dx[8] = {1, -1, 0, 0, 1, 1, -1, -1};
int dy[8] = {0, 0, 1, -1, 1, -1, 1, -1};
//bool isSquare(ll x){ll sq=sqrt(x);return sq*sq==x;}
//long long int gcd(long long int a , long long int b){if(a%b==0)return b;if(b==0)return a;return gcd(b,a%b);}
//long long int lcm(long long int a , long long int b){ return (a / gcd(a, b)) * b;}
//int isprime(long long n){if(n==1)return 0;if(n==2||n==3)return 1;if(n % 2 == 0) return 0;for(long long i = 2; i * i <= n; i++){if(n % i == 0){return 0;}}return 1;}
//int egcd(int a,int b,int &x,int &y){if(b==0){x=1;y=0;return a;}int x1,y1;int d=egcd(b,a%b,x1,y1);x=y1;y=x1-y1*(a/b);return d;}
//int _compare_double(double a, double b){return fabs(a-b)<=EPS? 0: a<b? -1:1;/*0 for equal 1 if a>b*/}
/*ll bs_sqrt(ll x){
ll left=1,right = 2000000123;while (right>left){ll mid = (left+right)/2;if(mid*mid > x)right = mid;else left = mid+1;}
return left-1;
}*/
/*struct vobon
{
int roll,age;
string name ;
};*/
void solve()
{
/* check FIO if not using C IO */
int n,m;
cin >> n;
vi brc(n), nec(n);
fx(brc)cin >> x;
fx(nec)cin >> x;
sort(all(brc));
sort(all(nec));
fx(brc)cout << x << " ";
cout << "\n";
fx(nec)cout << x << " ";
cout << "\n";
}
int main()
{
FIO
#ifndef ONLINE_JUDGE
//FRW
#endif
//auto START = std::chrono::steady_clock::now();
int t = 1 ;
cin >> t ;
while (t--)
{
solve();
}
//auto END = std::chrono::steady_clock::now();
//double MMM = double(std::chrono::duration_cast <std::chrono::nanoseconds>(END-START).count());
//cout<<"Shomoy gese : "<<MMM/1e9<<" sec"<<endl;
return 0 ;
}
| cpp |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | [
"implementation",
"strings"
] | #include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const ll mod = 1e9 + 7;
const ll mm = 2e5 + 10;
string s[25],t[25];
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)cin>>s[i-1];
for(int i=1;i<=m;i++)cin>>t[i-1];
int q;
cin>>q;
while(q--){
ll y;
cin>>y;
cout<<s[(y-1)%n]<<t[(y-1)%m]<<'\n';
}
}
| 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"
] | // BEGIN BOILERPLATE CODE
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include <bits/stdc++.h>
using namespace std;
#ifdef KAMIRULEZ
const bool kami_loc = true;
const long long kami_seed = 69420;
#else
const bool kami_loc = false;
const long long kami_seed = chrono::steady_clock::now().time_since_epoch().count();
#endif
const string kami_fi = "kamirulez.inp";
const string kami_fo = "kamirulez.out";
mt19937_64 kami_gen(kami_seed);
long long rand_range(long long rmin, long long rmax) {
uniform_int_distribution<long long> rdist(rmin, rmax);
return rdist(kami_gen);
}
long double rand_real(long double rmin, long double rmax) {
uniform_real_distribution<long double> rdist(rmin, rmax);
return rdist(kami_gen);
}
void file_io(string fi, string fo) {
if (fi != "" && (!kami_loc || fi == kami_fi)) {
freopen(fi.c_str(), "r", stdin);
}
if (fo != "" && (!kami_loc || fo == kami_fo)) {
freopen(fo.c_str(), "w", stdout);
}
}
void set_up() {
if (kami_loc) {
file_io(kami_fi, kami_fo);
}
ios_base::sync_with_stdio(0);
cin.tie(0);
}
void just_do_it();
void just_exec_it() {
if (kami_loc) {
auto pstart = chrono::steady_clock::now();
just_do_it();
auto pend = chrono::steady_clock::now();
long long ptime = chrono::duration_cast<chrono::milliseconds>(pend - pstart).count();
string bar(50, '=');
cout << '\n' << bar << '\n';
cout << "Time: " << ptime << " ms" << '\n';
}
else {
just_do_it();
}
}
int main() {
set_up();
just_exec_it();
return 0;
}
// END BOILERPLATE CODE
// BEGIN MAIN CODE
const int ms = 5e5 + 20;
const int inf = 1e9 + 20;
int a[ms];
pair<int, int> p[ms];
int b[ms];
int res[ms];
int pos;
void fix(int <, int &rt) {
if (lt == 0) {
lt = -inf;
rt = inf;
}
else if (b[lt] == 1 && b[rt] == 1) {
lt = -inf;
rt = inf;
}
else if (b[lt] == 2 && b[rt] == 1) {
rt = (lt + rt) / 2;
}
else if (b[lt] == 1 && b[rt] == 2) {
lt = (lt + rt) / 2 + 1;
}
}
void inter(int &l1, int &r1, int l2, int r2) {
if (l1 > r1 || l2 == -inf) {
return;
}
if (l1 <= min(r1, l2 - 1)) {
r1 = min(r1, l2 - 1);
}
else if (max(l1, r2 + 1) <= r1) {
l1 = max(l1, r2 + 1);
}
else {
l1 = inf;
r1 = -inf;
}
}
void update(int l1, int r1, int l2, int r2, int l3, int r3, int val) {
fix(l1, r1);
if (l1 == -inf) {
return;
}
b[pos] = 1;
fix(l2, r2);
fix(l3, r3);
b[pos] = 2;
inter(l1, r1, l2, r2);
inter(l1, r1, l3, r3);
for (int i = l1; i <= r1; i++) {
if (res[i] != -1) {
exit(0);
}
res[i] = val;
}
}
void just_do_it() {
int n, k;
cin >> n;
k = 1;
//cin >> k;
set<int> s;
multiset<int> len;
for (int i = 1; i <= n; i++) {
cin >> a[i];
p[i] = {a[i], i};
b[i] = 1;
res[i] = -1;
s.insert(i);
len.insert(1);
}
int mx = 1;
sort(p + 1, p + n + 1, greater<>());
for (int i = 1; i <= n; i++) {
int l1 = -1;
int r1 = -1;
int l2 = -1;
int r2 = -1;
int l3 = -1;
int r3 = -1;
int val = p[i].first;
pos = p[i].second;
auto it = prev(s.upper_bound(pos));
l2 = (*it);
if (it != s.begin()) {
it--;
r1 = l2 - 1;
l1 = (*it);
it++;
}
it++;
if (it == s.end()) {
r2 = n;
}
else {
r2 = (*it) - 1;
l3 = r2 + 1;
it++;
if (it == s.end()) {
r3 = n;
}
else {
r3 = (*it) - 1;
}
}
b[pos] = 2;
if (l2 == r2 && l2 > 1 && r2 < n) {
update(l1, r3, l1, r1, l3, r3, val);
len.erase(len.find(r1 - l1 + 1));
s.erase(l2);
len.erase(len.find(r2 - l2 + 1));
s.erase(l3);
len.erase(len.find(r3 - l3 + 1));
len.insert(r3 - l1 + 1);
}
else {
len.erase(len.find(r2 - l2 + 1));
if (pos > l2) {
update(l2, pos - 1, l2, r2, 0, 0, val);
len.insert(pos - l2);
}
else {
s.erase(l2);
}
if (pos < r2) {
update(pos + 1, r2, l2, r2, 0, 0, val);
s.insert(pos + 1);
len.insert(r2 - pos);
}
if (pos == l2 && l2 > 1) {
update(l1, pos, l1, r1, 0, 0, val);
len.erase(len.find(r1 - l1 + 1));
len.insert(pos - l1 + 1);
}
else if (pos == r2 && r2 < n) {
update(pos, r3, l3, r3, 0, 0, val);
s.erase(l3);
len.erase(len.find(r3 - l3 + 1));
s.insert(pos);
len.insert(r3 - pos + 1);
}
else {
update(pos, pos, l2, r2, 0, 0, val);
s.insert(pos);
len.insert(1);
}
}
if (val != p[i + 1].first) {
mx = max(mx, *len.rbegin());
}
}
cout << (mx - 1) / 2 << '\n';
if (k == 1) {
for (int i = 1; i <= n; i++) {
cout << res[i] << " ";
}
}
}
// END MAIN CODE | 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;
typedef long long int ll;
// start
class lazySegTreeForMin{
public :
class node{
public :
ll mn,lazySet,lazyIncrement;
bool setAll;
node(){
mn = 1e18+1;
setAll = false;
lazyIncrement = 0;
}
void reset(){
setAll = false;
lazyIncrement = 0;
}
};
ll n;
vector <node> tree;
lazySegTreeForMin(vector <ll> v){
n = (ll)1<<(ll)ceil(log2((ll)v.size()));
tree.assign(2*n,node());
for(ll i=0;i<(ll)v.size();i++){
tree[i+n].mn = v[i];
}
build(1);
}
void build(ll u){
if(u<n){
build(2*u);
build(2*u+1);
tree[u].mn = min(tree[2*u].mn,tree[2*u+1].mn);
}
}
void pushToChild(ll par,ll child){
if(tree[par].setAll){
tree[child].setAll = true;
tree[child].lazySet = tree[par].lazySet;
tree[child].lazyIncrement = tree[par].lazyIncrement;
}
else{
tree[child].lazyIncrement += tree[par].lazyIncrement;
}
}
void push(ll index,ll x,ll y){
if(tree[index].setAll){
tree[index].mn = tree[index].lazySet;
}
tree[index].mn += tree[index].lazyIncrement;
if(x!=y){
pushToChild(index,2*index);
pushToChild(index,2*index+1);
}
tree[index].reset();
}
void rangeSet(ll l,ll r,ll val){
lazySet(l,r,1,0,n-1,val);
}
void rangeUpdate(ll l,ll r,ll val){
lazyUpdate(l,r,1,0,n-1,val);
}
ll rangeMin(ll l,ll r){
return lazyMin(l,r,1,0,n-1);
}
void lazySet(ll a,ll b,ll index,ll x,ll y,ll val){
if(x>b || y<a) return;
if(x>=a && y<=b){
tree[index].setAll = true;
tree[index].lazySet = val;
tree[index].lazyIncrement = 0;
return;
}
push(index,x,y);
ll mid = (x+y)/2;
lazySet(a,b,2*index,x,mid,val);
lazySet(a,b,2*index+1,mid+1,y,val);
push(2*index,x,mid);
push(2*index+1,mid+1,y);
tree[index].mn = min(tree[2*index].mn,tree[2*index+1].mn);
}
void lazyUpdate(ll a,ll b,ll index,ll x,ll y,ll val){
if(x>b || y<a) return;
if(x>=a && y<=b){
tree[index].lazyIncrement += val;
return;
}
push(index,x,y);
ll mid = (x+y)/2;
lazyUpdate(a,b,2*index,x,mid,val);
lazyUpdate(a,b,2*index+1,mid+1,y,val);
push(2*index,x,mid);
push(2*index+1,mid+1,y);
tree[index].mn = min(tree[2*index].mn,tree[2*index+1].mn);
}
ll lazyMin(ll a,ll b,ll index,ll x,ll y){
if(x>b || y<a){
return 1e18+1;
}
push(index,x,y);
if(x>=a && y<=b){
return tree[index].mn;
}
ll mid = (x+y)/2;
return min(lazyMin(a,b,2*index,x,mid),lazyMin(a,b,2*index+1,mid+1,y));
}
};
// end
/* NOTE
Use .rangeUpdate(), .rangeMin(), .rangeSet()
*/
void solve(){
ll n;
cin >> n;
vector <ll> v(n),ind(n+1),a(n),s(n+1,0);
for(ll i=0;i<n;i++){
cin >> v[i];
ind[v[i]] = i;
}
for(ll i=0;i<n;i++){
cin >> a[i];
s[i+1] += a[i];
s[i+1] += s[i];
}
lazySegTreeForMin st(s);
ll ans = st.rangeMin(1,n-1);
for(ll i=1;i<=n;i++){
st.rangeUpdate(0,ind[i],a[ind[i]]);
st.rangeUpdate(ind[i]+1,n,-a[ind[i]]);
ans = min(ans, st.rangeMin(1,n-1));
}
cout << ans << endl;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tc;
tc = 1;
//cin >> tc;
for(int i=1;i<=tc;i++){
//cout << "Case #" << i << ": ";
solve();
}
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"
] | // LUOGU_RID: 94439220
/*****************************************
Note :
******************************************/
#include <queue>
#include <math.h>
#include <stack>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <iomanip>
#include <string.h>
#include <algorithm>
#include <time.h>
#define LL long long
#define IL inline
const int N = 1e6+10;
const LL INF = 1e18;
using namespace std;
IL int read()
{
char ch = getchar();
int f = 1, num = 0;
while(ch>'9'||ch<'0')
{
if(ch=='-') f = -1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
num = num*10+ch-'0', ch = getchar();
return num*f;
}
LL dp[20][100],dis[100][100],ans=INF;
int col[100];
int n,k,t=5000;
int main()
{
srand((unsigned)time(NULL));
n=read(),k=read();
for(int i = 1;i<=n;i++)
for(int j = 1;j<=n;j++)
dis[i][j]=read();
while(t--)
{
for(int i = 1;i<=n;i++)
{
col[i]=rand()&1;
dp[0][i]=INF;
}
dp[0][1]=0;
for(int i = 0 ;i<k;i++)
{
for(int j = 1;j<=n;j++)
dp[i+1][j]=INF;
for(int j = 1;j<=n;j++)
for(int u = 1;u<=n;u++)
if(col[j]!=col[u])
dp[i+1][u]=min(dp[i+1][u],dp[i][j]+dis[j][u]);
}
ans=min(ans,dp[k][1]);
}
printf("%lld\n",ans);
}
| 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<iostream>
using namespace std;
int main(){
int t;
cin >> t;
for(int i=0;i<t;i++){
int n;
cin >> n;
int arr[n];
for(int j=0;j<n;j++){
cin >> arr[j];
}
int min=arr[0];
for(int k=0;k<n;k++){
if(min>arr[k]){
min=arr[k];
}
}
for(int j=0;j<n;j++){
arr[j]=arr[j]-min;
}
int p=0;
for(int j=0;j<n;j++){
if ((arr[j] % 2)==1){
p=-1;
break;
}
}
if (p==-1){
cout<<"NO"<<endl;
}
else{
cout<<"YES"<<endl;
}
}
} | cpp |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | /*
Date: 16 February 2023
Problem Link: https://codeforces.com/problemset/problem/1285/B
Author: Tareq Munawer Taj
CSE, Rajshahi University
*/
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vii vector<int>
#define vll vector<ll>
#define vull vector<ull>
#define vss vector<string>
#define FOR(i, n, x) for (int i = 0; i < n; i = i + x)
#define FORR(i, n, x) for (int i = n; i >= 0; i = i - x)
#define SORT(v) sort(v.begin(), v.end())
#define RSORT(v) sort(v.rbegin(), v.rend())
#define REVERSE(v) reverse(v.rbegin(), v.rend())
#define lowbound(name, val) lower_bound(name.begin(), name.end(), val) - name.begin()
#define uppbound(name, val) upper_bound(name.begin(), name.end(), val) - name.begin()
#define matrix(x) vector<vector<x>>
#define ms(a, b) memset(a, b, sizeof(a))
#define setdigit(n) fixed << setprecision(n)
#define MOD(a, b) (a % b + b) % b
#define lcm(a, b) ((a) * ((b) / __gcd(a, b)))
#define ff first
#define ss second
#define YES printf("YES\n")
#define NO printf("NO\n")
#define nl "\n"
#define PI (acos(-1.0))
#define mod 1000000007
#define INF (ll)1e17
#define N 100005
using namespace std;
void solve()
{
int size;
cin >> size;
vll num(size);
ll sum = 0, sub_sum = 0, max_sum = -INF;
for (int i = 0; i < size; i++)
{
cin >> num[i];
sum += num[i];
}
for (int i = 0; i < size - 1; i++)
{
if (sub_sum + num[i] <= 0)
sub_sum = 0;
else
sub_sum += num[i];
max_sum = max(max_sum, sub_sum);
}
sub_sum = 0;
for (int i = 1; i < size; i++)
{
if (sub_sum + num[i] <= 0)
sub_sum = 0;
else
sub_sum += num[i];
max_sum = max(max_sum, sub_sum);
}
if (sum > max_sum)
cout << "YES" << nl;
else
cout << "NO" << nl;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tc = 1;
cin >> tc;
while (tc--)
solve();
return 0;
} | cpp |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds. | [
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
int n;
cin>>n;
string str;
cin>>str;
int count1=0;
int count2=0;
for(int i=0;i<n;i++){
if(str[i]=='(') count1++;
else count2++;
}
if(count1!=count2){
cout<<-1<<"\n";
}
else{
int len=0;
int sum=0;
for(int i=0;i<n;i++){
if(str[i]=='('){
if(sum==-1) len++;
sum++;
}
else{
sum--;
}
if(sum<0) len++;
}
cout<<len<<"\n";
}
}
//8929031003
// | cpp |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
#define rep(i,x,y) for(int i=x;i<=y;i++)
#define per(i,x,y) for(int i=x;i>=y;i--)
using namespace std;
const int mod=1e9+7;
const int N=4e5+10;
#define int long long
int qmi(int a,int b){
int res=1;
for(;b;a=a*a%mod,b>>=1)
if(b&1)res=res*a%mod;
return res;
}
int cnt[N];
void solve(){
int n,m,ans=0;cin>>n>>m;
vector<vector<int>>a(n+1,vector<int>(m+1));
rep(i,1,n)rep(j,1,m)cin>>a[i][j];
rep(j,1,m){
rep(i,0,n)cnt[i]=0;
int mn=n;
rep(i,1,n)if((a[i][j]-j)%m==0 and a[i][j]<=n*m){
int res=i-((a[i][j]-j)/m+1);
if(res<0)res+=n;
cnt[res]++;
}
rep(i,0,n-1)mn=min(mn,i+n-cnt[i]);
ans+=mn;
}
cout<<ans;
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
int tc=1;
//cin>>tc;
for (int i=1;i<=tc;i++){
solve();
}
} | 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"
] | #include <bits/stdc++.h>
#define int unsigned long long
using namespace std;
const int maxn=2e5+5;
int a[26][maxn];
signed main()
{
//freopen("in.txt","r",stdin);
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
string s;
int n;
cin>>s>>n;
for(int i=0;i<(int)s.size();i++)
{
for(int j=0;j<26;j++)
{
a[j][i+1]=a[j][i];
}
a[s[i]-'a'][i+1]++;
}
for(int i=1;i<=n;i++)
{
int x,y;
cin>>x>>y;
if(x==y||s[x-1]!=s[y-1])
{
cout<<"Yes\n";
continue;
}
int num=0;
for(int i=0;i<26&&num<3;i++)
{
if(a[i][y]>a[i][x-1])
{
num++;
}
}
if(num>2)
{
cout<<"Yes\n";
}
else
{
cout<<"No\n";
}
}
return 0;
}
| 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"
] | #ifdef LOCAL
#define _GLIBCXX_DEBUG
#endif
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
#define sz(s) ((int)s.size())
#define all(v) begin(v), end(v)
typedef long double ld;
const int MOD = 1000000007;
#define ff first
#define ss second
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
// *-> KISS*
int solve() {
ll n; cin >> n;
ll ans = n * n;
vector<pair<int, int>> v;
for(int i = 0; i < n; ++i) {
int si; cin >> si;
vector<int> t(si, 0);
for(int j = 0; j < si; ++j) cin >> t[j];
reverse(all(t));
if(is_sorted(all(t))) {
v.push_back({t[0], t[si - 1]});
}
}
sort(all(v));
for(int i = 0; i < sz(v); ++i) {
ans -= v.end() - lower_bound(all(v), pair(v[i].ss, -1));
}
cout << ans;
return 0;
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
int TET = 1;
//cin >> TET;
cout << fixed << setprecision(6);
for (int i = 1; i <= TET; i++) {
#ifdef LOCAL
cout << "##################" << '\n';
#endif
if (solve()) {
break;
}
cout << '\n';
}
#ifdef LOCAL
cout << endl << "finished in " << clock() * 1.0 / CLOCKS_PER_SEC << " sec" << endl;
#endif
return 0;
}
// -> Keep It Simple Stupid! | cpp |
1324 | E | E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good. | [
"dp",
"implementation"
] | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
//---------------------------------------------------------------------------------
#define ll long long
#define fixed(n) cout << fixed << setprecision(n)
#define sz(x) int(x.size())
#define TC int t; cin >> t; while(t--)
#define all(s) s.begin(), s.end()
#define rall(s) s.rbegin(), s.rend()
#define dl "\n"
#define Ceil(a, b) ((a / b) + (a % b ? 1 : 0))
#define pi 3.141592
#define OO 2'000'000'000
#define MOD 1'000'000'007
#define EPS 1e-10
using namespace std;
using namespace __gnu_pbds;
//---------------------------------------------------------------------------------
template <typename K, typename V, typename Comp = std::less<K>>
using ordered_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = std::greater<K>>
using ordered_set = ordered_map<K, null_type, Comp>;
template <typename K, typename V, typename Comp = std::less_equal<K>>
using ordered_multimap = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = std::less_equal<K>>
using ordered_multiset = ordered_multimap<K, null_type, Comp>;
// order_of_key(val) count elements smaller than val
// *s.find_by_order(idx) element with index idx
template<typename T = int > istream& operator >> (istream &in , vector < T > &v){
for(auto &i : v) in >> i ;
return in ;
}
template<typename T = int > ostream& operator << (ostream &out ,vector < T > &v){
for(auto &i : v) out << i << ' ' ;
return out ;
}
//-----------------------------------------------------------------------------------------
void ZEDAN() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin) ;
freopen("output.txt", "w", stdout) ;
#endif
}
//-----------------------------------------(notes)-----------------------------------------
/*
*/
//-----------------------------------------(function)--------------------------------------
ll n , h , l , r ;
vector<ll>v ;
vector<vector<ll>>dp ;
bool valid(ll t){
return t>=l &&t<=r ;
}
ll rec(ll i=0 , ll t=0){
if(i>=n) return 0 ;
ll &ret = dp[i][t] ;
if(~ret) return ret ;
return ret = max(valid((t+v[i])%h)+rec(i+1,(t+v[i])%h),valid((t+v[i]-1)%h)+rec(i+1,(t+v[i]-1)%h)) ;
}
//-----------------------------------------(code here)-------------------------------------
void solve(){
ll n , h , l , r ;
cin >> n >> h >> l >> r;
vector<ll>v(n) ;
vector<vector<ll>>dp(2,vector<ll>(h+5)) ;
cin >> v ;
auto valid=[&](ll t){
return t>=l && t<=r ;
};
for(ll i=n-1 ; i>=0 ; i--){
for(ll t=0 ; t<h ; t++){
ll &ret = dp[i%2][t] ;
ret = 0 ;
ret = max(ret,valid((t+v[i])%h)+dp[(i+1)%2][(t+v[i])%h]) ;
ret = max(ret,valid((t+v[i]-1)%h)+dp[(i+1)%2][(t+v[i]-1)%h]) ;
}
}
cout << dp[0][0] ;
}
//-----------------------------------------------------------------------------------------
int main()
{
ZEDAN() ;
ll t = 1 ;
// cin >> t ;
while(t--){
solve() ;
if(t) cout << dl ;
}
return 0;
} | cpp |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | #include "bits/stdc++.h"
using namespace std;
#define all(x) begin(x),end(x)
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = " "; return os; }
#define debug(a) cerr << "(" << #a << ": " << a << ")\n";
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> pi;
const int mxN = 1e5+1, oo = 1e9;
typedef complex<int> pt;
#define X real()
#define Y imag()
auto cross(pt u, pt v) {return (ll)u.X*v.Y-(ll)u.Y*v.X;}
auto sgn(ll a) {return a==0?0:(a>0?1:-1);}
auto ccw(pt p1, pt p2, pt p3) {auto u = p2-p1, v = p3-p2;return cross(u,v);}
auto in(pt p1, pt p2) {return (ll)p1.X*p2.X+(ll)p1.Y*p2.Y;}
auto norm(pt p) {return (ll)p.X*p.X+(ll)p.Y*p.Y;}
bool comp(const pt& a, const pt& b) { return a.X<b.X or (a.X==b.X and a.Y < b.Y);}
void read(pt& p) {
int a,b; cin >> a >> b;
p = {a,b};
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n; cin >> n;
vector<pt> pts(n);
for(auto& i : pts) read(i);
pt prv = pts.back();
vector<pt> vecs;
for(auto i : pts) {
auto v = i-prv;
if(comp(v,0)) v=-v;
vecs.push_back(v);
prv = i;
}
sort(all(vecs),comp);
vecs.push_back({0,0});
bool yes=true;
for(int i=0;i<n;i+=2) {
yes&=vecs[i]==vecs[i+1];
}
cout << (yes?"YES\n":"NO\n");
} | cpp |
1305 | E | E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5) | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | // time-limit: 1000
// problem-url: https://codeforces.com/contest/1305/problem/E
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "debug.h"
#else
#define debug(...) 42
#endif
#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define forn(i, a) rep(i, 0, a)
#define per(i, a, b) for (int i = (b)-1; i >= (a); --i)
#define rofn(i, a) per(i, 0, a)
#define IOS \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0)
#define dbg(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 ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define sz(x) (int)(x).size()
#define lb lower_bound
#define ub upper_bound
#define endl "\n"
#define mem0(a) memset(a, 0, sizeof(a))
#define mem1(a) memset(a, -1, sizeof(a))
#define memf(a) memset(a, false, sizeof(a))
#define memt(a) memset(a, true, sizeof(a))
#define meminf(a) memset(a, 0x7f, sizeof(a))
#define nO \
{ \
cout << "NO\n"; \
return; \
}
#define yES \
{ \
cout << "YES\n"; \
return; \
}
#define neg \
{ \
cout << "-1\n"; \
return; \
}
#define each(a, x) for (auto &a : x)
#define ar array
mt19937_64 rng(std::chrono::steady_clock::now().time_since_epoch().count());
#define int long long
template <typename T> using V = vector<T>;
template <typename T> bool ckmin(T &a, const T &b) {
return b < a ? a = b, 1 : 0;
} // set a = min(a,b)
template <typename T> bool ckmax(T &a, const T &b) {
return a < b ? a = b, 1 : 0;
}
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
using ll = long long;
using db = long double;
using vd = vector<db>;
using vs = vector<string>;
using pi = pair<int, int>;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vpi = vector<pi>;
template <class T> using MaxHeap = priority_queue<T>;
template <class T> using MinHeap = priority_queue<T, vector<T>, greater<T>>;
template <class A> void read(V<A> &v);
template <class A, size_t S> void read(ar<A, S> &a);
template <class T> void read(T &x) { cin >> x; }
void read(double &d) {
string t;
read(t);
d = stod(t);
}
void read(long double &d) {
string t;
read(t);
d = stold(t);
}
template <class H, class... T> void read(H &h, T &...t) {
read(h);
read(t...);
}
template <class A> void read(V<A> &x) { each(a, x) read(a); }
template <class A, size_t S> void read(ar<A, S> &x) { each(a, x) read(a); }
// bitwise ops
constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set
constexpr int bits(
int x) { // assert(x >= 0); // make C++11 compatible until USACO updates ...
return x == 0 ? 0 : 31 - __builtin_clz(x);
} // floor(log2(x))
constexpr int p2(int x) { return 1 << x; }
constexpr int msk2(int x) { return p2(x) - 1; }
const ll INF = 1e18;
const db PI = acos((db)-1);
const int MOD = 1000000007;
vector<int>fac, inv, ifac;
void pre(int lim)
{
fac.push_back(1); fac.push_back(1);
ifac.push_back(1); ifac.push_back(1);
inv.push_back(0); inv.push_back(1);
for (int i = 2; i <= lim; i++)
{
fac.push_back(fac.back()*i % MOD);
inv.push_back(MOD - (inv[MOD % i] * (MOD / i) % MOD));
ifac.push_back(ifac.back()*inv.back() % MOD);
}
}
int ncr(int n, int r)
{
if (n < r || n < 0)
return 0;
if (r == 0)
return 1;
return (((fac[n] * ifac[r]) % MOD) * ifac[n - r]) % MOD;
}
void solve() {
int n,m;
cin >> n >> m;
vi v(n), f(n);
forn(i,n) v[i] = i + 1;
int sum = 0;
rep(i,2,n) f[i] = i / 2, sum += f[i];
if(m > sum) neg;
int X = 5005;
int Y = 1e9;
int idx = n-1;
//debug(v,f);
while(sum > m){
int x = f[idx];
int val = v[idx];
if(m + x > sum){
int rem = sum - m;
if(val&1ll) v[idx] += rem * 2 - 1;
else v[idx] += rem * 2;
break;
}
else{
v[idx] = Y;
sum -= x;
Y -= X;
}
idx--;
}
forn(i,n) cout << v[i] << " ";
cout << endl;
}
signed main() {
IOS;
//pre(5e5+10);
int tt = 1;
// cin >> tt;
for (int ii = 1; ii <= tt; ii++)
solve();
}
| 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>
#define pii pair<int,int>
#define fi first
#define se second
#define eb emplace_back
#define ll long long
using namespace std;
const int M=1e6+9;
int n,m,sz;
int id[M],c[M][26],b[M],t[M],dp[M],L[M],R[M],val[M];
bool vis[M],bo[M];
int Min(int x,int y){
return id[x]<id[y]?x:y;
}
int Max(int x,int y){
return id[x]>id[y]?x:y;
}
void dfs(int u){
id[u]=++sz;
L[u]=n+1,R[u]=0;
if(vis[u]){
L[u]=u;
R[u]=u;
}
for(int i=0;i<26;++i){
if(c[u][i]){
dfs(c[u][i]);
if(R[c[u][i]]){
if(R[u]){
L[u]=Min(L[u],L[c[u][i]]);
R[u]=Max(R[u],R[c[u][i]]);
}
else L[u]=L[c[u][i]],R[u]=R[c[u][i]];
}
}
}
}
void solve(int u,int z){
if(vis[u])dp[u]=min(dp[u],z+val[u]);
if(R[u])z=min(z,dp[u]+1-val[L[u]]);
for(int i=0;i<26;++i){
if(c[u][i]){
dp[c[u][i]]=dp[u]+1;
solve(c[u][i],z);
}
}
}
int main(){
cin>>n;
for(int i=1;i<=n;++i){
int p;
char s[5];
cin>>p>>s;
c[p][s[0]-'a']=i;
}
cin>>m;
for(int i=1;i<=m;++i){
cin>>b[i];
t[i]=i;
vis[b[i]]=1;
}
dfs(0);
sort(t+1,t+m+1,[&](const int&l,const int&r){return id[b[l]]<id[b[r]];});
for(int i=1;i<=m;++i){
val[b[t[i]]]=i;
}
solve(0,0);
for(int i=1;i<=m;++i){
cout<<dp[b[i]]<<" \n"[i==m];
}
return 0;
}
/*
1 2 2 4 3 6
*/ | cpp |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | #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=modint998244353;
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 t; cin >> t;
auto f=[&](int i, int j,int m){
return (i*(m+1)+j);
};
vi anss;
rep(test,t){
string s,t; cin >> s >> t;
int n=s.size();
int m=t.size();
int ans=0;
int up=(m+1)*(m+1)+5;
vvll dp(m+1,vll(m+1,inf));
vvll next(n+1,vll(26,inf));
{
vll now(26,inf);
for(int i=n-1; i>=0; i--){
next[i+1]=now;
now[s[i]-'a']=i+1;
}
next[0]=now;
}
rep(num,m+1){
rep(i,m+1)rep(j,m+1)dp[i][j]=inf;
dp[0][num]=0;
for(int i=0; i<=num; i++)for(int j=num; j<=m; j++){
ll now=dp[i][j];
if(now==inf)continue;
int id=dp[i][j];
if(i+1<=num && next[id][t[i+1-1]-'a']!=inf)chmin(dp[i+1][j],next[id][t[i+1-1]-'a']);
if(j+1<=m && next[id][t[j+1-1]-'a'])chmin(dp[i][j+1],next[id][t[j+1-1]-'a']);
}
ans|=(dp[num][m]<=n);
}
anss.push_back(ans);
}
for(auto u:anss)cout << (u?"YES":"NO") << endl;
}
| 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;
int main(){
int t;
cin>>t;
for(int k=0;k<t;k++)
{
long long int a,b,x,y;
cin>>x>>y>>a>>b;
if((y-x)%(a+b)!=0)
{
cout<<-1<<endl;
}
else
{
cout<<(y-x)/(a+b)<<endl;
}
}
return 0;
} | cpp |
13 | D | D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7 | [
"dp",
"geometry"
] | #include<iostream>
#include<algorithm>
using namespace std;
int n, m;
typedef long long ll;
typedef struct p {
ll x, y;
}p;
p r[505], b[505];
ll f[505][505];
bool cmp(p a, p b)
{
return a.y < b.y;
}
bool toleft(p i, p j, p k)//判断点k是否在i->j的左侧
{
if (k.y >= max(i.y, j.y) || k.y < min(i.y, j.y))return 0;
return (i.x * j.y + k.x * i.y + j.x * k.y - k.x * j.y - i.x * k.y - j.x * i.y) > 0;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> r[i].x >> r[i].y;
for (int i = 1; i <= m; i++)
cin >> b[i].x >> b[i].y;
sort(r + 1, r + n + 1, cmp);
sort(b + 1, b + m + 1, cmp);
for (int i = 1; i < n; i++)
for (int j = i + 1; j <= n; j++)
for (int k = 1; k <= m; k++)
if (toleft(r[i], r[j], b[k]))f[i][j]++;
/*for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
cout << f[i][j] << " ";
cout << endl;
}*/
ll ans = 0;
for (int i = 1; i < n; i++)
for (int j = i + 1; j < n; j++)
for (int k = j + 1; k <= n; k++)
if (f[i][j] + f[j][k] == f[i][k]) ans++;
cout << ans << endl;
return 0;
} | cpp |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | #include<bits/stdc++.h>
#define endl "\n"
using namespace std;
#define mod 1000000007
#define int long long
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t; cin>>t;
while(t--){
int n,g,b;
cin>>n>>g>>b;
if(g>=n){
cout<<n<<endl;
continue;
}
int min_good=(n+1)/2;
int max_bad=(n)/2;
if(g>=min_good){
cout<<n<<endl;
continue;
}
if(g>=b){
cout<<n<<endl;
continue;
}
if(min_good%g==0){
int turns=min_good/g;
int ans=min_good+(turns-1)*b;
ans=max(ans,n);
cout<<ans<<endl;
}
else{
int turns=(min_good)/g;
int ans=min_good;
ans+=turns*b;
ans=max(ans,n);
cout<<ans<<endl;
}
}
return 0;
} | cpp |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] | #include <cstdio>
#include <bitset>
using namespace std;
bitset<100100> s11, s12, s13, s2;
int main() {
int n, q, r, c;
scanf("%d %d", &n, &q);
while(q--) {
scanf("%d %d", &r, &c);
if(r == 1) {
s11.flip(c);
if(c - 1 > 0) s12.flip(c - 1);
if(c + 1 <= n) s13.flip(c + 1);
} else {
s2.flip(c);
}
if((s11 & s2).none() && (s12 & s2).none() && (s13 & s2).none()) {
printf("Yes\n");
} else {
printf("No\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 <bits/stdc++.h>
using namespace std;
bool ck(double x) {
return double(int(x)) != x;
}
void solve() {
double a, b, c, n;
cin >> a >> b >> c >> n;
double mid = (a + b + c + n) / 3;
if (a > mid || b > mid || c > mid || ck(mid)) cout << "NO" << endl;
else cout << "YES" << endl;
}
int main() {
int t; cin >> t;
while (t--) solve();
} | cpp |
1322 | D | D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
OutputCopy6
InputCopy2 2
1 2
0 0
2 1 -100 -100
OutputCopy2
InputCopy5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
OutputCopy62
NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11. | [
"bitmasks",
"dp"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// 8845946851
#define fi first
#define se second
inline int read()
{
int s = 0, w = 1;
char ch = getchar();
while (!isdigit(ch))
{
if (ch == '-')
w = -1;
ch = getchar();
}
while (isdigit(ch))
{
s = s * 10 + ch - '0';
ch = getchar();
}
return s * w;
}
const int N = 4001;
int n, l[N], s[N], c[N], m;
int f[N][N], t[N];
// f(i, j) last chosen item = i, and state = j, the reason is an item most advances log steps, j = 2^{log_2 n} = n level.
// but we can not achieve succinct transformation.
// so, f(i, j) last chosen val = i, state = j. but we need to for every item, O(n^3) sad.
// what we've found? log steps, and no others?
// look back our first dp. f(i, j) = max_{k < i, a_k < a_i, S} f(k, S) + c(a_i) - s_i
// attention that if j != 0, the useful a_k's sorts is less than log V.That's mean we just need to make max to useful S.
// if j == 0, that can be deal easily. It seems to could be finished in O(n^2\log n) times. Even O(n^2) times.
// we can change it ---- S is subset of S'. That is hard.
/* ---------------------------------------------------------------------------*/
int main() {
n = read(); m = read(); m += n;
for(int i = 1; i <= n; ++i) l[i] = read();
for(int i = 1; i <= n; ++i) s[i] = read();
for(int i = 1; i <= m; ++i) c[i] = read();
reverse(l + 1, l + n + 1);
reverse(s + 1, s + n + 1);
memset(f, -0x3f, sizeof f);
for(int i = 0; i <= m; ++i) f[i][0] = 0;
t[0] = n;
for(int i = 1; i <= m; ++i) t[i] = t[i - 1] >> 1;
for(int i = 1; i <= n; ++i) {
int v = l[i];
for(int j = n; j; --j) f[v][j] = max(f[v][j], f[v][j - 1] + c[v] - s[i]);
for(int j = v; j <= m; ++j) {
for(int k = 0; k <= t[j - v]; ++k) {
f[j + 1][k / 2] = max(f[j + 1][k / 2], f[j][k] + (k >> 1) * c[j + 1]);
}
}
}
cout << f[m][0] << '\n';
return 0;
} | cpp |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void sxseven();
int main() {
ios::sync_with_stdio(false);
int _=1;
cin >> _;
while(_--) {
sxseven();
}
return 0;
}
const int N=1e5+5;
map<ll,ll> mp;
void sxseven() {
ll n,x;
string s;
cin >> n >> x >> s;
mp.clear();
ll k=0;
for(int i=0; i<n; ++i) {
++mp[k];
if(s[i]=='0') ++k;
else --k;
}
if(k==0){
if(mp[x]) cout << -1 << endl;
else cout << 0 << endl;
}
else {
ll an=0;
for(auto it:mp) {
if(abs(x-it.first)%abs(k)==0 && (x-it.first)/k>=0) {
an+=it.second;
}
}
cout << an << endl;
}
}
| cpp |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | // LUOGU_RID: 102066497
#include <bits/stdc++.h>
using namespace std;
int f[200005],ff[200005],n,a[200005],u,v;
vector<int> g[200005];
inline int read(){
int x=0,f=1;char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar()) if(ch=='-') f=-1;
for(;ch>='0'&&ch<='9';ch=getchar()) x=(x<<3)+(x<<1)+(ch^48);
return f*x;
}
void dfs(int x,int fa){
f[x]=a[x];
for(int i=0;i<g[x].size();i++)
if(g[x][i]^fa)
dfs(g[x][i],x),f[x]+=max(0,f[g[x][i]]);
}
void dfs2(int x,int fa){
for(int i=0;i<g[x].size();i++)
if(g[x][i]^fa)
ff[g[x][i]]=a[g[x][i]]+max(ff[x]+f[x]-max(f[g[x][i]],0)-a[x],0),dfs2(g[x][i],x);
}
int main(){
n=read();
for(int i=1;i<=n;i++)
a[i]=(read()?1:-1);
for(int i=1;i<n;i++)
u=read(),v=read(),g[u].push_back(v),g[v].push_back(u);
dfs(1,0),ff[1]=a[1];
dfs2(1,0);
for(int i=1;i<=n;i++)
printf("%d ",f[i]+max(0,ff[i]-a[i]));
putchar(10);
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: 93094030
#include<bits/stdc++.h>
using namespace std;
#define pi pair<int,int>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define ls (rt<<1)
#define rs (rt<<1|1)
#define mid ((l+r)>>1)
#define lowbit(x) (x&-x)
const int maxn=3e5+5,M=2e5+5,mod=998244353;
inline int read(){
char ch=getchar();bool f=0;int x=0;
for(;!isdigit(ch);ch=getchar())if(ch=='-')f=1;
for(;isdigit(ch);ch=getchar())x=(x<<1)+(x<<3)+(ch^48);
if(f==1){x=-x;}return x;
}
void print(int x){
static int a[55];int top=0;
if(x<0) putchar('-'),x=-x;
do{a[top++]=x%10,x/=10;}while(x);
while(top) putchar(a[--top]+48);
}
int n,m,fa[maxn],cnt[maxn],mx,x;
long long ans;
int find(int x){if(x==fa[x])return x;return fa[x]=find(fa[x]);}
void merge(int x,int y){
int u=find(x),v=find(y);
if(u==v)return;
ans+=1ll*(x+y)*(cnt[u]+cnt[v]-1);fa[u]=v;cnt[v]=1;
}
signed main(){
//freopen("1.in","r",stdin);
//freopen(".out","w",stdout);
n=read();cnt[0]++;
for(int i=1;i<=n;i++)x=read(),cnt[x]++,ans-=x;
mx=(1<<18)-1;
for(int i=0;i<=mx;i++)fa[i]=i;
for(int i=mx;i>=0;i--){
for(int j=i;j;j=(j-1)&i)if(cnt[j]&&cnt[i^j])merge(j,i^j);
if(cnt[i])merge(i,0);
}cout<<ans<<endl;
return 0;
} | cpp |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
long long int a,b,ans,dis;
cin>>t;
while(t--){
ans=dis=0;
cin>>a>>b;
if(a == b){
cout<<0<<"\n";
continue;
}
if(a>b){
dis=a - b;
ans++;
if(dis % 2 !=0){
ans++;
}
}
else if(a < b){
dis= b - a;
ans++;
if(dis % 2 != 1){
ans++;
}
}
cout<<ans<<"\n";
}
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"
] | /**
* Surly
* 18.2.2023
**/
#include<bits/stdc++.h>
#define pb push_back
#define nw cout<<"\n";
#define rep(i,n) for(int i=0;i<n;i++)
#define all(v) v.begin(),v.end()
#define allr(v) v.rbegin(),v.rend()
#define mpr make_pair
#define memset(v,x) memset(v,x,sizeof(v))
#define len(v) int(v.size())
#define put(v,x) v.insert(begin(v),x)
#define wis(x) std::cerr <<"Line"<<__LINE__<<": "<<#x<<" is "<<x<<std::endl
using namespace std;
typedef int_fast64_t ll;
typedef vector<int> vi;
typedef vector<ll> vll;
#ifndef ONLINE_JUDGE
#include "debug.hpp"
#define debug(...) cerr << "[" << #__VA_ARGS__ << "] --> [", _debug(__VA_ARGS__);
#endif
template<typename type>istream& operator>>(istream& istream , deque<type> &v) {
if(v.size()) { for(auto &i : v) { istream>> i; } return istream; }
istream>>ws; string str; getline(istream , str); stringstream stream(str);
move(istream_iterator<type>(stream),istream_iterator<type>(),back_inserter(v));
return istream;}template<typename type>ostream& operator<<(ostream& ostream , vector<type> &
v){move(all(v),ostream_iterator<type>(ostream," ")); nw; return ostream;}
int main ( void )
{
time_t Time;
time(&Time);
cerr<<ctime(&Time);
ios_base::sync_with_stdio(false);
cin.tie(NULL),cout.tie(NULL);
cout<<fixed<<setprecision(2);
auto starttime=chrono::steady_clock::now();
string str; cin>> str;
deque<int> left , right;
int first = 0 , last = len(str)-1;
while(first<last) {
while(first<len(str) and str.at(first)==')')
first++;
while(last>0 and str.at(last)=='(')
last--;
if(first<len(str) and last>=0 and first<last) {
left.pb(first+1);
right.push_front(last+1);
first++;
last--;
}
}
if(!len(left) and !len(right)) {
cout<<0; nw;
}
else {
cout<< 1 <<'\n' << 2*len(left); nw;
for(auto &i : left)
cout<<i <<" ";
for(auto &i : right)
cout<< i <<" ";
}
auto endtime=chrono::steady_clock::now();
cerr<<endl<<"Elapsed Time: "
<<chrono::duration_cast<chrono::milliseconds> (endtime-starttime).count()
<<" milliseconds"<<endl;
return 0;
}
| 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 <bits/stdc++.h>
#define ll long long
#define N 502
using namespace std;
int n,m,q,i,j,bin[N],rmq[N][N][10][10],f[N][N][5],c[N][N];
int sum(int x1,int y1,int x2,int y2,int k)
{
return f[x2][y2][k]-f[x1-1][y2][k]-f[x2][y1-1][k]+f[x1-1][y1-1][k];
}
bool check(int x,int y,int k)
{
int tg=k*k;
return sum(x-k+1,y-k+1,x,y,0)==tg
&& sum(x-k+1,y+1,x,y+k,1)==tg
&& sum(x+1,y-k+1,x+k,y,2)==tg
&& sum(x+1,y+1,x+k,y+k,3)==tg;
}
int get(int x1,int y1,int x2,int y2)
{
int kx=bin[x2-x1+1],ky=bin[y2-y1+1];
return max(max(rmq[x2][y2][kx][ky],rmq[x1+(1<<kx)-1][y1+(1<<ky)-1][kx][ky]),
max(rmq[x2][y1+(1<<ky)-1][kx][ky],rmq[x1+(1<<kx)-1][y2][kx][ky]));
}
int main()
{
// freopen("ntu.inp","r",stdin);
// freopen("ntu.out","w",stdout);
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin>>n>>m>>q;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
char ch; cin>>ch;
for(int ok=0;ok<4;ok++)
f[i][j][ok]=f[i-1][j][ok]+f[i][j-1][ok]-f[i-1][j-1][ok];
f[i][j][0]+=(ch=='R');
f[i][j][1]+=(ch=='G');
f[i][j][2]+=(ch=='Y');
f[i][j][3]+=(ch=='B');
}
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
int l=0,r=min(min(i,j),min(n-i,m-j));
while(l<r)
{
int mid=(l+r+1)>>1;
if(check(i,j,mid)) l=mid; else r=mid-1;
}
c[i][j]=l;
}
for(i=1;i<=max(n,m);i++) bin[i]=trunc(log2(i));
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
for(int ki=0;ki<=bin[i];ki++)
for(int kj=0;kj<=bin[j];kj++)
{
if(ki==0 && kj==0) rmq[i][j][ki][kj]=c[i][j];
else if(ki==0)
rmq[i][j][ki][kj]=max(rmq[i][j][ki][kj-1],rmq[i][j-(1<<(kj-1))][ki][kj-1]);
else
rmq[i][j][ki][kj]=max(rmq[i][j][ki-1][kj],rmq[i-(1<<(ki-1))][j][ki-1][kj]);
}
while(q--)
{
int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2;
int l=0,r=min(x2-x1+1,y2-y1+1)/2;
while(l<r)
{
int mid=(l+r+1)>>1;
if(get(x1+mid-1,y1+mid-1,x2-mid,y2-mid)>=mid) l=mid; else r=mid-1;
}
cout<<4*l*l<<'\n';
}
}
| cpp |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | #include<bits/stdc++.h>
#include <iostream>
#include <cmath>
#include <set>
#include <map>
#include <cctype>
#include <algorithm>
#include <cstdlib>
#include <string.h>
#include <string>
#include <sstream>
using namespace std;
//#define int long long int
#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define F first
#define S second
typedef long long int ll;
const int N = 1e7+7;
const int mod=1e9+7;
//cout<<fixed<<setprecision(10);
/*void subarray(){
int n,ans;
ll t;
cin>>n>>t;
int a[n+5],s[n+5]={0};
for(int i=1; i<=n; ++i)
{
cin>>a[i];
s[i]=s[i-1]+a[i];
}
for(int i=1; i<=n; ++i)
{
if(a[i]>t)continue;
int l=i,r=n;
while(l<r)
{
int mid=(l+r)>>1;
mid++;
if(s[mid]-s[i-1]<=t)l=mid;
else r=mid-1;
}
ans=max(ans,l-i+1);
}
cout<<ans;
}
*/
/*void E2()
{
int n,m,k;
cin>>n>>m>>k;
vector<int>v;
ll ans=0;
for(int i=0; i<n; i++)
{
int x;
cin>>x;
v.push_back(x);
}
sort(v.begin(),v.end());
for(int i=0; i<n; i++)
{
auto idx=upper_bound(v.begin(),v.end(),v[i]+k)-v.begin();
idx-=1;
if(idx-i+1>=m)
ans=(ans%MOD+ncr(idx-i,m-1)%MOD)%MOD;
}
cout<<ans<<'\n';
}*/
ll power(ll a,ll b)
{
if(b==0)
{
return 1;
}
ll s= power(a,b/2);
return(b&1 ?a*s*s:s*s);
}
ll gcd(ll a,ll b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
const int D = 1e5 + 5;
int prime[D];
void Sieve()
{
for (int i = 2; i < D; ++i)
{
if (!prime[i])
{
for (int j = i + i; j <= D; j += i)
{
prime[j]=1;
}
}
}
}
ll fact[1000006],inv[1000006];
ll mul(ll a,ll b)
{
return (a%mod * b%mod)%mod;
}
ll npr(ll n, ll r)
{
return mul(fact[n],inv[n-r]);
}
ll ncr(ll n, ll r)
{
return mul(fact[n],mul(inv[n-r],inv[r]));
}
ll fast_power(ll base,ll exp)
{
if(exp==0)
return 1;
ll ans = fast_power(base,exp/2);
ans = mul(ans,ans);
if(exp%2!=0)
ans = mul(ans,base);
return ans;
}
void calcFacAndInv(ll n)
{
fact[0] = inv[0] = 1;
for(ll i=1; i<=n; i++)
{
fact[i] = (i*fact[i-1])%mod;
inv[i] = fast_power(fact[i],mod-2);
}
}
ll prime_factorize(ll n)
{
// O(sqrt(N))
for(ll i=2; i*i<=n; i++)
{
while(n%(i*i)==0)
{
n/=i;
}
}
return n;
}
bool isSquare(ll n)
{
double sqn=sqrt(n);
if(sqn==int(sqn))
{
return 1;
}
else
{
return 0;
}
}
void work1()
{
int n;
cin>>n;
int ans=0;
for(int i=2; i<n; i++)
{
int k=n;
while(k)
{
ans+=(k%i);
k/=i;
}
}
int x =n-2;
int G =gcd(ans,x);
cout<<ans/G<<"/"<<x/G;
}
int main()
{
FIO
int t=1;
//calcFacAndInv(100005);
//cin>>t;
while(t--)
work1();
}
| 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 <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
int t,n,odd,even;
cin>>t;
for(int i=0;i<t;i++){
odd=0,even=0;
cin>>n;
int a[n];
for(int j=0;j<n;j++){
cin>>a[j];
if(a[j]%2==0){
even++;
}
else{
odd++;
}
}
if(even==n||odd==n){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
} | 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"
] | #pragma GCC optimize("O3")
#define pb push_back
#define ll long long
#define F first
#define S second
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define pii pair<int, int>
#define pll pair<ll, ll>
#define ull unsigned long long
#include<bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int>a(n);
for(int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a.rbegin(), a.rend());
for(auto to : a) {
cout << to << " ";
}
cout << endl;
}
int main() {
fast;
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int t;
cin >> t;
while(t--) {
solve();
}
return 0;
}
| cpp |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | #include <iostream>
using namespace std;
void solve()
{
int n; cin >> n;
string s; cin >> s;
int ans = 1;
string res = s;
for(int i=2; i<=n; i++) {
string t = s.substr(i-1);
if((i&1) == (n&1)) {
for(int j=i-2; j>=0; j--) t += s[j];
} else {
for(int j=0; j<=i-2; j++) t += s[j];
}
if(t < res) {
ans = i;
res = t;
}
}
cout << res << '\n' << ans << endl;
}
int main()
{
int T;
cin >> T;
while(T--) {
solve();
}
return 0;
}
| cpp |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | #include <algorithm>
#include <iostream>
using namespace std;
long long cross(int x0, int y0, int x1, int y1) {
return (long long) x0 * y1 - (long long) x1 * y0;
}
long long cross(int x0, int y0, int x1, int y1, int x2, int y2) {
return cross(x1 - x0, y1 - y0, x2 - x0, y2 - y0);
}
long long dot(int x0, int y0, int x1, int y1) {
return (long long) x0 * x1 + (long long) y0 * y1;
}
bool check2(int xl0, int yl0, int xr0, int yr0, int xl1, int yl1, int xr1, int yr1, int xl2, int yl2, int xr2, int yr2) {
if (xl0 != xl1 || yl0 != yl1)
return false;
if (xr0 == xr1 && yr0 == yr1)
return false;
if (dot(xr0 - xl0, yr0 - yl0, xr1 - xl1, yr1 - yl1) < 0)
return false;
if (cross(xl0, yl0, xr0, yr0, xl2, yl2))
return false;
if (cross(xl1, yl1, xr1, yr1, xr2, yr2))
return false;
if (xl2 < xl0 && xl2 < xr0)
return false;
if (xl2 > xl0 && xl2 > xr0)
return false;
if (yl2 < yl0 && yl2 < yr0)
return false;
if (yl2 > yl0 && yl2 > yr0)
return false;
if (xr2 < xl1 && xr2 < xr1)
return false;
if (xr2 > xl1 && xr2 > xr1)
return false;
if (yr2 < yl1 && yr2 < yr1)
return false;
if (yr2 > yl1 && yr2 > yr1)
return false;
int l, r;
if (xl0 != xr0) {
l = xl0 - xl2;
r = xl2 - xr0;
} else {
l = yl0 - yl2;
r = yl2 - yr0;
}
l = abs(l);
r = abs(r);
if (l > r)
swap(l, r);
if (l * 4 < r)
return false;
if (xl1 != xr1) {
l = xl1 - xr2;
r = xr2 - xr1;
} else {
l = yl1 - yr2;
r = yr2 - yr1;
}
l = abs(l);
r = abs(r);
if (l > r)
swap(l, r);
if (l * 4 < r) {
return false;
}
return true;
}
bool check1(int xl0, int yl0, int xr0, int yr0, int xl1, int yl1, int xr1, int yr1, int xl2, int yl2, int xr2, int yr2) {
if (check2(xl0, yl0, xr0, yr0, xl1, yl1, xr1, yr1, xl2, yl2, xr2, yr2))
return true;
if (check2(xr0, yr0, xl0, yl0, xl1, yl1, xr1, yr1, xl2, yl2, xr2, yr2))
return true;
if (check2(xl0, yl0, xr0, yr0, xr1, yr1, xl1, yl1, xl2, yl2, xr2, yr2))
return true;
if (check2(xl0, yl0, xr0, yr0, xl1, yl1, xr1, yr1, xr2, yr2, xl2, yl2))
return true;
if (check2(xl0, yl0, xr0, yr0, xr1, yr1, xl1, yl1, xr2, yr2, xl2, yl2))
return true;
if (check2(xr0, yr0, xl0, yl0, xl1, yl1, xr1, yr1, xr2, yr2, xl2, yl2))
return true;
if (check2(xr0, yr0, xl0, yl0, xr1, yr1, xl1, yl1, xl2, yl2, xr2, yr2))
return true;
if (check2(xr0, yr0, xl0, yl0, xr1, yr1, xl1, yl1, xr2, yr2, xl2, yl2))
return true;
return false;
}
bool check0(int xl0, int yl0, int xr0, int yr0, int xl1, int yl1, int xr1, int yr1, int xl2, int yl2, int xr2, int yr2) {
if (check1(xl0, yl0, xr0, yr0, xl1, yl1, xr1, yr1, xl2, yl2, xr2, yr2))
return true;
if (check1(xl1, yl1, xr1, yr1, xl2, yl2, xr2, yr2, xl0, yl0, xr0, yr0))
return true;
if (check1(xl2, yl2, xr2, yr2, xl0, yl0, xr0, yr0, xl1, yl1, xr1, yr1))
return true;
return false;
}
int main() {
int t; cin >> t;
for (int h = 0; h < t; h++) {
int xl0, yl0, xr0, yr0; cin >> xl0 >> yl0 >> xr0 >> yr0;
int xl1, yl1, xr1, yr1; cin >> xl1 >> yl1 >> xr1 >> yr1;
int xl2, yl2, xr2, yr2; cin >> xl2 >> yl2 >> xr2 >> yr2;
cout << (check0(xl0, yl0, xr0, yr0, xl1, yl1, xr1, yr1, xl2, yl2, xr2, yr2) ? "YES" : "NO") << '\n';
}
return 0;
}
| cpp |
1286 | F | F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3
1 10 100
OutputCopy3
InputCopy3
5 3 -2
OutputCopy2
InputCopy1
0
OutputCopy0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed. | [
"brute force",
"constructive algorithms",
"dp",
"fft",
"implementation",
"math"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 22
ll n;
ll p[N],a[N];
ll f[1<<N];
ll cnn[1<<N];
bool vis[1<<N];
inline ll suan(ll x){
if(f[x]!=-1)return f[x];
ll an=(vis[x]);
for(int i=(x-1)&x;i;i=(i-1)&x){
if(!vis[x^i])continue;
// if(cnn[i]/2+1<=an)break;
an=max(an,suan(i)+1);
}return f[x]=an;
}
map<ll,ll>dui;
ll cc=0;
vector<ll>hs[1<<(N-2)];
int main()
{
// freopen("test1.in","r",stdin);
//freopen(".in","r",stdin);
//freopen("test1.out","w",stdout);
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
ll len;cin>>len;
for(int i=1;i<=len;i++)cin>>p[i];
for(int i=1;i<=len;i++)if(p[i]!=0)a[++n]=p[i];
for(int i=1;i<(1<<n);i++){
ll sum=0,cn=0;
for(int j=1;j<=n;j++){
if(i&(1<<(j-1)))sum+=a[j],p[++cn]=a[j];
}cnn[i]=cn;
bool kz=0;
if(cn>=2&&((sum+cn-1)&1)==0){
for(ll k=(sum-cn+1)/2;k<=(sum+cn-1)/2;k++){
if(dui.find(k)!=dui.end()){
for(auto o:hs[dui[k]])if((o|i)==i){kz=1;break;}
}if(kz)break;
}
}
if(dui.find(sum)==dui.end())dui[sum]=++cc;
hs[dui[sum]].push_back(i);
if(!kz)continue;
vis[i]=1;
}memset(f,-1,sizeof(f));
cout<<n-suan((1<<n)-1);
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>
#include <complex>
#include <queue>
#include <set>
#include <unordered_set>
#include <list>
#include <chrono>
#include <random>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <stack>
#include <iomanip>
#include <fstream>
using namespace std;
using namespace chrono;
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD 1000000007
#define MOD1 998244353
#define INF 1e18
#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 ll long long
#define imax INT_MAX
#define llmax LLONG_MAX
#define precise_cout(a,b) cout<<fixed<<setprecision(b)<<a<<"\n";
#define f(i,a,b) for(int i=a;i<=(int)b;i++)
#define fn(i,b,a) for(int i=b;i>=(int)a;i--)
#define debug(x) cerr << #x<<" : "; _print(x); cerr << endl;
#define vi vector<int>
#define vll vector<ll>
// #ifndef ONLINE_JUDGE
// #define debug(x) cerr << #x<<" "; _print(x); cerr << endl;
// #endif
typedef unsigned long long ull;
typedef long double lld;
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;}
void _print(ll 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);}
void swap(int &x, int &y) {int temp = x; x = y; y = temp;}
int expo(int a, int b, int mod) {int res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
void extendgcd(int a, int b, int*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); int x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3
int mminv(int a, int b) {int arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b
int mminvprime(int a, int b) {return expo(a, b - 2, b);}
int mod_add(int a, int b, int m) {a = a % m; b = b % m; return (((0ll + a + b) % m) + m) % m;}
int mod_mul(int a, int b, int m) {a = a % m; b = b % m; return (((1ll * a * b) % m) + m) % m;}
int mod_sub(int a, int b, int m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
int mod_div(int a, int b, int m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m
// binary exponentiation
ll bexp(ll a, ll b) { ll res = 1; while (b > 0) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; }
// binary exponentiation modulo mod
ll bexpM(ll a, ll b, ll mod) { ll res = 1; while (b > 0) { if (b & 1) res = (res * a) % mod; a = (a * a) % mod; b >>= 1; } return res; }
// sieve of eratosthenes for primes
const int P = 10000000;
int prime[P + 1];
void sieve() { prime[0] = 0; prime[1] = 0; for (int i = 2; i <= P; i++) { prime[i] = 1; } for (int i = 2; i * i <= P; i++) { if (prime[i] == 1) { for (int j = i * i; j <= P; j += i) { prime[j] = 0; } } } }
// sieve of eratosthenes for 'prime' factorization, O(n(log(log(n)))) for precomputation of spf, O(log(n)) thereafter to factorize each n
ll spf[P + 1];
vector<ll> primefactorize(ll n) { vector<ll> f; while(n>1){ f.pb(spf[n]); n/=spf[n]; } return f; }
void sieve_spf() { spf[0] = 0; spf[1] = 0; for (int i = 2; i <= P; i++) { spf[i] = -1; } for (int i = 2; i <= P; i++) { if (spf[i] == -1) { for (int j = i; j <= P; j += i) { if (spf[j] == -1) { spf[j] = i; } } } } }
// extended euclid algorithm
ll extendedgcd(ll a, ll b, ll &x, ll &y) { if (b == 0) { x = 1; y = 0; return a; } ll x1, y1; ll d = extendedgcd(b, a % b, x1, y1); x = y1; y = x1 - y1 * (a / b); return d; }
// modulo multiplicative inverse
ll modInverse(ll a, ll m) { ll x, y; ll g = extendedgcd(a, m, x, y); ll res = (x % m + m) % m; return res; }
// nCr (O(n))
ll ncr(ll n, ll k) { ll res = 1; if (k > n - k) k = n - k; for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; }
// nCr with modulo (O(rlogn))
ll ncrMOD(ll n, ll k, ll mod) { ll res = 1; if (k > n - k) k = n - k; for (int i = 0; i < k; ++i) { res = (res * (n - i)) % mod; res = (res * modInverse(i + 1, mod)) % mod; } return res % mod; }
// factorial without modulo
ll factorial(ll n) { ll res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; }
// factorial with modulo
ll factorialMOD(ll n, ll m) { ll res = 1; for (int i = 2; i <= n; i++) res = ((res % m) * (i % m)) % m; return res % m; }
// Check if a number is a Perfect square
bool checkperfectsquare(ll n) { if (ceil((double)sqrt(n)) == floor((double)sqrt(n))) { return true; } else { return false; } }
// Divisors of a number in O(sqrt N) -> including 1 and n
vector<ll> factorize(ll n) { vector<ll> v; for(int i=2;i<=sqrt(n);i++) { if (n % i == 0) { v.push_back(i); v.push_back(n / i); } } if (checkperfectsquare(n) == 1) { v.push_back(sqrt(n)); } if (n != 1) { v.pb(n); } return v; }
// calculate mex of a set
ll calculateMex(unordered_set<ll> Set) { ll Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex); }
// count number of set bits in a number
ll countSetBits(ll n) { if (n == 0) return 0; return (n & 1) + countSetBits(n >> 1); }
/*--------------------------------------------------------------------------------------------------------------------------*/
void showq(queue<int> gq)
{
queue<int> g = gq;
while (!g.empty()) {
cerr<<g.front()<<" ";
g.pop();
}
cerr << '\n';
}
void solve(){
int n,m;
cin>>n>>m;
vector<vi> G(n+1);
f(i,0,m-1){
int a,b;
cin>>a>>b;
G[b].pb(a); // transpose graph
}
vi dist(n+1,imax);
vi cnt(n+1,0); // array to store number of shortest paths from t to current vertex
vi pushed(n+1,0);
int len;
cin>>len;
vi p(len,0);
f(i,0,n-1) cin>>p[i];
queue<int> q;
q.push(p[len-1]);
pushed[p[len-1]]=1;
dist[p[len-1]]=0;
int d=0;
while(!q.empty()){
int v=q.front();
q.pop();
// d++;
for(auto child:G[v]){
int d=dist[v]+1;
if(!pushed[child]){
q.push(child);
pushed[child]=1;
}
if(dist[child]>d){
cnt[child]=1;
dist[child]=d;
}
else if(dist[child]==d)
cnt[child]++;
}
////////////
// debug(v) showq(q); debug(dist)
//////////////
}
int mn=0, mx=0;
fn(i,len-2,0){
if(dist[p[i]]<dist[p[i+1]]+1) {
mn++;
mx++;
}else{
if(cnt[p[i]]>1)
mx++;
}
}
cout<<mn<<" "<<mx<<"\n";
// debug(dist) debug(cnt)
}
signed main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
freopen("error.txt","w",stderr);
#endif
fastio();
auto start1 = high_resolution_clock::now();
int t=1;
// cin>>t;
while(t--){
solve();
}
auto stop1 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop1 - start1);
#ifndef ONLINE_JUDGE
cerr << "Time: " << duration . count() / 1000 << endl;
#endif
} | cpp |
1307 | D | D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | #include<bits/stdc++.h>
#define f first
#define s second
#define pb push_back
#define read(x) for(auto& qw : (x)) cin >> qw;
#define endl "\n"; //para problemas iterativos comentar essa linha
#define all(v) v.begin(), v.end()
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pii;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fll;
const ll MOD = 1000000007;
const ll NO_OPERTATION = -1;
vector<int> graph [200009];
int dist1[200009];
int dist2[200009];
void bfs(int a)
{
if(a==0)
{
memset(dist1,-1,sizeof(dist1));
dist1[a]=0;
queue<int> fila;
fila.push(a);
while(fila.empty()==false)
{
int u = fila.front();
fila.pop();
for(auto x: graph[u])
{
if(dist1[x]==-1){dist1[x]=dist1[u]+1; fila.push(x);}
}
}
}
else
{
memset(dist2,-1,sizeof(dist2));
dist2[a]=0;
queue<int> fila;
fila.push(a);
while(fila.empty()==false)
{
int u = fila.front();
fila.pop();
for(auto x: graph[u])
{
if(dist2[x]==-1){dist2[x]=dist2[u]+1; fila.push(x);}
}
}
}
return;
}
int main ()
{
ios::sync_with_stdio(0);
cin.tie(0);
ll n;
ll m;
ll k;
cin>>n>>m>>k;
vector<ll> special (k);
for(int i=0;i<k;i++)
{
cin>>special[i];
special[i]--;
}
for(int i=0;i<m;i++)
{
int a;
int b;
cin>>a>>b;
a--;
b--;
graph[a].pb(b);
graph[b].pb(a);
}
bfs(0);
bfs(n-1);
vector<pii> dif;
sort(all(special));
for(int i=0;i<k;i++)
{
dif.pb({dist1[special[i]]-dist2[special[i]],special[i]});
}
sort(all(dif));
int ans = 0;
int melhor = dist1[dif[0].s];
for(int i=1;i<special.size();i++)
{
ans = max(ans,melhor+dist2[dif[i].s]+1);
melhor=max(melhor,dist1[dif[i].s]);
}
cout<<min(ans,dist1[n-1])<<endl;
return 0;
}
| cpp |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | /*#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("O3")
#pragma GCC target ("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")*/
#include<bits/stdc++.h>
#define sz(v) (int)v.size()
#define ll long long
#define pb push_back
#define x first
#define y second
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define nl "\n"
using namespace std;
using pii = pair<int, int>;
const int N = (int)3e5 + 7; // make sure this is right
const int M = (int)15e6 + 7;
const int inf = (int)1e9 + 7;
const ll INF = (ll)3e18 + 7;
const ll MOD = (ll)998244353; // make sure this is right
pii dir[] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int a, b, x, y;
void solve() {
cin >> a >> b >> x >> y;
cout << max(max(x, a - x - 1) * b, max(y, b - y - 1) * a) << nl;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int test = 1;
cin >> test;
for(int i = 1; i <= test; ++i) {
//cout << "Case #" << i << ": ";
solve();
}
return 0;
} | cpp |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
| [
"dp",
"greedy",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
int T; cin >> T;
while (T--) {
string s, t; cin >> s >> t;
int a{1}, i{}, j{};
vector<vector<int>> F(26);
for (auto c: s) F[c - 'a'].push_back(i++);
for (auto c: t) {
auto &f = F[c - 'a'];
auto it = lower_bound(begin(f), end(f), j);
if (it == end(f)) {
a++;
it = lower_bound(begin(f), end(f), 0);
if (it == end(f)) { a = -1; break;}
}
j = (*it) + 1;
}
cout << a << '\n';
}
} | cpp |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
int n;cin>>n;
vector<int>x(n+1),y(n+1);
for(int i=1;i<n+1;i++)cin>>x[i]>>y[i];
if(n%2==1)cout<<"NO\n";
else{
set<pair<int,int>>st;
for(int i=1;i<=(n/2);i++){
double X=(x[i]+x[i+(n/2)]);
double Y=(y[i]+y[i+(n/2)]);
st.insert({X,Y});
}
if(st.size()==1)cout<<"YES";
else cout<<"NO\n";
}
} | cpp |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
void solve() {
string s , t;
cin >> s >> t;
int N = s.length();
deque<char>a , b;
for(auto i : t) b.push_back(i);
bool Alive = true;
while(Alive) {
a.push_back(b.front());
b.pop_front();
int n = a.size() , m = b.size();
vector<vector<int>>dp(N + 1 , vector<int>(n + 1 , -1));
dp[0][0] = 0;
for(int i = 0 ; i <= N ; i++) {
for(int j = 0 ; j <= n ; j++) {
/*
if(dp[i][j] == -1 && i < N && j == 0 && s[i] == a[j]) {
dp[i + 1][j] = max(dp[i + 1][j] , 0);
}
*/
int extra = 0;
if(i < N && dp[i][j] >= 0 && dp[i][j] < m && b[dp[i][j]] == s[i]) extra = 1;
if(i < N) dp[i + 1][j] = max(dp[i + 1][j] , dp[i][j] + extra);
if(j < n && i < N && s[i] == a[j])
dp[i + 1][j + 1] = max(dp[i + 1][j + 1] , dp[i][j]);
if(i < N) dp[i + 1][j] = max(dp[i + 1][j] , dp[i][j]);
}
}
if(dp[N][n] == m) {
cout << "YES\n";
return;
}
if(b.empty()) Alive = false;
}
cout << "NO\n";
return;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tt = 1;
cin >> tt;
while(tt--) {
solve();
}
return 0;
}
| cpp |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | #include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
string s;
cin >> n >> s;
int odd = 0, cnt = 0;
for (char c : s) if ((c - '0') & 1) odd++;
if (odd <= 1) { cout << -1 << endl; continue; }
for (char c : s) {
if ((c - '0') & 1) { cout << c; cnt++; }
if (cnt == 2) break;
}
cout << endl;
}
} | cpp |
1286 | D | D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2
1 1 100
3 1 0
OutputCopy1
InputCopy3
7 10 0
9 4 86
14 5 100
OutputCopy0
InputCopy4
6 4 50
11 25 50
13 16 50
15 8 50
OutputCopy150902884
| [
"data structures",
"math",
"matrices",
"probabilities"
] | #include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=2e5+10,mod=998244353;
ll n,XX[N],VV[N],P[N];
struct node{
ll d,v,x,y,f1,f2;
}nd[N];
ll i100;
ll ksm(ll x,ll y){ll res=1;while(y){if(y&1)res=res*x%mod;x=x*x%mod;y>>=1;}return res;}
int lim[N][2][2];
struct Segment{
int l,r;
ll v[2][2];
void print(){
for(int i=0;i<2;i++){
for(int j=0;j<2;j++)
printf("%d ",v[i][j]);
puts("");
}
puts("");
}
}s[N<<2];
void pushup(int x){
int l=s[x<<1].r,r=s[x<<1|1].l;
//s[x<<1].print(),s[x<<1|1].print();
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
s[x].v[i][j]=0;
for(int xx=0;xx<2;xx++){
for(int y=0;y<2;y++){
//printf("%d ",lim[r][x][y]);
if(!lim[r][xx][y])
//printf("%d %d %d %d %lld %lld\n",i,x,y,j,s[x<<1].v[i][x],s[x<<1|1].v[y][j]);
s[x].v[i][j]=(s[x].v[i][j]+s[x<<1].v[i][xx]*s[x<<1|1].v[y][j]%mod)%mod;
}
//puts("");
}
}
}
return ;
}
void build(int x,int l,int r){
s[x].l=l,s[x].r=r;
if(l==r){
s[x].v[0][0]=(100-P[l])*i100%mod;
s[x].v[1][1]=P[l]*i100%mod;
return ;
}
int mid=(l+r)>>1;
build(x<<1,l,mid);
build(x<<1|1,mid+1,r);
pushup(x);
}
bool cmp(node q,node p){
return q.d*p.v<p.d*q.v;
}
void upd(int x,int p){
if(s[x].l==p&&s[x].r==p)return ;
int mid=(s[x].l+s[x].r)/2;
if(p<=mid)upd(x<<1,p);
else upd(x<<1|1,p);
pushup(x);
}
int main(){
i100=ksm(100,mod-2);
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lld%lld%lld",&XX[i],&VV[i],&P[i]);
int qwq=0;
for(int i=1;i<n;i++){
nd[++qwq]=(node){(XX[i+1]-XX[i]),(VV[i+1]+VV[i]),i,i+1,1,0};
if(VV[i]>VV[i+1])nd[++qwq]=(node){(XX[i+1]-XX[i]),(VV[i]-VV[i+1]),i,i+1,1,1};
if(VV[i]<VV[i+1])nd[++qwq]=(node){(XX[i+1]-XX[i]),(VV[i+1]-VV[i]),i,i+1,0,0};
}
sort(nd+1,nd+qwq+1,cmp);
build(1,1,n);
ll res=0,nw=1;
for(int i=1;i<=qwq;i++){
lim[nd[i].y][nd[i].f1][nd[i].f2]=1;
upd(1,nd[i].y);
ll t=(s[1].v[0][0]+s[1].v[0][1]+s[1].v[1][0]+s[1].v[1][1])%mod;
res=(res+nd[i].d*ksm(nd[i].v,mod-2)%mod*(nw-t)%mod)%mod;
//printf("%lld [%lld,%lld] %lld %lld %lld %lld\n",nd[i].x,nd[i].f1,nd[i].f2,t,nd[i].d,ksm(nd[i].v,mod-2)%mod);
//for(int j=1;j<=10;j++)s[j].print();
nw=t;
}
printf("%lld\n",(res%mod+mod)%mod);
return 0;
} | cpp |
1286 | F | F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3
1 10 100
OutputCopy3
InputCopy3
5 3 -2
OutputCopy2
InputCopy1
0
OutputCopy0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed. | [
"brute force",
"constructive algorithms",
"dp",
"fft",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define mp make_pair
#define inf 1e9
#define pii pair <int, int>
const int mod = 1e9 + 7;
int read () {
int x = 0, f = 1;
char ch = getchar ();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar ();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar ();
}
return x * f;
}
void write (int x) {
if (x < 0) x = -x, putchar ('-');
if (x >= 10) write (x / 10);
putchar (x % 10 + '0');
}
int quickmod (int x, int y) {
int Ans = 1;
while (y) {
if (y & 1) Ans = (Ans * x) % mod;
x = (x * x) % mod;
y >>= 1;
}
return Ans;
}
int n;
int a[25];
int cnt[(1<<20)+5], sum[(1<<20)+5];
int Abs(int x) {
if(x > 0) return x;
return -x;
}
int f[(1<<20)+5], g[(1<<20)+5];
signed main () {
// freopen (".in", "r", stdin);
// freopen (".out", "w", stdout);
n = read();
for(int i = 1; i <= n; i++) {
a[i] = read();
if(!a[i]) i--, n--;
}
for(int S = 0; S < (1 << n); S++) for(int i = 1; i <= n; i++) cnt[S] += (S >> (i - 1) & 1), sum[S] += (S >> (i - 1) & 1) * a[i];
for(int S = 1; S < (1 << n); S++) {
f[S] = 0;
if((sum[S] & 1) == (cnt[S] & 1)) continue;
for(int S2 = (S & (S - 1)); S2 && !f[S]; S2 = (S & (S2 - 1))) {
if(Abs(sum[S2] - sum[S2^S]) < cnt[S]) f[S] = 1;
}
}
for(int S = 1; S < (1 << n); S++) {
if(!g[S] && f[S]) {
g[S] = 1;
int t = (((1 << n) - 1) ^ S);
for(int S2 = t; S2; S2 = t & (S2 - 1)) {
if(g[S2|S] < f[S] + g[S2]) {
g[S2|S] = f[S] + g[S2];
}
}
}
}
write(n - g[(1<<n)-1]), putchar('\n');
return 0;
}
/*
20
526805827792 2946441309935 2619096608386 9462003520606 829843147948 5909009666920 2206445867397 3851452239345 6154793167158 1650033916993 6214706573505 3819943114210 1014716803427 768188477266 1627392133013 400808866999 5142425094925 1819004093493 5772426450305 6635878556611
f[i|j]=min{f[i]+f[j]}
*/ | 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 <bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int n;
cin >> n;
vector<int> a(n);
int countOdd = 0 ,countEven = 0;
for(int i = 0; i < n; i++)
{
cin >> a[i];
if(a[i] % 2 != 0)
{
countOdd++;
}
else countEven++;
}
if(countOdd == 0) cout<<"NO"<<endl;
else if(countOdd % 2 != 0)cout<<"YES"<<endl;
else if(countEven>=1) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
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 <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define out(x) cout << #x << '=' << x << endl;
#define lowbit(x) (x & -x);
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t = 1;
//cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 2; i <= n; i++) {
cin >> a[i];
}
auto build = [&](int start) -> vector<int> {
vector<int> ans(n + 1);
for (int i = 1; i <= n; i++) {
start += a[i];
ans[i] = start;
}
return ans;
};
vector<int> b(build(1));
set<int> vis;
int ch = 1;
for (int i = 1; i <= n; i++) {
if (vis.count(b[i])) {
cout << -1 << endl;
ch = 0;
break;
}
vis.insert(b[i]);
}
if (ch) {
int mi = 1 - *min_element(b.begin() + 1, b.end());
b = build(1 + mi);
vector<int> bb(b);
sort(bb.begin() + 1, bb.end());
for (int i = 1; i <= n; i++) {
//out(bb[i]);
if (bb[i] != i) {
ch = 0;
cout << -1 << endl;
break;
}
}
if (ch) {
for (int i = 1; i <= n; i++) {
cout << b[i] << ' ';
}
cout << endl;
}
}
}
} | cpp |
1292 | F | F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0. After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3
2 6 8
OutputCopy2
InputCopy5
2 3 4 9 12
OutputCopy4
InputCopy4
5 7 2 9
OutputCopy1
NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible: b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8]) b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible: b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4]) b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9]) b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12]) b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty. | [
"bitmasks",
"combinatorics",
"dp"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long i64;
typedef vector<int> vi;
typedef pair<int,int> pii;
template<typename T>
inline T read(){
T x=0,f=0;char ch=getchar();
while(!isdigit(ch)) f|=(ch=='-'),ch=getchar();
while(isdigit(ch)) x=x*10+(ch^48),ch=getchar();
return f?-x:x;
}
#define rdi read<int>
#define rdi64 read<i64>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
const int N=65,MOD=1e9+7;
int n,a[N];
vi e[N],_e[N];
i64 C[N][N],fac[N];
void init(int n){
fac[0]=1;
for(int i=1;i<=n;i++) fac[i]=fac[i-1]*i%MOD;
for(int i=0;i<=n;i++){
C[i][0]=1;
for(int j=1;j<=i;j++)
C[i][j]=(C[i-1][j-1]+C[i-1][j])%MOD;
}
}
int id[N];
i64 f[(1<<(N/4))+1][N];
pair<int,i64> solve(const vi &nodes){
if(nodes.size()==1) {return {0,1};}
for(int i=1;i<=n;i++) id[i]=0;
vi S,T;
int cnt=0;
for(auto x:nodes)
if(_e[x].empty()) S.pb(x),id[x]=++cnt;
else T.pb(x);
static int s[N];
for(auto x:T){
s[x]=0;
for(auto y:_e[x])
if(id[y]) s[x]|=(1<<(id[y]-1));
}
f[0][0]=1;
for(int i=0;i<(1<<cnt);i++){
for(int j=0;j<=T.size();j++){
i64 &v=(f[i][j]%=MOD);
if(!v) continue;
int c=0;
for(auto x:T){
if((s[x]&i)==s[x]) ++c;
else if((s[x]&i)||!j) (f[s[x]|i][j+1]+=v)%=MOD;
}
if(j<c) f[i][j+1]+=v*(c-j)%MOD;
}
}
pair<i64,int> ret={(int)(nodes.size()-S.size()-1),f[(1<<cnt)-1][T.size()]};
for(int i=0;i<(1<<cnt);i++)
for(int j=0;j<=T.size();j++) f[i][j]=0;
return ret;
}
struct Dsu{
int f[N];
void init(int n) {iota(f+1,f+n+1,1);}
int find(int x) {return x==f[x]?f[x]:f[x]=find(f[x]);}
void merge(int x,int y) {f[find(x)]=find(y);}
}d;
void solve(){
d.init(n);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j) continue;
if(a[j]%a[i]==0)
e[i].pb(j),_e[j].pb(i),d.merge(i,j);
}
}
static vi buf[N];
for(int i=1;i<=n;i++) buf[d.find(i)].pb(i);
i64 ans=1;
for(int i=1,sum=0;i<=n;i++)
if(buf[i].size()){
auto tmp=solve(buf[i]);
ans=ans*tmp.se%MOD*C[sum+=tmp.fi][tmp.fi]%MOD;
}
cout<<ans<<endl;
}
int main(){
#ifdef LOCAL
freopen(".in","r",stdin);
freopen(".out","w",stdout);
#endif
n=rdi();init(n);
for(int i=1;i<=n;i++) a[i]=rdi();
solve();
return 0;
}
| cpp |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | #include <iostream>
#include <cstring>
#include <algorithm>
const int N=5e5+10;
int a[N];
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m,i,j,sum=0;
cin>>n>>m;
for(i=0; i<n; i++)
{
cin>>a[i];
sum+=a[i];
}
cout<<min(sum,m)<<endl;
}
return 0;
}
| cpp |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | #include<bits/stdc++.h>
//#define feyn
#define int long long
#define ll __int128
using namespace std;
const int N=200010;
const int mod=1e15+7;
inline void read(int &wh){
wh=0;int f=1;char w=getchar();
while(w<'0'||w>'9'){if(w=='-')f=-1;w=getchar();}
while(w<='9'&&w>='0'){wh=wh*10+w-'0';w=getchar();}
wh*=f;return;
}
int m,n,cnt[N];
char w[N];
int p[N]={1},aa[N],bb[N],pl[N];
inline int get(int l,int r,int a[]){
ll now=(ll)a[r]-(ll)a[l-1]*p[r-l+1];
return (now%mod+mod)%mod;
}
signed main(){
#ifdef feyn
freopen("in.txt","r",stdin);
#endif
read(m);scanf("%s",w+1);int num=0;
for(int i=1;i<=m;i++)cnt[i]=cnt[i-1]+(w[i]=='0');
for(int i=1;i<=m;i++)if(w[i]=='0')pl[++num]=i&1;
for(int i=1;i<=num;i++){
p[i]=p[i-1]*2%mod;
aa[i]=(aa[i-1]*2ll+pl[i])%mod;
bb[i]=(bb[i-1]*2ll+1-pl[i])%mod;
}
read(n);
while(n--){
int x,y,len;read(x);read(y);read(len);
if(cnt[x+len-1]-cnt[x-1]!=cnt[y+len-1]-cnt[y-1]){
puts("No");continue;
}
if((x&1)==(y&1)){
if(get(cnt[x-1]+1,cnt[x+len-1],aa)==get(cnt[y-1]+1,cnt[y+len-1],aa))puts("Yes");
else puts("No");
}
else{
if(get(cnt[x-1]+1,cnt[x+len-1],aa)==get(cnt[y-1]+1,cnt[y+len-1],bb))puts("Yes");
else puts("No");
}
}
return 0;
} | cpp |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define f first
#define s second
const int N = 1e6+5;
ll arr[N];
ll brr[N];
ll pre[N];
ll mod = 1000000007 ;
vector < ll > vec ;
set < ll > st ;
map < ll, ll > mp;
pair < ll, ll > p[N];
void cc()
{
vec.clear();
st.clear();
mp.clear();
}
int main()
{
int t = 1;
cin >> t ;
while(t--)
{
ll n , x , mx = 0 ;
cin >> n >> x;
bool ok = 0 ;
for(int i=1 ; i <= n ; i++)
{
cin >> arr[i] ;
mx = max(mx , arr[i]);
if(arr[i] == x) ok = 1 ;
}
if(x == mx || ok)
{
cout << 1 << endl;
continue;
}
if(mx > x)
{
cout << 2 << endl;
continue;
}
cout << (x + mx-1) / mx << endl;
}
}
| 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"
] | /*
_/ _/ _/_/_/ _/ _/ _/ _/_/_/_/_/
_/ _/ _/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/
_/_/ _/ _/ _/ _/_/_/_/
_/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/
_/ _/ _/_/_/ _/ _/_/_/_/_/ _/_/_/_/_/
*/
#include <bits/stdc++.h>
#define ll long long
#define lc(x) ((x) << 1)
#define rc(x) ((x) << 1 | 1)
#define ru(i, l, r) for (int i = (l); i <= (r); i++)
#define rd(i, r, l) for (int i = (r); i >= (l); i--)
#define mid ((l + r) >> 1)
#define pii pair<int, int>
#define mp make_pair
#define fi first
#define se second
#define sz(s) (int)s.size()
#define maxn 100005
using namespace std;
const int mo = 1e9 + 7;
inline int read() {
int x = 0, w = 0; char ch = getchar();
while(!isdigit(ch)) {w |= ch == '-'; ch = getchar();}
while(isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}
return w ? -x : x;
}
int n, m, vis[maxn];
vector<pii> G[maxn];
int dep[maxn], tp, fl;
int haha[7];
int f[5005][5005];
void clear() {
ru(i, 0, 4) haha[i] = 0;
}
void ins(int x) {
// printf("!!! %d %d\n", x, fl);
rd(i, 4, 0) if((x >> i) & 1) {
if(!haha[i]) {
haha[i] = x;
ru(i, 0, 4) if(haha[i]) {
rd(j, i - 1, 0) if(haha[j] && ((haha[i] >> j) & 1)) {
haha[i] ^= haha[j];
}
}
return;
}
x ^= haha[i];
}
fl = 1;
}
inline int calc() {
int tmp[5] = {haha[0], max(0, haha[1] - 1), max(0, haha[2] - 3), max(0, haha[3] - 7), max(0, haha[4] - 15)};
return tmp[0] * 3 * 5 * 9 * 17 + tmp[1] * 5 * 9 * 17 + tmp[2] * 9 * 17 + tmp[3] * 17 + tmp[4] + 1;
}
int D[maxn];
void dfs(int x, int fa) {
vis[x] = 1;
for (auto t: G[x]) if(t.fi != fa) {
int V = t.fi, w = t.se;
if(V == 1) tp = dep[V] ^ dep[x] ^ w;
else if(vis[V]) {
if(D[V] < D[x]) ins(dep[V] ^ dep[x] ^ w);
}
else dep[V] = dep[x] ^ w, D[V] = D[x] + 1, dfs(V, x);
}
}
int b[10];
int arr[5005][10], tot, id[5005];
void work() {
ru(i, 0, 4) ru(j, i + 1, 4) if(b[i] && b[j] && ((b[j] >> i) & 1)) {
return;
}
ru(i, 0, 4) haha[i] = b[i];
tot++;
id[calc()] = tot;
ru(i, 0, 4) arr[tot][i] = b[i];
}
void dfs(int step) {
if(step > 4) {
work();
return;
}
b[step] = 0;
dfs(step + 1);
ru(i, (1 << step), (1 << (step + 1)) - 1) {
b[step] = i;
dfs(step + 1);
}
}
int dp[4600], nxt[4600];
inline void upd(int &x, int y) {
x += y; if(x >= mo) x -= mo;
}
int main() {
dfs(0);
// printf("%d\n", tot);
n = read(), m = read();
ru(i, 1, m) {
int x = read(), y = read(), z = read();
G[x].push_back(mp(y, z));
G[y].push_back(mp(x, z));
}
ru(i, 0, tot) ru(j, 0, tot) {
ru(k, 0, 4) haha[k] = arr[i][k];
fl = 0;
ru(k, 0, 4) if(arr[j][k]) ins(arr[j][k]);
if(fl) f[i][j] = -1;
else f[i][j] = id[calc()];
}
dp[1] = 1;
vis[1] = 1;
// printf("cnm %d\n", f[1][2295]);
for (auto t: G[1]) if(!vis[t.fi]) {
clear();
tp = -1, fl = 0;
dep[t.fi] = t.se, dfs(t.fi, 1);
// printf("%d %d\n", fl, tp);
if(fl) continue;
int tmp = id[calc()];
memcpy(nxt, dp, sizeof(nxt));
if(tp > -1) {
ins(tp);
ru(i, 1, tot) if(dp[i] && f[i][tmp] > -1) {
upd(nxt[f[i][tmp]], 2ll * dp[i] % mo);
}
// printf("???%d ", tmp);
if(!fl) {
tmp = id[calc()];
ru(i, 1, tot) if(dp[i] && f[i][tmp] > -1) {
upd(nxt[f[i][tmp]], dp[i]);
}
// printf("%d\n", tmp);
}
}
else {
ru(i, 1, tot) if(dp[i] && f[i][tmp] > -1) {
upd(nxt[f[i][tmp]], dp[i] % mo);
}
}
memcpy(dp, nxt, sizeof(dp));
// ru(i, 0, 4599) if(dp[i]) {
// printf("%d %d\n", i, dp[i]);
// }
}
int ans = 0; ru(i, 1, tot) ans = (ans + dp[i]) % mo;
printf("%d\n", 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"
] | // LUOGU_RID: 101865513
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 100001
ll n,k;
inline bool gt(ll x){
cout<<"? "<<x<<'\n';
char tem;
cout.flush();cin>>tem;
if(tem=='N')return 0;
return 1;
}
inline void clear(){
cout<<'R'<<'\n';
return ;
}
ll an[N];
int main()
{
// freopen("test1.in","r",stdin);
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>n>>k;
if(k==1){
ll ans=n;
for(int i=2;i<=n;i++){
for(int j=1;j<i;j++){
gt(j);ll o=gt(i);an[i]|=o;
}
if(an[i])ans--;
}cout<<"! "<<ans;
return 0;
}
ll ji=k/2,g=n/ji,ans=n;
for(int i=1;i<=g;i++){
for(int j=1;j<=i;j++){
if(j>g-i)continue;
for(int k=j;k<=g;k+=i){
for(int p=(k-1)*ji+1;p<=k*ji;p++)an[p]|=gt(p);
}clear();
}
}
for(int i=1;i<=n;i++)if(an[i])ans--;
cout<<"! "<<ans;
return 0;
}
| cpp |
1310 | E | E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function ff of multiset aa as the multiset of number of occurences of every number, that is present in aa.E.g., f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}.Let's define fk(a)fk(a), as applying ff to array aa kk times: fk(a)=f(fk−1(a)),f0(a)=afk(a)=f(fk−1(a)),f0(a)=a. E.g., f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}.You are given integers n,kn,k and you are asked how many different values the function fk(a)fk(a) can have, where aa is arbitrary non-empty array with numbers of size no more than nn. Print the answer modulo 998244353998244353.InputThe first and only line of input consists of two integers n,kn,k (1≤n,k≤20201≤n,k≤2020).OutputPrint one number — the number of different values of function fk(a)fk(a) on all possible non-empty arrays with no more than nn elements modulo 998244353998244353.ExamplesInputCopy3 1
OutputCopy6
InputCopy5 6
OutputCopy1
InputCopy10 1
OutputCopy138
InputCopy10 2
OutputCopy33
| [
"dp"
] | #include<bits/stdc++.h>
#define IL inline
#define reg register
#define N 2040
#define mod 998244353
IL int read()
{
reg int x=0;reg char ch=getchar();
while(ch<'0'||ch>'9')ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x;
}
IL int Add(reg int x,reg int y){return x+y<mod?x+y:x+y-mod;}
IL void Pls(reg int &x,reg int y){x=Add(x,y);}
int n,k,x[N],a[N],b[N+N],tot,ans;
IL void calc(reg int m)
{
if(!m)return;
for(reg int i=1;i<=m;++i)a[i]=x[i];
for(reg int i=k,j;i>2;--i)
{
tot=0;
for(j=m;j;--j)
{
while(a[j]--)b[++tot]=m-j+1;
if(tot>n)return;
}
m=tot;
for(j=1;j<=m;++j)a[j]=b[j];
}
for(reg int i=1,j=m,r=0;i<=m;++i,--j)
{
r+=j*a[i];
if(r>n)return;
}
++ans;
}
void dfs(reg int u,reg int s,reg int c,reg int las)
{
calc(u-1);
for(reg int i=las;s+c*i*(i+1)/2+i*(i+1)*(i+2)/6<=n;++i)
x[u]=i,dfs(u+1,s+c*i*(i+1)/2+i*(i+1)*(i+2)/6,c+i,i);
}
namespace sub1
{
int f[N][N],ans;
int main()
{
f[0][0]=1;
for(reg int i=1,j,k,w;i<=n;++i)for(j=0;j<=n;++j)if(w=f[i-1][j])
for(k=0;j+k<=n;k+=i)Pls(f[i][j+k],w);
for(reg int i=1;i<=n;++i)Pls(ans,f[n][i]);
return printf("%d",ans),0;
}
}
namespace sub2
{
const int ans[]={0, 1, 2, 4, 6, 8, 12, 16, 20, 26, 33, 40, 50, 61, 72, 87, 104, 121, 143, 167, 192, 224, 259, 295, 339, 387, 437, 497, 563, 631, 712, 801, 893, 1000, 1117, 1238, 1379, 1532, 1691, 1872, 2069, 2274, 2507, 2759, 3021, 3316, 3636, 3968, 4340, 4741, 5158, 5623, 6124, 6644, 7219, 7838, 8483, 9193, 9956, 10749, 11618, 12551, 13522, 14581, 15715, 16895, 18181, 19555, 20985, 22534, 24188, 25910, 27773, 29758, 31823, 34048, 36420, 38887, 41541, 44362, 47296, 50445, 53790, 57268, 60992, 64941, 69050, 73441, 78093, 82928, 88085, 93545, 99221, 105264, 111654, 118292, 125351, 132808, 140555, 148775, 157451, 166464, 176017, 186088, 196547, 207613, 219275, 231383, 244181, 257649, 271629, 286389, 301915, 318025, 335013, 352863, 371385, 390894, 411381, 432628, 454985, 478448, 502781, 528357, 555175, 582975, 612175, 642773, 674488, 707762, 742604, 778710, 816566, 856180, 897219, 940204, 985166, 1031733, 1080475, 1131419, 1184169, 1239342, 1296983, 1356651, 1419012, 1484114, 1551500, 1621879, 1695319, 1771308, 1850620, 1933336, 2018911, 2108169, 2201208, 2297430, 2397746, 2502260, 2610330, 2722917, 2840156, 2961358, 3087567, 3218928, 3354697, 3495983, 3642979, 3794876, 3952872, 4117166, 4286898, 4463357, 4646781, 4836231, 5033091, 5237619, 5448835, 5668212, 5896052, 6131274, 6375467, 6628978, 6890664, 7162208, 7444003, 7734806, 8036449, 8349358, 8672217, 9006953, 9354056, 9712125, 10083238, 10467918, 10864668, 11275687, 11701596, 12140784, 12595614, 13066740, 13552450, 14055271, 14575951, 15112644, 15668044, 16242956, 16835452, 17448387, 18082666, 18736202, 19412048, 20111207, 20831484, 21576103, 22346166, 23139309, 23959014, 24806474, 25679197, 26580844, 27512739, 28472234, 29463255, 30487223, 31541332, 32629717, 33753992, 34911161, 36105636, 37339129, 38608483, 39918386, 41270741, 42662175, 44097665, 45579240, 47103389, 48675380, 50297444, 51965815, 53686096, 55460717, 57285728, 59167038, 61107291, 63102267, 65158298, 67278236, 69457647, 71703173, 74017922, 76397220, 78848152, 81374045, 83969977, 86643390, 89397957, 92228464, 95142826, 98144942, 101229335, 104404384, 107674355, 111033430, 114490480, 118050050, 121706096, 125467978, 129340637, 133317637, 137408880, 141619696, 145943379, 150390349, 154966353, 159664278, 164495221, 169465334, 174567181, 179812402, 185207630, 190745063, 196437070, 202290722, 208297832, 214471372, 220819046, 227332236, 234024685, 240904568, 247962863, 255214063, 262667022, 270312228, 278164978, 286234669, 294511456, 303011440, 311744736, 320700935, 329897028, 339343848, 349030595, 358975121, 369189027, 379660902, 390409679, 401447743, 412763223, 424375956, 436299202, 448520551, 461060995, 473934631, 487128517, 500664632, 514558170, 528795598, 543400126, 558387836, 573744623, 589494913, 605655980, 622213039, 639191823, 656610611, 674454125, 692749413, 711516042, 730737958, 750443631, 770653908, 791352191, 812568331, 834324553, 856603433, 879436517, 902847437, 926818156, 951381682, 976563168, 4099492, 30514210, 57589628, 85306270, 113700592, 142801114, 172587556, 203098326, 234363569, 266362239, 299134671, 332713066, 367075477, 402264295, 438313522, 475200581, 512969956, 551657858, 591240712, 631765230, 673269807, 715730192, 759195328, 803705981, 849236828, 895839454, 943557047, 992363494, 44068385, 95206229, 147505623, 201023388, 255807958, 311831397, 369153064, 427824496, 487816780, 549192323, 612005495, 676226453, 741920607, 809145738, 877870910, 948164773, 21843859, 95365195, 170556386, 247481995, 326109113, 406513189, 488762479, 572823307, 658774643, 746688724, 836530571, 928383195, 24078565, 120069544, 218198520, 318546165, 421075572, 525877907, 633038239, 742518685, 854414432, 968815614, 87438920, 206872986, 328968347, 453684991, 581127521, 711396425, 844450483, 980399334, 121104325, 263012188, 407993323, 556159472, 707467342, 862037082, 21742139, 183027245, 347773661, 516105681, 687977935, 863522236, 44625223, 227729465, 414728276, 605759711, 800776548, 1678892, 205100749, 412749672, 624776404, 841334383, 64130169, 289810445, 520292122, 755525204, 995674854, 242666962, 492939183, 748420053, 11043951, 277248052, 548968795, 826394592, 111228413, 400148067, 695107338, 996053224, 304938931, 618461754, 938323134, 266485705, 599657542, 939539742, 288103949, 642069557, 4892619, 373288154, 749254152, 134490686, 525722455, 924960250, 333903686, 749288499, 174893693, 607151626, 49831640, 499704271, 958468342, 428149344, 905531434, 394069384, 890533841, 398746834, 915140080, 443519432, 980699729, 530135973, 90380014, 660018827, 242507025, 834655014, 440333662, 57731445, 685428265, 327312793, 979818225, 646807015, 326919230, 20100260, 724960464, 445426817, 179689898, 926376784, 689434296, 467054085, 259635534, 67636119, 889248517, 728401249, 583817590, 455447951, 343727870, 249159940, 171695795, 111790093, 69969400, 46188140, 40920659, 54719059, 87539191, 139876752, 212310215, 304798556, 417858551, 552096273, 707473286, 884529730, 85655813, 307305317, 551796575, 819794852, 113024420, 428561753, 768858470, 135642780, 526016294, 942464263, 386718944, 855908847, 354308016, 878387151, 432324935, 15164771, 625137557, 266450752, 936428957, 638576648, 371863954, 137165895, 932725142, 762810620, 626582104, 524045397, 455989888, 423373102, 426207739, 465318068, 541705191, 655390132, 807231226, 31756, 230309868, 500717009, 812347797, 166996485, 562085284, 2271079, 484090662, 12028957, 583770869, 202887175, 866881439, 580516117, 342105701, 152707995, 13629947, 923199528, 886030181, 901732338, 970401427, 94942626, 273271748, 507254806, 798088920, 149020450, 556662914, 25776488, 554406495, 146205580, 798962253, 517814287, 301164405, 150367985, 67122481, 51604520, 105225544, 229759217, 425401129, 693622328, 38028387, 455325206, 948800819, 522142956, 173834135, 903714902, 717312272, 613133632, 592841130, 658538957, 810513240, 52251704, 382438497, 803142905, 317923380, 925559094, 629902187, 431076077, 331469545, 331453737, 432983464, 638551309, 948559719, 366801210, 892362877, 529191570, 277651498, 140454039, 118069315, 212705191, 427186772, 762022350, 221265904, 804352933, 515341098, 354867194, 326002123, 429335701, 667357683, 45025401, 559459081, 216762560, 18516829, 963645586, 60112845, 306128641, 704175658, 258818528, 970168275, 842515586, 877025705, 79229451, 446448992, 983481097, 696012849, 583179154, 648143130, 895002193, 326462196, 942303951, 750303778, 749720816, 943979940, 339280291, 933190768, 732785659, 740935042, 958791609, 391816817, 43072438, 912026743, 7802752, 330148788, 882123959, 669493206, 695721665, 962193014, 474835362, 237326667, 251137633, 520604731, 53140084, 846792988, 909586559, 247405746, 858394465, 750754246, 928855877, 396208736, 155935508, 214407497, 573483969, 239992650, 218808848, 511899500, 126293510, 67131540, 336498036, 939874412, 886191214, 177650056, 816439290, 813532359, 171259380, 892032030, 987121993, 458989775, 312039446, 554340064, 190247731, 224405547, 665205096, 517147203, 785129294, 479629886, 601790312, 160278279, 162409722, 611239747, 515708618, 883486988, 719553697, 31374085, 825237504, 109806327, 887570467, 173980604, 967350997, 281007176, 122022905, 494166105, 407566421, 871467145, 891594172, 476645036, 636292538, 376468640, 704456494, 633884508, 169148844, 317878624, 94165522, 500877553, 549521545, 252909642, 614147821, 645116879, 359128633, 759536828, 858615088, 670184559, 199616008, 456076342, 455678262, 204061423, 710812730, 992593907, 57087546, 910803590, 574489058, 52606119, 355629098, 501385642, 496405940, 353385464, 89009754, 708372302, 228169324, 662209601, 21192103, 315288343, 564234280, 775567459, 963495893, 148434937, 334776318, 539020624, 780538691, 69369175, 417308184, 846208357, 366507629, 990581601, 742800469, 630502657, 670176204, 883460752, 281642801, 878320815, 699460721, 753282215, 59298265, 637292389, 501224629, 667762630, 162827328, 993840757, 185191395, 756677652, 723256070, 104759855, 923677983, 197251829, 940796077, 186540668, 941745138, 233023941, 84833664, 510274075, 533249412, 182755374, 470736496, 421922611, 66384957, 416687540, 498415967, 342744454, 962890790, 387081216, 644128500, 751429220, 734618126, 627204224, 445535459, 216193513, 972158798, 734015645, 527580220, 388856310, 335680013, 396634600, 609039037, 991518091, 575471572, 397817439, 478001526, 846754595, 545917246, 594031697, 24719103, 875998610, 174324759, 947465042, 243725929, 81702509, 495640411, 531883334, 213503574, 574243060, 662056959, 501005941, 127887212, 588805121, 910618243, 133218512, 302672915, 446909595, 605461704, 829682246, 148621598, 599731023, 239714015, 95269077, 208853774, 635554991, 406788266, 564788163, 168367852, 246681986, 845318641, 26866235, 818270692, 272033193, 445824164, 374957907, 108373769, 707657978, 211289781, 666458813, 142263581, 671605576, 310523780, 125163156, 153454167, 449806808, 86269708, 100576649, 549097486, 506350884, 13458062, 127041193, 922419846, 445911578, 754478669, 927830417, 12279270, 66937845, 174250656, 380587697, 750811208, 370171231, 285167681, 562968847, 291743679, 519940080, 318868546, 776183306, 945878146, 899972768, 730988366, 493251967, 261336543, 130967404, 158658661, 421614882, 20628860, 12707152, 477790317, 520088808, 200711955, 600650281, 827648657, 945239349, 40847139, 220591941, 552275882, 126323616, 54387162, 405115528, 272052035, 770724671, 974240641, 977600013, 902112079, 821919869, 835346437, 69590627, 598193275, 526419836, 982245085, 49221025, 827385502, 456150126, 16921020, 616907451, 398326125, 445792323, 872069933, 822324071, 386269896, 678814317, 849983684, 992944578, 230169981, 711427157, 536971647, 829928506, 750518734, 399187449, 903383119, 430407721, 82787824, 992424335, 333898762, 211944724, 764822284, 171031048, 539425950, 16528792, 779694449, 949037197, 672479592, 136938780, 461677482, 801437079, 351137906, 234583322, 610007792, 678772965, 571161944, 450799257, 523942404, 925747125, 827190849, 441382441, 906768537, 401831311, 145013192, 281732848, 992923671, 509575369, 978997834, 591775204, 581173314, 105347252, 355958340, 577531072, 932256320, 621850941, 895346944, 922647312, 910475842, 119628455, 720935779, 931602258, 20940476, 166152473, 589904096, 570285841, 294629546, 989503045, 943810490, 351707939, 447451356, 527518020, 793126563, 489942277, 920573674, 297045783, 867939978, 951036135, 762396203, 562537736, 675979784, 328329691, 787050094, 390700103, 369451959, 3251647, 636280362, 512284990, 916964169, 210969211, 639650377, 503518932, 171271459, 898887147, 996751988, 845467616, 711973387, 913290115, 844052807, 780688227, 52483577, 63204205, 100842470, 503728417, 692194640, 962604635, 666222051, 235036633, 974124668, 249765682, 504305588, 58887119, 284642544, 643429173, 465817567, 136935902, 131604513, 790142952, 513821731, 790845229, 975217570, 479466794, 807406769, 327066330, 460911231, 732340725, 520339915, 262951627, 498388629, 618733374, 78085995, 429958981, 81723308, 498661857, 257155539, 773271158, 532755233, 126559258, 985171647, 611732006, 614114717, 441191760, 606969926, 742019943, 310596392, 841573218, 987086186, 227214448, 107976234, 300123439, 300122319, 673403661, 113468701, 130125453, 308793816, 362830451, 821242729, 289945655, 501048357, 5034471, 421924217, 512004582, 840798457, 53497858, 926994928, 52962706, 90139005, 844955326, 925315273, 16383964, 944380288, 341068837, 908168052, 506406384, 779798076, 459556610, 427694533, 353368869, 987446457, 244502927, 810803066, 466331324, 148513544, 570134608, 534035904, 8331858, 727841745, 522457414, 388330301, 88282946, 473067291, 572997367, 176169365, 160177726, 585170342, 267045348, 111113539, 209972873, 404631941, 630663703, 15891039, 425492102, 826177200, 380139416, 981136230, 627883151, 514503794, 567660834, 813723420, 486753687, 542032423, 39763648, 248006427, 156781620, 855861479, 657153761, 579428577, 748208609, 513357387, 926846799, 152795869, 576643268, 289867578, 487363763, 601905030, 756728477, 187431881, 366486101, 455239552, 725775579, 698612632, 570785796, 653776272, 513833449, 386619355, 624159464, 839830718, 310771890, 429004335, 856331393, 910902020, 31211249, 923636103, 951992222, 597293686, 620678214, 425964135, 539662322, 777393227, 587740380, 544135714, 516412006, 997535359, 612646536, 285633265, 556964929, 101481071, 898630281, 543086594, 755510445, 579659107, 655320976, 759276753, 994142842, 55156240, 767950734, 302840365, 403193792, 955619908, 192811148, 911465174, 60762306, 930597541, 384813423, 422834218, 409401999, 261483656, 42655397, 185654679, 667497431, 616012872, 535634024, 465236300, 595081431, 505128043, 297911065, 229838918, 954863232, 644578393, 621616629, 619668809, 874269669, 781534711, 155203568, 298544981, 679631588, 196363661, 223437561, 302960421, 415707569, 13515608, 711111667, 579817498, 145367927, 102616550, 608808893, 271169275, 863302053, 637904289, 278854856, 644436632, 81821175, 355669397, 412926362, 694414611, 54964503, 523954378, 645471547, 359968052, 788681183, 578339180, 757516980, 543668132, 685352031, 307195916, 718443169, 779550867, 708487860, 914265514, 368626240, 385746710, 477151865, 727231752, 554305063, 571809873, 981656437, 307575381, 267724556, 186540228, 690769600, 613443344, 401302903, 790721374, 727259790, 785195760, 815380773, 877456509, 678366032, 184913442, 573962746, 688844774, 615590381, 655185331, 787354778, 222573289, 385819653, 400649394, 601825283, 547114325, 504156653, 937477029, 539450670, 725832509, 97920471, 479449229, 445348233, 730594182, 304484480, 894786804, 382687354, 876560383, 273561006, 592828975, 97930544, 845841741, 13489606, 9860998, 68421312, 514040917, 917510780, 688308603, 308780830, 508891301, 878693386, 66009142, 962612313, 349447869, 35423592, 87475629, 471775284, 173657943, 432842386, 412943722, 273276422, 434735230, 261832859, 94695322, 538414491, 165565660, 500216590, 340390443, 466957742, 598423909, 725453495, 848234975, 881436172, 17384986, 475986551, 377031529, 116313095, 146616970, 791369126, 660770759, 442876658, 674063447, 181118811, 892086543, 567267306, 252434553, 127166268, 173109099, 666299275, 44529020, 516739924, 597276795, 981825180, 123700694, 771218496, 893689192, 186364740, 647026179, 520412782, 750467161, 594401455, 576251690, 898939173, 82686046, 938126856, 937708508, 866266355, 837669720, 592269847, 192098560, 56599567, 205018788, 982166672, 126610968, 938619123, 60417736, 543727449, 991858781, 341671185, 977129533, 805270389, 67427416, 488407271, 285632388, 14676454, 750097623, 29649783, 728251065, 284545139, 556536248, 757362815, 688661754, 547958159, 886920909, 884824772, 86017887, 389554799, 362382452, 901387773, 271187862, 429145282, 639559481, 533268963, 477399118, 109697280, 437009732, 246573242, 558050899, 769525916, 95771306, 948310065, 128586186, 284645364, 239433246, 197531416, 262176453, 669504156, 47035150, 956016187, 65719535, 426811397, 82878087, 133507613, 78179433, 442537803, 778649268, 40922458, 251593381, 425296807, 979895406, 455498689, 336348140, 519375925, 69001416, 954861501, 568999861, 509858687, 250808184, 681235443, 956325832, 62464217, 403147748, 700827766, 466928140, 637554148, 515176398, 149795715, 22443053, 30396022, 776517995, 304057563, 118663311, 392194212, 737923023, 292227227, 807328628, 486366474, 105656841, 18213417, 27146017, 568185794, 610861760, 575485082, 574289279, 205540203, 522752620, 333270567, 879011810, 868278398, 815981806, 629348113, 681343498, 217569422, 822853626, 558777805, 414816215, 675983147, 105119088, 456129819, 732440196, 415776134, 47436640, 362356034, 581767393, 53878908, 265868162, 197087158, 19715774, 994283891, 879601062, 692140281, 487561921, 816836420, 567642642, 607355689, 306514041, 438405919, 706833065, 320929650, 963820865, 198423360, 88690196, 255514716, 136230757, 678220326, 461778683, 820740133, 610412824, 389074564, 415513953, 470181881, 119235685, 566285570, 544376546, 648805630, 57411430, 472513135, 549839358, 460814473, 908922894, 632604973, 822302676, 209497342, 637437945, 348203115, 120140171, 935484533, 111328523, 499287897, 252518612, 781006347, 49191678, 397551074, 369547591, 57602174, 29628582, 981866228, 172305602, 419451595, 608755665, 183579945, 251157466, 910564423, 826106642, 423353828, 47391678, 608297608, 884565347, 500283800, 646314918, 483212749, 942783583, 533742331, 829699471, 109690883, 222547425, 198046322, 687692016, 924422819, 424788175, 250113151, 46671996, 852255937, 180806582, 123215899, 281116366, 646137554, 798974091, 939664901, 580003018, 819694156, 499911123, 686681966, 44025974, 86828623, 479361944, 482795682, 334082239, 331747923, 373923999, 459103235, 562543041, 261299985, 357067424, 542958458, 116393997, 725573864, 826163315, 476472589, 219872186, 312144263, 617781034, 620954098, 426198734, 746432063, 53622136, 342557307, 225740431, 205602345, 221155702, 823277998, 601212187, 480384464, 3535769, 887816399, 102725500, 223963789, 159050633, 957392975, 291875829, 301770979, 178251381, 728053808, 388998366, 538921108, 179429083, 90842450, 896984163, 845866725, 122285137, 646599177, 966297568, 728006335, 210666282, 313205620, 203101314, 571117110, 732363248, 433621931, 836581792, 728542915, 497481491, 837532722, 68797065, 281347647, 765049368, 431670062, 143738365, 844354663, 103557556, 616285894, 52186140, 692847745, 146205666, 859772859, 908168103, 866663048, 42575440, 356511459, 430929446, 493996760, 391715441, 858619339, 120258044, 10774654, 456000940, 744986166, 779480405, 750308184, 85974036, 821455289, 495322621, 747106472, 829809642, 699519098, 291060249, 144604665, 718685165, 322228492, 861716848, 385148203, 647733719, 11142634, 187678686, 471448817, 752910717, 504844089, 638316867, 660145656, 887190178, 938205410, 22685276, 389776982, 455169670, 216818093, 953907225, 966859160, 134545046, 857012024, 414108695, 653238616, 200909244, 401726601, 175532403, 462982324, 780720725, 211227999, 114449495, 274266061, 34860355, 279450347, 162224033, 387607811, 470355417, 36014479, 254116262, 376210714, 605592670, 685596838, 713699658, 579729932, 705253438, 149500294, 596855417, 261947189, 275875218, 236676089, 258331666, 666770221, 88077034, 649645173, 994703633, 891533801, 606738414, 218132987, 757084516, 748798616, 834053130, 435907800, 454848061, 225665108, 684348765, 240747497, 51017762, 696074989, 220363945, 736578462, 606792767, 636112630, 38860062, 83231486, 476715801, 669911334, 983215395, 163307065, 37203372, 117426394, 327612522, 26518142, 60111240, 673141579, 902792264, 80512222, 916641064, 282895284, 139918703, 821383558, 185688185, 979945249, 317045299, 195576536, 313768729, 709417768, 698383262, 84918327, 993882020, 224386598, 846662841, 248552502, 869960735, 229613930, 130244107, 840523811, 490144985, 475944810, 72111343, 190112496, 170340, 958784367, 949925569, 89317722, 205789585, 331483534, 713405904, 747573452, 801813954, 441614579, 818479730, 832456776, 557414216, 102873697, 91804879, 302528568, 6951786, 751955981, 223243330, 55924757, 929576348, 637192543, 395141788, 223041477, 226038587, 419289643, 377266189, 732673109, 520809215, 85910357, 806463433, 963649584, 896936296, 954598470, 891351471, 270553404, 635101334, 453581286, 742501526, 476757332, 75450402, 249184754, 637400501, 859528283, 565150907, 299445750, 133382188, 899310419, 302600188, 119353704, 622678142, 923468026, 773351888, 143508061, 806988289, 758134418, 930612039, 33005788, 565782753, 700837546, 345657600, 796738642, 736132589, 545470203, 603207283, 382769936, 24466838, 277829946, 697786903, 470647192, 17813970, 268061582, 746430442, 850508249, 189199847, 921549557, 735647740, 223317638, 490981509, 827724999, 128410260, 755745874, 930465676, 165634029, 403513576, 124905360, 788468406, 248407584, 578709202, 525013854, 177342297, 556707812, 34961665, 278191847, 609205586, 372126098, 163907792, 963136209, 447993159, 496047089, 117653547, 679828181, 713471676, 629064912, 863216292, 962508869, 128274828, 241791128, 247384760, 523436716, 791735602, 778639832, 444330549, 739656161, 571437254, 887142803, 279942023, 233828457, 106060063, 535941826, 7924040, 707429221, 751629473, 36517261, 17755331, 712729289, 865451558, 646409217, 416607917, 200692067, 336641799, 979387316, 888416017, 31441130, 812551235, 183568672, 212932908, 31424549, 241309553, 500637949, 140847875, 895968732, 507531234, 989819307, 704222810, 968377693, 990420049, 247715974, 154506580, 613966233, 731438735, 544753645, 174851692, 867009055, 819581331, 900249795, 33976925, 115700533, 306832774, 744165078, 590225935, 847228311, 421781113, 303456866, 905212099, 464688273, 385135389, 66986870, 648381623, 543616219, 726650628, 830838423, 881299720, 30430100, 553617, 49082078, 118721011, 637730178, 726601839, 743225133, 447119252, 463146180, 208385423, 406090433, 847940444, 660655236, 187362725, 53963296, 760978639, 935870485, 727985672, 694013267, 421472410, 278749113, 574270987, 548985657, 507424656, 218051871, 279660929, 659280914, 311132094, 913499526, 843714904, 972816220, 801302355, 867476364, 721533143, 431879083, 476638337, 848673933, 955413763, 6814103, 222642992, 129999699, 472751165, 506490940, 675251949, 84218479, 833073632, 104687862, 198676209, 902164536, 963080920, 738674105, 550935311, 561012005, 59856346, 770931835, 143486216, 284759565, 215939822, 548445724, 129434351};
int main(){return printf("%d",ans[n]),0;}
}
namespace sub3
{
const int ans[]={0, 1, 1, 2, 3, 3, 4, 5, 5, 5, 7, 8, 8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 18, 18, 19, 21, 21, 22, 24, 25, 25, 27, 28, 28, 30, 33, 34, 35, 36, 38, 39, 41, 43, 44, 44, 45, 48, 49, 51, 53, 55, 56, 57, 58, 59, 63, 67, 67, 70, 72, 72, 75, 76, 78, 79, 82, 84, 86, 87, 89, 93, 96, 98, 101, 102, 103, 106, 109, 110, 114, 119, 121, 124, 125, 128, 130, 133, 133, 137, 139, 142, 146, 149, 151, 155, 157, 160, 164, 167, 168, 172, 178, 180, 183, 185, 190, 193, 196, 200, 204, 206, 209, 213, 218, 219, 222, 227, 228, 231, 236, 242, 245, 248, 251, 255, 260, 267, 272, 274, 278, 283, 285, 290, 296, 301, 302, 308, 314, 316, 323, 329, 333, 336, 339, 343, 347, 352, 359, 363, 368, 371, 377, 382, 384, 392, 400, 402, 406, 413, 417, 422, 432, 437, 444, 451, 453, 458, 463, 469, 472, 479, 487, 492, 496, 501, 513, 520, 526, 534, 537, 538, 545, 550, 554, 562, 571, 577, 584, 590, 595, 602, 613, 621, 627, 635, 641, 647, 653, 655, 667, 677, 684, 691, 699, 704, 709, 720, 726, 733, 742, 751, 758, 765, 772, 779, 785, 797, 805, 813, 818, 827, 835, 840, 848, 857, 869, 880, 887, 894, 903, 913, 921, 934, 942, 950, 957, 967, 977, 986, 994, 1000, 1014, 1023, 1031, 1044, 1054, 1063, 1071, 1080, 1089, 1097, 1109, 1118, 1129, 1137, 1146, 1159, 1169, 1176, 1185, 1197, 1209, 1218, 1231, 1237, 1250, 1265, 1274, 1283, 1295, 1308, 1319, 1333, 1345, 1354, 1364, 1373, 1383, 1395, 1408, 1424, 1437, 1446, 1456, 1469, 1479, 1496, 1513, 1518, 1530, 1549, 1561, 1573, 1582, 1594, 1605, 1618, 1625, 1639, 1650, 1665, 1680, 1692, 1707, 1721, 1729, 1740, 1755, 1773, 1784, 1803, 1826, 1836, 1844, 1856, 1873, 1885, 1899, 1913, 1927, 1938, 1949, 1969, 1989, 2005, 2019, 2034, 2047, 2060, 2079, 2093, 2109, 2130, 2141, 2156, 2176, 2189, 2202, 2215, 2237, 2249, 2266, 2282, 2296, 2313, 2326, 2341, 2361, 2373, 2388, 2403, 2421, 2435, 2452, 2468, 2485, 2509, 2529, 2549, 2565, 2584, 2602, 2618, 2631, 2651, 2673, 2690, 2707, 2721, 2735, 2755, 2773, 2793, 2816, 2833, 2851, 2870, 2888, 2910, 2934, 2956, 2977, 2996, 3011, 3027, 3052, 3076, 3088, 3105, 3128, 3144, 3163, 3186, 3202, 3224, 3244, 3267, 3288, 3305, 3320, 3342, 3370, 3393, 3413, 3429, 3451, 3478, 3502, 3520, 3545, 3567, 3579, 3599, 3629, 3647, 3670, 3701, 3722, 3738, 3765, 3790, 3811, 3834, 3857, 3880, 3901, 3928, 3952, 3978, 3994, 4023, 4050, 4068, 4092, 4122, 4139, 4159, 4192, 4214, 4240, 4264, 4293, 4314, 4332, 4361, 4387, 4408, 4438, 4464, 4486, 4504, 4540, 4572, 4591, 4621, 4649, 4669, 4695, 4720, 4747, 4772, 4804, 4839, 4864, 4895, 4910, 4937, 4967, 4990, 5022, 5053, 5081, 5106, 5133, 5156, 5190, 5231, 5258, 5286, 5319, 5347, 5369, 5391, 5427, 5456, 5489, 5524, 5555, 5581, 5606, 5638, 5674, 5701, 5724, 5760, 5783, 5819, 5852, 5878, 5905, 5946, 5982, 6010, 6042, 6070, 6098, 6134, 6162, 6189, 6219, 6255, 6289, 6323, 6352, 6385, 6424, 6465, 6502, 6532, 6566, 6595, 6626, 6657, 6686, 6716, 6759, 6801, 6829, 6861, 6892, 6926, 6960, 7001, 7038, 7066, 7101, 7143, 7178, 7216, 7259, 7294, 7334, 7377, 7414, 7450, 7487, 7526, 7557, 7593, 7622, 7662, 7699, 7726, 7775, 7816, 7858, 7895, 7933, 7961, 7993, 8032, 8083, 8126, 8165, 8200, 8237, 8275, 8321, 8361, 8408, 8447, 8479, 8516, 8550, 8591, 8629, 8673, 8724, 8763, 8797, 8834, 8885, 8925, 8967, 9022, 9061, 9099, 9145, 9178, 9217, 9264, 9305, 9347, 9392, 9437, 9481, 9528, 9573, 9625, 9668, 9706, 9751, 9789, 9832, 9877, 9937, 9981, 10022, 10074, 10120, 10170, 10220, 10273, 10307, 10349, 10395, 10453, 10496, 10526, 10577, 10626, 10664, 10726, 10777, 10816, 10860, 10919, 10956, 11000, 11057, 11103, 11146, 11206, 11252, 11303, 11362, 11417, 11464, 11509, 11552, 11607, 11667, 11712, 11763, 11809, 11853, 11893, 11946, 12001, 12052, 12114, 12171, 12214, 12266, 12324, 12376, 12432, 12491, 12547, 12604, 12658, 12711, 12766, 12808, 12865, 12924, 12973, 13038, 13094, 13146, 13191, 13253, 13313, 13367, 13426, 13485, 13542, 13600, 13656, 13711, 13762, 13825, 13879, 13934, 13986, 14046, 14112, 14169, 14224, 14281, 14344, 14409, 14468, 14519, 14563, 14636, 14699, 14755, 14821, 14873, 14934, 15000, 15063, 15128, 15189, 15247, 15313, 15374, 15434, 15496, 15556, 15604, 15664, 15733, 15799, 15865, 15936, 15989, 16048, 16112, 16177, 16255, 16332, 16384, 16443, 16514, 16581, 16646, 16721, 16792, 16851, 16920, 16989, 17044, 17110, 17187, 17257, 17330, 17402, 17467, 17526, 17580, 17653, 17716, 17788, 17869, 17943, 18008, 18070, 18142, 18212, 18287, 18363, 18429, 18496, 18562, 18636, 18716, 18788, 18857, 18929, 18996, 19066, 19136, 19215, 19284, 19358, 19436, 19496, 19578, 19661, 19739, 19808, 19881, 19955, 20028, 20105, 20178, 20240, 20322, 20400, 20476, 20560, 20627, 20702, 20780, 20861, 20949, 21026, 21104, 21170, 21258, 21334, 21412, 21503, 21579, 21660, 21746, 21823, 21901, 21989, 22064, 22145, 22217, 22299, 22390, 22475, 22560, 22644, 22728, 22790, 22879, 22969, 23055, 23130, 23221, 23292, 23364, 23455, 23548, 23640, 23734, 23825, 23894, 23979, 24063, 24157, 24244, 24323, 24418, 24514, 24595, 24685, 24765, 24841, 24925, 25030, 25115, 25205, 25302, 25394, 25488, 25572, 25661, 25746, 25837, 25918, 26020, 26107, 26173, 26279, 26388, 26471, 26559, 26654, 26743, 26834, 26934, 27024, 27110, 27209, 27313, 27407, 27489, 27581, 27680, 27790, 27897, 28000, 28093, 28174, 28277, 28384, 28472, 28576, 28687, 28780, 28862, 28964, 29062, 29152, 29280, 29378, 29455, 29552, 29661, 29759, 29862, 29962, 30056, 30163, 30272, 30370, 30482, 30573, 30686, 30805, 30900, 30995, 31099, 31211, 31293, 31421, 31544, 31642, 31747, 31863, 31960, 32052, 32163, 32269, 32370, 32482, 32588, 32693, 32792, 32905, 33025, 33131, 33245, 33358, 33466, 33575, 33673, 33782, 33882, 33998, 34110, 34217, 34330, 34427, 34554, 34674, 34788, 34917, 35025, 35136, 35239, 35359, 35468, 35596, 35722, 35826, 35932, 36050, 36158, 36279, 36404, 36516, 36628, 36748, 36869, 37007, 37129, 37232, 37356, 37482, 37598, 37708, 37847, 37961, 38077, 38207, 38316, 38427, 38554, 38684, 38811, 38928, 39062, 39186, 39298, 39419, 39551, 39696, 39822, 39941, 40075, 40174, 40287, 40424, 40570, 40701, 40836, 40968, 41080, 41194, 41327, 41465, 41598, 41747, 41877, 41993, 42110, 42231, 42373, 42504, 42643, 42781, 42895, 43011, 43156, 43277, 43403, 43550, 43698, 43825, 43955, 44087, 44210, 44353, 44509, 44657, 44792, 44924, 45065, 45198, 45316, 45452, 45602, 45729, 45867, 46031, 46160, 46296, 46444, 46595, 46732, 46882, 47022, 47159, 47310, 47457, 47596, 47721, 47863, 48018, 48158, 48293, 48441, 48586, 48723, 48870, 49024, 49173, 49330, 49494, 49635, 49774, 49927, 50088, 50238, 50401, 50543, 50685, 50830, 50969, 51127, 51287, 51414, 51573, 51745, 51886, 52030, 52197, 52339, 52482, 52661, 52795, 52943, 53112, 53281, 53432, 53585, 53745, 53890, 54053, 54206, 54364, 54519, 54667, 54852, 55017, 55168, 55322, 55484, 55639, 55785, 55948, 56116, 56274, 56455, 56619, 56772, 56929, 57083, 57236, 57413, 57587, 57746, 57930, 58090, 58243, 58421, 58594, 58781, 58969, 59135, 59283, 59447, 59630, 59798, 59980, 60143, 60305, 60472, 60635, 60801, 60961, 61142, 61323, 61515, 61688, 61856, 62032, 62175, 62354, 62551, 62727, 62902, 63087, 63273, 63438, 63624, 63794, 63972, 64164, 64362, 64536, 64713, 64893, 65064, 65254, 65431, 65625, 65814, 65999, 66174, 66354, 66520, 66720, 66908, 67096, 67269, 67459, 67647, 67831, 68019, 68195, 68374, 68580, 68768, 68950, 69135, 69319, 69516, 69712, 69913, 70084, 70291, 70450, 70659, 70870, 71049, 71227, 71430, 71646, 71823, 72034, 72221, 72407, 72604, 72828, 73033, 73221, 73414, 73607, 73801, 73993, 74195, 74403, 74594, 74789, 75022, 75218, 75421, 75635, 75827, 76018, 76238, 76456, 76636, 76839, 77062, 77264, 77478, 77692, 77904, 78081, 78282, 78502, 78724, 78931, 79130, 79351, 79548, 79755, 79979, 80188, 80412, 80636, 80854, 81069, 81253, 81456, 81680, 81907, 82140, 82373, 82576, 82769, 82994, 83219, 83431, 83655, 83904, 84137, 84341, 84552, 84764, 84982, 85218, 85463, 85685, 85901, 86116, 86352, 86579, 86769, 86990, 87229, 87449, 87660, 87894, 88113, 88332, 88593, 88831, 89048, 89278, 89514, 89739, 89970, 90187, 90427, 90662, 90902, 91150, 91377, 91600, 91834, 92088, 92315, 92529, 92780, 93011, 93255, 93518, 93739, 93965, 94230, 94493, 94739, 94973, 95213, 95432, 95669, 95908, 96156, 96412, 96663, 96902, 97140, 97359, 97586, 97845, 98092, 98347, 98624, 98874, 99117, 99374, 99620, 99873, 100113, 100398, 100658, 100903, 101156, 101392, 101637, 101889, 102146, 102409, 102658, 102919, 103189, 103425, 103675, 103944, 104204, 104475, 104770, 105024, 105279, 105572, 105824, 106073, 106334, 106578, 106842, 107118, 107364, 107638, 107903, 108165, 108441, 108734, 108988, 109238, 109508, 109778, 110039, 110308, 110574, 110838, 111139, 111420, 111686, 111939, 112212, 112488, 112763, 113038, 113312, 113581, 113844, 114150, 114420, 114699, 114968, 115276, 115573, 115839, 116138, 116417, 116699, 116992, 117246, 117521, 117827, 118090, 118379, 118686, 118964, 119240, 119561, 119848, 120112, 120417, 120702, 120985, 121287, 121575, 121855, 122141, 122440, 122722, 123010, 123303, 123588, 123908, 124204, 124492, 124790, 125096, 125383, 125707, 125998, 126297, 126629, 126931, 127222, 127542, 127859, 128144, 128465, 128754, 129066, 129366, 129657, 129936, 130252, 130566, 130893, 131227, 131546, 131854, 132155, 132467, 132788, 133093, 133406, 133694, 134000, 134311, 134612, 134918, 135254, 135584, 135905, 136233, 136543, 136836, 137144, 137468, 137823, 138163, 138470, 138807, 139114, 139443, 139804, 140116, 140417, 140768, 141072, 141376, 141702, 142021, 142347, 142697, 143031, 143346, 143674, 144013, 144353, 144690, 145014, 145355, 145697, 146024, 146385, 146725, 147041, 147379, 147748, 148105, 148421, 148769, 149127, 149430, 149778, 150112, 150436, 150790, 151156, 151506, 151830, 152172, 152496, 152845, 153191, 153544, 153915, 154266, 154631, 155017, 155362, 155682, 156042, 156398, 156718, 157072, 157432, 157780, 158145, 158507, 158884, 159236, 159599, 159982, 160331, 160677, 161034, 161401, 161775, 162142, 162527, 162876, 163236, 163650, 164023, 164368, 164727, 165139, 165497, 165837, 166219, 166583, 166947, 167290, 167682, 168062, 168412, 168800, 169173, 169533, 169916, 170323, 170683, 171044, 171438, 171844, 172212, 172606, 173004, 173372, 173752, 174112, 174504, 174891, 175272, 175661, 176062, 176443, 176820, 177216, 177588, 177954, 178367, 178802, 179195, 179576, 179994, 180367, 180777, 181193, 181568, 181953, 182360, 182776, 183195, 183543, 183937, 184366, 184739, 185166, 185581, 185964, 186353, 186788, 187198, 187571, 187970, 188390, 188782, 189220, 189656, 190063, 190452, 190880, 191317, 191706, 192101, 192522, 192958, 193346, 193747, 194193, 194607, 195020, 195442, 195848, 196241, 196687, 197121, 197545, 197991, 198450, 198869, 199282, 199696, 200119, 200563, 201001, 201484, 201933, 202310, 202738, 203186, 203599, 204047, 204510, 204937, 205343, 205796, 206233, 206654, 207108, 207550, 207983, 208454, 208855, 209293, 209768, 210185, 210640, 211095, 211535, 211980, 212452, 212895, 213323, 213786, 214257, 214682, 215127, 215590, 216019, 216490, 216953, 217402, 217857, 218317, 218798, 219260, 219722, 220211, 220690, 221144, 221579, 222035, 222480, 222945, 223429, 223890, 224353, 224799, 225264, 225729, 226230, 226705, 227148, 227622, 228096, 228560, 229075, 229537, 229992, 230506, 230958, 231445, 231932, 232412, 232869, 233404, 233887, 234335, 234799, 235279, 235771, 236281, 236738, 237222, 237722, 238228, 238716, 239224, 239711, 240175, 240716, 241219, 241712, 242205, 242697, 243171, 243686, 244173, 244626, 245122, 245675, 246172, 246689, 247204, 247689, 248191, 248670, 249185, 249702, 250191, 250733, 251297, 251786, 252285, 252847, 253400, 253882, 254389, 254895, 255393, 255921, 256473, 256982, 257462, 257983, 258517, 259038, 259548, 260092, 260598, 261132, 261656, 262191, 262704, 263245, 263779, 264334, 264838, 265393, 265935, 266484, 267061, 267588, 268090, 268607, 269131, 269645, 270194, 270690, 271262, 271830, 272357, 272903, 273479, 274013, 274567, 275160, 275682, 276219, 276802, 277357, 277854, 278436, 279004, 279553, 280113, 280674, 281216, 281759, 282337, 282916, 283490, 284026, 284553, 285091, 285657, 286201, 286786, 287361, 287899, 288488, 289071, 289604, 290204, 290800, 291392, 292012, 292556, 293099, 293667, 294252, 294843, 295430, 295989, 296591, 297174, 297747, 298307, 298908, 299463, 300054, 300683, 301250, 301807, 302396, 303016, 303585, 304196, 304827, 305434, 306041, 306671, 307231, 307819, 308417, 309030, 309633, 310231, 310811, 311433, 312014, 312584, 313215, 313823, 314423, 315062, 315676, 316260, 316865, 317521, 318134, 318757, 319355, 319963, 320595, 321209, 321835, 322444, 323034, 323680, 324341, 324957, 325563, 326213, 326808, 327398, 328047, 328694, 329310, 329942, 330614, 331244, 331844, 332518, 333158, 333778, 334434, 335048, 335679, 336298, 336963, 337642, 338286, 338920, 339601, 340253, 340860, 341523, 342167, 342790, 343433, 344094, 344743, 345373, 346050, 346691, 347317, 347990, 348679, 349369, 350032, 350696, 351348, 351963, 352645, 353338, 353995, 354622, 355298, 355984, 356644, 357329, 358012, 358715, 359345, 360016, 360707, 361362, 362025, 362710, 363431, 364118, 364797, 365512, 366171, 366851, 367596, 368257, 368929, 369664, 370374, 371016, 371704, 372395, 373083, 373802, 374493, 375188, 375881, 376577, 377319, 378042, 378731, 379413, 380138, 380834, 381513, 382256, 382934, 383632, 384390, 385118, 385807, 386551, 387261, 387962, 388697, 389405, 390093, 390830, 391563, 392278, 393012, 393678, 394401, 395176, 395952, 396666, 397400, 398111, 398815, 399553, 400316, 401010, 401762, 402531, 403271, 403975, 404699, 405459, 406206, 406985, 407716, 408478, 409194, 409924, 410671, 411432, 412148, 412925, 413682, 414441, 415223, 415981, 416745, 417539, 418303, 419009, 419773, 420519, 421312, 422079, 422819, 423590, 424384, 425112, 425895, 426674, 427446, 428195, 428996, 429751, 430500, 431327, 432111, 432897, 433679, 434455, 435193, 436039, 436852, 437637, 438418, 439237, 439989, 440731, 441536, 442311, 443096, 443905, 444714, 445538, 446336, 447112, 447937, 448732, 449543, 450365, 451174, 451945};
int main(){return printf("%d",ans[n]),0;}
}
main()
{
n=read(),k=read();
if(k>8)return puts("1"),0;
if(k==1)return sub1::main();
if(k==2)return sub2::main();
if(k==3)return sub3::main();
dfs(1,0,0,1),printf("%d",ans);
} | 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>
#define pb push_back
#define endl '\n'
#define mod 998244353
#define N 500005
#define vi vector<int>
#define vvi vector<vector<int>>
#define vb vector<bool>
#define control ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define int long long int
#define ffor(i, n) for(int i=0; i<n; i++)
#define fforr(i, n) for(int i=1; i<=n; i++)
#define rfor(i, n) for(int i=n-1; i>=0; i--)
#define rforr(i, n) for(int i=n; i>0; i--)
#define all(x) x.begin(), x.end()
#define F first
#define S second
#define inf 9223372036854775807
using namespace std;
void setIO()
{
control;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
}
void print(bool chk){
if(chk){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
}
int min(int a, int b){
return a>b?b:a;
}
int max(int a, int b){
return a<b?b:a;
}
int power(int x,int y,int p)
{
int ans=1;
x=x%p;
if(x==0)
{
return 0;
}
while(y>0)
{
if(y&1)
{
ans=(ans*x)%p;
}
y=y>>1;
x=(x*x)%p;
}
return ans;
}
vi fact(N+3, 1);
vi inv(N+3, 1);
int C(int n, int k) {
if (k > n) return 0;
int multiply = (1LL * fact[n] * inv[k]) % mod;
multiply = (1LL * multiply * inv[n - k]) % mod;
return multiply;
}
int32_t main(){
fforr(i, N){
fact[i] = (fact[i-1]*i)%mod;
inv[i] = power(fact[i], mod-2, mod);
}
int n, m; cin >> n >> m;
int ans = 0;
if(n > 2){
ans = C(m, n-1)%mod*(n-2)%mod*power(2, n-3, mod)%mod;
}
cout << ans << endl;
} | 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;
long long st[800009];
long long lazy[800009];
long long a[200009];
long long b[200009];
void push(int id){
lazy[id*2]+=lazy[id];
lazy[id*2+1]+=lazy[id];
st[id*2]+=lazy[id];
st[id*2+1]+=lazy[id];
lazy[id]=0;
}
void update(int id,int l,int r,int u,int v,long long val){
if (l>v||r<u||u>v)return;
if (u<=l&&r<=v){
st[id]+=val;
lazy[id]+=val;
return;
}
int mid=(l+r)/2;
push(id);
update(id*2,l,mid,u,v,val);
update(id*2+1,mid+1,r,u,v,val);
st[id]=min(st[id*2],st[id*2+1]);
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin>>n;
for (int i=1;i<=n;i++)cin>>a[i];
for (int i=1;i<=n;i++){
cin>>b[i];
update(1,1,n,1,a[i]-1,b[i]);
}
long long ans=1e18;
for (int i=n;i>=2;i--){
update(1,1,n,1,a[i]-1,-b[i]);
update(1,1,n,a[i]+1,n,b[i]);
ans=min(ans,st[1]);
}
cout<<ans;
}
| 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>
#define pii pair<int,int>
#define fi first
#define se second
#define eb emplace_back
#define ll long long
using namespace std;
const int M=1e6+9;
int n,m,sz;
int c[M][26],b[M],dp[M],L[M],R[M];
bool vis[M];
void dfs(int u){
if(vis[u]){
L[u]=R[u]=u;
}
for(int i=0;i<26;++i){
if(c[u][i]){
dfs(c[u][i]);
if(!L[u])L[u]=L[c[u][i]];
if(R[c[u][i]])R[u]=R[c[u][i]];
}
}
}
void solve(int u,int z){
if(vis[u])sz++,dp[u]=min(dp[u],z+sz);
if(R[u])z=min(z,dp[u]-(sz-vis[u]));
for(int i=0;i<26;++i){
if(c[u][i]){
dp[c[u][i]]=dp[u]+1;
solve(c[u][i],z);
}
}
}
int main(){
cin>>n;
for(int i=1;i<=n;++i){
int p;
char s[5];
cin>>p>>s;
c[p][s[0]-'a']=i;
}
cin>>m;
for(int i=1;i<=m;++i){
cin>>b[i];
vis[b[i]]=1;
}
dfs(0);
solve(0,0);
for(int i=1;i<=m;++i){
cout<<dp[b[i]]<<" \n"[i==m];
}
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 <stdio.h>
#include <string>
#include <vector>
#include <stdlib.h>
#include <bits/stdc++.h>
using namespace std;
#define fast \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0)
typedef long long ll;
#define int long long
#define mod7 1000000007
#define mod9 1000000009
#define endl "\n"
#define Endl "\n"
#define no cout << "NO" << endl
#define yes cout << "YES" << endl
#define all(v) v.begin(), v.end()
#define f(i, a, b) for (ll i = a; i < b; ++i)
#define fr(i, a, b) for (ll i = a; i >= b; i--)
ll binary_expo(ll a, ll b, ll mod = 1)
{
ll ans = 1;
while (b)
{
if (b & 1)
{
ans = (ans * 1LL * a) % mod;
}
a = (a * 1LL * a) % mod;
b >>= 1;
}
return ans;
}
bool isPerfectSquare(ll x)
{
if (x >= 0)
{
ll sr = sqrt(x);
return (sr * sr == x);
}
return false;
}
ll moduloMultiplication(ll a, ll b, ll mod)
{
ll res = 0;
a %= mod;
while (b)
{
if (b & 1)
res = (res + a) % mod;
b >>= 1;
}
return res;
}
/*input*/
template <typename T>
istream &operator>>(std::istream &in, vector<T> &a)
{
for (auto &it : a)
in >> it;
return in;
}
template <typename T1, typename T2>
istream &operator>>(std::istream &in, pair<T1, T2> &a)
{
in >> a.first >> a.second;
return in;
}
/*output*/
template <typename T>
ostream &operator<<(std::ostream &out, vector<T> &a)
{
for (auto it : a)
{
out << ' ' << it;
}
out << endl;
return out;
}
template <typename T1, typename T2>
ostream &operator<<(std::ostream &out, pair<T1, T2> &a)
{
out << a.first << ' ' << a.second;
return out;
}
bool isPowerOfTwo(long long x) { return x && (!(x & (x - 1))); }
#define debug(x) \
cerr << #x << " "; \
_print(x); \
cerr << endl;
void _print(int t)
{
cerr << t;
}
void _print(string t) { cerr << t; }
void _print(char t) { cerr << t; }
void _print(double 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.first);
cerr << ",";
_print(p.second);
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 << "]";
}
const int N = 1e5 + 10;
const int INF = 1e9;
signed main()
{
fast;
int n;
cin >> n;
vector<int> visited(n + 1, 0);
vector<int> brr(n - 1);
cin >> brr;
map<int, int> temp;
for (auto child : brr)
temp[child]++;
long long sum = 0;
long long min_val = 0;
for (int i = 0; i + 1 < n; i++)
{
cin >> brr[i];
sum += brr[i];
if (sum < min_val)
min_val = sum;
}
vector<long long> p(n);
p[0] = 1 - min_val;
if (p[0] > n || p[0] < 0)
{
cout << -1 << endl;
return 0;
}
for (int i = 0; i < n - 1; i++)
{
p[i + 1] = p[i] + brr[i];
if (p[i + 1] > n || p[i + 1] < 0)
{
cout << -1 << endl;
return 0;
}
}
if (set<int>(all(p)).size() == n)
cout << p << endl;
else
cout << -1 << Endl;
return 0;
} | cpp |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define MOD 1000000007
void solve(){
int n,m,x,sum=0; cin >> n >> m;
for(int i=0;i<n;i++){
cin >> x;
sum+=x;
}
cout << ((sum<m)?sum:m) << endl;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
while(t--){
solve();
}
return 0;
}
| cpp |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | [
"implementation",
"strings"
] | /* لا اله الا الله محمد رسول الله */
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
#define sad cin.tie(0);cin.sync_with_stdio(0);
#define el "\n"
#define all(x) x.begin(), x.end()
#define ll long long
#define Test unsigned ll TC; cin >> TC; while(TC--)
#define NO cout<<"NO\n";
#define YES cout<<"YES\n";
#define sz(s) int(s.size())
const ll MOD = 1e9 + 7;
ll n, m, p, q;
string tmp;
vector<string>v1,v2;
int main() {
sad;;;;;;;;;;;;
cin >> n >> m;
for (int i = 0; i < n; ++i) {
cin >> tmp;
v1.push_back(tmp);
}
for (int i = 0; i < m; ++i) {
cin >> tmp;
v2.push_back(tmp);
}
Test {
cin >> p;p--;
cout << v1[p % n] << v2[p % m] << el;
};
}
/*
* sinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
*/ | cpp |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define all(a) begin(a), end(a)
#define len(a) int((a).size())
namespace rn = ranges;
namespace vw = rn::views;
template<int SZ>
struct hash_t {
static bool initialized;
static int MOD[SZ], BASE[SZ];
static std::vector<int> POWER[SZ];
static void initialize() {
assert(!initialized);
initialized = true;
std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());
for (int i = 0; i < SZ; i++) {
auto is_prime = [&](int x) {
for (int i = 2; i * i <= x; i++)
if (x % i == 0)
return false;
return true;
};
MOD[i] = int(8e5) + rng() % int(2e8 + 228);
while (!is_prime(MOD[i]))
MOD[i]++;
BASE[i] = rng() % MOD[i];
if (!(BASE[i] & 1))
BASE[i]++;
POWER[i].push_back(1);
}
}
static void ensure(int n) {
assert(initialized);
if (int(POWER[0].size()) >= n)
return;
for (int i = 0; i < SZ; i++)
for (int j = POWER[i].size(); j < n; j++)
POWER[i].push_back(int64_t(POWER[i].back()) * BASE[i] % MOD[i]);
}
int length;
std::array<int, SZ> h;
hash_t() : length(0) {
h.fill(0);
if (!initialized)
initialize();
}
template<typename T>
hash_t(const T &value, int length = 1) : length(length) {
if (!initialized)
initialize();
ensure(length);
h.fill(0);
for (int i = 0; i < SZ; i++)
for (int j = 0; j < length; j++) {
h[i] += int64_t(value + 1) * POWER[i][j] % MOD[i];
if (h[i] >= MOD[i])
h[i] -= MOD[i];
}
}
hash_t<SZ>& operator+=(const hash_t<SZ> &x) {
assert(initialized);
ensure(x.length + 1);
for (int i = 0; i < SZ; i++)
h[i] = (int64_t(h[i]) * POWER[i][x.length] + x.h[i]) % MOD[i];
length += x.length;
return *this;
}
hash_t<SZ>& operator-=(const hash_t<SZ> &x) {
assert(initialized);
assert(x.length <= length);
ensure(length - x.length + 1);
for (int i = 0; i < SZ; i++) {
h[i] -= int64_t(x.h[i]) * POWER[i][length - x.length] % MOD[i];
if (h[i] < 0)
h[i] += MOD[i];
}
length -= x.length;
return *this;
}
bool operator==(const hash_t<SZ> &x) const {
if (length != x.length)
return false;
return h == x.h;
}
bool operator<(const hash_t<SZ> &x) const {
if (length != x.length)
return length < x.length;
return h < x.h;
}
friend hash_t<SZ> operator+(const hash_t<SZ> &left, const hash_t<SZ> &right) {
return hash_t<SZ>(left) += right;
}
friend hash_t<SZ> operator-(const hash_t<SZ> &left, const hash_t<SZ> &right) {
return hash_t<SZ>(left) -= right;
}
};
template<int SZ> bool hash_t<SZ>::initialized = false;
template<int SZ> int hash_t<SZ>::MOD[SZ] = {};
template<int SZ> int hash_t<SZ>::BASE[SZ] = {};
template<int SZ> std::vector<int> hash_t<SZ>::POWER[SZ] = {};
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int n;
string s;
cin >> n >> s;
vector<int> pref_one(n + 1), zeroes;
for (int i = 0; i < n; i++) {
if (s[i] == '0') zeroes.push_back(i);
pref_one[i + 1] = pref_one[i] + (s[i] == '1');
}
using hash = hash_t<4>;
array<vector<hash>, 2> pref_hash;
for (int rot : {0, 1}) {
vector<hash> cur;
cur.push_back(hash());
for (auto i : zeroes) {
cur.push_back(cur.back() + hash('0' + ((pref_one[i + 1] % 2) ^ rot)));
}
pref_hash[rot] = cur;
}
int q;
cin >> q;
while (q--) {
int l1, l2, l;
cin >> l1 >> l2 >> l, l1--, l2--;
cout << ([&]() {
if (pref_one[l1 + l] - pref_one[l1] != pref_one[l2 + l] - pref_one[l2]) {
return false;
}
if (pref_one[l1 + l] - pref_one[l1] == l) {
return true;
}
auto query = [&](int l, int r) {
int from = rn::lower_bound(zeroes, l) - zeroes.begin();
int to = rn::lower_bound(zeroes, r) - zeroes.begin();
assert(to - from > 0);
int parity = pref_one[l] % 2;
return pref_hash[parity][to] - pref_hash[parity][from];
};
return query(l1, l1 + l) == query(l2, l2 + l);
}() ? "Yes" : "No") << '\n';
}
}
| cpp |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | /* ________
/ \
/ / \ \
________/ / \ \________
/ \ / \
/ / \ \ ______ / / \ \
/ / \ \________/ / \ \
\ / \ /
\ ______ / / \ \ ______ /
\________/ / \ \________/
/ \ / \
/ / \ \ ______ / / \ \
/ / \ \________/ / \ \
\ / \ /
\ ______ / / \ \ ______ /
\________/ / \ \________/
\ /
\ ______ /
\________/
*/
#include <bits/stdc++.h>
typedef long long ll ;
typedef long double ld ;
#define endl '\n'
#define T ll tt ; cin >> tt ; while (tt--)
#define pb push_back
#define F first
#define S second
using namespace std ;
const int N = 1e6 + 9 ;
const ll M = 1e9 + 7 ;
ll dx[] = {0 , 0 , -1 , 1} ;
ll dy[] = {1 , -1 , 0 , 0} ;
vector <ld> v , v1 ;
ll n , m , x , y , z , x1 , y1 , k , l , r , L , R , len , mid , cntt , cntt1 , g , h , q , id , ind , idx , sum , sum1 , cnt , ans , maxxx , maxx = -1e11 , minn = 1e11 , a[N] , b[N] , c , d ;
ll pi = 3.1415926535897932384626433832795 ;
string s , t ;
bool f , ff ;
ll fp(ll x , ll y)
{
if(y == 0)
return 1 ;
if(y == 1)
return x ;
ll ret = fp(x , y / 2) ;
ret = (ret * ret) % M ;
if(y % 2)
ret = (ret * x) % M ;
return ret ;
}
int32_t main()
{
ios :: sync_with_stdio(false) ; cin.tie(0) ;
T {
f = ff = 0 ;
cin >> n >> k ;
for (int i = 0 ; i < n ; i ++) {
cin >> a[i] ;
if (a[i] == k)
f = 1 ;
else if (a[i] > k)
ff = 1 ;
}
if (f) {
cout << 1 << endl ;
continue ;
}
if (ff) {
cout << 2 << endl ;
continue ;
}
sort (a , a + n) ;
cout << (k - 1) / *max_element(a ,a + n) + 1 << endl ;
}
return 0 ;
}
| cpp |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | #include<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=1e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
int T;
int n,m,k;
int w[N];
void solve() {
n=read(),m=read();
int maxn=1;
bool flag=false;
for(int i=1;i<=n;i++) {
w[i]=read();maxn=max(maxn,w[i]);
if(w[i]==m) flag=true;
}
int l=0,r=1e9;
while(l<r) {
int mid=l+r>>1;
if((ll)mid*maxn>=m) r=mid;
else l=mid+1;
}
if(flag) printf("1\n");
else if(((ll)l*maxn==m)||((ll)l*maxn>m&&l!=1)) printf("%d\n",l);
else printf("%d\n",l+1);
}
int main() {
// init();
// stin();
scanf("%d",&T);
// T=1;
while(T--) solve();
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>
using namespace std;
using ll=long long int;
#define MOD 1e9 + 7;
#define loop_up(a,b) for(ll i=a;i<b;i++)
#define loop_down(a,b) for(ll i=a;i>b;i--)
#define TEST ll t; cin>>t; while(t--)
vector <ll> prime_factors;
//__gcd(a,b) is used to find GCD of 2 numbers.
//bin-pow (binary exponentiation) - (a^b)%m types.
ll pw(ll a, ll b, ll m){
if(b==0){
return a%m;
}
if(b%2==0){
ll t=pw(a, b/2, m);
return(t*t%m);
}
else{
ll t=pw(a,(b-1)/2, m);
t=(t*t%m);
return(a*t%m);
}
}
//multiplicative inverse for division under mod provided that M IS PRIME.
// (a/b)%m = a*(inv b)%m
//invb is multiplicative inverse for division under mod for b - this function returns that
ll modinv(ll x, ll m){
return(pw(x,m-2,m));
}
//PRIME NUMBER CHECK
bool isPrime(ll p){
if(p==1)return false;
if(p==2 | p==3)return true;
if(p%2==0 | p%3==0)return false;
for(ll i=5; i*i<p; i+=6)
if(p%i==0 | p%(i+2)==0)
return false;
return true;
}
//SIEVE OF ERATOSTHENES - prime factors
//remove < if(n%i==0) > to return lll prime numbers before some n
void sieve(ll n){
vector<bool> temp_isPrime(n+1, true);
prime_factors.clear();
for(ll i=2; i<=n; i++){
if(temp_isPrime[i]){
if(n%i==0)
prime_factors.push_back(i);
for(ll j=i*i; j<=n; j+=i){
temp_isPrime[j]=false;
}
}
}
}
//PALINDROME CHECK
bool isPalindrome(string x){
ll i=0; ll j=x.length()-1;
while(i<=j){
if(x[i]!=x[j])
return(false);
i++; j--;
}
return(true);
}
//STRING REVERSAL
string reverse(string str){
ll len = str.length();
ll n = len;
string r="";
while(n--)
r+=str[n];
return(r);
}
ll digitsum(ll x){
ll sum=0;
while(x>0){
sum+=(x%10);
x/=10;
}
return(sum);
}
bool mycmp(pair<ll,ll> a, pair<ll,ll> b){
return(a.first<b.first);
}
int main() {
string s;
cin>>s;
ll n=s.length();
ll op[n],cl[n];
ll cnt=0;
vector<ll> v1,v2;
loop_up(0,s.length()){
if(s[i]=='('){
cnt++;
v1.push_back(i+1);
}
else{
v2.push_back(i+1);
}
op[i]=cnt;
}
cnt=0;
loop_down(s.length()-1,-1) {
if (s[i] == ')') {
cnt++;
}
cl[i] = cnt;
}
ll j=-1,i;
for(i=0; i<n; i++){
if(op[i]>cl[i]){
j=i-1;
break;
}
}
if(j==-1){
if((op[n-1]==1) & (cl[n-1]==1)){
cout<<1<<endl;
cout<<2<<endl;
cout<<1<<' '<<n<<endl;
}
else
cout<<0<<endl;
}
else if(op[j]==0){
cout<<0<<endl;
}
else{
cout<<1<<endl;
cout<<op[j]*2<<endl;
for(ll i=0; i<op[j]; i++)
cout<<v1[i]<<' ';
ll l=v2.size()-1;
vector<ll> temp;
while(op[j]--){
temp.push_back(v2[l]);
l--;
}
for (auto it = temp.end() - 1; it >= temp.begin(); it--)
cout << *it << " ";
}
}
| cpp |
1320 | E | E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1
| [
"data structures",
"dfs and similar",
"dp",
"shortest paths",
"trees"
] | // LUOGU_RID: 93909098
#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;
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);
}
template<typename T, typename ...Args>
void LOG(T str, Args ...args) {
#ifdef DEBUG
fprintf(stderr, str, args...);
#endif
}
#define fre(s) freopen(#s ".in", "r", stdin), freopen(#s ".out", "w", stdout)
const int kN = 2e5 + 5;
int n, q, s[kN], f[kN], dep[kN], dfn[kN], son[kN], top[kN], clk;
std::vector<int> G[kN];
void dfs1(int u) {
s[u] = 1;
for (int v : G[u]) if (v ^ f[u]) {
f[v] = u;
dep[v] = dep[u] + 1;
dfs1(v);
s[u] += s[v];
if (s[v] > s[son[u]]) son[u] = v;
}
}
void dfs2(int u) {
dfn[u] = ++clk;
if (!top[u]) top[u] = u;
if (son[u]) top[son[u]] = top[u], dfs2(son[u]);
for (int v : G[u]) if (v != f[u] && v != son[u]) dfs2(v);
}
int lca(int u, int v) {
while (top[u] ^ top[v]) {
if (dep[top[u]] > dep[top[v]]) u = f[top[u]];
else v = f[top[v]];
}
return dep[u] < dep[v] ? u : v;
}
// virtual tree
int head[kN], ecnt = 1;
struct Arc {
int next, to, w;
} e[kN << 1];
void addEdge(int from, int to, int w) {
e[ecnt] = (Arc) {
head[from], to, w
};
head[from] = ecnt++;
}
int k, m, vert[kN * 2], sp[kN], upd[kN], qry[kN], st[kN];
int c[kN], rem[kN], t[kN];
bool vis[kN];
std::priority_queue<std::pair<pii, int> > hp;
void solve() {
scanf("%d%d", &k, &m);
For(i, 1, k) scanf("%d%d", upd + i, sp + i), vert[i] = upd[i];
For(i, 1, m) scanf("%d", qry + i), vert[i + k] = qry[i];
vert[0] = 1;
std::sort(vert, vert + k + m + 1, [](int u, int v) {
return dfn[u] < dfn[v];
});
For(i, 0, k + m) head[vert[i]] = 0;
ecnt = 1;
int top = 1;
st[top] = 1;
For(i, 1, k + m) {
if (vert[i] == vert[i - 1]) continue;
int p = lca(vert[i], st[top]);
while (top > 1 && dep[p] <= dep[st[top - 1]]) {
addEdge(st[top - 1], st[top], dep[st[top]] - dep[st[top - 1]]);
addEdge(st[top], st[top - 1], dep[st[top]] - dep[st[top - 1]]);
--top;
}
if (p != st[top]) {
head[p] = 0;
vis[p] = false, t[p] = 1e9, c[p] = 0; // ERR
addEdge(st[top], p, dep[st[top]] - dep[p]);
addEdge(p, st[top], dep[st[top]] - dep[p]);
st[top] = p;
}
st[++top] = vert[i];
}
while (top > 1) {
addEdge(st[top], st[top - 1], dep[st[top]] - dep[st[top - 1]]);
addEdge(st[top - 1], st[top], dep[st[top]] - dep[st[top - 1]]);
--top;
}
For(i, 0, k + m) vis[vert[i]] = false, t[vert[i]] = 1e9, c[vert[i]] = 0; // ERR
For(i, 1, k) {
t[upd[i]] = 0;
c[upd[i]] = i;
rem[upd[i]] = 0;
hp.push({pii(0, -i), upd[i]});
}
while (!hp.empty()) {
int u = hp.top().se;
hp.pop();
if (vis[u]) continue;
vis[u] = true;
eFor(i, u, v) {
int nt = rem[u] < e[i].w ? t[u] + (e[i].w - rem[u] + sp[c[u]] - 1) / sp[c[u]] : t[u];
int nr = (nt - t[u]) * sp[c[u]] + rem[u] - e[i].w; // ERR
if (t[v] && pii(nt, c[u]) < pii(t[v], c[v])) { // ERR
t[v] = nt;
c[v] = c[u];
rem[v] = nr;
hp.push({pii(-t[v], -c[v]), v});
}
}
}
For(i, 1, m) printf("%d ", c[qry[i]]);
printf("\n");
}
int main() {
scanf("%d", &n);
For(i, 1, n - 1) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v), G[v].push_back(u);
}
dfs1(1), dfs2(1);
scanf("%d", &q);
For(kase, 1, q) solve();
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 | 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 |
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"
] | /*
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
*/
#include<bits/stdc++.h>
using namespace std;
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define eb emplace_back
#define PI 3.14159265359
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define BIT(x,i) (1&((x)>>(i)))
#define MASK(x) (1LL<<(x))
#define task "tnc"
typedef long long ll;
const ll INF=1e18;
const int maxn=1e6+5;
const int mod=1e9+7;
const int mo=998244353;
using pi=pair<ll,ll>;
using vi=vector<ll>;
using pii=pair<pair<ll,ll>,ll>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int n,m;
int a[maxn];
int jump[maxn];
int cnt[maxn];
const int blk=350;
pair<int,int>get(int x){
int sum=1;
while(true){
sum+=cnt[x];
x=jump[x];
if(x==jump[x])break;
}
return {x,sum};
}
void update(int x){
int j=x/blk;
for(int i=x;i>=j*blk;i--){
if(i+a[i]>=n){
jump[i]=i;
cnt[i]=0;
}
else if((i+a[i])/blk!=i/blk){
cnt[i]=1;
jump[i]=i+a[i];
}
else{
cnt[i]=cnt[i+a[i]]+1;
jump[i]=jump[i+a[i]];
}
}
}
signed main()
{
cin.tie(0),cout.tie(0)->sync_with_stdio(0);
//freopen(task".inp" , "r" , stdin);
//freopen(task".out" , "w" , stdout);
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
if(i==n-1 || i/blk != (i+1)/blk)update(i);
}
for(int i=1;i<=m;i++){
int type;
cin>>type;
if(type==1){
int x;
cin>>x;
x--;
pair<int,int>k=get(x);
cout<<k.fi+1<<" "<<k.se<<"\n";
}
else{
int x,y;
cin>>x>>y;
x--;
a[x]=y;
update(x);
}
}
return 0;
}
// 3 1 1 1 1 2 8 2
// 0 3 4 5 | 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>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#pragma GCC optimize("O3")
#define all(x) x.begin(),x.end()
#define pb push_back
#define m_p make_pair
#define fi first
#define se second
#define sz(x) (int)x.size()
#define fr(i, l, r) for(ll i = l; i <= r; i ++)
#define fe(x, y) for(auto& x : y)
#define rf(x, l, r) for(int x = l; x >= r; x--)
#define sq(x) ((x)*(x))
#define pw(x) (1ll << x)
#define ook order_of_key
#define fbo find_by_order
using namespace std;
using namespace __gnu_pbds;
mt19937_64 rng(chrono::system_clock::now().time_since_epoch().count());
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
template <typename T>
using oset = tree <T, null_type, less <T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T>
bool umx(T& a, T b)
{
return a < b ? a = b, 1 : 0;
}
template <typename T>
bool umn(T& a, T b)
{
return a > b ? a = b, 1 : 0;
}
const ll INF = 3e18;
const int INTF = 1e9;
const ll mod = 32768;
const ld eps = 0.00000001;
const ll N = 2e5 + 22;
const bool TEST = 0;
ll mn = 1e18;
int n;
ll a[N];
gp_hash_table<ll, bool> s;
bool TL() {
return (double)clock() / CLOCKS_PER_SEC > 2.2;
}
void check(ll x) {
if (s.find(x) != s.end()) return;
s[x] = 1;
if (TL()) return;
if(x == 0 || x == 1)return;
ll sum = 0;
assert(x != 0);
for(int i = 0;i < n;i ++) {
if(a[i] >= x)sum += min(a[i] % x, x - (a[i] % x));
else sum += x - a[i];
}
mn = min(mn, sum);
}
void f(ll x) {
for(int i = 2;1LL * i * i <= x;i ++) {
assert(x != 0);
if(x % i == 0) {
if (TL()) break;
check(i);
while(x % i == 0) {
// if (TL()) return;
x /= i;
assert(x != 0);
}
}
}
if(x > 1)check(x);
}
void solve() {
cin >> n;
mn = n;
for(int i = 0;i < n;i ++)cin >> a[i];
shuffle(a, a + n, rng);
int i = 0;
while(!TL()) {
f(a[i]);
if (TL()) break;
f(a[i] + 1);
if (TL()) break;
f(a[i] - 1);
i++;
if (i == n) break;
}
cout << mn << endl;
}
int main()
{
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#else // LOCAL
// freopen("half.in", "r", stdin);
// freopen("half.out", "w", stdout);
#endif // LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int q = 1;
if(TEST)cin >> q;
while(q--)
{
solve();
}
return 0;
}
| cpp |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
| [
"dp",
"greedy",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr);
int TC; cin >> TC; while (TC--) {
string S; cin >> S; int N = S.size();
string T; cin >> T; int M = T.size();
int pos[N+10][30];
for (int i = 0; i < N; ++i) for (int j = 0; j < 26; ++j) pos[i][j] = -1;
for (int i = N-1; i >= 0; --i) {
pos[i][S[i]-'a'] = i;
for (int j = 0; j < 26; ++j) {
if (i+1 < N && pos[i][j] == -1) pos[i][j] = pos[i+1][j];
}
}
int res = 1, idx = 0;
for (int i = 0; i < M; ++i) {
if (idx == N) {
++res; idx = 0;
}
int next = pos[idx][T[i]-'a'];
if (next == -1) {
next = pos[0][T[i]-'a'];
if (next == -1) {
res = -1; break;
} else {
++res; idx = ++next;
}
} else {
idx = ++next;
}
}
cout << res << endl;
}
return 0;
} | cpp |
1288 | F | F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB
| [
"constructive algorithms",
"flows"
] | #line 1 "/home/maspy/compro/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 u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
constexpr T infty = 0;
template <>
constexpr int infty<int> = 1'000'000'000;
template <>
constexpr ll infty<ll> = ll(infty<int>) * infty<int> * 2;
template <>
constexpr u32 infty<u32> = infty<int>;
template <>
constexpr u64 infty<u64> = infty<ll>;
template <>
constexpr i128 infty<i128> = i128(infty<ll>) * infty<ll>;
template <>
constexpr double infty<double> = infty<ll>;
template <>
constexpr long double infty<long double> = infty<ll>;
using pi = pair<ll, ll>;
using vi = vector<ll>;
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 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 overload4(a, b, c, d, e, ...) e
#define overload3(a, b, c, d, ...) d
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) overload3(__VA_ARGS__, 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
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, 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 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()
template <typename T>
T POP(deque<T> &que) {
T a = que.front();
que.pop_front();
return a;
}
template <typename T>
T POP(pq<T> &que) {
T a = que.top();
que.pop();
return a;
}
template <typename T>
T POP(pqg<T> &que) {
assert(!que.empty());
T a = que.top();
que.pop();
return a;
}
template <typename T>
T POP(vc<T> &que) {
assert(!que.empty());
T a = que.back();
que.pop_back();
return a;
}
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);
}
// ? は -1
vc<int> s_to_vi(const string &S, char first_char) {
vc<int> A(S.size());
FOR(i, S.size()) { A[i] = (S[i] != '?' ? S[i] - first_char : -1); }
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;
}
// stable sort
template <typename T>
vector<int> argsort(const vector<T> &A) {
vector<int> ids(len(A));
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return (A[i] == A[j] ? i < j : A[i] < A[j]); });
return ids;
}
// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
vc<T> B(len(I));
FOR(i, len(I)) B[i] = A[I[i]];
return B;
}
#endif
#line 1 "/home/maspy/compro/library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace fastio {
#define 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 "/home/maspy/compro/library/flow/bflow.hpp"
enum Objective {
MINIMIZE = 1,
MAXIMIZE = -1,
};
enum class Status {
OPTIMAL,
INFEASIBLE,
};
template <class Flow = ll, class Cost = ll,
Objective objective = Objective::MINIMIZE, Flow SCALING_FACTOR = 2>
struct MinCostFlow {
private:
using V_id = uint32_t;
using E_id = uint32_t;
struct Edge {
friend struct MinCostFlow;
private:
V_id frm, to;
Flow flow, cap;
Cost cost;
E_id rev;
public:
Edge() = default;
Edge(const V_id frm, const V_id to, const Flow cap, const Cost cost,
const E_id rev)
: frm(frm), to(to), flow(0), cap(cap), cost(cost), rev(rev) {}
[[nodiscard]] Flow residual_cap() const { return cap - flow; }
};
public:
struct EdgePtr {
friend struct MinCostFlow;
private:
const MinCostFlow *instance;
const V_id v;
const E_id e;
EdgePtr(const MinCostFlow *instance, const V_id v, const E_id e)
: instance(instance), v(v), e(e) {}
[[nodiscard]] const Edge &edge() const { return instance->g[v][e]; }
[[nodiscard]] const Edge &rev() const {
const Edge &e = edge();
return instance->g[e.to][e.rev];
}
public:
[[nodiscard]] V_id frm() const { return rev().to; }
[[nodiscard]] V_id to() const { return edge().to; }
[[nodiscard]] Flow flow() const { return edge().flow; }
[[nodiscard]] Flow lower() const { return -rev().cap; }
[[nodiscard]] Flow upper() const { return edge().cap; }
[[nodiscard]] Cost cost() const { return edge().cost; }
[[nodiscard]] Cost gain() const { return -edge().cost; }
};
private:
V_id n;
std::vector<std::vector<Edge>> g;
std::vector<Flow> b;
public:
MinCostFlow(int n) : n(n) {
g.resize(n);
b.resize(n);
}
V_id add_vertex() {
++n;
g.resize(n);
b.resize(n);
return n - 1;
}
std::vector<V_id> add_vertices(const size_t size) {
std::vector<V_id> ret;
for (V_id i = 0; i < size; ++i) ret.emplace_back(n + i);
n += size;
g.resize(n);
b.resize(n);
return ret;
}
void add(const V_id frm, const V_id to, const Flow lo, const Flow hi,
const Cost cost) {
const E_id e = g[frm].size(), re = frm == to ? e + 1 : g[to].size();
assert(lo <= hi);
g[frm].emplace_back(Edge{frm, to, hi, cost * objective, re});
g[to].emplace_back(Edge{to, frm, -lo, -cost * objective, e});
edges.eb(EdgePtr{this, frm, e});
}
void add_source(const V_id v, const Flow amount) { b[v] += amount; }
void add_sink(const V_id v, const Flow amount) { b[v] -= amount; }
private:
static Cost constexpr unreachable = std::numeric_limits<Cost>::max();
Cost farthest;
std::vector<Cost> potential;
std::vector<Cost> dist;
std::vector<Edge *> parent;
std::priority_queue<std::pair<Cost, int>, std::vector<std::pair<Cost, int>>,
std::greater<>>
pq;
std::vector<V_id> excess_vs, deficit_vs;
std::vector<EdgePtr> edges;
Edge &rev(const Edge &e) { return g[e.to][e.rev]; }
void push(Edge &e, const Flow amount) {
e.flow += amount;
g[e.to][e.rev].flow -= amount;
}
Cost residual_cost(const V_id frm, const V_id to, const Edge &e) {
return e.cost + potential[frm] - potential[to];
}
bool dual(const Flow delta) {
dist.assign(n, unreachable);
parent.assign(n, nullptr);
excess_vs.erase(std::remove_if(std::begin(excess_vs), std::end(excess_vs),
[&](const V_id v) { return b[v] < delta; }),
std::end(excess_vs));
deficit_vs.erase(
std::remove_if(std::begin(deficit_vs), std::end(deficit_vs),
[&](const V_id v) { return b[v] > -delta; }),
std::end(deficit_vs));
for (const auto v: excess_vs) pq.emplace(dist[v] = 0, v);
farthest = 0;
std::size_t deficit_count = 0;
while (!pq.empty()) {
const auto [d, u] = pq.top();
pq.pop();
if (dist[u] < d) continue;
farthest = d;
if (b[u] <= -delta) ++deficit_count;
if (deficit_count >= deficit_vs.size()) break;
for (auto &e: g[u]) {
if (e.residual_cap() < delta) continue;
const auto v = e.to;
const auto new_dist = d + residual_cost(u, v, e);
if (new_dist >= dist[v]) continue;
pq.emplace(dist[v] = new_dist, v);
parent[v] = &e;
}
}
pq = decltype(pq)();
for (V_id v = 0; v < n; ++v) {
potential[v] += std::min(dist[v], farthest);
}
return deficit_count > 0;
}
void primal(const Flow delta) {
for (const auto t: deficit_vs) {
if (dist[t] > farthest) continue;
Flow f = -b[t];
V_id v;
for (v = t; parent[v] != nullptr && f >= delta; v = parent[v]->frm) {
f = std::min(f, parent[v]->residual_cap());
}
f = std::min(f, b[v]);
if (f < delta) continue;
for (v = t; parent[v] != nullptr;) {
auto &e = *parent[v];
push(e, f);
const size_t u = parent[v]->frm;
parent[v] = nullptr;
v = u;
}
b[t] += f;
b[v] -= f;
}
}
void saturate_negative(const Flow delta) {
excess_vs.clear();
deficit_vs.clear();
for (auto &es: g)
for (auto &e: es) {
const Flow rcap = e.residual_cap();
const Cost rcost = residual_cost(e.frm, e.to, e);
if (rcost < 0 && rcap >= delta) {
push(e, rcap);
b[e.frm] -= rcap;
b[e.to] += rcap;
}
}
for (V_id v = 0; v < n; ++v)
if (b[v] != 0) { (b[v] > 0 ? excess_vs : deficit_vs).emplace_back(v); }
}
public:
std::pair<Status, i128> solve() {
potential.resize(n);
for (auto &es: g)
for (auto &e: es) {
const Flow rcap = e.residual_cap();
if (rcap < 0) {
push(e, rcap);
b[e.frm] -= rcap;
b[e.to] += rcap;
}
}
Flow inf_flow = 1;
for (const auto &es: g)
for (const auto &e: es) inf_flow = std::max(inf_flow, e.residual_cap());
Flow delta = 1;
while (delta <= inf_flow) delta *= SCALING_FACTOR;
for (delta /= SCALING_FACTOR; delta; delta /= SCALING_FACTOR) {
saturate_negative(delta);
while (dual(delta)) primal(delta);
}
i128 value = 0;
for (const auto &es: g)
for (const auto &e: es) { value += e.flow * e.cost; }
value /= 2;
if (excess_vs.empty() && deficit_vs.empty()) {
return {Status::OPTIMAL, value / objective};
} else {
return {Status::INFEASIBLE, value / objective};
}
}
template <class T>
T get_result_value() {
T value = 0;
for (const auto &es: g)
for (const auto &e: es) { value += (T)(e.flow) * (T)(e.cost); }
value /= (T)2;
return value / objective;
}
std::vector<Cost> get_potential() {
std::fill(potential.begin(), potential.end(), 0);
for (int i = 0; i < (int)n; i++)
for (const auto &es: g)
for (const auto &e: es)
if (e.residual_cap() > 0)
potential[e.to]
= std::min(potential[e.to], potential[e.frm] + e.cost);
return potential;
}
std::vector<EdgePtr> get_edges() { return edges; }
};
#line 4 "main.cpp"
void solve() {
LL(N1, N2, M, R, B);
STR(S1, S2);
VEC(pi, edge, M);
for (auto&& [a, b]: edge) --a, --b;
auto left = [&](int v) -> int { return v; };
auto right = [&](int v) -> int { return N1 + v; };
int source = N1 + N2;
int sink = N1 + N2 + 1;
MinCostFlow<ll, ll> G(sink + 1);
FOR(i, M) {
auto [a, b] = edge[i];
G.add(left(a), right(b), 0, 1, R);
G.add(right(b), left(a), 0, 1, B);
}
FOR(v, N1) {
char c = S1[v];
if (c == 'R') G.add(source, left(v), 1, infty<int>, 0);
if (c == 'B') G.add(left(v), sink, 1, infty<int>, 0);
if (c == 'U') G.add(source, left(v), 0, infty<int>, 0);
if (c == 'U') G.add(left(v), sink, 0, infty<int>, 0);
}
FOR(v, N2) {
char c = S2[v];
if (c == 'B') G.add(source, right(v), 1, infty<int>, 0);
if (c == 'R') G.add(right(v), sink, 1, infty<int>, 0);
if (c == 'U') G.add(source, right(v), 0, infty<int>, 0);
if (c == 'U') G.add(right(v), sink, 0, infty<int>, 0);
}
G.add(sink, source, 0, infty<int>, 0);
auto [status, cost] = G.solve();
if (status == Status::INFEASIBLE) return print(-1);
auto edges = G.get_edges();
vc<int> F(M + M);
FOR(i, M + M) F[i] = edges[i].flow();
string ANS;
FOR(i, M) {
int a = F[2 * i + 0], b = F[2 * i + 1];
if (a) ANS += "R";
elif (b) ANS += "B";
else ANS += "U";
}
print(cost);
print(ANS);
}
signed main() {
int T = 1;
// INT(T);
FOR(T) solve();
return 0;
}
| cpp |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <ranges>
#include <set>
#include <string>
#include <vector>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V> &x) {
cerr << '{';
__print(x.first);
cerr << ',';
__print(x.second);
cerr << '}';
}
template <typename T>
void __print(const T &x) {
int f = 0;
cerr << '{';
for (auto &i : x) cerr << (f++ ? "," : ""), __print(i);
cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
__print(t);
if (sizeof...(v)) cerr << ", ";
_print(v...);
}
#ifdef DUPA
#define debug(x...) \
cerr << "[" << #x << "] = ["; \
_print(x)
#else
#define debug(x, ...)
#endif
typedef long long LL;
// HMMMM
#define int LL
typedef pair<int, int> PII;
typedef pair<int, PII> PIII;
const int INF = 1e18 + 1;
int g(deque<PII> left, deque<PII> right) {
sort(all(left));
sort(all(right));
int res = 0;
int sum = 0;
for (auto [y, _] : right) sum += y;
for (auto [x, d1] : left) {
assert(d1 <= 0);
while (!right.empty()) {
auto [y, d2] = right.front();
if (d1 == 0 && d2 == 0) {
sum -= y;
right.pop_front();
} else if (!(y > x)) {
sum -= y;
right.pop_front();
} else
break;
}
res += sum - right.size() * x;
}
return res;
}
void add(vector<int> &tree, int k, int x) {
int n = tree.size() - 1;
k = n - k;
assert(k >= 1);
while (k <= n) {
tree[k] += x;
k += k & -k;
}
}
int get(vector<int> &tree, int k) {
int n = tree.size() - 1;
k = n - k;
assert(k >= 1);
int s = 0;
while (k >= 1) {
s += tree[k];
k -= k & -k;
}
return s;
}
int f(deque<PII> right) {
sort(all(right));
map<int, int> re_map;
for (auto [_, y] : right) re_map[y] = 0;
int idx = 0;
for (auto &[_, y] : re_map) y = idx++;
for (auto &[_, y] : right) y = re_map[y];
int sz = re_map.size() + 2;
vector<int> sum(sz, 0);
vector<int> cnt(sz, 0);
for (auto [y, d2] : right) {
add(sum, d2, y);
add(cnt, d2, 1);
}
int res = 0;
for (auto [x, d1] : right) {
add(sum, d1, -x);
add(cnt, d1, -1);
res += get(sum, d1) - x * get(cnt, d1);
}
return res;
}
int solve() {
int n;
vector<PII> dupa;
cin >> n;
dupa.resize(n);
for (int i = 0; i < n; i++) cin >> dupa[i].first;
for (int i = 0; i < n; i++) cin >> dupa[i].second;
deque<PII> left, right;
for (auto x : dupa) {
if (x.second < 0) left.push_back(x);
if (x.second >= 0) right.push_back(x);
}
int res = g(left, right);
for (auto &[x, y] : left) {
x *= -1;
y *= -1;
}
res += f(left);
res += f(right);
return res;
}
#undef int
int main() {
ios::sync_with_stdio(false);
cin.exceptions(cin.failbit);
cin.tie(0);
int t = 1;
#ifdef DUPA
cin >> t;
#endif
for (int i = 0; i < t; i++) cout << solve() << endl;
}
| cpp |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define N 200001
int P = 7;
int M1 = 1000000009, M2 = 1000000007;
int Power(int x, int y, int M){
int res = 1;
while (y){
if (y % 2){
res *= x;
res %= M;
}
x *= x;
x %= M;
y >>= 1;
}
return res;
}
int ModInv(int a, int M){
return Power(a, M - 2, M);
}
class StringHash{
public:
int M;
string s;
int n;
vector<int> pref;
vector<int> b;
vector<int> nb;
vector<int> st;
StringHash(int n, string s, int M){
this->n = n;
this->s = s;
this->M = M;
pref.assign(n, 0);
b.assign(n, 0);
nb.assign(n, 0);
st.assign(n, 0);
int pr = 1;
int c = 0;
for (int i = 0; i < n; i++){
st[i] = ModInv(pr, M);
if (s[i] == '0'){
if (c % 2){
b[i] = 1;
}
pref[i] = (1 + b[i]) * pr;
pr *= P;
pr %= M;
c = 0;
}
else c++;
if (i) pref[i] += pref[i - 1];
pref[i] %= M;
}
for (int i = n - 2; i >= 0; i--){
if (s[i] != '0') b[i] = b[i + 1];
}
nb[n - 1] = (s[n - 1] == '0' ? 0 : 1);
for (int i = n - 2; i >= 0; i--){
nb[i] = (s[i] == '0' ? 0 : (nb[i + 1] ^ 1));
}
}
int hashval(int i, int l){
int val = pref[i + l - 1] - (i == 0 ? 0 : pref[i - 1]);
val %= M;
val *= st[i];
val -= b[i] + 1;
val += nb[i] + 1;
val %= M;
val += M;
val %= M;
return val;
}
};
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n; cin >> n;
string s; cin >> s;
int c1[n];
c1[0] = (s[0] == '0');
for (int i = 1; i < n; i++){
c1[i] = c1[i - 1] + (s[i] == '0');
}
StringHash H1(n, s, M1);
StringHash H2(n, s, M2);
int q; cin >> q;
for (int i = 0; i < q; i++){
int l1, l2, len; cin >> l1 >> l2 >> len;
l1--; l2--;
if (c1[l1 + len - 1] - (l1 == 0 ? 0 : c1[l1 - 1]) == 0){
cout << (c1[l2 + len - 1] - (l2 == 0 ? 0 : c1[l2 - 1]) == 0 ? "YES" : "NO") << endl;
}
else if (c1[l2 + len - 1] - (l2 == 0 ? 0 : c1[l2 - 1]) == 0){
cout << "NO" << endl;
}
else{
if (H1.hashval(l1, len) == H1.hashval(l2, len)){
cout << "YES" << endl;
}
else cout << "NO" << endl;
}
}
} | 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"
] | /* | In The Name Of Allah | */
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename key>
using ordered_set = tree<key, null_type, less<key>, rb_tree_tag, tree_order_statistics_node_update>; // less_equal
/////////////////////////////////////////////////////////////////////////////////////////////////////////
#define LL __int128
#define ll long long
#define int long long
#define ld long double
#define all(v) ((v).begin()), ((v).end())
#define sz(v) ((int)((v).size()))
#define dpp(v, d) memset(v, d, sizeof(v))
#define MP make_pair
#define ceil(n, m) (((n) / (m)) + ((n) % (m) ? 1 : 0))
#define rep(i, f, t) for (int i = f; i < t; i++)
#define lep(i, f, t) for (int i = f; i >= t; i--)
#define cin(vec) for (auto &i : vec) cin >> i
#define cin_2d(vec, n, m) for(int i = 0; i < n; i++) for(int j = 0; j < m && cin >> vec[i][j]; j++);
#define cout(vec) for(auto& i : vec) cout << i << " "; cout << "\n";
#define cout_2d(vec, n, m) for(int i = 0; i < n; i++, cout << "\n") for(int j = 0; j < m && cout << vec[i][j] << " "; j++);
#define TC int tt; cin >> tt; while (tt--)
#define count1(n) __builtin_popcount(n) // count 1s in Binary number
#define count0(n) __builtin_ctz(n) // trailing 0s in the begin from right
#define countb0(n) __builtin_clz(n) // trailing 0s in the begin from left (LOL)
int setBit(int num, int idx, int val) { return val ? (num | (1 << idx)) : (num & (~(1 << idx))); }
int getBit(int num, int idx) { return (((1 << idx) & num) >= 1); }
int addt(int x, int y, int mod) { return ((x % mod) + (y % mod)) % mod; }
int mult(int x, int y, int mod) { return ((x % mod) * (y % mod)) % mod; }
int subt(int x, int y, int mod) { return ((x % mod) - (y % mod) + mod) % mod; }
/////////////////////////////////////////////////////////////////////////////////////////////////////////
const int inf = (int)(1e18);
const int mod = (int)(1e9 + 7);
int a[200], p[200];
void Test_Case() {
int n, m;
cin >> n >> m;
string str;
cin >> str;
int prf[n + 1] = {};
for (int i = 0, x; i < m; i++) {
cin >> x;
prf[0] += 1, prf[x] -= 1;
}
prf[0]++;
for (int i = 0; i < n; i++) {
if (i)
prf[i] += prf[i - 1];
}
vector<int> frq(26, 0);
for (int i = 0; i < n; i++) {
frq[str[i] - 'a'] += prf[i];
}
cout(frq);
}
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
#endif
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cout << fixed << setprecision(3);
//////////////////////////////////////////////////////
int tt = 1;
cin >> tt;
while (tt--) { Test_Case(); }
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"
] | /* Code by Amaan Parvez (amaan0016) */
#include<bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL)
#define pb push_back
#define ppb pop_back
#define ff first
#define ss second
#define lb lower_bound
#define ub upper_bound
#define sz(x) ((int)(x).size())
#define vi vector<ll>
#define mkp make_pair
#define PI 3.141592653589793238462
#define all(v) v.begin(), v.end()
using namespace std;
// const ll M = 1e9+7;
const ll MOD =1e18;
const ll N=100000000;
const ll M=998244353;
#ifndef ONLINE_JUDGE
#define dbg(x) cerr<<#x<<" ";_print_(x);cerr<<endl;
#else
#define dbg(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_(long double t) { cerr << t; }
void _print_(double t) { cerr << t; }
template <class T, class V> void _print_(pair <T, V> p);
template <class T, class V> void _print_(pair <T, V> p) { cerr << "{"; _print_(p.first); cerr << ","; _print_(p.second); cerr << "}"; }
template <class T> void _print_(set <T> v);
template <class T> void _print_(set <T> v) { cerr << "[ "; for (T i : v) { _print_(i); cerr << " "; } cerr << "]"; }
template <class T, class V> void _print_(map <T, V> v);
template <class T, class V> void _print_(map <T, V> v) { cerr << "[ "; for (auto i : v) { _print_(i); cerr << " "; } cerr << "]"; }
template <class T> void _print_(multiset <T> v);
template <class T> void _print_(multiset <T> v) { cerr << "[ "; for (T i : v) { _print_(i); cerr << " "; } cerr << "]"; }
template <class T> void _print_(vector <T> v);
template <class T> void _print_(vector <T> v) { cerr << "[ "; for (T i : v) { _print_(i); cerr << " "; } cerr << "]"; }
/*---------------------------------------------------------------------------------------------------------------------------*/
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 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;}
ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
/*---------------------------------------------------------------------------------------------------------------------------*/
const int Number=10000005;
vector<bool> Prime(Number,true);
vector<int> spf(Number, Number);
void Sieve(){
Prime[0]=false;Prime[1] =false;
for (int i=2;i<Number;i++) {
if(Prime[i]){
spf[i]=i;
for (int j=i*2;j<Number;j+=i){
Prime[j]=false;
spf[j]=min(spf[j], i);
}
}
}
}
ll power(ll x,ll y,ll p){
ll res = 1;
x = x % p;
while (y>0){
if (y & 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return (res + p) % p;
}
ll modinv(ll x){
return power(x, M - 2, M);
}
ll sum(ll n){
// sum 1 to n = (n*(n+1))/2
ll retval = ((((n % M) * ((n + 1) %
M)) % M) * modinv(2)) % M;
return retval;
}
// divisors
vi div(ll n){
vi num;
for (ll i=1; i*i<=(n); i++){
if (n%i==0){
if (n/i == i)
num.pb(i);
else{
num.pb(i);
num.pb(n/i);
}
}
}
return num;
}
// TC --> O(sqrt(n))
// To calculate sum of divisors of a number
ll divisorSum(ll n){
ll l = 1;
ll ans = 0;
while (l <= n){
ll k = n / l;
ll r = n / k;
k %= M;
ans += ((sum(r) - sum(l - 1) %M) * k) % M;
ans %= M;
l = r + 1;
}
ans = ans % M;
if (ans < 0){
return ans+M;
}else{
return ans;
}
}
// Factorial Calcultion
ll inverse(int n,int m){
if(n==1){
return 1;
}else{
return inverse(m%n,m)*(m-m/n)%m;
}
}
// Change Acc. to constraints
const ll fac_size=200005;
ll fac[fac_size+1];
ll inv[fac_size+1];
void Cal_Factorial(){
fac[0]=1;
rep(i,1,fac_size+1){
fac[i]=mod_mul(fac[i-1],i,M);
}
inv[fac_size]=inverse(fac[fac_size],M);
for(int i=fac_size;i>0;i--){
inv[i-1]=mod_mul(inv[i],i,M);
}
}
ll C(ll n,ll r){
ll val=1LL*(fac[n]*inv[r]%M*inv[n-r]%M);
return val;
}
void solve(){
int n,m;
cin >> n >> m;
ll ans = C(m,n-1);
ans = mod_mul(ans,n-2,M);
dbg(ans);
ll ways = expo(2,n-3,M);
ans = mod_mul(ans,ways,M);
cout << ans << endl;
}
int main(){
fast;
int t=1;
Cal_Factorial();
// cin>>t;
while(t--){
#ifndef ONLINE_JUDGE
freopen("error.txt", "w", stderr);
#endif
solve();
}
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"
] |
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 200000;
int ans[MAX_N + 5];
int main()
{
int tc;
cin >> tc;
while (tc--)
{
int n, i, j;
string s;
cin >> n >> s;
int num = n, last = 0;
for (i = 0; i < n; i++)
{
if (i == n - 1 || s[i] == '>')
{
for (j = i; j >= last; j--)
ans[j] = num--;
last = i + 1;
}
}
for (i = 0; i < n; i++)
cout << ans[i] << (i == n - 1 ? '\n' : ' ');
num = 1, last = 0;
for (i = 0; i < n; i++)
{
if (i == n - 1 || s[i] == '<')
{
for (j = i; j >= last; j--)
ans[j] = num++;
last = i + 1;
}
}
for (i = 0; i < n; i++)
cout << ans[i] << (i == n - 1 ? '\n' : ' ');
}
} | cpp |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11. | [
"graphs",
"hashing",
"math",
"number theory"
] | // LUOGU_RID: 101673469
#include<bits/stdc++.h>
#include<unordered_map>
#include<algorithm>
using namespace std;
#define ll long long
#define pii pair<ll,ll>
//struct Edge {
// int from, to, nex;
//}edge[400010];
//int tot, head[200010];
//void add(int u, int v) {
// edge[++tot] = { u,v,head[u] };
// head[u] = tot;
//}
const ll mod = 998244353;
ll qpow(ll x, ll y) {
ll res = 1;
while (y) {
if (y & 1) res = (x * res) % mod;
x = x * x % mod;
y >>= 1;
}
return res;
}
ll n,m;
ll gcd(ll a, ll b) {
return b ? gcd(b, a % b) : a;
}
void solve()
{
cin >> n >> m;
vector<ll> a(n + 1);
vector<set<int>> s(n + 1);
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
s[v].insert(u);
}
map<set<int>, ll> mp;
for (int i = 1; i <= n; i++) {
if(!s[i].empty()) mp[s[i]] += a[i];
}
ll ans = 0;
for (auto i : mp) {
if (ans) ans = gcd(ans, i.second);
else ans = i.second;
}
cout << ans << '\n';
}
signed main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int tt = 1;
cin >> tt;
while (tt--) solve();
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>
using namespace std;
#define int long long
struct segtree
{
vector<int> v;
vector<int> ops;
void init(int n)
{
int curr=1;
while(curr<n){curr=curr*2;}
for(int i=0;i<2*curr;i++)
{
v.push_back(0);
ops.push_back(0);
}
}
void update(int lx,int rx,int curr,int l,int r,int z)
{
//Add z from l to r
if(lx>=l && rx<=r){v[curr]+=z;ops[curr]+=z;return;}
if(lx>=r || l>=rx){return ;}
int m=(lx+rx)/2;
update(lx,m,2*curr+1,l,r,z);
update(m,rx,2*curr+2,l,r,z);
v[curr]=max(v[2*curr+1],v[2*curr+2])+ops[curr];
}
int getans(int lx,int rx,int curr,int l,int r)
{
if(lx>=l && rx<=r){return v[curr];}
if(l>=rx || lx>=r){return -1e12;}
int m=(lx+rx)/2;
auto a=max(getans(lx,m,2*curr+1,l,r),getans(m,rx,2*curr+2,l,r));
return a+ops[curr];
}
};
int32_t main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n,m,p;
cin>>n>>m>>p;
pair<int,int> a[n];
for(int i=0;i<n;i++){cin>>a[i].first>>a[i].second;}
sort(a,a+n);
pair<int,int> b[m];
for(int i=0;i<m;i++){cin>>b[i].first>>b[i].second;}
sort(b,b+m);
tuple<int,int,int> c[p];
for(int i=0;i<p;i++)
{
int x,y,z;
cin>>x>>y>>z;
c[i]={x,y,z};
}
sort(c,c+p);
struct segtree st;
st.init(m);
for(int i=0;i<m;i++)
{
st.update(0,m,0,i,i+1,-b[i].second);
}
int curr=0;
int ans=-1e18;
for(int i=0;i<n;i++)
{
while(curr<p && (get<0>)(c[curr])<a[i].first)
{
int x=(get<0>)(c[curr]);
int y=(get<1>)(c[curr]);
int z=(get<2>)(c[curr]);
int ax=lower_bound(b,b+m,make_pair(y+1,(int)(-1)))-b;
st.update(0,m,0,ax,m,z);
curr++;
}
ans=max(ans,st.getans(0,m,0,0,m)-a[i].second);
}
cout<<ans;
}
| 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"
] | // LUOGU_RID: 98653475
#include <bits/stdc++.h>
using namespace std;
using i64=long long;
using u64=unsigned long long;
using db=double;
using vi=vector<int>;
using pii=pair<int,int>;
template<typename T>
inline T read(){
T x=0,f=0;char ch=getchar();
while(!isdigit(ch)) f|=(ch=='-'),ch=getchar();
while(isdigit(ch)) x=(x*10)+(ch^48),ch=getchar();
return !f?x:-x;
}
#define rdi read<int>
#define rdi64 read<i64>
#define fi first
#define se second
#define mp make_pair
#define pb push_back
const int N=5e5+10;
int n,m;
vi e[N];
pii p[N];
int f[N],siz[N],son[N],dep[N];
void dfs(int x,int fa){
f[x]=fa,siz[x]=1,dep[x]=dep[fa]+1;
for(auto y:e[x]){
if(y==fa) continue;
dfs(y,x);
siz[x]+=siz[y];
if(siz[y]>siz[son[x]]) son[x]=y;
}
}
int dfn[N],low[N],ti,seq[N];
int top[N];
void dfs1(int x,int tp){
top[x]=tp,dfn[x]=++ti,seq[ti]=x;
if(son[x]) dfs1(son[x],tp);
for(auto y:e[x]){
if(y==f[x]||y==son[x]) continue;
dfs1(y,y);
}
low[x]=ti;
}
int LCA(int x,int y){
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]]) swap(x,y);
x=f[top[x]];
}
return dep[x]<dep[y]?x:y;
}
int g_son(int x,int y){
while(dep[x]<dep[f[top[y]]]) y=f[top[y]];
return top[x]==top[y]?son[x]:top[y];
}
struct Dsu{
int f[N*2];
void init(int n) {iota(f+1,f+n+1,1);}
int find(int x) {return x==f[x]?x:f[x]=find(f[x]);}
void merge(int x,int y) {f[find(y)]=find(x);}
}d;
void merge(int x,int y,bool rev){
d.merge(x*2,y*2+rev),d.merge(x*2+1,y*2+(rev^1));
}
int subv[N],subv1[N],bl[N],typ[N];
void dfs2(int x){
for(auto y:e[x]){
if(y==f[x]) continue;
dfs2(y);
subv[x]+=subv[y],subv1[x]+=subv1[y];
}
if(subv[x]>0) merge(x,f[x],0);
}
int c[N];
bool dfs_c(int x,int k){
int L=1,R=k;
for(auto y:e[x]){
if(y==f[x]) continue;
if(!dfs_c(y,k)) return false;
if(bl[y]&&bl[y]==bl[x]){
if(typ[x]^typ[y]) R=min(R,k-c[y]);
else L=max(L,c[y]+1);
}
}
static vi vec[N];
for(auto y:e[x])
if(y!=f[x]&&bl[y]&&bl[y]!=bl[x])
vec[bl[y]].pb(y);
if(L>R) return false;
int l1=1,r1=k;
for(auto y:e[x]){
if(bl[y]&&!vec[bl[y]].empty()){
vi &v=vec[bl[y]];
int l=1,r=k;
for(auto y:v){
if(typ[y]) r=min(r,k-c[y]);
else l=max(l,c[y]+1);
}
v.clear();
if(l>r) return false;
pii p=min((pii){l,r},(pii){k+1-r,k+1-l});
if(p.se>=(k+1)/2) L=max(L,p.fi),R=min(R,k+1-p.fi);
else l1=max(l1,p.fi),r1=min(r1,p.se);
}
}
if(l1>r1) return false;
if(max(L,l1)<=min(R,r1)) {c[x]=max(L,l1);return true;}
else if(max(L,k+1-r1)<=min(R,k+1-l1)) {c[x]=max(L,k+1-r1);return true;}
return false;
}
int res[N];
void construct(int x,int k,bool fl){
res[x]=(fl?k+1-c[x]:c[x]);
for(auto y:e[x]){
if(y==f[x]) continue;
if(bl[y]&&bl[y]==bl[x])
construct(y,k,fl^(typ[x]^typ[y]));
else if(!bl[y])
construct(y,k,0);
}
static vi vec[N];
for(auto y:e[x])
if(y!=f[x]&&bl[y]&&bl[y]!=bl[x])
vec[bl[y]].pb(y);
static bool tmp[N];
for(auto y:e[x]){
if(bl[y]&&!vec[bl[y]].empty()){
vi &v=vec[bl[y]];
int l=1,r=k;
for(auto y:v){
if(typ[y]) r=min(r,k-c[y]);
else l=max(l,c[y]+1);
}
for(auto y:v)
tmp[y]=(l<=res[x]&&res[x]<=r)?typ[y]:typ[y]^1;
v.clear();
}
}
for(auto y:e[x])
if(y!=f[x]&&bl[y]&&bl[y]!=bl[x])
construct(y,k,tmp[y]);
}
void solve(){
dfs(1,0),dfs1(1,1);
d.init(2*n+1);
for(int i=1;i<=m;i++){
int x=p[i].fi,y=p[i].se,lc=LCA(x,y);
int sx=g_son(lc,x),sy=g_son(lc,y);
subv1[x]++,subv1[y]++,subv1[lc]-=2;
if(x!=lc) subv[x]++,subv[sx]--;
if(y!=lc) subv[y]++,subv[sy]--;
if(x!=lc&&y!=lc) merge(sx,sy,1);
}
dfs2(1);
bl[1]=0;
for(int i=2;i<=n;i++){
int x=i*2,y=i*2+1;
if(d.find(x)==d.find(y)) {puts("-1");exit(0);}
if(subv1[i]) bl[i]=d.find(x)/2,typ[i]=d.find(x)&1;
else bl[i]=0;
}
int l=1,r=n;
while(l<r){
int mid=(l+r)/2;
if(dfs_c(1,mid)) r=mid;
else l=mid+1;
}
dfs_c(1,l),construct(1,l,0);
cout<<l<<'\n';
for(int i=1;i<=n;i++)
cout<<res[i]<<' ';
cout<<'\n';
}
int main(){
n=rdi(),m=rdi();
for(int i=1;i<n;i++){
int x=rdi(),y=rdi();
e[x].pb(y),e[y].pb(x);
}
for(int i=1;i<=m;i++){
int x=rdi(),y=rdi();
p[i]={x,y};
}
solve();
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>
using namespace std;
#define int long long
const int mod = 1e9 + 7;
//const int mod = 998244353;
#define PII pair<long long, long long>
#define x first
#define y second
#define pi 3.14159265359
int qpow(int a, int b)
{
int res = 1;
while (b != 0)
{
if (b & 1)res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
int _qpow(int a, int b)
{
int res = 1;
while (b != 0)
{
if (b & 1)res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
int inv(int a)
{
return qpow(a, mod - 2);
}
int exgcd(int ai, int bi, int& xi, int& yi)
{
if (bi == 0)
{
xi = 1, yi = 0;
return ai;
}
int d = exgcd(bi, ai % bi, yi, xi);
yi -= ai / bi * xi;
return d;
}
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
/*----------------------------------------------------------------------*/
bool st[200005];
int cnt;
int primes[200005];
int phi[200005];
void getPrime(int n)
{
for (int i = 2; i <= n; i++)
{
if (!st[i])primes[cnt++] = i, phi[i] = i - 1;
for (int j = 0; primes[j] * i <= n; j++)
{
st[primes[j] * i] = 1;
if (i % primes[j])phi[primes[j] * i] = phi[i] * primes[j] * (primes[j] - 1) * primes[j];
else
{
phi[i * primes[j]] = phi[i] * primes[j];
break;
}
}
}
}
void solve()
{
int a, m;
cin >> a >> m;
int d = gcd(a, m);
int tmp = m / d;
int res = tmp;
for (int i = 0; i < cnt; i++)
{
if (tmp % primes[i] == 0)
{
res = res / primes[i] * (primes[i] - 1);
while (tmp % primes[i] == 0)
{
tmp /= primes[i];
}
}
}
if (tmp != 1)res = res / tmp * (tmp - 1);
cout << res << "\n";
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tt = 1;
getPrime(2e5);
cin >> tt;
while (tt--)solve();
return 0;
} | cpp |
1304 | F1 | F1. Animal Observation (easy 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 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≤min(m,20)1≤k≤min(m,20)) – 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"
] | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = tuple<int, int>;
using vii = vector<ii>;
using vi = vector<ll>;
using vvi = vector<vi>;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
ll n, m, k;
cin >> n >> m >> k;
vvi a(n+1, vi(m+1));
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j], a[i][j] += a[i][j-1];
vvi dp(n+1, vi(m+1));
vii b(1, {0, m+2}), c;
for (ll i = 1; i <= n; i++) {
for (ll j = 1; j <= m; j++) {
ll r = j+k-1;
if (r > m) r = m;
ll bs = a[i][r] - a[i][j-1];
if (i < n) bs += a[i+1][r] - a[i+1][j-1];
for (ii z : b) {
ll w, l;
tie(w, l) = z;
ll s = bs;
s += w;
if (s <= dp[i][j]) break;
ll li = max(l, j);
ll ri = min(l+k-1, r);
if (li <= ri) s -= a[i][ri] - a[i][li-1];
if (s > dp[i][j]) dp[i][j] = s;
if (li > ri) break;
}
c.push_back({dp[i][j], j});
}
sort(c.begin(), c.end(), greater<ii>());
swap(b, c);
c.clear();
}
cout << get<0>(b[0]) << '\n';
} | 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<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=500+5;
string inp[N];
// vll adj[N]; ///for graph(or tree) use this !!-><-!!
int dp[N][N][N];
void ok_boss()
{
int n,m,qq;
cin >> n>>m>>qq;
f(i,0,n)
{
inp[i].clear();
cin>>inp[i];
debug(inp[i]);
}
ms(dp,0);
f(ssz,2,min(n,m)+1)
{
f(i,0,n-ssz+1)
{
f(j,0,m-ssz+1)
{
dp[i][j][ssz]=max(dp[i][j][ssz],dp[i][j][ssz-1]);
dp[i][j][ssz]=max(dp[i][j][ssz],dp[i+1][j][ssz-1]);
dp[i][j][ssz]=max(dp[i][j][ssz],dp[i][j+1][ssz-1]);
dp[i][j][ssz]=max(dp[i][j][ssz],dp[i+1][j+1][ssz-1]);
bool good=0;
if(dp[i+1][j+1][ssz-2]==ssz-2)
{
debug(i);
debug(j);
debug(ssz);
good=1;
ll mmid=(ssz>>1ll);
{
f(ok,j,j+ssz)
{
if((ok<(mmid+j) && inp[i][ok]!='R') || (ok>=(mmid+j) && inp[i][ok]!='G'))
{
good=0;
break;
}
}
}
debug(good);
{
f(ok,i,i+ssz)
{
if((ok<(mmid+i) && inp[ok][j]!='R') || (ok>=(mmid+i) && inp[ok][j]!='Y'))
{
good=0;
break;
}
}
}
debug(good);
{
f(ok,j,j+ssz)
{
if((ok<(mmid+j) && inp[i+ssz-1][ok]!='Y') || (ok>=(mmid+j) && inp[i+ssz-1][ok]!='B'))
{
good=0;
break;
}
}
}
debug(good);
{
f(ok,i,i+ssz)
{
if((ok<(mmid+i) && inp[ok][j+ssz-1]!='G') || (ok>=(mmid+i) && inp[ok][j+ssz-1]!='B'))
{
good=0;
break;
}
}
}
}
debug(good);
if(good)
{
dp[i][j][ssz]=ssz;
}
}
}
}
int r1,c1,r2,c2;
while(qq--)
{
cin>>r1>>c1>>r2>>c2;
r1--,r2--,c1--,c2--;
int sqq=min(r2-r1,c2-c1)+1;
int anss=0;
if(r2-r1+1==sqq)
{
f(i,c1,c2-sqq+2)
{
anss=max(anss,dp[r1][i][sqq]);
}
}
else
{
f(i,r1,r2-sqq+2)
{
anss=max(anss,dp[i][c1][sqq]);
}
}
c1(anss*anss);
}
}
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 |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long int
void solve()
{
int n, k;
cin >> n >> k;
vector<string> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
int ans = 0;
string text = "SET";
for (int i = 0; i < n; i++)
{
map<string, int> mp;
for (int j = i + 1; j < n; j++)
mp[a[j]]++;
for (int j = i + 1; j < n; j++)
{
mp[a[j]]--;
string t;
for (int w = 0; w < k; w++)
{
if (a[i][w] == a[j][w])
t.push_back(a[j][w]);
else
{
for (int m = 0; m < 3; m++)
{
if (a[i][w] != text[m] && a[j][w] != text[m])
{
t.push_back(text[m]);
}
}
}
}
ans += mp[t];
}
}
cout << ans;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
// cin >> t;
while (t--)
{
solve();
cout << "\n";
}
return 0;
} | cpp |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | [
"greedy"
] | #include<bits/stdc++.h>
using namespace std;
signed main(){
int x,i,j,m=0,n=0;
cin>>x;
int a[2*x]={0};
for(i=0;i<2*x;i++){
cin>>a[i];
}
for(i=0;i<x;i++){
if(a[i]>a[x+i]) m++;
if(a[i]<a[i+x]) n++;
}
if(m==0) cout<<-1<<endl;
else cout<<n/m+1<<endl;
}
| cpp |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | /*
* Solution author: Mahmud-Sayed
* while(days) keep_going();
*/
#include <bits/stdc++.h>
using namespace std;
#define GO_FASTER ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define TC int TT;cin >> TT;while(TT--)
#define el '\n'
#define all(v) v.begin(), v.end()
#define allr(v) v.rbegin() , v.rend()
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pair<int , int>> vpii;
typedef map<string , int> mpsi;
typedef map<int , int> mpii;
typedef map<int , string> mpis;
typedef map<int , char> mpic;
typedef map<char, int> mpci;
const int N = 2e5 + 6;
int a[N], ans[N];
int main(){
GO_FASTER
TC {
int n;
cin >> n;
for (int i = 0; i < 2 * n; i++) {
cin >> a[i];
}
sort(a, a + 2*n);
cout << a[n] - a[n - 1] << el;
}
return 0;
}
| cpp |
1305 | E | E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5) | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int tt, tc;
void solve() {
int n; ll m;
cin >> n >> m;
if (m == 0) {
for (int i = 1; i <= n; i++) cout << 3 * i + 1 << " ";
cout << "\n";
return;
}
vector<ll> a(n + 1);
ll sum = 0;
bool did_find = false;
for (int i = 1; i <= n; i++) {
sum += (ll)(i - 1) / 2;
if (m < sum) {
did_find = true;
sum -= (ll)(i - 1) / 2;
a[i] = 2 * i - 1 - 2 * (m - sum);
for (int j = i + 1; j <= n; j++) a[j] = (ll)(1e8) + 1 + (ll)(1e4) * 1LL * j;
break;
}
a[i] = i;
}
if (!did_find && m > sum) return void(cout << -1 << "\n");
for (int i = 1; i <= n; i++) cout << a[i] << " ";
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
tt = 1, tc = 1; // cin >> tt;
while (tt--) solve(), tc++;
}
| cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.