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 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
| [
"constructive algorithms",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define w(t) int t;cin >> t; while(t--)
#define ll long long
#define get_arr(x,o,n) for(int i=o;i<n;i++){cin >> x[i];}
#define fr(i,x,y) for(int i=x;i<y;i++)
#define fr_rev(i,x,y) for(int i=x;i>y;i--)
#define sz(x) x.size()
#define sp " "
#define vsort(v) sort(v.begin(),v.end())
#define vsort_rev(v) sort(v.begin(),v.end(), greater<int>())
#define pb push_back
#define vi vector<int>
#define br cout << endl;
#define prints(v) for(auto u:v)cout << u << sp;
#define print(v) for(auto u:v)cout << u ;
#define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL));
bool compare(int a ,int b)
{
return a > b ? true : false;
}
void solve(){
}
int main(int argc, char const *argv[])
{
fastread()
w(t)
{
int n;
cin >> n;
vector<int>v(n);
get_arr(v,0,n);
vsort_rev(v);
prints(v);br
}
} | 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"
] | //**Template_begin**//
#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;
typedef tree<long long, null_type, less<long long>, rb_tree_tag, tree_order_statistics_node_update> pbds; // find_by_order, order_of_key
#define ll long long
#define ld long double
#define int unsigned int
#define inf 1000000000000000005
#define mod 1000000007
typedef pair<int, int> pii;
typedef vector<int> vii;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
#define pb push_back
#define ppb pop_back
#define puf push_front
#define pof pop_front
#define lb lower_bound
#define ub upper_bound
#define fi first
#define se second
#define sz(x) (ll)x.size()
#define _BENZ_ ios_base::sync_with_stdio(false);cin.tie(NULL);
const int N = 1e6 + 10;
// std::cout << std::fixed;
// std::cout << std::setprecision(12);
// floor(2.3)
// ceil(2.3)
//******//
//**Template_end***//
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
}; // unordered_map<ll , ll , custom_hash> mp;
ll expo(ll a, ll b, ll mod1) {ll res = 1; while (b > 0) {if (b & 1ll)res = (res * a) % mod1; a = (a * a) % mod1; b = b >> 1ll;} return res;}
vector<vll> adj1 , adj2;
void solve(){
ll n , m;
cin >> n >> m;
adj1.assign(n + 5ll , {});
adj2.assign(n + 5ll , {});
for(ll i = 1; i <= m; ++i) {
ll x , y;
cin >> x >> y;
adj1[x].pb(y);
adj2[y].pb(x);
}
ll k;
cin >> k;
vll v(k + 5ll , 0ll);
for(ll i = 1; i <= k; ++i) {
cin >> v[i];
}
ll start = v[k];
vll dis(n + 5ll , -1ll);
queue<ll> qu;
qu.push(start);
dis[start] = 0ll;
while(sz(qu)) {
ll fr = qu.front();
qu.pop();
for(auto &it : adj2[fr]) {
if(dis[it] != -1ll) continue;
dis[it] = dis[fr] + 1ll;
qu.push(it);
}
}
ll ans_mx = 0ll , ans_mn = 0ll;
// for(ll i = 1; i <= n; ++i) {
// cout << dis[i] << " ";
// }
// cout << "\n";
vll vis(n + 5ll , 0ll);
for(ll i = 1; i <= k - 1ll; ++i) {
vis[v[i]] = 1ll;
if (dis[v[i]] != dis[v[i + 1]] + 1)
++ans_mn;
for(auto &it : adj1[v[i]]) {
if(it == v[i + 1ll]) continue;
// if(vis[it]) continue;
if(dis[it] <= dis[v[i + 1ll]]) {
ans_mx++;
break;
}
}
}
cout << ans_mn << " " << ans_mx << "\n";
}
int32_t main(){
_BENZ_
ll t = 1;
// cin >> t;
while(t--){
solve();
}
// cout << "HELLO " << "\n";
/*
Think of the edge case (n == 1 ?).
Don't get stuck on a single approach for a long time.
Also don't get stuck on a single problem for a long time :).
*/
return 0;
}
/*
*/
| cpp |
1286 | E | E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
OutputCopy1
2
4
5
7
9
12
InputCopy4
a 2
y 2
z 0
y 2
OutputCopy2
2
2
2
InputCopy5
a 7
u 5
t 3
s 10
s 11
OutputCopy7
9
11
12
13
NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313. | [
"data structures",
"strings"
] | #define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 600010, M = N << 1;
const ll mod = 1e18;
int n;
ll w[N], s[N];
int pr[N], ne[N];
int col[N], fa[N][28];
int minn[N << 3];
void pushup(int p)
{
minn[p] = min(minn[p << 1], minn[p << 1 | 1]);
}
void segchg(int p, int l, int r, int pos, int k)
{
if(l == r)
{
minn[p] = k;
return;
}
int mid = (l + r) >> 1;
if(pos <= mid)segchg(p << 1, l, mid, pos, k);
else segchg(p << 1 | 1, mid + 1, r, pos, k);
pushup(p);
}
int segmin(int p, int l, int r, int ql, int qr)
{
if(ql <= l && r <= qr)return minn[p];
int mid = (l + r) >> 1;
int res = 2e9;
if(ql <= mid)res = min(res, segmin(p << 1, l, mid, ql, qr));
if(qr > mid)res = min(res, segmin(p << 1 | 1, mid + 1, r, ql, qr));
return res;
}
map<ll, int>bib;
ll sum;
void add(ll x, int k)
{
bib[x] += k;
sum += x * k;
}
ll sta[N], tt;
int update(int x)
{
int res = 0; tt = 0;
for(auto it = bib.upper_bound(x); it != bib.end(); it++)
{
sta[++tt] = it->first;
res += it->second;
sum -= it->first * it->second;
}
while(tt)bib.erase(sta[tt--]);
return res;
}
ll ansh, ansl;
ll ans26, ansb;
void addans(ll x)
{
ansl += x;
if(ansl >= mod)ansl -= mod, ansh++;
ans26 = (ans26 + x) % 26;
ansb = (ansb + x) & ((1 << 30) - 1);
}
void print()
{
if(ansh == 0)printf("%lld\n", ansl);
else printf("%lld%018lld\n", ansh, ansl);
}
char c[5];
int main()
{
scanf("%d", &n);
scanf("%s%d", c, &w[1]);
s[1] = c[0] - 'a';
segchg(1, 1, n, 1, w[1]);
addans(w[1]);
print();
for(int i = 2, j = 0; i <= n; i++)
{
scanf("%s%d", c, &w[i]);
s[i] = (c[0] - 'a' + ans26) % 26;
w[i] ^= ansb;
if(s[1] == s[i])add(w[i], 1);
segchg(1, 1, n, i, w[i]);
addans(segmin(1, 1, n, 1, i));
j = ne[i - 1];
while(j && s[j + 1] != s[i])j = ne[j];
ne[i] = j + (s[j + 1] == s[i]), col[i - 1] = s[i];
for(int j = 0; j < 26; j++)fa[i][j] = fa[ne[i]][j];
fa[i][col[ne[i]]] = ne[i];
for(int c = 0; c < 26; c++)
{
if(c == s[i])continue;
for(int j = fa[i - 1][c]; j; j = fa[j][c])
add(segmin(1, 1, n, i - j, i - 1), -1);
}
add(w[i], update(w[i]));
addans(sum);
print();
}
return 0;
} | 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"
] | // LUOGU_RID: 99710629
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define mod 998244353
struct mat{
int p[3][3];
mat operator*(const mat&a){
mat nw;
nw.p[1][1]=(p[1][1]*a.p[1][1]+p[1][2]*a.p[2][1])%mod;
nw.p[1][2]=(p[1][1]*a.p[1][2]+p[1][2]*a.p[2][2])%mod;
nw.p[2][1]=(p[2][1]*a.p[1][1]+p[2][2]*a.p[2][1])%mod;
nw.p[2][2]=(p[2][1]*a.p[1][2]+p[2][2]*a.p[2][2])%mod;
return nw;
}
};
mat g[1000001];
int qpow(int a,int k){
int ans=1;
while(k){
if(k&1)ans=ans*a%mod;
k>>=1;a=a*a%mod;
}
return ans;
}
#define mid(l,r) ((l+r)>>1)
void modify(int l,int r,int t,mat s,int id){
if(l==r){
g[id]=s;
return ;
}
if(t<=mid(l,r))modify(l,mid(l,r),t,s,id*2);
else modify(mid(l,r)+1,r,t,s,id*2+1);
g[id]=g[id*2+1]*g[id*2];
return ;
}
mat query(int l,int r,int t,int id){
if(l==r)return g[id];
if(t<=mid(l,r))return query(l,mid(l,r),t,id*2);
return query(mid(l,r)+1,r,t,id*2+1);
}
struct pr{
int x,y,type,l;
}w[700001];
int pos[300001];
int v[300001];
int c[300001];
int ptr=0;
int inv=qpow(100,mod-2);
void build(int l,int r,int id){
if(l==r){
g[id].p[1][1]=(100-c[l])*inv%mod;
g[id].p[1][2]=(100-c[l])*inv%mod;
g[id].p[2][1]=c[l]*inv%mod;
g[id].p[2][2]=c[l]*inv%mod;
return ;
}
build(l,mid(l,r),id*2);build(mid(l,r)+1,r,id*2+1);
g[id]=g[id*2+1]*g[id*2];
return ;
}
signed main(){
int n;cin>>n;
for(int i=1;i<=n;i++)cin>>pos[i]>>v[i]>>c[i];
for(int i=2;i<=n;i++){
if(c[i]!=100 and c[i-1]!=0)w[++ptr]={pos[i]-pos[i-1],v[i]+v[i-1],0,i};
if(v[i]!=v[i-1]){
if(v[i]>v[i-1] and (c[i]==100 or c[i-1]==100))continue;
if(v[i]<v[i-1] and (c[i]==0 or c[i-1]==0))continue;
w[++ptr]={pos[i]-pos[i-1],abs(v[i]-v[i-1]),1,i};
}
}
sort(w+1,w+1+ptr,[](pr a,pr b){return a.x*b.y<a.y*b.x;});
build(1,n,1);
int ans=0;
for(int i=1;i<=ptr;i++){
mat a=query(1,n,w[i].l-1,1);
mat b=query(1,n,w[i].l,1);
mat tmp=a,tmp2=b;
if(w[i].type==0){
b.p[1][2]=0;
tmp.p[1][1]=0;tmp.p[1][2]=0;
tmp2.p[2][1]=0;tmp2.p[2][2]=0;
}else{
if(v[w[i].l-1]<v[w[i].l]){
b.p[1][1]=0;
tmp.p[2][1]=0;tmp.p[2][2]=0;
tmp2.p[2][1]=0;tmp2.p[2][2]=0;
}else{
b.p[2][2]=0;
tmp.p[1][1]=0;tmp.p[1][2]=0;
tmp2.p[1][1]=0;tmp2.p[1][2]=0;
}
}
modify(1,n,w[i].l-1,tmp,1);modify(1,n,w[i].l,tmp2,1);
ans=(ans+(g[1].p[1][1]+g[1].p[2][1])*(w[i].x*qpow(w[i].y,mod-2)%mod))%mod;
modify(1,n,w[i].l-1,a,1);modify(1,n,w[i].l,b,1);
}
if(ans<0)ans+=mod;
cout<<ans<<endl;
return 0;
} | cpp |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | #include<bits/stdc++.h>
#define ll long long
#define int long long
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rrep(i,a,b) for(int i=a;i>=b;i--)
#define repin rep(i,0,n)
#define di(a) int a;cin>>a;
#define precise(i) cout<<fixed<<setprecision(i)
#define vi vector<int>
#define si set<int>
#define mii map<int,int>
#define take(a,n) for(int j=0;j<n;j++) cin>>a[j];
#define give(a,n) for(int j=0;j<n;j++) cout<<a[j]<<' ';
#define vpii vector<pair<int,int>>
#define sis string s;
#define sin string s;cin>>s;
#define db double
#define be(x) x.begin(),x.end()
#define pii pair<int,int>
#define pb push_back
#define pob pop_back
#define ff first
#define ss second
#define lb lower_bound
#define ub upper_bound
#define bpc(x) __builtin_popcountll(x)
#define btz(x) __builtin_ctz(x)
using namespace std;
const long long INF=1e18;
const long long M=1e9+7;
const long long MM=998244353;
int power( int N, int M){
int power = N, sum = 1;
if(N == 0) sum = 0;
while(M > 0){if((M & 1) == 1){sum *= power;}
power = power * power;M = M >> 1;}
return sum;
}
const int N =200005;
vector<int> adj[N];
vector<int> bfs(int n,int s){
queue<int> q;
vector<bool> used(n+1);
vector<int> d(n+1), p(n+1);
q.push(s);
used[s] = true;
p[s] = -1;
while (!q.empty()) {
int v = q.front();
q.pop();
for (int u : adj[v]) {
if (!used[u]) {
used[u] = true;
q.push(u);
d[u] = d[v] + 1;
p[u] = v;
}
}
}
return d;
}
pair<vector<int>, vector<int>> bfs1(int n,int s){
queue<int> q;
vector<int> used(n+1);
vector<int> d(n+1), p(n+1);
q.push(s);
used[s] = true;
p[s] = -1;
while (!q.empty()) {
int v = q.front();
q.pop();
for (int u : adj[v]) {
if (!used[u]) {
used[u] = true;
q.push(u);
d[u] = d[v] + 1;
p[u] = v;
}
}
}
return {used,p};
}
vi path(int u,vector<int> used,vector<int> p){
// if (!used[u]) {
// cout << "No path!";
// } else {
vector<int> path;
for (int v = u; v != -1; v = p[v])
path.push_back(v);
reverse(path.begin(), path.end());
return path;
// }
}
void solve()
{
di(n)
rep(i,0,n-1){
di(u) di(v)
adj[u].pb(v);
adj[v].pb(u);
}
int temp = 0;
int p = -1;
vi d = bfs(n,1);
rep(i,1,n+1){
if(d[i]>p){p=d[i];temp=i;}
}
vi ans;
ans.pb(temp);
int res = 0;
d=bfs(n,temp);
auto y = bfs1(n,temp);
temp = 0;
p = -1;
rep(i,1,n+1){
if(d[i]>p){p=d[i];temp=i;}
}
res+=d[temp];
ans.pb(temp);
// cout<<res<<"\n";
// for(auto x : ans){cout<<x<<" ";}cout<<"\n";
vi f = path(temp,y.ff,y.ss);
queue<int> q;
vector<int> used(n+1);
vector<int> d1(n+1);
for(auto s : f){
q.push(s);
used[s] = true;
}
while (!q.empty()) {
int v = q.front();
q.pop();
for (int u : adj[v]) {
if (!used[u]) {
used[u] = true;
q.push(u);
d1[u] = d1[v] + 1;
// p[u] = v;
}
}
}
temp = 0;
p = -1;
rep(i,1,n+1){
if(d1[i]>p && i!=ans[0] && i!=ans[1]){p=d1[i];temp=i;}
}
res+=d1[temp];
ans.pb(temp);
cout<<res<<"\n";
for(auto x : ans){cout<<x<<" ";}cout<<"\n";
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef NCR
init();
#endif
#ifdef SIEVE
sieve();
#endif
solve();
return 0;
} | cpp |
1301 | D | D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running): | [
"constructive algorithms",
"graphs",
"implementation"
] | #include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
// #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
using namespace std;
typedef long long ll;
typedef long double ldb;
typedef vector<int> vi;
typedef vector<long long> vl;
typedef vector<double> vdb;
typedef vector<vector<int>> vvi;
typedef vector<vector<ll>> vvl;
typedef vector<string> vs;
typedef set<int> si;
typedef set<long long> sl;
typedef set<double> sdb;
typedef set<string> ss;
typedef set<char> sc;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define ftb(i, a, b) for (int i = a, _b = b; i <= _b; i++)
#define ft(i, a, b) for (int i = a, _b = b; i < _b; i++)
#define fgb(i, a, b) for (int i = a, _b = b; i >= _b; i--)
#define fg(i, a, b) for (int i = a, _b = b; i > _b; i--)
#define endl "\n"
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m, k;
cin >> n >> m >> k;
vector<pair<int, string>> ans;
//xuoi
int temp = m - 1;
int z = k / 4;
int q = temp / 4;
int mn = min(z, q);
if (mn > 0) {
string l = "RRRR";
ans.push_back({ mn,l });
temp -= mn * 4;
k -= mn * 4;
}
if (k > 0 && temp > 0) {
mn = min(k, temp);
k -= mn;
string l = "";
ft(i, 0, mn) {
l += 'R';
}
ans.push_back({ 1,l });
}
//nguoc
temp = m - 1;
z = k / 4;
q = temp / 4;
mn = min(z, q);
if (mn > 0) {
string l = "LLLL";
ans.push_back({ mn,l });
temp -= mn * 4;
k -= mn * 4;
}
if (k > 0 && temp > 0) {
mn = min(k, temp);
k -= mn;
string l = "";
ft(i, 0, mn) {
l += 'L';
}
ans.push_back({ 1,l });
}
for (int i = 1; i < n;i++) {
if (k > 0) {
ans.push_back({ 1,"D" });
k -= 1;
}
temp = m - 1;
z = k / 4;
q = temp / 4;
mn = min(z, q);
if (mn > 0) {
string l = "RRRR";
ans.push_back({ mn,l });
temp -= mn * 4;
k -= mn * 4;
}
if (k > 0 && temp > 0) {
mn = min(k, temp);
k -= mn;
string l = "";
ft(i, 0, mn) {
l += 'R';
}
ans.push_back({ 1,l });
}
temp = m - 1;
z = k / 3;
mn = min(temp, z);
if (mn > 0) {
string l = "UDL";
ans.push_back({ mn,l });
temp -= mn;
k -= mn * 3;
}
if (k > 0 && temp > 0) {
if (k == 1) {
ans.push_back({ 1,"U" });
k -= 1;
}
else {
k -= 2;
ans.push_back({ 1,"UD" });
}
}
}
if (k > 0) {
temp = n - 1;
z = k / 4;
q = temp / 4;
mn = min(z, q);
if (mn > 0) {
string l = "UUUU";
ans.push_back({ mn,l });
temp -= mn * 4;
k -= mn * 4;
}
if (k > 0 && temp > 0) {
mn = min(k, temp);
k -= mn;
string l = "";
ft(i, 0, mn) {
l += 'U';
}
ans.push_back({ 1,l });
}
}
if (k > 0) {
cout << "NO" << endl;
}
else {
cout << "YES" << endl;
cout << ans.size() << endl;
for (auto it : ans) {
cout << it.first << " " << it.second << endl;
}
}
return 0;
}
| cpp |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | #include <bits/stdc++.h>
using namespace std;
#define ll long long
void solution()
{
ll int A,B;
cin >> A >> B;
ll int b=9;
ll int count=0;
ll int p=0;
while(b<=B){
count+=A;
p++;
b+=9*pow(10,p);
// cout<<b<<endl;
}
cout<<count<<endl;
}
int main()
{
// Makes input and output fast
ios_base :: sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
// Test cases
int T;
cin>>T;
while(T--)
solution();
return 0;
} | cpp |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main()
{
int s;
cin>>s;
while(s--)
{
int n=3;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
if(a[0]>=4)
{
cout<<"7"<<endl;
continue;
}
if(a[0]==3)
{
cout<<"6"<<endl;
continue;
}
if(a[0]==2)
{
if(a[2]==2)
cout<<"4"<<endl;
else
cout<<"5"<<endl;
continue;
}
if(a[0]==1)
{
if(a[1]==1)
cout<<"3"<<endl;
else
cout<<"4"<<endl;
}
if(a[0]==0)
{
if(a[1]>=2)
{
cout<<"3"<<endl;
continue;
}
if(a[1]==1)
{
cout<<"2"<<endl;
continue;
}
if(a[1]==0)
{
if(a[2]==0)
cout<<"0"<<endl;
else
cout<<"1"<<endl;
continue;
}
}
}
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>
#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<math.h>
#include<map>
#include<algorithm>
#include<set>
#include<unordered_map>
#include <unordered_set>
#define fast ios_base::sync_with_stdio(false),cin.tie(NULL)
#define popcount __builtin_popcount
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define int long long int
typedef long double lld;
#define FOR(i,n) for(int i=0;i<n;i++)
#define yes cout<<"YES"<<endl;
#define no cout<<"NO"<<endl;
#define p0(a) cout << a << " "
#define p1(a) cout << a << endl
#define p2(a, b) cout << a << " " << b << endl
#define p3(a, b, c) cout << a << " " << b << " " << c << endl
#define p4(a, b, c, d) cout << a << " " << b << " " << c << " " << d << endl
#define MOD 1000000007
#define vi vector<int>
#define pii pair<int, int>
#define vii vector<pii>
#define fr front()
#define bk back()
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define max_heap priority_queue <int>
#define min_heap priority_queue <int, vector <int> , greater <int> >
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pair<int, int> > vpii;
typedef unordered_set<int> us;
typedef map<int,int> mp;
//debugging
#ifndef ONLINE_JUDGE
#define debug1(a) cerr <<#a<<" " <<a << endl
#define debug2(a, b) cerr <<#a<<" "<< a << " "<<#b<<" " << b << endl
#define debug3(a, b, c) cerr <<#a<<" "<<a << " "<<#b<<" " << b << " "<<#c<<" " << c << endl
#define debug4(a, b, c, d) cerr << #a<<" "<<a << " " <<#b<<" "<< b << " "<<#c<<" " << c << " "<<#d<<" "<< d << endl
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#define debug2(x,y)
#define debug3(x,y,z)
#define debug4(x,y,z,a)
#endif
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;}
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 << "]";}
template <class T, class V> void _print(multimap <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
//Constants
const long double pi= 3.141592653589793238;
const int INF= 1e18;
const int mod=1e9+7;
//MATHEMATICAL FUNCTIONS
int gcd(int a, int b){if (b == 0)return a;return gcd(b, a % b);} //gcd
int lcm(int a, int b){return (a/gcd(a,b)*b);} //lcm
//sieve
vector<int> sieve(int n) {int*arr = new int[n + 1](); vector<int> 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;}
//binary exponentation
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;}
//CHECK
bool isprime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
bool ispoweroftwo(int n){if(n==0)return false;return (ceil(log2(n)) == floor(log2(n)));}
bool isperfectsquare(int x){if (x >= 0) {int sr = sqrt(x);return (sr * sr == x);}return false;}
int ceils(int x, int y) {return x / y + (x % y > 0);}
// Operator overloads
template<typename T1, typename T2> // cin >> pair<T1, T2>
istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.first >> p.second); }
template<typename T> // cin >> vector<T>
istream& operator>>(istream &istream, vector<T> &v){for (auto &it : v)cin >> it;return istream;}
template<typename T1, typename T2> // cout << pair<T1, T2>
ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.first << " " << p.second); }
template<typename T> // cout << vector<T>
ostream& operator<<(ostream &ostream, const vector<T> &c) { for (auto &it : c) cout << it << " "; return ostream; }
//USEFUL
void printarr(vi arr, int n){FOR(i,n) cout << arr[i] << " ";cout << "\n";}
void solve(){
int n,m,i,j;
cin>>n>>m;
vi arr(n);
cin>>arr;
sort(arr.begin(), arr.end());
int ind=lower_bound(arr.begin(), arr.end(),m)-arr.begin();
if(ind!=n){
if(arr[ind]==m){
cout<<1<<endl;
return;
}
cout<<2<<endl;
return;
}
int val=arr[n-1];
int req=(m+val-1)/val;
cout<<req<<endl;
}
int32_t main()
{
fast;
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t;
t=1;
cin>>t;
while(t--){
// cout<<t;
solve();
}
return 0;
}
| cpp |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | //ashrafsusts19
#include <bits/stdc++.h>
#include <limits>
using namespace std;
typedef long long int lli;
#define prnt(a) cout << a << "\n"
#define prnt2(a, b) cout << a << " " << b << "\n";
#define prnt3(a, b, c) cout << a << " " << b << " " << c << "\n";
#define forp1(a) for (lli i = 0; i < a; i++)
#define forp2(a, b) for (lli i = a; i < b; i++)
#define forf(a, b, c) for (lli i = a; i < b; i += c)
#define forv1(i, a) for (lli i = 0; i < a; i++)
#define forv2(i, a, b) for (lli i = a; i < b; i++)
#define all(x) (x).begin(), (x).end()
#define refill(a, b, c) a.clear();a.resize(b, c);
#define reloc(a, b) a.clear();a.resize(b);
void debug(vector<lli> &lst){
cout << "Debug: ";
for (lli i = 0; i < lst.size(); i++) cout << lst[i] << " ";
cout << "\n";
}
void debug2(string name, vector<lli> &lst)
{
cout << name << ": ";
for (lli i = 0; i < lst.size(); i++) cout << lst[i] << " ";
cout << "\n";
}
lli n;
vector<vector<lli>> roads;
vector<vector<pair<lli, lli>>> premx, sufmx, lmx;
lli a = -1, b = -1, c = -1, mxcnt = 0;
pair<lli, lli> dfs(lli ind, lli parent){
lli rn = roads[ind].size();
premx[ind].resize(rn + 2, {-1, -1});
sufmx[ind].resize(rn + 2, {-1, -1});
lmx[ind].resize(rn, {-1, -1});
pair<lli, lli> mxd = {0, ind};
for (lli i = 0; i < roads[ind].size(); i++){
lli cind = roads[ind][i];
if (cind == parent) continue;
pair<lli, lli> p = dfs(cind, ind);
lmx[ind][i] = p;
premx[ind][i + 1] = p;
sufmx[ind][i + 1] = p;
mxd = max(mxd, p);
}
mxd.first++;
return mxd;
}
void fndfs(lli ind, lli parent, pair<lli, lli> prev){
for (lli i = 0; i < roads[ind].size(); i++){
if (roads[ind][i] == parent){
lmx[ind][i] = prev;
premx[ind][i + 1] = prev;
sufmx[ind][i + 1] = prev;
}
premx[ind][i + 1] = max(premx[ind][i], premx[ind][i + 1]);
}
for (lli i = roads[ind].size(); i >= 0; i--){
sufmx[ind][i] = max(sufmx[ind][i], sufmx[ind][i + 1]);
}
sort(all(lmx[ind]));
reverse(all(lmx[ind]));
lli i;
lli ctot = 0;
for (i = 0; i < roads[ind].size() && i < 3; i++){
ctot += lmx[ind][i].first;
}
if (ctot > mxcnt){
mxcnt = ctot;
a = lmx[ind][0].second;
if (i >= 2){
b = lmx[ind][1].second;
}
else {
b = ind;
}
if (i >= 3){
c = lmx[ind][2].second;
}
}
for (lli i = 0; i < roads[ind].size(); i++){
lli cind = roads[ind][i];
if (cind == parent) continue;
pair<lli, lli> curr = max(prev, max(premx[ind][i], sufmx[ind][i + 2]));
curr.first++;
fndfs(cind, ind, curr);
}
return;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
roads.resize(n);
premx.resize(n);
sufmx.resize(n);
lmx.resize(n);
forp1(n - 1){
lli a, b;
cin >> a >> b;
roads[--a].push_back(--b);
roads[b].push_back(a);
}
dfs(0, -1);
fndfs(0, -1, {0, 0});
prnt(mxcnt);
cout << a + 1 << " " << b + 1 << " ";
if (c == -1){
c = 0;
while (c == a || c == b) c++;
}
cout << c + 1 << "\n";
} | cpp |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | #include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <string>
#define all(a) a.begin(), a.end()
using namespace std;
#define int int64_t
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<int> s(n);
for (int i = 0; i < n; i++) {
cin >> s[i];
}
vector<vector<pair<int, int>>> dp(n, vector<pair<int, int>>(n, {-1, 1e5})); // 1-значение 2-размер
for (int len = 1; len <= n; len++) {
for (int l = 0; l < n - len + 1; l++) {
int r = l + len - 1;
if (len == 1) {
dp[l][r].first = s[l];
dp[l][r].second = 1;
} else {
for (int m = l; m < r; m++) {
if (dp[l][m].first == dp[m + 1][r].first && dp[l][m].first != -1) {
dp[l][r] = {dp[l][m].first + 1, 1};
} else if (dp[l][m].second + dp[m + 1][r].second < dp[l][r].second) {
dp[l][r]={-1,dp[l][m].second + dp[m + 1][r].second};
}
}
}
}
}
cout << dp[0][n-1].second;
} | 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>
#define I inline
#define ll long long
#define db double
#define lb long db
#define N (60+5)
#define M ((1<<15)+5)
#define K (700+5)
#define mod 1000000007
#define Mod (mod-1)
#define eps (1e-5)
#define ui unsigned int
#define ull unsigned ll
#define Gc() getchar()
#define Me(x,y) memset(x,y,sizeof(x))
#define Mc(x,y) memcpy(x,y,sizeof(x))
#define d(x,y) ((k+1)*(x)+(y))
#define R(n) (rnd()%(n)+1)
#define Pc(x) putchar(x)
#define LB lower_bound
#define UB upper_bound
#define PB push_back
using namespace std;
int n,k,vis[N],Ct,In[N],Fl[N],fa[N],C[N],B[N],Bh,Ch,g[M],W[M],P[N],A[N];ll ToT=1,dp[M],frc[M],Inv[M];
I ll mpow(ll x,int y=mod-2){ll Ans=1;while(y) y&1&&(Ans=Ans*x%mod),y>>=1,x=x*x%mod;return Ans;}
I ll Ps(int x,int y){return frc[x]*Inv[x-y]%mod*Inv[y]%mod;}
I int GF(int x){return fa[x]^x?fa[x]=GF(fa[x]):x;}
int main(){
//freopen("1.in","r",stdin);
int i,j,h,x,y;scanf("%d",&n);for(i=1;i<=n;i++) scanf("%d",A+i),Fl[A[i]]=1;sort(A+1,A+n+1);for(frc[0]=Inv[0]=i=1;i<=60;i++) frc[i]=frc[i-1]*i%mod,Inv[i]=mpow(frc[i]);
for(i=1;i<=n;i++) fa[i]=i;for(i=1;i<=n;i++) for(j=1;j<=n;j++) i^j&&A[i]%A[j]==0&&(In[i]++,fa[GF(i)]=GF(j));
for(i=1;i<=n;i++){if(vis[i]) break;Bh=Ch=0;for(j=1;j<=n;j++) GF(j)==GF(i)&&(vis[j]=1,(In[j]?C[++Ch]:B[++Bh])=A[j]);
if(!Ch) continue;Me(g,0x3f);Me(dp,0);Me(W,0);dp[0]=1;g[0]=0;k=(1<<Bh)-1;
for(j=0;j<=k;j++){Me(P,0);for(h=1;h<=Bh;h++) if(!(j>>(h-1)&1)) for(x=B[h]*2;x<=60;x+=B[h]) P[x]++;for(h=1;h<=Ch;h++) W[j]+=(P[C[h]]>0);}
for(j=0;j<=k;j++){
Me(P,0);for(h=1;h<=Bh;h++) if(!(j>>(h-1)&1)) for(x=B[h]*2;x<=60;x+=B[h]) P[x]++;for(x=1;x<=Ch;x++) if(P[C[x]]){
int op=1;h=j;for(y=1;y<=Bh;y++) if(C[x]%B[y]==0&&!(j>>(y-1)&1)) h|=(1<<y-1);else if(C[x]%B[y]==0) op=0;g[h]>g[j]+op&&(g[h]=g[j]+op,dp[h]=0);
(g[h]==g[j]+op)&&(dp[h]=(dp[j]*Ps(W[j]-1,W[h])%mod*frc[W[j]-1-W[h]]+dp[h])%mod);
}
}ToT=ToT*dp[k]%mod*Ps(Ch-1+Ct,Ct)%mod;Ct+=Ch-1;cerr<<ToT<<' '<<Ct<<'\n';
}printf("%lld\n",ToT);
} | cpp |
1310 | F | F. Bad Cryptographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: Let's fix a finite field and two it's elements aa and bb. One need to fun such xx that ax=bax=b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 22k−122k−1 for some positive integer kk . Bitwise exclusive or (⊕⊕) operation is used as addition. One of ways to define multiplication operation (⊙⊙) is following properties: 0⊙a=a⊙0=00⊙a=a⊙0=0 1⊙a=a⊙1=a1⊙a=a⊙1=a a⊙b=b⊙aa⊙b=b⊙a a⊙(b⊙c)=(a⊙b)⊙ca⊙(b⊙c)=(a⊙b)⊙c a⊙(b⊕c)=(a⊙b)⊕(a⊙c)a⊙(b⊕c)=(a⊙b)⊕(a⊙c) If a=22na=22n for some integer n>0n>0, and b<ab<a, then a⊙b=a⋅ba⊙b=a⋅b. If a=22na=22n for some integer n>0n>0, then a⊙a=32⋅aa⊙a=32⋅a. For example: 4⊙4=64⊙4=6 8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13.8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13. 32⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=14132⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=141 5⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=85⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans;}multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a⊙k=a⊙a⊙⋯⊙ak timesa⊙k=a⊙a⊙⋯⊙a⏟k times.You need to analyze the proposed scheme strength. For pairs of numbers aa and bb you need to find such xx, that a⊙x=ba⊙x=b, or determine that it doesn't exist. InputIn the first line of input there is single integer tt (1≤t≤1001≤t≤100) — number of pairs, for which you need to find the discrete logarithm.In each of next tt line there is a pair of integers aa bb (1≤a,b<2641≤a,b<264). OutputFor each pair you should print one integer xx (0≤x<2640≤x<264), such that a⊙x=ba⊙x=b, or -1 if no such x exists. It can be shown, that if any such xx exists, there is one inside given bounds. If there are several good values, you can output any of them. ExampleInputCopy7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
OutputCopy1
1
2
4
-1
6148914691236517205
68943624821423112
| [
"math",
"number theory"
] | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const ull l = 0xFFFFFFFFFFFFFFFF;
const int p[] = {3, 5, 17, 257, 641, 65537, 6700417}, m[] = {1, 2, 6, 16, 25, 256, 2588}, I[] = {2, 2, 1, 32, 590, 16384, 3883315};
ull F[65][65], T[65][257][257], a, b, ans; int t, r[7];
ull mul(ull, ull) ;
ull mul2(ull a, ull b) {
if (a == 1 || b == 1) return a * b;
if (a < b) swap(a, b);
int x = __builtin_ctzll(a), y = __builtin_ctzll(b), z = 1 << 63 - __builtin_clz(x);
if (y & z) return mul((1ull << z >> 1) * 3, mul2(a >> z, b >> z));
return mul2(a >> z, b) << z;
}
ull mul(ull a, ull b) {
ull x, y, c = 0;
for (ull i=a; i; i^=x) {
x = 1ull << __builtin_ctzll(i);
for (ull j=b; j; j^=y)
y = 1ull << __builtin_ctzll(j), c ^= mul2(x, y);
} return c;
}
ull prod(ull a, ull b) {
ull c = 0;
for (int i=0; i<8; i++)
for (int j=0; j<8; j++)
c ^= T[i<<3|j][a>>(i<<3)&255][b>>(j<<3)&255];
return c;
}
ull qpow(ull x, ull y) {
ull t = 1;
for (; y; y>>=1) {
if (y & 1) t = prod(t, x);
x = prod(x, x);
} return t;
}
int main() {
for (int x=0; x<64; x++)
for (int y=0; y<64; y++)
F[x][y] = mul2(1ull << x, 1ull << y);
for (int i=0; i<8; i++)
for (int j=0; j<8; j++) {
for (int x=0; x<8; x++)
for (int y=0; y<8; y++)
T[i<<3|j][1<<x][1<<y] = F[i<<3|x][j<<3|y];
for (int a=1; a<256; a++)
for (int b=1; b<256; b++)
if (a^a&-a) T[i<<3|j][a][b] = T[i<<3|j][a&-a][b] ^ T[i<<3|j][a^a&-a][b];
else if (b^b&-b) T[i<<3|j][a][b] = T[i<<3|j][a][b&-b] ^ T[i<<3|j][a][b^b&-b];
}
cin >> t;
while (t --) {
scanf ("%llu%llu", &a, &b), ans = 0;
for (int i=0; i<7; i++) {
ull A = qpow(a, l / p[i]), B = qpow(b, l / p[i]), Am = qpow(A, m[i]), P = 1; int res = -1;
unordered_map <ull, int> id;
for (int j=0; j<m[i]; j++)
id[B] = j, B = prod(B, A);
for (int j=0, u=(p[i]-1)/m[i]; j<=u; j++) {
if (id. find(P) != id. end()) {
res = (j * m[i] - id[P] + p[i]) % p[i];
break;
} P = prod(P, Am);
}
if (~ res) r[i] = res;
else { puts ("-1"); goto E; }
}
for (int i=0; i<7; i++)
ans = (ans + (__int128) I[i] * (l / p[i]) * r[i]) % l;
printf ("%llu\n", ans); E : ;
}
} | cpp |
1291 | F | F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"graphs",
"interactive"
] | // LUOGU_RID: 91495277
#include<bits/stdc++.h>
using namespace std;
int const M=1233;int i,j,n,k,Ans,B,Bound,a[M],L[M],R[M];
void clr(){cout<<"R"<<endl;}
bool ask(int x){
cout<<"? "<<x<<endl;
char ch;cin>>ch;
return ch!='Y';
}
void solve(int x){
for (int i=L[x];i<=R[x];i++)
a[i]&=ask(i);
}
int main(){ cin>>n>>k;
for (i=1;i<=n;i++) a[i]=1;
if (k==n){
for (i=1;i<=n;i++) Ans+=ask(i);
return cout<<"! "<<Ans<<endl,0;
}
B=max(1,k/2);Bound=n/B;
for (i=1;i<=Bound;i++) L[i]=R[i-1]+1,R[i]=i*B;
for (i=1;i<Bound;i++)
for (j=i+1;j<=Bound;j++)
solve(i),solve(j),clr();
for (i=1;i<=n;i++) Ans+=a[i];
return cout<<"! "<<Ans<<endl,0;
} | cpp |
1325 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14. | [
"constructive algorithms",
"greedy",
"number theory"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define ld long double
int32_t main()
{
ios_base::sync_with_stdio(false); cin.tie(NULL);
int t; cin>>t;
while(t--)
{
int n; cin>>n;
cout<<1<<" "<<n-1<<endl;
}
}
| 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;
using ll = long long;
using ld = long double;
constexpr int N = int(4e2) + 5;
constexpr int inf = 0x7f7f7f7f;
constexpr int MOD = int(1e9) + 7;
short dp[N][N][N];
string s, t;
short check(short x, short y, short z){
if(x == s.size()){
return z == t.size() ? y : -500;
}
auto& r = dp[x][y][z];
if(r != -1) return r;
r = check(x + 1, y, z);
if(y < t.size() && s[x] == t[y]) r = max(r, check(x + 1, y + 1, z));
if(z < t.size() && s[x] == t[z]) r = max(r, check(x + 1, y, z + 1));
return r;
}
void solve(){
cin >> s >> t;
for(int i = 0; i <= s.size(); i++){
for(int j = 0; j <= t.size(); j++){
for(int k = 0; k <= t.size(); k++){
dp[i][j][k] = -1;
}
}
}
for(short i = 0; i < t.size(); i++){
if(check(0, 0, i + 1) > i){
cout << "YES\n";
return;
}
}
cout << "NO\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
cin >> t;
while(t--){
solve();
}
}
| 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 <iostream>
#include <utility>
#include <cstdlib>
#include <map>
#include <unordered_map>
#include <vector>
#include <queue>
#include <algorithm>
#include <math.h>
#include <set>
#include <array>
#include <iomanip>
#include <stack>
#include <unordered_map>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#include <sstream>
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define yes cout<<"yes"<<endl
#define no cout<<"no"<<endl
#define First cout<<"First"<<endl
#define Second cout<<"Second"<<endl
#define lll __int128
#define int long long
#pragma GCC target ("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC optimization ("unroll-loops")
#define lb(x) (x &-x)
const int N = 100;
vector<vector<int>>dp(N, vector<int>(N, -1));
int ncr(int n, int r)
{
if (n == r)return 1;
if (r == 1)return n;
if (dp[n][r] != -1)return dp[n][r];
return dp[n][r] = ncr(n - 1, r - 1) + ncr(n - 1, r);
}
long double power(long double x, int y)
{
if (y == 0)return 1;
long double k = power(x, y / 2);
return k * k * (y & 1 ? x : 1);
}
long double pr(int n)
{
return ncr(70, n) * power(10.00/70, n) * (power(60.00 / 70, 70 - n));
}
void solver()
{
int n, k;
cin>>n>>k;
int ans = 0;
map<string, int>mp;string s[n] = {};
for (int i = 0; i < n and cin>>s[i]; i ++)mp[s[i]] ++;
for (int i = 0; i < n; i ++)
{
mp[s[i]] --;
for (int j = i + 1; j < n; j ++)
{
mp[s[j]] --;
string s1, s2;
for (int l = 0; l < k; l ++)
{
if (s[i][l] == s[j][l])s1.push_back(s[i][l]);
else
{
string b = "SET";
for (char ch : b)if (s[i][l] != ch && s[j][l] != ch)s1.push_back(ch);
}
}
if (mp.find(s1) != mp.end())ans += mp[s1];
}
for (int j = i + 1; j < n; j ++)mp[s[j]] ++;
}
cout<<ans<<endl;
}
signed main()
{
cin.tie(0)->sync_with_stdio(0);cout.tie(0);
//freopen("outputcut2.in", "r", stdin);
int t;t = 1;
while (t --)
{
solver();
}
}
| cpp |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
| [
"constructive algorithms",
"sortings"
] | #include <iostream>
#include <fstream>
#include <stack>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <array>
#include <bitset>
#include <queue>
#include <cstring>
#include <iomanip>
#define int long long
#define all(v) begin(v), end(v)
#define ve vector
#define vi vector<int>
#define vd vector<double>
#define pb push_back
#define pii pair<int,int>
#define rep(i, n) for(int i = 0; i < (n); i++)
using namespace std;
using ll = long long;
using ull = unsigned long long;
const double pi = atan(1) * 4;
void fast() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cout << fixed; cout.precision(10);
}
void solve() {
int n;
cin >> n;
vi v(n);
for (auto& i : v)
cin >> i;
sort(all(v));
reverse(all(v));
for (int i : v)
cout << i << " ";
cout << "\n";
}
signed main() {
#ifdef LOCAL
freopen("local.in", "r", stdin);
freopen("local.out", "w", stdout);
#endif
fast();
int T = 1;
cin >> T;
while (T--)
solve();
return 0;
} | 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"
] | #ifdef MY_LOCAL
#include "D://competitive_programming/debug/debug.h"
#define debug(x) cerr << "[" << #x<< "]:"<<x<<"\n"
#else
#define debug(x)
#endif
#define REP(i, n) for(int i = 0; i < n; i ++)
#define REPL(i,m, n) for(int i = m; i < n; i ++)
#define SORT(arr) sort(arr.begin(), arr.end())
#define LSOne(S) ((S)&-(S))
#define INF 1e18
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
#define int ll
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<vii> vvii;
typedef double ld;
typedef tree<int,null_type,less<int>, rb_tree_tag, tree_order_statistics_node_update> ost;
ll _sieve_size;
bitset<10000010> bs; // 10^7 is the rough limit
vi p; // compact list of primes
void sieve(ll upperbound) { // range = [0..upperbound]
_sieve_size = upperbound+1; // to include upperbound
bs.set(); // all 1s
bs[0] = bs[1] = 0; // except index 0+1
for (ll i = 2; i < _sieve_size; ++i) if (bs[i]) {
// cross out multiples of i starting from i*i
for (ll j = i*i; j < _sieve_size; j += i) bs[j] = 0;
p.push_back(i); // add prime i to the list
}
}
const int MOD1 = 7909287493;
const int MOD2 = 4302840181;
void solve() {
int n,m;cin>>n>>m;
vi arr(n);
REP(i, n) {
cin>>arr[i];
}
vi indeg(n,0);
vi hsh1(n,1);
vi hsh2(n,1);
REP(i, m) {
int u,v;cin>>u>>v;u--;v--;
indeg[v]++;
int pr = p[u];
hsh1[v] = hsh1[v]*pr%MOD1;
hsh2[v] = hsh2[v]*pr%MOD2;
}
map<ii, vi> mpping;
REP(i, n) {
if (indeg[i] == 0) continue;
mpping[make_pair(hsh1[i], hsh2[i])].push_back(i);
}
vi nos;
for (auto [ppp, aarr]: mpping) {
int cur = 0;
for (auto idx: aarr) {
cur += arr[idx];
}
nos.push_back(cur);
}
int gd = nos[0];
for (auto x: nos) {
gd = __gcd(x, gd);
}
cout<<gd<<"\n";
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
sieve(10000000);
int tc;
cin>>tc;
REP(i, tc) {
solve();
}
} | 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"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <random>
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef unsigned long long ull;
typedef tree<pair<int, int>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
#define AboTaha_on_da_code ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define X first
#define Y second
const int dx[8]={0, 0, 1, -1, 1, -1, -1, 1}, dy[8]={1, -1, 0, 0, 1, -1, 1, -1};
const int M = 1e9+7, M2 = 998244353;
const double EPS = 1e-9;
int n1, n2, m, r, b, tot;
int s, os, ot, t, id;
vector <vector <vector <array <int, 4>>>> adj; // {cap, cost, id, flow}
void add(int u, int v, int mn, int mx, int cost)
{
if (mn > 0) {
adj[s][v].push_back({mn, cost, id});
adj[v][s].push_back({0, -cost, id++});
adj[u][t].push_back({mn, cost, id});
adj[t][u].push_back({0, -cost, id++});
}
if (mx > mn) {
adj[u][v].push_back({mx-mn, cost, id});
adj[v][u].push_back({0, -cost, id++});
}
}
void burn(int tc)
{
cin >> n1 >> n2 >> m >> r >> b;
os = n1+n2, ot = os+1, s = ot+1, t = s+1;
tot = t+1, id = 0;
adj.assign(tot, vector <vector <array <int, 4>>> (tot));
int cnt = 0;
for (int i = 0; i < n1; i++) {
char x; cin >> x;
if (x == 'R') cnt++, add(os, i, 1, m, 0);
else if (x == 'B') cnt++, add(i, ot, 1, m, 0);
else {
adj[os][i].push_back({m, 0, id});
adj[i][os].push_back({0, 0, id++});
adj[i][ot].push_back({m, 0, id});
adj[ot][i].push_back({0, 0, id++});
}
}
for (int i = 0; i < n2; i++) {
char x; cin >> x;
if (x == 'B') cnt++, add(os, i+n1, 1, m, 0);
else if (x == 'R') cnt++, add(i+n1, ot, 1, m, 0);
else {
adj[os][i+n1].push_back({m, 0, id});
adj[i+n1][os].push_back({0, 0, id++});
adj[i+n1][ot].push_back({m, 0, id});
adj[ot][i+n1].push_back({0, 0, id++});
}
}
vector <pair<int, int>> ed(m);
for (int i = 0; i < m; i++) {
int x, y; cin >> x >> y;
x--, y--;
ed[i] = {x, y};
adj[x][y+n1].push_back({1, r, id});
adj[y+n1][x].push_back({0, -r, id++});
adj[y+n1][x].push_back({1, b, id});
adj[x][y+n1].push_back({0, -b, id++});
}
adj[ot][os].push_back({(int)1e9, 0, id});
adj[os][ot].push_back({0, 0, id++});
while(true) {
vector <int> dis(tot, 1e9);
dis[s] = 0;
vector <pair<int, int>> par(tot, {-1, -1});
queue <int> q;
vector <bool> inq(tot, false);
q.push(s);
while(!q.empty()) {
auto cur = q.front();
q.pop();
inq[cur] = false;
for (int i = 0; i < tot; i++) {
for (int e = 0; e < adj[cur][i].size(); e++) {
auto &f = adj[cur][i][e][0], &c = adj[cur][i][e][1];
if (f && dis[i] > dis[cur] + c) {
dis[i] = dis[cur] + c;
par[i] = {cur, e};
if (!inq[i]) {
q.push(i);
inq[i] = true;
}
}
}
}
}
if (!~par[t].X) break;
cnt--;
int cur = t;
while(cur != s) {
int &pre = par[cur].X, &idx = par[cur].Y;
adj[pre][cur][idx][0]--;
adj[pre][cur][idx][3]++;
for (auto &e : adj[cur][pre]) {
if (e[2] == adj[pre][cur][idx][2]) {
e[0]++, e[3]--;
break;
}
}
cur = pre;
}
}
// cnt != 0 --> no answer.
if (cnt) return void (cout << -1);
vector <vector <int>> flow(n1, vector <int> (n2));
for (int i = 0; i < n1; i++) {
for (int j = n1; j < n1+n2; j++) {
for (auto [cap, c, dum, f] : adj[i][j])
flow[i][j-n1]+=f;
}
}
int ans = 0;
string col;
for (auto [x, y] : ed) {
auto &ret = flow[x][y];
if (ret > 0) {
ret--, ans+=r;
col.push_back('R');
}
else if (ret < 0) {
ret++, ans+=b;
col.push_back('B');
}
else col.push_back('U');
}
cout << ans << '\n' << col;
}
int main()
{
AboTaha_on_da_code
// freopen("Ain.txt", "r", stdin);
// freopen("Aout.txt", "w", stdout);
int T = 1; // cin >> T;
for (int i = 1; i <= T; i++) {
// cout << "Case " << i << ": ";
burn(i);
cout << '\n';
}
return 0;
} | cpp |
1301 | F | F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105) — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m) — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2); mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4); mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4); mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4). | [
"dfs and similar",
"graphs",
"implementation",
"shortest paths"
] | #include<iostream>
#include <bits/stdc++.h>
#include <ext/numeric>
using namespace std;
using L = __int128;
#include<ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define nd "\n"
#define all(x) (x).begin(), (x).end()
#define lol cout <<"i am here"<<nd;
#define py cout <<"YES"<<nd;
#define pp cout <<"ppppppppppppppppp"<<nd;
#define pn cout <<"NO"<<nd;
#define popcount(x) __builtin_popcount(x)
#define clz(n) __builtin_clz(n)//31 -x
const double PI = acos(-1.0);
double EPS = 1e-9;
#define print2(x , y) cout <<x<<' '<<y<<nd;
#define print3(x , y , z) cout <<x<<' '<<y<<' '<<z<<nd;
#define watch(x) cout << (#x) << " = " << x << nd;
template<class container>
void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;}
//template <class Type1 , class Type2>
ll fp(ll a , ll p){ if(!p) return 1; ll v = fp(a , p/2); v*=v;return p & 1 ? v*a : v; }
ll inf = 1e9+5 , mod= 1e9+7;//998244353;//
template <typename T> using ordered_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;
const int N = 1e6,LOG = 12;
ll mul (ll a, ll b){
return ( ( a % mod ) * ( b % mod ) ) % mod;
}
ll add (ll a , ll b){
return (a + b + mod) % mod;
}
template< typename T > using min_heap = priority_queue <T , vector <T > , greater < T > > ;
// m n
ll f (ll a ,ll b){
return (a + b - 1)/ b;
}
ll Fp (ll x , ll p){
if (!p) return 1;
ll v = Fp(x , p/2);
v = mul(v , v);
if (p & 1)
v = mul(x , v);
return v;
}
int dx [] {0 , 0 , 1 ,-1};
int dy [] {1 ,-1 , 0 , 0};
void main_(int tc){
ll n , m , k; cin >> n >> m >> k;
vector < vector <int > > grid(n , vector <int > (m));
vector < vector <pair <int , int > > > nodes (k+5);
for (int i = 0; i < n; ++i){
for (int j = 0; j < m; ++j){
cin >> grid[i][j];
nodes[grid[i][j]].emplace_back(i , j);
}
}
vector < vector < vector <int > > > dist(40+5 , vector < vector <int > > (n+5 , vector <int > (m+5 , inf)));
auto v =[&] (pair <int , int > p)-> bool{
return p.first >=0 && p.second >=0 && p.first <n && p.second < m;
};
auto bfs =[&](int c){
deque <pair <int , int > > q;
vector < bool > mark(k+5);
for (auto &i : nodes[c])
q.emplace_back(i.first , i.second) ,dist[c][i.first][i.second] = 0;
mark[c] = 1;
while (!q.empty()){
auto top = q.front(); q.pop_front();
if (!mark[grid[top.first][top.second]]){
mark[grid[top.first][top.second]] =1;
for (auto &i : nodes[grid[top.first][top.second]]){
if (dist[c][i.first][i.second] > dist[c][top.first][top.second]+ 1) {
dist[c][i.first][i.second] = 1 + dist[c][top.first][top.second];
q.emplace_back(i.first, i.second);
}
}
}
for (int i = 0; i < 4; ++i){
int nr = top.first + dx[i];
int nc = top.second + dy[i];
if (!v({nr , nc})) continue;
if (dist[c][nr][nc] > dist[c][top.first][ top.second]+1){
q.emplace_back( nr , nc);
dist[c][nr][nc] =dist[c][top.first][top.second]+1;
}
}
}
};
for (int i = 1; i <= k; ++i) bfs(i);
int q ,r1 , c1 , r2 , c2; cin >> q;
while (q--){
cin >> r1 >> c1 >> r2 >> c2;
--r1 , --r2 , --c1 , --c2;
int ans = abs(r1-r2) + abs(c1-c2);
for (int i = 1; i <= k; ++i) ans = min(ans , 1 + dist[i][r1][c1] + dist[i][r2][c2]);
cout << ans << nd;
}
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
//the_best_is_still_yet_to_come();
//freopen("red2.in ","r",stdin);// freopen("output.txt","w",stdout);
int tt = 1 , tc = 0;
// cin>>tt;
while(tt--) main_(++tc);
#ifndef ONLINE_JUDGE
cout << "Running Time: " << 1.0 * clock() / CLOCKS_PER_SEC << " s .\n";
#endif
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];
}
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] = par[0][fv];
cout << fv << ' ' << fa[fv] << ' ' << v << ' ' << u << '\n';
} else {
for (int i = 18; i --; )
if (h[find(par[i][fu])] > h[w])
fu = par[i][fu];
fa[fu] = par[0][fu];
cout << fu << ' ' << fa[fu] << ' ' << v << ' ' << u << '\n';
}
}
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;
iota(fa + 1, fa + n + 1, 1);
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);
cout << n - 1 << '\n';
solve(1, 0);
}
| cpp |
1303 | G | G. Sum of Prefix Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define the sum of prefix sums of an array [s1,s2,…,sk][s1,s2,…,sk] as s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk)s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk).You are given a tree consisting of nn vertices. Each vertex ii has an integer aiai written on it. We define the value of the simple path from vertex uu to vertex vv as follows: consider all vertices appearing on the path from uu to vv, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.InputThe first line contains one integer nn (2≤n≤1500002≤n≤150000) — the number of vertices in the tree.Then n−1n−1 lines follow, representing the edges of the tree. Each line contains two integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi), denoting an edge between vertices uiui and vivi. It is guaranteed that these edges form a tree.The last line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤1061≤ai≤106).OutputPrint one integer — the maximum value over all paths in the tree.ExampleInputCopy4
4 2
3 2
4 1
1 3 3 7
OutputCopy36
NoteThe best path in the first example is from vertex 33 to vertex 11. It gives the sequence [3,3,7,1][3,3,7,1], and the sum of prefix sums is 3636. | [
"data structures",
"divide and conquer",
"geometry",
"trees"
] | // LUOGU_RID: 101261866
#include<bits/stdc++.h>
#define N 600010
#define int long long
#define ls k*2
#define rs k*2+1
#define mid (l+r)/2
#define pb push_back
using namespace std;
int read() {
int res=0,f=1;char ch=getchar();
while(!isdigit(ch)) f=ch=='-'?-1:1,ch=getchar();
while(isdigit(ch)) res=res*10+ch-'0',ch=getchar();
return f*res;
}
int n;
int cnt,head[N],to[N],nxt[N];
void insert(int u,int v) {
cnt++;
to[cnt]=v;
nxt[cnt]=head[u];
head[u]=cnt;
}
struct line{int k,b;}a[N];
int d[N<<1];
int f(int x,int id) {return a[id].k*x+a[id].b;}
void update(int k,int l,int r,int id) {
if(l==r) {
if(f(l,id)>f(l,d[k])) d[k]=id;
return ;
}
if(f(mid,id)>f(mid,d[k])) swap(id,d[k]);
if(f(l,id)>f(l,d[k])) update(ls,l,mid,id);
else if(f(r,id)>f(r,d[k])) update(rs,mid+1,r,id);
}
int query(int k,int l,int r,int x) {
if(l==r) return f(x,d[k]);
return max(f(x,d[k]),x<=mid?query(ls,l,mid,x):query(rs,mid+1,r,x));
}
void clear(int k,int l,int r) {
d[k]=0;if(l==r) return ;
clear(ls,l,mid),clear(rs,mid+1,r);
}
int siz[N],son[N],rt,vis[N];
void gtrt(int now,int fa,int S) {
siz[now]=1,son[now]=0;
for(int i=head[now]; i; i=nxt[i]) if(to[i]!=fa&&!vis[to[i]]) {
gtrt(to[i],now,S),siz[now]+=siz[to[i]];
son[now]=max(son[now],siz[to[i]]);
} son[now]=max(son[now],S-siz[now]);
if(son[now]<son[rt]) rt=now;
}
int mx,val[N],ans;
struct node{
int v1,v2,l,s,fr;
};
vector<node> v[N];
void dfs(int now,int v1,int v2,int s,int dep,int fr,int fa) {
// printf("%lld\n",now);
if(now!=rt&&!fr) fr=now;
mx=max(mx,dep);
if(!nxt[head[now]]) {
// printf("%d %d %d %d\n",now,v1,v2,s-val[rt]);
return v[fr].pb(node{v1,v2,dep,s-val[rt],fr}),void();
}
for(int i=head[now]; i; i=nxt[i]) if(to[i]!=fa&&!vis[to[i]])
dfs(to[i],v1+s+val[to[i]],v2+val[to[i]]*dep,s+val[to[i]],dep+1,fr,now);
}
int tmp[N],tn;
void solve(int now,int S){
vis[now]=1,tn=0;int tot=0;mx=0;
dfs(now,val[now],0,val[now],1,0,0),clear(1,1,mx);
for(int i=head[now]; i; i=nxt[i]) if(!vis[to[i]]) {
for(node p:v[to[i]]) ans=max(ans,query(1,1,mx,p.l)+p.v1);
for(node p:v[to[i]]) a[++tot]=line{p.s,p.v2},update(1,1,mx,tot);
tmp[++tn]=to[i];
// printf("%lld\n",ans);
} ans=max(ans,query(1,1,mx,1)+val[now]);
// printf("%lld\n",ans);
clear(1,1,mx);
for(int i=tn; i; i--) {
for(node p:v[tmp[i]]) ans=max(ans,query(1,1,mx,p.l)+p.v1);
for(node p:v[tmp[i]]) a[++tot]=line{p.s,p.v2},update(1,1,mx,tot);
v[tmp[i]].clear();
}
// printf("%lld\n",ans);
for(int i=head[now]; i; i=nxt[i]) if(!vis[to[i]]) {
int tS=siz[to[i]]<siz[now]?siz[to[i]]:S-siz[now];
if(tS>1) rt=0,gtrt(to[i],now,tS),solve(rt,tS);
}
}
signed main() {
n=son[0]=read();
if(n==2) {puts("5");return 0;}
for(int i=1; i<n; i++) {
int u=read(),v=read();
insert(u,v),insert(v,u);
}
for(int i=1; i<=n; i++) val[i]=read(),ans=max(ans,val[i]);
gtrt(1,0,n);
solve(rt,n);
printf("%lld",ans);
} | 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;
typedef long long ll;
ll GCD(ll x, ll y)
{
return y ? GCD(y, x % y) : x;
}
int main()
{
int T; cin >> T;
while(T--)
{
ll a, m; cin >> a >> m;
vector <ll> Div;
for(ll x = 1; x * x <= m; x++)
{
if(m % x == 0)
{
Div.push_back(x);
if(x * x != m) Div.push_back(m / x);
}
}
sort(Div.begin(), Div.end(), greater <ll> ());
vector <ll> Dp(Div.size());
ll L = a - 1;
ll R = a + m - 1;
for(int i = 0; i < Div.size(); i++)
{
ll x = Div[i];
Dp[i] = R / x - L / x;
for(int j = 0; j < i; j++)
if(Div[j] % Div[i] == 0)
Dp[i] -= Dp[j];
}
ll Ans = 0;
ll G = GCD(a, m);
for(int i = 0; i < Div.size(); i++)
{
ll x = Div[i];
if(x == G)
{
Ans = Dp[i];
break;
}
}
cout << Ans << endl;
}
}
| cpp |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
void solve()
{
int n, m, k;
string str;
cin >> n >> str;
for (char i = 'z'; i >= 'b'; i -- ) {
if (str.size() == 1) break;
while (true) {
if (str.size() == 1) break;
bool flag = false;
for (int j = 0; j < str.size(); j ++ ) {
if (str[j] != i) continue;
if (j == 0) {
if (str[j + 1] == i - 1) {
flag = true;
str.erase(str.begin() + j, str.begin() + j + 1);
break;
}
}
else if (j == str.size() - 1) {
if (str[j - 1] == i - 1) {
flag = true;
str.erase(str.begin() + j, str.begin() + j + 1);
break;
}
}
else {
if (str[j - 1] == i - 1 || str[j + 1] == i - 1) {
flag = true;
str.erase(str.begin() + j, str.begin() + j + 1);
break;
}
}
}
if (!flag) break;
}
}
cout << n - (int)str.size() << "\n";
return ;
}
signed main()
{
int t = 1;
while (t -- ) {
solve();
}
return 0;
}
| cpp |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
using int32 = int32_t;
using int64 = int64_t;
const int64 INF = 1'000'000'000LL * 1'000'000'000;
int32 getPopCount(int32 mask)
{
return popcount((uint32_t)mask);
}
int32 main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int32 N, P, K;
cin >> N >> P >> K;
vector<int32> A(N + 1);
for (int32 i = 1; i <= N; ++i)
{
cin >> A[i];
}
vector<vector<int32>> S(N + 1, vector<int32>(P));
for (int32 i = 1; i <= N; ++i)
{
for (int32 j = 0; j < P; ++j)
{
cin >> S[i][j];
}
}
vector<int32> order(N);
iota(order.begin(), order.end(), 1);
sort(order.begin(), order.end(), [&](int32 i, int32 j)
{ return A[i] > A[j]; });
int32 have_seen = 0;
vector<int64> dp(1 << P, -INF);
dp[0] = 0;
for (int32 i : order)
{
++have_seen;
vector<int64> new_dp = dp;
for (int32 mask = 0; mask < (1 << P); ++mask)
{
if (new_dp[mask] == -INF)
{
continue;
}
if (have_seen - getPopCount(mask) <= K)
{
new_dp[mask] += A[i];
}
}
for (int32 position = 0; position < P; ++position)
{
for (int32 mask = 0; mask < (1 << P); ++mask)
{
if ((mask >> position & 1) == 0 || dp[mask ^ (1 << position)] == -INF)
{
continue;
}
new_dp[mask] = max(new_dp[mask], dp[mask ^ (1 << position)] + S[i][position]);
}
}
dp.swap(new_dp);
}
cout << dp[(1 << P) - 1] << "\n";
return 0;
} | cpp |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | #include <bits/stdc++.h>
#pragma optimization_level 3
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
#pragma GCC optimize("Ofast")//Comment optimisations for interactive problems (use endl)
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
using namespace std;
struct PairHash {inline std::size_t operator()(const std::pair<int, int> &v) const { return v.first * 31 + v.second; }};
// speed
#define Code ios_base::sync_with_stdio(false);
#define By ios::sync_with_stdio(0);
#define Sumfi cout.tie(NULL);
// alias
using ll = long long;
using ld = long double;
using ull = unsigned long long;
// constants
const ld PI = 3.14159265358979323846; /* pi */
const ll INF = 1e18;
const ld EPS = 1e-6;
const ll MAX_N = 202020;
const ll mod = 998244353;
// typedef
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
typedef array<ll,3> all3;
typedef array<ll,4> all4;
typedef array<ll,5> all5;
typedef vector<all3> vall3;
typedef vector<all4> vall4;
typedef vector<all5> vall5;
typedef pair<ld, ld> pld;
typedef vector<pld> vpld;
typedef vector<ld> vld;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<vll> vvll;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef deque<ll> dqll;
typedef deque<pll> dqpll;
typedef pair<string, string> pss;
typedef vector<pss> vpss;
typedef vector<string> vs;
typedef vector<vs> vvs;
typedef unordered_set<ll> usll;
typedef unordered_set<pll, PairHash> uspll;
typedef unordered_map<ll, ll> umll;
typedef unordered_map<pll, ll, PairHash> umpll;
// macros
#define rep(i,m,n) for(ll i=m;i<n;i++)
#define rrep(i,m,n) for(ll i=n;i>=m;i--)
#define all(a) begin(a), end(a)
#define rall(a) rbegin(a), rend(a)
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define INF(a) memset(a,0x3f3f3f3f3f3f3f3fLL,sizeof(a))
#define ASCEND(a) iota(all(a),0)
#define sz(x) ll((x).size())
#define BIT(a,i) (a & (1ll<<i))
#define BITSHIFT(a,i,n) (((a<<i) & ((1ll<<n) - 1)) | (a>>(n-i)))
#define pyes cout<<"YES\n";
#define pno cout<<"NO\n";
#define endl "\n"
#define pneg1 cout<<"-1\n";
#define ppossible cout<<"Possible\n";
#define pimpossible cout<<"Impossible\n";
#define TC(x) cout<<"Case #"<<x<<": ";
#define X first
#define Y second
// utility functions
template <typename T>
void print(T &&t) { cout << t << "\n"; }
template<typename T>
void printv(vector<T>v){ll n=v.size();rep(i,0,n){cout<<v[i];if(i+1!=n)cout<<' ';}cout<<endl;}
template<typename T>
void printvv(vector<vector<T>>v){ll n=v.size();rep(i,0,n)printv(v[i]);}
template<typename T>
void printvln(vector<T>v){ll n=v.size();rep(i,0,n)cout<<v[i]<<endl;}
void fileIO(string in = "input.txt", string out = "output.txt") {freopen(in.c_str(),"r",stdin); freopen(out.c_str(),"w",stdout);}
void readf() {freopen("", "rt", stdin);}
template <typename... T>
void in(T &...a) { ((cin >> a), ...); }
template<typename T>
void readv(vector<T>& v){rep(i,0,sz(v)) cin>>v[i];}
template<typename T, typename U>
void readp(pair<T,U>& A) {cin>>A.first>>A.second;}
template<typename T, typename U>
void readvp(vector<pair<T,U>>& A) {rep(i,0,sz(A)) readp(A[i]); }
void readvall3(vall3& A) {rep(i,0,sz(A)) cin>>A[i][0]>>A[i][1]>>A[i][2];}
void readvall5(vall5& A) {rep(i,0,sz(A)) cin>>A[i][0]>>A[i][1]>>A[i][2]>>A[i][3]>>A[i][4];}
void readvvll(vvll& A) {rep(i,0,sz(A)) readv(A[i]);}
struct Combination {
vll fac, inv;
ll n, MOD;
ll modpow(ll n, ll x, ll MOD = mod) { if(!x) return 1; ll res = modpow(n,x>>1,MOD); res = (res * res) % MOD; if(x&1) res = (res * n) % MOD; return res; }
Combination(ll _n, ll MOD = mod): n(_n + 1), MOD(MOD) {
inv = fac = vll(n,1);
rep(i,1,n) fac[i] = fac[i-1] * i % MOD;
inv[n - 1] = modpow(fac[n - 1], MOD - 2, MOD);
rrep(i,1,n - 2) inv[i] = inv[i + 1] * (i + 1) % MOD;
}
ll fact(ll n) {return fac[n];}
ll nCr(ll n, ll r) {
if(n < r or n < 0 or r < 0) return 0;
return fac[n] * inv[r] % MOD * inv[n-r] % MOD;
}
};
struct Matrix {
ll r,c;
vvll matrix;
Matrix(ll r, ll c, ll v = 0): r(r), c(c), matrix(vvll(r,vll(c,v))) {}
Matrix(vvll m) : r(sz(m)), c(sz(m[0])), matrix(m) {}
Matrix operator*(const Matrix& B) const {
Matrix res(r, B.c);
rep(i,0,r) rep(j,0,B.c) rep(k,0,B.r) {
res.matrix[i][j] = (res.matrix[i][j] + matrix[i][k] * B.matrix[k][j] % mod) % mod;
}
return res;
}
Matrix copy() {
Matrix copy(r,c);
copy.matrix = matrix;
return copy;
}
ll get(ll y, ll x) {
return matrix[y][x];
}
Matrix pow(ll n) {
assert(r == c);
Matrix res(r,r);
Matrix now = copy();
rep(i,0,r) res.matrix[i][i] = 1;
while(n) {
if(n & 1) res = res * now;
now = now * now;
n /= 2;
}
return res;
}
};
// geometry data structures
template <typename T>
struct Point {
T y,x;
Point(T y, T x) : y(y), x(x) {}
Point(pair<T,T> p) : y(p.first), x(p.second) {}
Point() {}
void input() {cin>>y>>x;}
friend ostream& operator<<(ostream& os, const Point<T>& p) { os<<p.y<<' '<<p.x<<'\n'; return os;}
Point<T> operator+(Point<T>& p) {return Point<T>(y + p.y, x + p.x);}
Point<T> operator-(Point<T>& p) {return Point<T>(y - p.y, x - p.x);}
Point<T> operator*(ll n) {return Point<T>(y*n,x*n); }
Point<T> operator/(ll n) {return Point<T>(y/n,x/n); }
bool operator<(const Point &other) const {if (x == other.x) return y < other.y;return x < other.x;}
Point<T> rotate(Point<T> center, ld angle) {
ld si = sin(angle * PI / 180.), co = cos(angle * PI / 180.);
ld y = this->y - center.y;
ld x = this->x - center.x;
return Point<T>(y * co - x * si + center.y, y * si + x * co + center.x);
}
ld distance(Point<T> other) {
T dy = abs(this->y - other.y);
T dx = abs(this->x - other.x);
return sqrt(dy * dy + dx * dx);
}
T norm() { return x * x + y * y; }
};
template<typename T>
struct Line {
Point<T> A, B;
Line(Point<T> A, Point<T> B) : A(A), B(B) {}
Line() {}
void input() {
A = Point<T>();
B = Point<T>();
A.input();
B.input();
}
T ccw(Point<T> &a, Point<T> &b, Point<T> &c) {
T res = a.x * b.y + b.x * c.y + c.x * a.y;
res -= (a.x * c.y + b.x * a.y + c.x * b.y);
return res;
}
bool isIntersect(Line<T> o) {
T p1p2 = ccw(A,B,o.A) * ccw(A,B,o.B);
T p3p4 = ccw(o.A,o.B,A) * ccw(o.A,o.B,B);
if (p1p2 == 0 && p3p4 == 0) {
pair<T,T> p1(A.y, A.x), p2(B.y,B.x), p3(o.A.y, o.A.x), p4(o.B.y, o.B.x);
if (p1 > p2) swap(p2, p1);
if (p3 > p4) swap(p3, p4);
return p3 <= p2 && p1 <= p4;
}
return p1p2 <= 0 && p3p4 <= 0;
}
pair<bool,Point<ld>> intersection(Line<T> o) {
if(!this->intersection(o)) return {false, {}};
ld det = 1. * (o.B.y-o.A.y)*(B.x-A.x) - 1.*(o.B.x-o.A.x)*(B.y-A.y);
ld t = ((o.B.x-o.A.x)*(A.y-o.A.y) - (o.B.y-o.A.y)*(A.x-o.A.x)) / det;
return {true, {A.y + 1. * t * (B.y - A.y), B.x + 1. * t * (B.x - A.x)}};
}
//@formula for : y = ax + fl
//@return {a,fl};
pair<ld, ld> formula() {
T y1 = A.y, y2 = B.y;
T x1 = A.x, x2 = B.x;
if(y1 == y2) return {1e9, 0};
if(x1 == x2) return {0, 1e9};
ld a = 1. * (y2 - y1) / (x2 - x1);
ld b = -x1 * a + y1;
return {a, b};
}
};
template<typename T>
struct Circle {
Point<T> center;
T radius;
Circle(T y, T x, T radius) : center(Point<T>(y,x)), radius(radius) {}
Circle(Point<T> center, T radius) : center(center), radius(radius) {}
Circle() {}
void input() {
center = Point<T>();
center.input();
cin>>radius;
}
bool circumference(Point<T> p) {
return (center.x - p.x) * (center.x - p.x) + (center.y - p.y) * (center.y - p.y) == radius * radius;
}
bool intersect(Circle<T> c) {
T d = (center.x - c.center.x) * (center.x - c.center.x) + (center.y - c.center.y) * (center.y - c.center.y);
return (radius - c.radius) * (radius - c.radius) <= d and d <= (radius + c.radius) * (radius + c.radius);
}
bool include(Circle<T> c) {
T d = (center.x - c.center.x) * (center.x - c.center.x) + (center.y - c.center.y) * (center.y - c.center.y);
return d <= radius * radius;
}
};
ll __gcd(ll x, ll y) { return !y ? x : __gcd(y, x % y); }
all3 __exgcd(ll x, ll y) { if(!y) return {x,1,0}; auto [g,x1,y1] = __exgcd(y, x % y); return {g, y1, x1 - (x/y) * y1}; }
ll __lcm(ll x, ll y) { return x / __gcd(x,y) * y; }
ll modpow(ll n, ll x, ll MOD = mod) { if(x < 0) return modpow(modpow(n,-x,MOD),MOD-2,MOD); n%=MOD; if(!x) return 1; ll res = modpow(n,x>>1,MOD); res = (res * res) % MOD; if(x&1) res = (res * n) % MOD; return res; }
ll solve(ll n, vll A, vll B) {
priority_queue<ll> q;
vpll S;
rep(i,0,n) S.push_back({A[i],B[i]});
sort(all(S));
S.push_back({INF,0});
ll res = 0, now = 0;
ll l = 0, r = 0;
while(r < n) {
while(r < n and S[r].first == S[l].first) {
q.push(S[r].second);
now += S[r].second;
r += 1;
}
if(sz(q)) {
now -= q.top();
q.pop();
}
ll diff = min(sz(q), S[r].first - S[l].first - 1);
while(diff--) {
res += now;
now -= q.top();
q.pop();
}
res += now;
l = r;
}
return res;
}
int main() {
Code By Sumfi
cout.precision(12);
ll tc = 1;
//in(tc);
rep(i,1,tc+1) {
ll n;
in(n);
vll A(n), B(n);
readv(A),readv(B);
print(solve(n,A,B));
}
return 0;
} | cpp |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] | // Submitted by Sakshi Agrawal
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define F first
#define S second
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int T = 1;
cin >> T;
while (T-- != 0) {
int a, b, p;
cin >> a >> b >> p;
string s;
cin >> s;
string res = s;
s = "C" + s;
int n = s.length(), cnt = 0, f = -1, prev = -1;
for (int i = n - 2; i > 0; i--) {
if (s[i] != s[i - 1]) {
cnt += (s[i] == 'A' ? a : b);
if (cnt > p) {
f = (prev == -1 ? n - 1 : prev);
break;
}
prev = i;
}
}
if (f == -1)
cout << 1 << endl;
else
cout << f << endl;
}
return 0;
}
| cpp |
1322 | E | E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5
1 2 1 2 1
OutputCopy2
1 1 1 1 1
InputCopy6
1 3 2 5 4 6
OutputCopy1
1 2 3 4 5 6
InputCopy6
1 1 2 2 1 1
OutputCopy0
1 1 2 2 1 1
NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00. | [
"data structures"
] | #include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
int n, a[N], l, r, mid, Max, ans[N];
multiset<int> le, ge;
multiset<int>::iterator it;
void ins(int x, int y){
if(x < mid) le.insert(x), le.insert(y), ge.insert(mid), mid = *le.rbegin(), le.erase(--le.end());
else ge.insert(x), ge.insert(y), le.insert(mid), mid = *ge.begin(), ge.erase(ge.begin());
}
bool del(int x){
it = le.find(x);
if(it != le.end()){
le.erase(it);
return false;
}else{
ge.erase(ge.find(x));
return true;
}
}
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
l = r = 1;
ans[1] = a[1], mid = a[1];
for(int i = 2; i <= n; i++){
if(l == r) l = i, r = i, mid = a[i];
else{
le.insert(mid);
bool f = del(a[l++]);
if(f) ge.insert(*le.rbegin()), le.erase(--le.end());
f = del(a[l++]);
if(f) mid = *le.rbegin(), le.erase(--le.end());
else mid = *ge.begin(), ge.erase(ge.begin());
}
bool flag = (a[i] > a[i - 1]) ^ ((i - l) & 1);
while(l > 1 && r < n){
if(flag && (a[l - 1] >= mid || a[r + 1] >= mid)) break;
else if(!flag && (a[l - 1] <= mid || a[r + 1] <= mid)) break;
ins(a[--l], a[++r]);
flag ^= 1;
}
ans[i] = mid;
Max = max(Max, i - l);
}
printf("%d\n", Max);
for(int i = 1; i <= n; i++) printf("%d ", ans[i]);
printf("\n");
return 0;
}
| cpp |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve() {
int n;
cin>>n;
n+=n;
vector<int>v(n);
for(int i=0;i<n;i++){
cin>>v[i];
}
sort(v.begin(),v.end());
cout<<v[n/2]-v[(n/2)-1]<<"\n";
return;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
long long t=1;
cin>>t;
while(t--){
solve();
}
return 0;
} | cpp |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | /*
You can have the world under your feet,
But all you do is cry,
I know you are scared of failing,
But Oh My Darlin, Give it a try.
IWRITESOMETIMES | Maansi :)
*/
#include <bits/stdc++.h>
using namespace std;
#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 vi vector<int>
#define vll vector<ll>
#define vvi vector<vi>
#define F first
#define S second
#define all(v) v.begin(), v.end()
#define FOR(i, a, b) for (int i = a; i < b; i++)
#define RFOR(i, a, b) for (int i = a; i >= b; i--)
#define rep(i, n) FOR(i, 0, n)
#define RREP(i, n) RFOR(i, n, 0)
#define mod 1000000007
#define inf 1000000000
#define endl "\n"
#define srt(ar) sort(ar.begin(), ar.end())
#define fastio \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
#define pq priority_queue
#define rpq priority_queue<int, vi, greater<int>>
#define init std::fill(hash.begin(), hash.end(), -1)
#define FAST_IO(n) \
cout.setf(ios::fixed); \
cout.precision(n);
#define print(v) \
rep(i, v.size()) \
cout \
<< v[i] << " "; \
cout << endl;
#define mii map<int, int>
ll power(ll x, ll y) {
ll res = 1;
while (y > 0) {
if (y & 1)
res = res * x;
y = y >> 1;
x = x * x;
}
return res;
}
void solve(){
int n, m;
cin>>n>>m;
vi ar(n);
vi b(m);
rep(i, n) cin>>ar[i];
rep(i, m) cin>>b[i];
srt(b);
vi dummy = ar;
vector<pii>vp;
int first = b[0];
for(int i = 0; i + 1 < m; i++){
if(b[i] + 1 != b[i + 1]){
vp.pb({first, b[i] + 1});
first = b[i + 1];
}
}
if(first != b[m-1]) vp.pb({first, b[m-1] + 1});
else vp.pb({first, first + 1});
for(auto i : vp){
int f = i.first;
int s = i.second;
f--, s;
sort(ar.begin() + f, ar.begin() + s);
}
srt(dummy);
if(dummy == ar) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
int main()
{
fastio;
int t = 1;
cin>>t;
while(t--){
solve();
}
return 0;
}
| cpp |
1290 | F | F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is: | [
"dp"
] | // LUOGU_RID: 94121184
#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<ctime>
#include<random>
#include<assert.h>
#define pb emplace_back
#define mp make_pair
#define fi first
#define se second
#define dbg(x) cerr<<"In Line "<< __LINE__<<" the "<<#x<<" = "<<x<<'\n'
#define dpi(x,y) cerr<<"In Line "<<__LINE__<<" the "<<#x<<" = "<<x<<" ; "<<"the "<<#y<<" = "<<y<<'\n'
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int>pii;
typedef pair<ll,int>pli;
typedef pair<ll,ll>pll;
typedef pair<int,ll>pil;
typedef vector<int>vi;
typedef vector<ll>vll;
typedef vector<pii>vpii;
typedef vector<pil>vpil;
template<typename T>T cmax(T &x, T y){return x=x>y?x:y;}
template<typename T>T cmin(T &x, T y){return x=x<y?x:y;}
template<typename T>
T &read(T &r){
r=0;bool w=0;char ch=getchar();
while(ch<'0'||ch>'9')w=ch=='-'?1:0,ch=getchar();
while(ch>='0'&&ch<='9')r=r*10+(ch^48),ch=getchar();
return r=w?-r:r;
}
template<typename T1,typename... T2>
void read(T1 &x,T2& ...y){read(x);read(y...);}
const int mod=998244353;
inline void cadd(int &x,int y){x=(x+y>=mod)?(x+y-mod):(x+y);}
inline void cdel(int &x,int y){x=(x-y<0)?(x-y+mod):(x-y);}
inline int add(int x,int y){return (x+y>=mod)?(x+y-mod):(x+y);}
inline int del(int x,int y){return (x-y<0)?(x-y+mod):(x-y);}
int bit(int x){
return 1<<x;
}
int n,m;
int a[6],b[6];
int f[31][21][21][21][21][2][2];
int chk(int c,int k,int p){
if(k==((m>>c)&1))return p;
return (k>((m>>c)&1));
}
int dfs(int pos,int xpos,int xneg,int ypos,int yneg,int p,int q){
if(pos==30)return !(xpos||xneg||ypos||yneg||p||q);
int &now=f[pos][xpos][xneg][ypos][yneg][p][q];
if(~now)
return now;
now=0;
for(int S=0;S<(1<<n);S++){
int xps=xpos,xng=xneg,yps=ypos,yng=yneg;
for(int i=1;i<=n;i++)
if(S&bit(i-1)){
if(a[i]>0)xps+=a[i];
else xng+=-a[i];
if(b[i]>0)yps+=b[i];
else yng+=-b[i];
}
if((xps&1)!=(xng&1) || (yps&1)!=(yng&1))continue;
cadd(now,dfs(pos+1,xps>>1,xng>>1,yps>>1,yng>>1,chk(pos,xps&1,p),chk(pos,yps&1,q)));
}
return now;
}
signed main(){
#ifdef do_while_true
// assert(freopen("data.in","r",stdin));
// assert(freopen("data.out","w",stdout));
#endif
read(n,m);
memset(f,-1,sizeof(f));
for(int i=1;i<=n;i++)read(a[i],b[i]);
cout << del(dfs(0,0,0,0,0,0,0),1) << '\n';
#ifdef do_while_true
cerr<<'\n'<<"Time:"<<1.0*clock()/CLOCKS_PER_SEC*1000<<" ms"<<'\n';
#endif
return 0;
} | cpp |
1303 | F | F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10
2 1 1
1 2 1
2 2 1
1 1 2
3 1 2
1 2 2
2 2 2
2 1 2
3 2 4
2 1 5
OutputCopy2
4
3
3
4
4
4
2
2
4
| [
"dsu",
"implementation"
] | #line 1 "library/my_template.hpp"
#if defined(LOCAL)
#include <my_template_compiled.hpp>
#else
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) \
vector<vector<vector<type>>> name( \
h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name( \
a, vector<vector<vector<type>>>( \
b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c))
#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)
#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) \
overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)
#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define stoi stoll
template <typename T, typename U>
T SUM(const vector<U> &A) {
T sum = 0;
for (auto &&a: A) sum += a;
return sum;
}
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) \
sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
template <typename T>
T pick(deque<T> &que) {
T a = que.front();
que.pop_front();
return a;
}
template <typename T>
T pick(pq<T> &que) {
T a = que.top();
que.pop();
return a;
}
template <typename T>
T pick(pqg<T> &que) {
assert(que.size());
T a = que.top();
que.pop();
return a;
}
template <typename T>
T pick(vc<T> &que) {
assert(que.size());
T a = que.back();
que.pop_back();
return a;
}
template <typename T, typename U>
T ceil(T x, U y) {
return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U>
T floor(T x, U y) {
return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
T q = floor(x, y);
return {q, x - q * y};
}
template <typename F>
ll binary_search(F check, ll ok, ll ng) {
assert(check(ok));
while (abs(ok - ng) > 1) {
auto x = (ng + ok) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return ok;
}
template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
FOR(iter) {
double x = (ok + ng) / 2;
tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
}
return (ok + ng) / 2;
}
template <class T, class S>
inline bool chmax(T &a, const S &b) {
return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
return (a > b ? a = b, 1 : 0);
}
vc<int> s_to_vi(const string &S, char first_char) {
vc<int> A(S.size());
FOR(i, S.size()) { A[i] = S[i] - first_char; }
return A;
}
template <typename T, typename U>
vector<T> cumsum(vector<U> &A, int off = 1) {
int N = A.size();
vector<T> B(N + 1);
FOR(i, N) { B[i + 1] = B[i] + A[i]; }
if (off == 0) B.erase(B.begin());
return B;
}
template <typename CNT, typename T>
vc<CNT> bincount(const vc<T> &A, int size) {
vc<CNT> C(size);
for (auto &&x: A) { ++C[x]; }
return C;
}
// stable
template <typename T>
vector<int> argsort(const vector<T> &A) {
vector<int> ids(A.size());
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
return ids;
}
// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
int n = len(I);
vc<T> B(n);
FOR(i, n) B[i] = A[I[i]];
return B;
}
#endif
#line 1 "library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace fastio {
// クラスが read(), print() を持っているかを判定するメタ関数
struct has_write_impl {
template <class T>
static auto check(T &&x) -> decltype(x.write(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_write : public decltype(has_write_impl::check<T>(std::declval<T>())) {
};
struct has_read_impl {
template <class T>
static auto check(T &&x) -> decltype(x.read(), std::true_type{});
template <class T>
static auto check(...) -> std::false_type;
};
template <class T>
class has_read : public decltype(has_read_impl::check<T>(std::declval<T>())) {};
struct Scanner {
FILE *fp;
char line[(1 << 15) + 1];
size_t st = 0, ed = 0;
void reread() {
memmove(line, line + st, ed - st);
ed -= st;
st = 0;
ed += fread(line + ed, 1, (1 << 15) - ed, fp);
line[ed] = '\0';
}
bool succ() {
while (true) {
if (st == ed) {
reread();
if (st == ed) return false;
}
while (st != ed && isspace(line[st])) st++;
if (st != ed) break;
}
if (ed - st <= 50) {
bool sep = false;
for (size_t i = st; i < ed; i++) {
if (isspace(line[i])) {
sep = true;
break;
}
}
if (!sep) reread();
}
return true;
}
template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
while (true) {
size_t sz = 0;
while (st + sz < ed && !isspace(line[st + sz])) sz++;
ref.append(line + st, sz);
st += sz;
if (!sz || st != ed) break;
reread();
}
return true;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
bool read_single(T &ref) {
if (!succ()) return false;
bool neg = false;
if (line[st] == '-') {
neg = true;
st++;
}
ref = T(0);
while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
if (neg) ref = -ref;
return true;
}
template <typename T,
typename enable_if<has_read<T>::value>::type * = nullptr>
inline bool read_single(T &x) {
x.read();
return true;
}
bool read_single(double &ref) {
string s;
if (!read_single(s)) return false;
ref = std::stod(s);
return true;
}
bool read_single(char &ref) {
string s;
if (!read_single(s) || s.size() != 1) return false;
ref = s[0];
return true;
}
template <class T>
bool read_single(vector<T> &ref) {
for (auto &d: ref) {
if (!read_single(d)) return false;
}
return true;
}
template <class T, class U>
bool read_single(pair<T, U> &p) {
return (read_single(p.first) && read_single(p.second));
}
template <size_t N = 0, typename T>
void read_single_tuple(T &t) {
if constexpr (N < std::tuple_size<T>::value) {
auto &x = std::get<N>(t);
read_single(x);
read_single_tuple<N + 1>(t);
}
}
template <class... T>
bool read_single(tuple<T...> &tpl) {
read_single_tuple(tpl);
return true;
}
void read() {}
template <class H, class... T>
void read(H &h, T &... t) {
bool f = read_single(h);
assert(f);
read(t...);
}
Scanner(FILE *fp) : fp(fp) {}
};
struct Printer {
Printer(FILE *_fp) : fp(_fp) {}
~Printer() { flush(); }
static constexpr size_t SIZE = 1 << 15;
FILE *fp;
char line[SIZE], small[50];
size_t pos = 0;
void flush() {
fwrite(line, 1, pos, fp);
pos = 0;
}
void write(const char val) {
if (pos == SIZE) flush();
line[pos++] = val;
}
template <class T, enable_if_t<is_integral<T>::value, int> = 0>
void write(T val) {
if (pos > (1 << 15) - 50) flush();
if (val == 0) {
write('0');
return;
}
if (val < 0) {
write('-');
val = -val; // todo min
}
size_t len = 0;
while (val) {
small[len++] = char(0x30 | (val % 10));
val /= 10;
}
for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
pos += len;
}
void write(const string s) {
for (char c: s) write(c);
}
void write(const char *s) {
size_t len = strlen(s);
for (size_t i = 0; i < len; i++) write(s[i]);
}
void write(const double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
void write(const long double x) {
ostringstream oss;
oss << fixed << setprecision(15) << x;
string s = oss.str();
write(s);
}
template <typename T,
typename enable_if<has_write<T>::value>::type * = nullptr>
inline void write(T x) {
x.write();
}
template <class T>
void write(const vector<T> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
template <class T, class U>
void write(const pair<T, U> val) {
write(val.first);
write(' ');
write(val.second);
}
template <size_t N = 0, typename T>
void write_tuple(const T t) {
if constexpr (N < std::tuple_size<T>::value) {
if constexpr (N > 0) { write(' '); }
const auto x = std::get<N>(t);
write(x);
write_tuple<N + 1>(t);
}
}
template <class... T>
bool write(tuple<T...> tpl) {
write_tuple(tpl);
return true;
}
template <class T, size_t S>
void write(const array<T, S> val) {
auto n = val.size();
for (size_t i = 0; i < n; i++) {
if (i) write(' ');
write(val[i]);
}
}
void write(i128 val) {
string s;
bool negative = 0;
if (val < 0) {
negative = 1;
val = -val;
}
while (val) {
s += '0' + int(val % 10);
val /= 10;
}
if (negative) s += "-";
reverse(all(s));
if (len(s) == 0) s = "0";
write(s);
}
};
Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);
void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
printer.write(head);
if (sizeof...(Tail)) printer.write(' ');
print(forward<Tail>(tail)...);
}
void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
scanner.read(head);
read(tail...);
}
} // namespace fastio
using fastio::print;
using fastio::flush;
using fastio::read;
#define INT(...) \
int __VA_ARGS__; \
read(__VA_ARGS__)
#define LL(...) \
ll __VA_ARGS__; \
read(__VA_ARGS__)
#define STR(...) \
string __VA_ARGS__; \
read(__VA_ARGS__)
#define CHAR(...) \
char __VA_ARGS__; \
read(__VA_ARGS__)
#define DBL(...) \
double __VA_ARGS__; \
read(__VA_ARGS__)
#define VEC(type, name, size) \
vector<type> name(size); \
read(name)
#define VV(type, name, h, w) \
vector<vector<type>> name(h, vector<type>(w)); \
read(name)
void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 2 "library/ds/unionfind/unionfind.hpp"
struct UnionFind {
int n, n_comp;
vc<int> dat; // par or (-size)
UnionFind(int n = 0) { build(n); }
void build(int m) {
n = m, n_comp = m;
dat.assign(n, -1);
}
int operator[](int x) {
while (dat[x] >= 0) {
int pp = dat[dat[x]];
if (pp < 0) { return dat[x]; }
x = dat[x] = pp;
}
return x;
}
int size(int x) {
assert(dat[x] < 0);
return -dat[x];
}
bool merge(int x, int y) {
x = (*this)[x], y = (*this)[y];
if (x == y) return false;
if (-dat[x] < -dat[y]) swap(x, y);
dat[x] += dat[y], dat[y] = x, n_comp--;
return true;
}
};
#line 4 "main.cpp"
void solve() {
LL(N, M, Q);
int H = N, W = M;
const int LIM = max(1000, ceil(2'000'000, N * M)) + 5;
// 色 0 :単調減少
// 色 k :単調増加 → 単調減少
// すべて、増加 → 減少 と見なせる
// (t,x,y)
using T3 = tuple<int, int, int>;
vvc<T3> ADD(LIM), RM(LIM);
vv(int, A, N, M);
FOR(t, Q) {
LL(a, b, c);
--a, --b;
if (A[a][b] == c) continue;
RM[A[a][b]].eb(t, a, b);
A[a][b] = c;
ADD[A[a][b]].eb(t, a, b);
}
auto idx = [&](int x, int y) -> int { return M * x + y; };
auto isin = [&](ll x, ll y) -> bool {
return (0 <= x && x < H && 0 <= y && y < W);
};
ll dx[] = {1, 0, -1, 0};
ll dy[] = {0, 1, 0, -1};
UnionFind uf(N);
vc<int> C(N * M);
int comp = 0;
auto reset = [&]() -> void {
uf.build(N * M);
fill(all(C), 0);
comp = 0;
};
auto add = [&](int x, int y) -> void {
int i = idx(x, y);
assert(C[i] == 0);
C[i] = 1;
++comp;
FOR(d, 4) {
int nx = x + dx[d], ny = y + dy[d];
if (isin(nx, ny) && C[idx(nx, ny)] && uf.merge(i, idx(nx, ny))) --comp;
}
};
vc<int> ANS(Q + 1);
FOR(color, LIM) {
if (ADD[color].empty() && RM[color].empty()) continue;
// クエリ [0,p) の答を計算済
int p = 0;
reset();
for (auto&& [t, a, b]: ADD[color]) {
ANS[p] += comp, ANS[t] -= comp;
add(a, b);
p = t;
}
// クエリ [q, Q) の答を計算済
int q = Q;
reset();
FOR(x, N) FOR(y, M) if (A[x][y] == color) add(x, y);
reverse(all(RM[color]));
for (auto&& [t, a, b]: RM[color]) {
assert(t < q);
ANS[t] += comp, ANS[q] -= comp;
q = t;
add(a, b);
}
assert(p <= q);
ANS[p] += comp, ANS[q] -= comp;
}
ANS = cumsum<int>(ANS, 0);
FOR(q, Q) print(ANS[q]);
}
signed main() {
solve();
return 0;
}
| cpp |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | #include <iostream>
#include <ranges>
#include <algorithm>
#include <numeric>
#include <vector>
#include <array>
#include <set>
#include <map>
#include <bit>
#include <sstream>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
typedef int integerType;
typedef integerType z;
typedef std::vector<integerType> v;
typedef std::vector<v> V;
typedef std::set<integerType> s;
typedef std::multiset<integerType> S;
typedef std::string r;
typedef std::vector<r> R;
typedef std::vector<bool> b;
struct RHEXAOCrocks {
RHEXAOCrocks() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); }
template<class T>
operator T() const { T n; std::cin >> n; return n; }
std::string operator()() { std::string s; std::cin >> s; return s; }
v operator()(integerType n) { v vec(n); for (auto& n : vec) std::cin >> n; return vec; }
R operator()(integerType n, char del) {
R vec(n); char ch; std::cin >> ch; vec[0].push_back(ch); int c;
for (integerType i{}; i < n;++i)
while ((c = std::cin.get()) != del)
vec[i].push_back(c);
return vec;
}
V operator()(integerType r, integerType c) { V tab(r, v(c)); for (auto& e : tab) for (auto& n : e) std::cin >> n; return tab; }
template<class T> RHEXAOCrocks& operator[](const T& t) { std::cout << t; return *this; }
RHEXAOCrocks& operator[](const R& a) { for (auto& e : a) std::cout << e << '\n'; return *this; }
template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const C<Ty>& c) {
for (auto Cc{ c.begin() }; Cc != c.end(); std::cout << *Cc << " \n"[++Cc == c.end()]); return *this;
}
template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const std::vector<C<Ty>>& c) {
for (auto& e : c) for (auto E{ e.begin() }; E != e.end(); )std::cout << *E << " \n"[++E == e.end()]; return *this;
}
}o;
#define i(b,e, ...) for(integerType i : std::views::iota(b,e) __VA_ARGS__)
#define _i(b,e, ...) for(integerType i : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define j(b,e, ...) for(integerType j : std::views::iota(b,e) __VA_ARGS__)
#define _j(b,e, ...) for(integerType j : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define k(b,e, ...) for(integerType k : std::views::iota(b,e) __VA_ARGS__)
#define _k(b,e, ...) for(integerType k : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define l(b,e, ...) for(integerType l : std::views::iota(b,e) __VA_ARGS__)
#define _l(b,e, ...) for(integerType l : std::views::iota(b,e) | std::views::reverse __VA_ARGS__)
#define Aa for(auto A{ a.begin() }, a_end{ a.end() }; A != a_end; ++A)
#define Bb for(auto B{ b.begin() }, b_end{ b.end() }; B != b_end; ++B)
#define Cc for(auto C{ c.begin() }, c_end{ c.end() }; C != c_end; ++C)
#define Dd for(auto D{ d.begin() }, d_end{ d.end() }; D != d_end; ++D)
#define z(a) (integerType)((a).size())
#define ff(...) auto f = [&](__VA_ARGS__, const auto& f)
#define f(...) f(__VA_ARGS__, f)
#define gg(...) auto g = [&](__VA_ARGS__, const auto& g)
#define g(...) g(__VA_ARGS__, g)
#define hh(...) auto h = [&](__VA_ARGS__, const auto& h)
#define h(...) h(__VA_ARGS__, h)
using namespace std;
namespace ra = ranges;
inline void nwmn(integerType nw, integerType& mn) { mn -= ((nw) < mn) * (mn - (nw)); }
inline void nwmx(integerType nw, integerType& mx) { mx += ((nw) > mx) * ((nw)-mx); }
z power(z a, z b, z M) { z r{ 1 }; do { if (b & 1) (r *= a) %= M; (a *= a) %= M; } while (b >>= 1); return r; }
#define w(...) if(__VA_ARGS__)
#define _ else
#define W(...) while(__VA_ARGS__)
#define A(...) for(auto __VA_ARGS__)
#define O while(true)
void solve_test_case()
{
z a{ o }, b{ o }, c{ o }, answer{ a + b + c - 3 }, answerA{ 1 }, answerB{ 1 }, answerC{ 1 };
for (z C{ 1 }; C < c + answer; ++C) {
z dc{ C > c ? C - c : c - C };
for (z B{ 1 }, r{ (z)sqrt(C) }, rr{ r + ((r + 1) * (r + 1) == C) }; B <= rr; ++B)
if (!(C % B)) for (z B : {B, C / B}) {
z db{ B > b ? B - b : b - B };
if (dc + db >= answer)
continue;
for (z A{ 1 }, r{ (z)sqrt(B) }, rr{ r + ((r + 1) * (r + 1) == B) }; A <= rr; ++A)
if (!(B % A)) for (z A : {A, B / A}) {
z da{ A > a ? A - a : a - A };
if (z delta{ da + db + dc }; delta < answer) {
answer = delta;
answerA = A;
answerB = B;
answerC = C;
}
}
}
}
o[answer]['\n'][answerA][' '][answerB][' '][answerC]['\n'];
}
int main()
{
z t{ o };
while (t--)
solve_test_case();
} | 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 ll long long
#define gmax(x,y) x=max(x,y)
#define gmin(x,y) x=min(x,y)
#define F first
#define S second
#define P pair
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,a,b) for(int i=a;i<b;i++)
#define V vector
#define RE return
#define ALL(a) a.begin(),a.end()
#define MP make_pair
#define PB emplace_back
#define PF push_front
#define FILL(a,b) memset(a,b,sizeof(a))
#define lwb lower_bound
#define upb upper_bound
#define lc (x<<1)
#define rc ((x<<1)|1)
#define sz(x) ((int)x.size())
using namespace std;
const int mod=998244353;
void add(int &x,int y){
x+=y;
if(x>=mod)x-=mod;
}
int dp[2050][2050],n,k,cnt=0;
int val[2050],len;
bool dfs(int x){
if(len){
V<int> now;
FOR(i,1,len)now.PB(val[i]);
bool f=1;reverse(ALL(now));
rep(i,1,k-1){
int tv=0;V<int> to;
int s=0,tot=0;
for(auto u:now)tot+=u;
for(auto u:now){
tv++;FOR(j,1,u)s+=(tot--)*tv;
}
tv=0;
if(s>n){
f=0;break;
}
if(i==k-2)break;
for(auto u:now){
++tv;
FOR(j,1,u)to.PB(tv);
}
reverse(ALL(to));
now=to;
}
if(f)cnt++;else RE 0;
}
FOR(i,x,n){
val[++len]=i;
bool now=dfs(i);
--len;
if(!now)break;
}
RE 1;
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n>>k;
if(k==1){
dp[0][0]=1;
int sum=0;
FOR(i,1,n)FOR(j,i,n){
dp[i][j]=dp[i-1][j-1];
add(dp[i][j],dp[i][j-i]);
add(sum,dp[i][j]);
}
cout<<sum<<'\n';
}else if(k==2){
dp[0][0]=1;
int ans=0;
FOR(i,1,n)FOR(j,0,n)if(dp[i-1][j]){
int mul=i*(i+1)/2;
FOR(k,0,n){
if(j+k*mul>n)break;
add(dp[i][j+k*mul],dp[i-1][j]);
if(k)add(ans,dp[i-1][j]);
}
}
cout<<ans<<'\n';
}else{
dfs(1);
cout<<cnt;
}
RE 0;
}
| 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 <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
#define ll long long
#define pii pair<int, int>
const int MOD = 998244353;
inline ll _p(ll x, ll y) {
ll ans = 1;
while (y) {
if (y & 1) ans = ans * x % MOD;
x = x * x % MOD, y >>= 1;
}
return ans;
}
inline ll inv(ll x) { return _p(x, MOD - 2); }
struct lazy_segment_tree {
vector<ll> t, lazy;
int n;
lazy_segment_tree() {}
lazy_segment_tree(int n) : n(n), t(4 * n), lazy(4 * n, 1) {}
inline void push(int v, int tl, int tr) {
if (tl == tr) return;
int l = 2 * v, r = 2 * v + 1;
lazy[l] = lazy[l] * lazy[v] % MOD;
lazy[r] = lazy[r] * lazy[v] % MOD;
t[l] = (t[l] * lazy[v]) % MOD;
t[r] = (t[r] * lazy[v]) % MOD;
lazy[v] = 1;
}
void upd(int v, int tl, int tr, int p, ll val) {
push(v, tl, tr);
if (tl == tr) {
t[v] = val;
return;
}
int m = (tl + tr) / 2;
if (p <= m) upd(2 * v, tl, m, p, val);
else upd(2 * v + 1, m + 1, tr, p, val);
t[v] = (t[2 * v] + t[2 * v + 1]) % MOD;
}
void upd(int v, int tl, int tr, int l, int r, ll mult) {
if (l > r) return;
push(v, tl, tr);
if (tl == l && tr == r) {
t[v] = (t[v] * mult) % MOD;
lazy[v] = mult;
return;
}
int m = (tl + tr) / 2;
upd(2 * v, tl, m, l, min(m, r), mult);
upd(2 * v + 1, m + 1, tr, max(m + 1, l), r, mult);
t[v] = (t[2 * v] + t[2 * v + 1]) % MOD;
}
ll qry(int v, int tl, int tr, int l, int r) {
if (l > r) return 0;
push(v, tl, tr);
if (tl == l && tr == r) return t[v];
int m = (tl + tr) / 2;
return (qry(2 * v, tl, m, l, min(m, r)) + qry(2 * v + 1, m + 1, tr, max(m + 1, l), r)) % MOD;
}
};
struct fraction {
ll a, b;
fraction() : a(0), b(1) {}
fraction(ll a, ll b) : a(a), b(b) {}
inline bool operator==(const fraction& rhs) {
return a * rhs.b == b * rhs.a;
}
inline bool operator!=(const fraction& rhs) {
return !(fraction(a, b) == rhs);
}
inline bool operator<(const fraction& rhs) {
return a * rhs.b < b * rhs.a;
}
};
struct proton {
ll pos, vel, p;
proton() {}
};
int n;
vector<proton> arr;
struct prefix_products {
vector<ll> left, right;
prefix_products() {
left.resize(2 * n), right.resize(2 * n);
ll percent = inv(100);
for (int i = 0; i < n; ++i) {
left[i + n] = (100 - arr[i].p) * percent % MOD;
right[i + n] = arr[i].p * percent % MOD;
}
for (int i = n - 1; i > 0; --i) {
left[i] = (left[2 * i] * left[2 * i + 1]) % MOD;
right[i] = (right[2 * i] * right[2 * i + 1]) % MOD;
}
}
ll qryLeft(int a, int b) {
// cout << "QUERY " << a << ' ' << b << endl;
ll ans = 1;
for (a += n, b += n + 1; a < b; a >>= 1, b >>= 1) {
if (a & 1) ans = ans * left[a++] % MOD;
if (b & 1) ans = ans * left[--b] % MOD;
}
// cout << "ANS " << ans << endl;
return ans;
}
ll qryRight(int a, int b) {
ll ans = 1;
for (a += n, b += n + 1; a < b; a >>= 1, b >>= 1) {
if (a & 1) ans = ans * right[a++] % MOD;
if (b & 1) ans = ans * right[--b] % MOD;
}
return ans;
}
};
struct probability_maintainer {
lazy_segment_tree segtree;
prefix_products pre;
set<pair<pii, pii>> s;
ll ans = 1;
probability_maintainer() : segtree(n), pre() {
for (int i = 0; i < n; ++i) s.insert({{i, i}, {i, i + 1}});
for (int i = 0; i < n; ++i) segtree.upd(1, 0, n, i, pre.qryRight(i, i));
}
void add(int i) {
if (ans == 0) return;
auto cur = s.lower_bound({{i, i}, {i, i}});
auto bef = prev(cur);
s.erase(cur), s.erase(bef);
pii sa = bef->first, sb = cur->first;
int a = sa.first, b = sa.second, c = sb.first, d = sb.second;
pii ra = bef->second, rb = cur->second;
int w = ra.first, x = ra.second, y = rb.first, z = rb.second;
// assert(a == w);
// assert(c == y);
// assert(x == b + 1);
// assert(z == d + 1);
ll tl = segtree.qry(1, 0, n, w, min(x, b));
// cout << w << ' ' << x << ' ' << tl << endl;
if (x == b + 1) tl += pre.qryLeft(a, b);
ll tr = segtree.qry(1, 0, n, y, min(z, d));
if (z == d + 1) tr += pre.qryLeft(c, d);
// cout << tl << ' ' << tr << endl;
ans = ans * inv(tl * tr % MOD) % MOD;
if (x <= b && y > c) {
ans = 0;
return;
}
segtree.upd(1, 0, n, a, b, pre.qryRight(c, d));
segtree.upd(1, 0, n, c, d, pre.qryLeft(a, b));
int nw = y > c ? y : w;
int nx = x <= b ? x : z;
// assert(nw == a);
// assert(nx == d + 1);
ll ad = segtree.qry(1, 0, n, nw, min(nx, d));
// cout << ad << endl;
if (nx == d + 1) ad += pre.qryLeft(a, d);
// cout << "p " << nx << ' ' << d + 1 << endl;
// cout << a << ' ' << d << ' ' << pre.qryLeft(a, d) << endl;
// cout << "final " << ad << endl;
ans = ans * ad % MOD;
s.insert({{a, d}, {nw, nx}});
}
void addRestriction(int i) {
if (ans == 0) return;
auto cur = --s.lower_bound({{i, i}, {i, i}});
s.erase(cur);
int a = cur->first.first, b = cur->first.second;
int w = cur->second.first, x = cur->second.second;
ll tl = segtree.qry(1, 0, n, w, min(x, b));
if (x == b + 1) tl += pre.qryLeft(a, b);
ans = ans * inv(tl) % MOD;
if (arr[i].vel > arr[i - 1].vel) {
if (w > i) {
ans = 0;
return;
}
x = min(x, i);
} else {
if (x < i) {
ans = 0;
return;
}
w = max(w, i);
}
tl = segtree.qry(1, 0, n, w, min(x, b));
if (x == b + 1) tl += pre.qryLeft(a, b);
ans = ans * tl % MOD;
s.insert({{a, b}, {w, x}});
}
ll getProbability() {
return ans;
}
};
int main() {
ll percent = inv(100);
cin >> n;
arr.resize(n);
for (int i = 0; i < n; ++i) cin >> arr[i].pos >> arr[i].vel >> arr[i].p;
vector<pair<fraction, int>> ways;
for (int i = 1; i < n; ++i) {
ll d = arr[i].pos - arr[i - 1].pos;
ll v = arr[i].vel + arr[i - 1].vel;
ways.push_back({fraction(d, v), i});
v = abs(arr[i].vel - arr[i - 1].vel);
if (v) ways.push_back({fraction(d, v), i});
}
sort(ways.begin(), ways.end(), [&](pair<fraction, int> a, pair<fraction, int> b) {
if (a.first != b.first) return a.first < b.first;
return a.second < b.second;
});
probability_maintainer maintainer;
vector<bool> done(n);
ll ans = 0;
for (int i = 0; i < ways.size(); ++i) {
ll prob = maintainer.getProbability();
// cout << "PROB " << prob << endl;
if (!prob) break;
int mx;
for (mx = i; mx < ways.size(); ++mx) if (ways[i].first != ways[mx].first) break;
fraction time = ways[i].first;
ll colt = time.a * inv(time.b) % MOD;
for (int j = i; j < mx; ++j) {
int i = ways[j].second;
if (!done[i]) maintainer.add(i);
else maintainer.addRestriction(i);
done[i] = true;
}
i = mx - 1;
ll prob2 = maintainer.getProbability();
ll left = (prob - prob2 + MOD) % MOD;
ans = (ans + left * colt) % MOD;
// cout << ans << endl;
// cout << endl;
}
cout << ans << '\n';
return 0;
} | cpp |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
void solve() {
ll u, v; cin >> u >> v;
if (u > v) cout << -1 << '\n';
else if (u == v) {
if (u == 0) cout << 0 << '\n';
else cout << 1 << '\n' << u << '\n';
} else {
if ((v - u) & 1) cout << -1 << '\n';
else {
ll a = (v - u) >> 1;
if (!(a & u)) cout << 2 << '\n' << a << ' ' << (a ^ u) << '\n';
else cout << 3 << '\n' << a << ' ' << a << ' ' << u << '\n';
}
}
}
int main() {
ios::sync_with_stdio(false);
int _ = 1;
// cin >> _;
while (_--)
solve();
return 0;
} | cpp |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample: | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | // LUOGU_RID: 102583755
#include <bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
#define fre(z) freopen(z".in","r",stdin),freopen(z".out","w",stdout)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> Pair;
const double eps=1e-8;
const int inf=2139062143;
#ifdef ONLINE_JUDGE
static char buf[1000000],*p1=buf,*p2=buf,obuf[1000000],*p3=obuf;
#define getchar() p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++
#endif
inline void qread(){}template<class T1,class ...T2>
inline void qread(T1 &a,T2&...b){
register T1 x=0;register bool f=false;char ch=getchar();
while(ch<'0') f|=(ch=='-'),ch=getchar();
while(ch>='0') x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
x=(f?-x:x);a=x;qread(b...);
}inline void dread(){}template<class T1,class ...T2>
inline void dread(T1 &a,T2&...b){
register double w=0;register ll x=0,base=1;
register bool f=false;char ch=getchar();
while(!isdigit(ch)) f|=(ch=='-'),ch=getchar();
while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
w=(f?-x:x);if(ch!='.') return a=w,dread(b...);x=0,ch=getchar();
while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),base*=10,ch=getchar();
register double tmp=(double)(x/(double)base);w=w+(double)(f?-tmp:tmp);a=w;dread(b...);
}template<class T>void cmax(T &x,T y){if(x<y) x=y;}template<class T>void cmin(T &x,T y){if(x>y) x=y;}
template<class T> T qmax(T x,T y){return x>y?x:y;}
template<class T,class ...Arg> T qmax(T x,T y,Arg ...arg){return qmax(x>y?x:y,arg...);}
template<class T> T qmin(T x,T y){return x<y?x:y;}
template<class T,class ...Arg> T qmin(T x,T y,Arg ...arg){return qmin(x<y?x:y,arg...);}
template<class T> T randint(T l,T r){static mt19937 eng(time(0));uniform_int_distribution<T>dis(l,r);return dis(eng);}
const int MAXN=1e5+7;
int n,m,dep[MAXN],f[MAXN],sqt,p;vector<int>e[MAXN],vec[MAXN],ans;bitset<MAXN>vis;
void dfs(int u,int fa){
for(auto v:e[u]){
if(v==fa) continue;
if(dep[v]){
if(dep[u]-dep[v]+1>=sqt){
puts("2");printf("%d\n%d ",dep[u]-dep[v]+1,u);
while(u!=v) printf("%d ",f[u]),u=f[u];exit(0);
}
}else f[v]=u,dep[v]=dep[u]+1,dfs(v,u);
}if(!vis[u]){
ans.emplace_back(u);
for(auto v:e[u]) vis[v]=true;
}
}int main(){
qread(n,m);int i,j;sqt=ceil(sqrt(n));
for(i=1;i<=m;i++){
int u,v;qread(u,v);
e[u].emplace_back(v);e[v].emplace_back(u);
}dep[1]=1;dfs(1,0);puts("1");for(i=0;i<sqt;i++) printf("%d ",ans[i]);
#ifndef ONLINE_JUDGE
cerr<<"Time: "<<clock()<<endl;
system("pause > null");
#endif
return 0;
} | cpp |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | #pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
#include <array>
// #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using lld = long double;
using ull = unsigned long long;
using vll = vector<ll>;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x<<" "; _print(x); cerr << endl;
#else
#define debug(x) ((void)0);
#endif
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define loop(i,k,n) for(ll i = k; i < n;i++)
#define MOD 1000000007
#define MOD1 998244353
#define nl "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define UNIQUE(X) X.erase(unique(all(X)),X.end())
const ll INF = 1e18;
template<class A> void read(vector<A>& v);
template<class T> void read(T& x) {
cin >> x;
}
template<class H, class... T> void read(H& h, T&... t) {
read(h);
read(t...);
}
template<class A> void read(vector<A>& x) {
for (auto& a: x)
read(a);
}
template<class A> void read1(vector<A>& x) {
for(ll i = 1; i <= sz(x) - 1; i++){
read(x[i]);
}
}
void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
template<class T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
void google(int t) {cout << "Case #" << t << ": ";}
ll mul(ll a, ll b, ll m) {
if (a < (1 << 14)) {
return (a * b) % m;
}
ll c = mul(a >> 14, b, m);
c <<= 14;
c %= m;
c = (c + (a % (1 << 14)) * b) % m;
return c;
}
ll fast_power(ll p, ll e, ll m) {
if (e == 0) {
return 1 % m;
}
if (e % 2 == 0) {
return fast_power(mul(p, p, m), e / 2, m);
}
else {
return mul(fast_power(p, e - 1, m), p, m);
}
}
// #define N 200005 // change N here
// vector<vll> adjl(N);
// vll visited(N);
// ll n, m;
// vector<ll> adj[N];
// void dfs(ll u){
// visited[u] = 1;
// for(ll v: adj[u]){
// if(!visited[v]){
// dfs(v);
// }
// }
// }
// vll dist;
// void bfs(ll s) {
// dist.assign(n + 1, -1); // n must be defined(i.e global)
// queue<ll> q;
// dist[s] = 0; q.push(s);
// while (q.size()) {
// ll u = q.front(); q.pop();
// for (ll v : adj[u]) {
// if (dist[v] == -1) {
// dist[v] = dist[u] + 1;
// q.push(v);
// }
// }
// }
// }
// const ll maxn = 1000; // set maxn accordingly
// ll C[maxn + 1][maxn + 1];
// void makenCr(){
// C[0][0] = 1;
// for (ll n = 1; n <= maxn; ++n) {
// C[n][0] = C[n][n] = 1;
// for (ll k = 1; k < n; ++k)
// C[n][k] = C[n - 1][k - 1] + C[n - 1][k];
// // C[n][k] %= MOD;
// }
// }
string SET = "SET";
set<string> us;
void solve(){
ll n, k;
cin >> n >> k;
vector<string> mt(n); read(mt);
for(auto x: mt) us.insert(x);
ll ans = 0;
loop(i, 0, n) loop(j, i + 1, n){
string req;
loop(z, 0, k)
if(mt[i][z] == mt[j][z]) req.pb(mt[i][z]);
else{
for(auto c: SET) if(c != mt[i][z] && c != mt[j][z])
req.pb(c);
}
if(us.count(req)) ans ++;
}
cout << ans / 3 << nl;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
cout << "---------------------" << nl;
cout << "OUTPUT:" << nl;
freopen("error.txt", "w", stderr);
#endif
int t = 1;
// cin>>t;
for(ll i = 1; i <= t; i ++)
{
// google(i);
solve();
// cout << "\n";
}
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"
template <class Flow = ll, class Cost = ll, bool MINIMIZE = 1>
struct MinCostFlow {
private:
static constexpr int objective = (MINIMIZE ? 1 : -1);
static constexpr int SCALING_FACTOR = 2;
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<bool, 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 {true, value / objective};
} else {
return {false, 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 [ok, cost] = G.solve();
if (!ok) 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 |
1141 | A | A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272. | [
"implementation",
"math"
] | #include <bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
#define endl '\n'
#define Y ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
const int N = 1e4 + 5;
int n, m, ans = -1;
void go(int res, int step) {
if (res == m) ans = max(ans, step);
if (res > m) return;
go(res * 2, step + 1);
go(res * 3, step + 1);
}
int main() {
Y
cin >> n >> m;
go(n, 0);
cout << ans;
return 0;
}
| cpp |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | #include <iostream>
#include <string>
int main() {
int n, left = 0, right = 0;
std::string s;
std::cin >> n >> s;
for (auto x : s) {
if (x == 'L') {
left++;
} else {
right++;
}
}
std::cout << left + right + 1;
return 0;
}
| 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;
typedef long long ll;
int tc, x, y, a, b;
ll sec;
void solve(){
cin >> x >> y >> a >> b;
if ((y - x) % (a + b) == 0){
cout << (y - x) / (a + b) << endl;
}
else
cout << -1 << endl;
return;
}
int main(){
cin >> tc;
while (tc--){
solve();
}
return 0;
}
| cpp |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5
| [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | #include <bits/stdc++.h>
#include "stdio.h"
using namespace std;
#define SZ(s) ((int)s.size())
#define all(x) (x).begin(), (x).end()
#define lla(x) (x).rbegin(), (x).rend()
#define bpc(x) __builtin_popcount(x)
#define bpcll(x) __builtin_popcountll(x)
#define MP make_pair
#define endl '\n'
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
typedef long long ll;
const int MOD = 1e9 + 7;
const int N = 2e6 + 3e2;
int lf[N], rg[N];
int cnt[N];
set<pair<int, int>> seg;
void del_point(int x){
auto it = seg.lower_bound(MP(x + 1, 0));
if (it == seg.begin()) return;
--it;
int l = it->first, r = it->second;
if (l > x || r < x) return;
seg.erase(it);
if (l < x) seg.insert(MP(l, x - 1));
if (x < r) seg.insert(MP(x + 1, r));
}
void add_point(int x){
seg.insert(MP(x, x));
auto it = seg.lower_bound(MP(x, x));
if (next(it) != seg.end()){
if (next(it)->first == x + 1){
pair<int, int> p = *next(it);
seg.erase(p);
seg.erase(it);
p.first = x;
seg.insert(p);
}
}
it = seg.lower_bound(MP(x, x));
if (it != seg.begin()){
if (prev(it)->second == x - 1){
pair<int, int> p = *prev(it);
pair<int, int> q = *it;
seg.erase(p);
seg.erase(q);
seg.insert(MP(p.first, q.second));
}
}
}
void solve(){
int n;
cin >> n;
map<int, int> mp;
for (int i = 1; i <= n; i++){
cin >> lf[i] >> rg[i];
mp[lf[i] - 1];
mp[lf[i]];
mp[rg[i]];
mp[rg[i] + 1];
}
int z = 0;
for (auto &now : mp){
now.second = ++z;
}
int lim = 8 * n + 5;
fill(cnt, cnt + lim, 0);
for (int i = 1; i <= n; i++){
lf[i] = mp[lf[i]] * 2, rg[i] = mp[rg[i]] * 2;
cnt[lf[i]]++;
cnt[rg[i] + 1]--;
}
for (int i = 1; i < lim; i++) cnt[i] += cnt[i - 1];
seg.clear();
for (int i = 0; i < lim;){
if (cnt[i] == 0){
i++;
continue;
}
int j = i;
while (j < lim && cnt[j]) j++;
seg.insert(MP(i, j - 1));
i = j;
}
vector<int> ones;
for (int i = 0; i < lim; i++){
if (cnt[i] == 1) ones.push_back(i);
}
int ans = 0;
for (int i = 1; i <= n; i++){
int pos = lower_bound(all(ones), lf[i]) - ones.begin();
for (int j = pos; j < ones.size(); j++){
if (ones[j] > rg[i]) break;
del_point(ones[j]);
}
int cur = (int)seg.size();
ans = max(ans, cur);
for (int j = pos; j < ones.size(); j++){
if (ones[j] > rg[i]) break;
add_point(ones[j]);
}
}
cout << ans << endl;
}
int main(){
clock_t startTime = clock();
ios_base::sync_with_stdio(false);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
#endif
int test_cases = 1;
cin >> test_cases;
for (int test = 1; test <= test_cases; test++){
solve();
}
cerr << "Time: " << int((double) (clock() - startTime) / CLOCKS_PER_SEC * 1000) << " ms" << endl;
return 0;
} | cpp |
1310 | F | F. Bad Cryptographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: Let's fix a finite field and two it's elements aa and bb. One need to fun such xx that ax=bax=b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 22k−122k−1 for some positive integer kk . Bitwise exclusive or (⊕⊕) operation is used as addition. One of ways to define multiplication operation (⊙⊙) is following properties: 0⊙a=a⊙0=00⊙a=a⊙0=0 1⊙a=a⊙1=a1⊙a=a⊙1=a a⊙b=b⊙aa⊙b=b⊙a a⊙(b⊙c)=(a⊙b)⊙ca⊙(b⊙c)=(a⊙b)⊙c a⊙(b⊕c)=(a⊙b)⊕(a⊙c)a⊙(b⊕c)=(a⊙b)⊕(a⊙c) If a=22na=22n for some integer n>0n>0, and b<ab<a, then a⊙b=a⋅ba⊙b=a⋅b. If a=22na=22n for some integer n>0n>0, then a⊙a=32⋅aa⊙a=32⋅a. For example: 4⊙4=64⊙4=6 8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13.8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13. 32⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=14132⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=141 5⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=85⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans;}multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a⊙k=a⊙a⊙⋯⊙ak timesa⊙k=a⊙a⊙⋯⊙a⏟k times.You need to analyze the proposed scheme strength. For pairs of numbers aa and bb you need to find such xx, that a⊙x=ba⊙x=b, or determine that it doesn't exist. InputIn the first line of input there is single integer tt (1≤t≤1001≤t≤100) — number of pairs, for which you need to find the discrete logarithm.In each of next tt line there is a pair of integers aa bb (1≤a,b<2641≤a,b<264). OutputFor each pair you should print one integer xx (0≤x<2640≤x<264), such that a⊙x=ba⊙x=b, or -1 if no such x exists. It can be shown, that if any such xx exists, there is one inside given bounds. If there are several good values, you can output any of them. ExampleInputCopy7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
OutputCopy1
1
2
4
-1
6148914691236517205
68943624821423112
| [
"math",
"number theory"
] | #pragma GCC optimize("O3","unroll-loops")
#pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define u64 unsigned long long
#define ull unsigned long long
#ifdef LOCAL
#define __int128 long long
#endif // LOCAL
int flag;
ull memo[256][256];
ull mul(ull x,ull y,int k=64){
if(k==flag)return memo[x][y];
k/=2;
ull a=x>>k;
ull b=x^(a<<k);
ull c=y>>k;
ull d=y^(c<<k);
ull bd=mul(b,d,k);
ull ac=mul(a,c,k);
ull abcd=mul(a^b,c^d,k);
return (abcd^bd)<<k ^ mul(ac,1ULL<<(k-1),k) ^ bd;
}
void init(){
flag=1;
memo[1][1]=1;
for(int i=0;i<256;i++)for(int j=0;j<256;j++)memo[i][j]=mul(i,j,8);
flag=8;
}
u64 po(u64 a,u64 b)
{
if(b==0) return 1;
if(b==1) return a;
if(!(b & 1)) {u64 u=po(a,b/2);return mul(u,u);}
else {u64 u=po(a,b-1);return mul(a,u);}
}
template<typename T>
T extgcd(T a, T b, T &x, T &y) {
if (a == 0) {
x = 0;
y = 1;
return b;
}
T p = b / a;
T g = extgcd(b - p * a, a, y, x);
x -= p * y;
return g;
}
template<typename T>
bool diophantine(T a, T b, T c, T &x, T &y, T &g) {
if (a == 0 && b == 0) {
if (c == 0) {
x = y = g = 0;
return true;
}
return false;
}
if (a == 0) {
if (c % b == 0) {
x = 0;
y = c / b;
__int128 b1=b;
g = (b1>0 ? b1 : -b1);
return true;
}
return false;
}
if (b == 0) {
if (c % a == 0) {
x = c / a;
y = 0;
g =(a>0 ? a : -a);
return true;
}
return false;
}
g = extgcd(a, b, x, y);
if (c % g != 0) {
return false;
}
T dx = c / a;
c -= dx * a;
T dy = c / b;
c -= dy * b;
x = dx + (T) ((__int128) x * (c / g) % b);
y = dy + (T) ((__int128) y * (c / g) % a);
__int128 g1=g;
g = (g1>0 ? g1 : -g1);
return true;
// |x|, |y| <= max(|a|, |b|, |c|) [tested]
}
bool crt(__int128 k1, __int128 m1, __int128 k2, __int128 m2, __int128 &k, __int128 &m) {
k1 %= m1;
if (k1 < 0) k1 += m1;
k2 %= m2;
if (k2 < 0) k2 += m2;
__int128 x, y, g;
if (!diophantine(m1, -m2, k2 - k1, x, y, g)) {
return false;
}
__int128 dx = m2 / g;
__int128 delta = x / dx - (x % dx < 0);
k = m1 * (x - dx * delta) + k1;
m = m1 / g * m2;
assert(0 <= k && k < m);
return true;
}
u64 go(vector<u64> v1,vector<u64> v2)
{
if(v1.size()==1) return v2[0];
__int128 mod1=v1.back();__int128 u1=v2.back();
v1.pop_back();v2.pop_back();
__int128 mod2=v1.back();__int128 u2=v2.back();
v1.pop_back();v2.pop_back();
__int128 mod3=mod1*mod2;__int128 res3;
crt(u1,mod1,u2,mod2,res3,mod3);
v1.push_back(mod3);v2.push_back(res3);
return go(v1,v2);
}
int32_t main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
init();
int t;cin>>t;
u64 h=(-1);
vector<u64> v={3,5,17,257,641,65537,6700417};
vector<u64> v1;
while(t--)
{
v1.clear();
u64 a,b;cin>>a>>b;
u64 inva=po(a,-2);
u64 res1=mul(a,inva);
bool ok1=true;
for(u64 mod:v)
{
u64 h=((u64) -1)/mod;
vector<pair<u64,int> > u;
int sq=sqrt(mod);
u64 s=po(a,sq*h);
u64 cur=1;
for(int i=0;i<=(mod+sq-1)/sq;++i)
{
u.push_back({cur,i*sq});cur=mul(cur,s);
}
sort(u.begin(),u.end());
cur=b;
bool ok=false;
for(u64 i=0;i<sq;++i)
{
u64 o=po(cur,h);
int pos=lower_bound(u.begin(),u.end(),make_pair(o,(int) 0))-u.begin();
if(pos==u.size() || u[pos].first!=o) {cur=mul(cur,inva);continue;}
ok=true;v1.push_back((i+u[pos].second)%mod);break;
}
if(!ok) {ok1=false;cout<<(-1)<<'\n';break;}
}
if(ok1)
{
u64 res=go(v,v1);
cout<<res<<'\n';
}
}
return 0;
}
| cpp |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
#define fs first
#define sc second
#define pii pair<int,int>
int f[7000]={0}, n, m, x, y, v[7000], now;
vector<pii>e[7000];
vector<int>q[7000];
bool dfs(int i, int par){
bool yes=(i==y);
for(pii ee:e[i]){
if(ee.fs==par)continue;
bool z=dfs(ee.fs,i);
if(z){
f[ee.sc]=max(f[ee.sc],v[now]);
q[now].push_back(ee.sc);
}
yes|=z;
}
return yes;
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n;
for(int i=1; i<n; i++){
cin >> x >> y;
e[x].push_back({y,i});
e[y].push_back({x,i});
}
cin >> m;
for(now=0; now<m; now++){
cin >> x >> y >> v[now];
dfs(x, x);
}
for(int i=0; i<m; i++){
int mn=INT_MAX;
for(int z:q[i])mn=min(mn, f[z]);
if(mn!=v[i]){
cout<<-1<<'\n';
exit(0);
}
}
for(int i=1; i<n; i++){
if(f[i]==0)f[i]=1e6;
cout << f[i] << ' ';}
cout << '\n';
} | cpp |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"data structures",
"dp",
"greedy"
] | #include <bits/stdc++.h>
#define debug(x) cerr << #x << " = " << x << '\n';
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll mod = 1e9 + 7;
const int N = 5e5 + 10;
ll dp[N], dp2[N];
void solve() {
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
stack<int> st;
for (int i = 1; i <= n; ++i) {
dp[i] = a[i];
while (st.size() && a[st.top()] > a[i]) {
st.pop();
}
int p = (st.size() == 0 ? 0 : st.top());
dp[i] += dp[p] + 1LL * (i - p - 1) * a[i];
st.push(i);
}
stack<int> st2;
for (int i = n; i >= 1; --i) {
dp2[i] = a[i];
while (st2.size() && a[st2.top()] > a[i]) {
st2.pop();
}
int p = (st2.size() == 0 ? n + 1 : st2.top());
dp2[i] += dp2[p] + 1LL * (p - i - 1) * a[i];
st2.push(i);
}
ll mx = 0, id;
for (int i = 1; i <= n; ++i) {
ll t = dp[i] + dp2[i] - a[i];
if (t > mx) {
mx = t;
id = i;
}
}
vector<int> ans(n + 1);
ans[id] = a[id];
for (int i = id - 1; i >= 1; --i) {
ans[i] = min(ans[i + 1], a[i]);
}
for (int i = id + 1; i <= n; ++i) {
ans[i] = min(ans[i - 1], a[i]);
}
for (int i = 1; i <= n; ++i) {
cout << ans[i] << " \n"[i == n];
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);cout.tie(nullptr);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
} | cpp |
1303 | F | F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10
2 1 1
1 2 1
2 2 1
1 1 2
3 1 2
1 2 2
2 2 2
2 1 2
3 2 4
2 1 5
OutputCopy2
4
3
3
4
4
4
2
2
4
| [
"dsu",
"implementation"
] | #include<bits/stdc++.h>
#define f first
#define s second
#define prev prv
#define pii pair<int,int>
using namespace std;
const int N = 300 + 5, M = 2e6 + 5, mod = 1e9 + 7; // !
int t, n, m, a[N][N], p[N * N], l[M], r[M], ans[M], prev[M];
int X[N][N];
int cn = 0;
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
struct query{
int x, y, v;
} qry[M];
int find(int x) {
return (p[x] == x ? x : p[x] = find(p[x]));
}
void merge(int x, int y) {
x = find(x), y = find(y);
if(x == y) return;
p[x] = y; --cn;
}
void add(int x, int y) {
for(int k = 0; k < 4; k++) {
int xn = x + dx[k], yn = y + dy[k];
if(a[x][y] == a[xn][yn] && xn && yn && xn <= n && yn <= m) merge(X[x][y], X[xn][yn]);
}
}
main(){
ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int q;
cin >> n >> m >> q;
for(int i = 1; i <= q; i++) {
cin >> qry[i].x >> qry[i].y >> qry[i].v;
if(qry[i].v != qry[i - 1].v) l[qry[i].v] = i;
r[qry[i].v] = i;
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) X[i][j] = m * (i - 1) + j;
}
for(int i = 1; i <= q; i++) {
for(int x = 1; x <= n; x++) {
for(int y = 1; y <= m; y++) {
p[X[x][y]] = X[x][y];
}
}
cn = 0;
for(int x = 1; x <= n; x++) {
for(int y = 1; y <= m; y++) {
if(a[x][y] == qry[i].v) add(x, y);
}
}
for(int j = l[qry[i].v]; j <= r[qry[i].v]; ++j) {
prev[j] = a[qry[j].x][qry[j].y];
a[qry[j].x][qry[j].y] = qry[i].v;
add(qry[j].x, qry[j].y);
ans[j] = cn;
}
cn = n * m;
for(int x = 1; x <= n; x++) {
for(int y = 1; y <= m; y++) {
p[X[x][y]] = X[x][y];
}
}
for(int x = 1; x <= n; x++) {
for(int y = 1; y <= m; y++) {
if(a[x][y] != qry[i].v) add(x, y);
}
}
for(int j = r[qry[i].v]; j >= l[qry[i].v]; --j) {
ans[j] += cn;
a[qry[j].x][qry[j].y] = prev[j];
if(prev[j] != qry[i].v)
add(qry[j].x, qry[j].y);
}
for(int j = l[qry[i].v]; j <= r[qry[i].v]; ++j) a[qry[j].x][qry[j].y] = qry[i].v;
i = r[qry[i].v];
}
for(int i = 1; i <= q; i++) cout << ans[i] << " ";
}
| 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"
] | /*Dev Karan Singh Sisodia*/
#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;
#define pyes cout << "Yes" << "\n";
#define pno cout << "No" << "\n";
#define br cout << "\n";
#define ff first
#define ss second
#define pb push_back
#define ppb pop_back
#define sz(x) ((long long)(x).size())
#define modd 1000000007
#define mod 998244353
#define inf 9223372036854775807
#define all(x) (x).begin(),(x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x << " -> "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
ll ceil_div(ll a, ll b) {return a % b == 0 ? a / b : a / b + 1;}
ll gcd(ll a, ll b){ if (a == 0ll) { return b;} return gcd(b % a, a);}
void solve(){
int n;
cin >> n;
vector<int> q(n);
for(int i = 0; i < n-1; i++){
cin >> q[i];
}
vector<int> arr(n, 0);
int sum = 0;
int maxi = INT_MIN;
int index;
for(int i = 0; i < n-1; i++){
sum += q[i];
if(sum > maxi){
maxi = sum;
index = i+1;
}
}
if(maxi < 0){
index = 0;
}
arr[index] = n;
for(int i = index; i < n-1; i++){
arr[i+1] = arr[i] + q[i];
}
for(int i = index - 1; i >= 0; i--){
arr[i] = arr[i+1] - q[i];
}
set<int> st;
for(int i = 0; i < n; i++){
st.insert(arr[i]);
}
if(*st.begin() == 1 && st.size() == n){
for(auto it : arr){
cout << it << " ";
}
}else{
cout << -1;
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("Error.txt", "w", stderr);
#endif // ONLINE_JUDGE
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
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<bits/stdc++.h>
#define ll long long
#define sc second
#define ft first
const int N = 1e8+9;
using namespace std;
vector<pair<long long, long long>> p(200005);
vector<ll> xs(200005), cnt(200005);
int m, n;
void update(vector<ll> &b, int u, int v) {
for (; u <= m; u += (u & (-u))) {
b[u] += v;
}
}
ll get(vector<ll> &b, int u) {
long long res = 0;
for (; u > 0; u -= (u & (-u))) {
res += b[u];
}
return res;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> p[i].ft;
// cout << p[i].ft << ' ';
}
vector<ll> vs;
for (int i = 1; i <= n; i++) {
cin >> p[i].sc;
vs.push_back(p[i].sc);
}
vs.push_back(-1*N);
sort(p.begin() + 1, p.begin() + n + 1);
sort(vs.begin(), vs.end());
vs.resize(unique(vs.begin(), vs.end()) - vs.begin());
m = vs.size();
long long ans = 0;
int pos;
for (int i = 1; i <= n; i++) {
pos = lower_bound(vs.begin(), vs.end(), p[i].sc) - vs.begin();
ans += 1LL*get(cnt, pos)*p[i].ft - get(xs, pos);
update(cnt, pos, 1);
update(xs, pos, p[i].ft);
}
// for (int i = 1; i <= n; i++) {
// cout << p[i].ft << "||" << p[i].sc << ' ';
// }
cout << ans;
} | cpp |
1286 | E | E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
OutputCopy1
2
4
5
7
9
12
InputCopy4
a 2
y 2
z 0
y 2
OutputCopy2
2
2
2
InputCopy5
a 7
u 5
t 3
s 10
s 11
OutputCopy7
9
11
12
13
NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313. | [
"data structures",
"strings"
] | #include <bits/stdc++.h>
#define ll __int128
#define int long long
#define fi first
#define se second
using namespace std;
void write(ll x){
if(x>9)write(x/10);
putchar(x%10+48);
}
const int _=6e5+7;
int n,top,st[_],fa[_],w[_],ne[_];
char s[_];
map<int,int>g;
signed main(){
scanf("%lld",&n);
cin>>s[1]>>w[1];
st[++top]=1;
ll ans=w[1],sum=0;
write(w[1]);putchar('\n');
for(int i=2,j=0;i<=n;i++){
cin>>s[i]>>w[i];
s[i]=(s[i]-'a'+ans)%26+'a',w[i]=w[i]^(int)(ans&((1<<30)-1));
while(j&&s[i]!=s[j+1])j=ne[j];
if(s[i]==s[j+1])j++;
ne[i]=j,fa[i]=s[i]!=s[ne[i-1]+1]?ne[i-1]+1:fa[ne[i-1]+1];
for(int j=i;j>1;){
if(s[j]==s[i]){j=fa[j];continue;}
int v=w[*lower_bound(st+1,st+top+1,i-j+1)];
if(!--g[v])g.erase(v);
sum-=v,j=ne[j-1]+1;
}
int num=0;
for(auto it=g.upper_bound(w[i]);it!=g.end();g.erase(it++))
num+=it->se,sum-=(int)(it->fi-w[i])*it->se;
if(s[1]==s[i])num++,sum+=w[i];
g[w[i]]+=num;
while(top&&w[st[top]]>=w[i])top--;
st[++top]=i;
write(ans+=sum+w[st[1]]),putchar('\n');;
}
return 0;
} | cpp |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using vvi = vector<vi>;
int best, a, b, c;
vvi all = {{0, 0, 1}, {0, 1, 0}, {1, 0, 0}, {0, 1, 1}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}};
vvi sets;
void subsets(int i) {
if (i == 7) {
int x = a, y = b, z = c;
int s = 0;
for (auto p : sets) {
if (p[0] > x || p[1] > y || p[2] > z) return;
s++, x -= p[0], y -= p[1], z -= p[2];
}
if (s > best) best = s;
return;
}
sets.push_back(all[i]);
subsets(i+1);
sets.pop_back();
subsets(i+1);
}
int main() {
cin.tie(0), ios::sync_with_stdio(0);
int k;
cin >> k;
while (k--) {
cin >> a >> b >> c;
sets = vvi();
best = 0;
subsets(0);
cout << best << '\n';
}
} | cpp |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"data structures",
"dp",
"greedy"
] | #include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
const int N = 1e6;
long long n, m, a[N], sumL[N], sumR[N];
void solve() {
stack<long long> L, R;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
while (!L.empty() && a[L.top()] > a[i]) {
L.pop();
}
if (!L.empty())
sumL[i] = sumL[L.top()] + (i - L.top()) * a[i];
else
sumL[i] = sumL[0] + i * a[i];
L.push(i);
}
long long t, s = 0;
for (int i = n; i >= 1; i--) {
while (!R.empty() && a[i] < a[R.top()]) {
R.pop();
}
if (!R.empty())
sumR[i] = sumR[R.top()] + (R.top() - i) * a[i];
else
sumR[i] = sumR[n + 1] + (n + 1 - i) * a[i];
R.push(i);
if (sumL[i] + sumR[i] - a[i] > s) {
s = sumL[i] + sumR[i] - a[i];
t = i;
}
}
for (int i = t - 1; i > 0; i--) {
if (a[i] > a[i + 1]) a[i] = a[i + 1];
}
for (int i = t + 1; i <= n; i++) {
if (a[i] > a[i - 1]) a[i] = a[i - 1];
}
for (int i = 1; i <= n; i++) cout << a[i] << " ";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
solve();
}
| cpp |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | // LUOGU_RID: 102634965
#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 |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | #include<bits/stdc++.h>
#define int long long
#define fa(i,a,n) for(int i=a;i<n;i++)
#define pb push_back
#define bp pop_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define vi vector<int>
#define Utaval ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
void solve(){
string s;
cin>>s;
vector<int>v;
int start=0,end=s.length()-1;
while(start<end){
if(s[end]=='(')end--;
else{
while(start<end){
if(s[start]=='('){
v.pb(start+1),v.pb(end+1);
start++,end--;
break;
}
else start++;
}
}
}
sort(v.begin(),v.end());
if(v.size()==0)cout<<0<<endl;
else{
cout<<1<<endl<<v.size()<<endl;
fa(i,0,v.size())cout<<v[i]<<" ";
cout<<endl;
}
return;
}
signed main()
{
Utaval;
int t=1;
// cin>>t;
while(t--)
solve();
} | cpp |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences. | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define int long long
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#pragma GCC optimize("Ofast")
#ifndef ONLINE_JUDGE
#include "dbg.hpp"
#else
#define debug(...) 8
#endif
void solve(){
int n;
cin>>n;
vector<pair<int,int>> v;
for(int i=1;i<=n;i++){
int k;
cin>>k;
vector<int> tmp(k);
for(int j=0;j<k;j++){
cin>>tmp[j];
}
debug(tmp);
bool ascent = false;
for(int j=0;j<k-1;j++){
if(tmp[j] < tmp[j+1]){
ascent = true;
}
}
if(!ascent){
v.push_back({tmp[0],tmp[k-1]});
}
}
v.push_back({1e13,1e13});
sort(v.begin(),v.end());
int ans=0;
for(int i=0;i<v.size()-1;i++){
ans += (int) (lower_bound(v.begin(),v.end(),make_pair(v[i].second,(int)1e13)) - v.begin());
}
debug(ans);
cout<< n*n - ans<<'\n';
}
signed main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t=1;
// cin>>t;
while(t--){
solve();
}
}
| cpp |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | #include <bits/stdc++.h>
#define int long long
using namespace std;
struct point{
int x,y;
};
struct line{
point p1,p2;
}a[4];
int len_line_pow(line a){//求线段长度的平方
return (a.p1.x-a.p2.x)*(a.p1.x-a.p2.x)+(a.p1.y-a.p2.y)*(a.p1.y-a.p2.y);
}
bool check_same_point(point p1,point p2){//判断两点是否相同
return p1.x==p2.x&&p1.y==p2.y;
}
bool check_one_line(line a,point p){//判断三点共线
return (a.p1.y-p.y)*(a.p2.x-p.x)==(a.p2.y-p.y)*(a.p1.x-p.x);
}
bool check_5_point(line a,point p){//判断p是不是在a的1/5点和4/5线之间
a.p1.x*=5,a.p2.x*=5,a.p1.y*=5,a.p2.y*=5;
p.x*=5,p.y*=5;
point p1={a.p1.x+(a.p2.x-a.p1.x)/5,a.p1.y+(a.p2.y-a.p1.y)/5};
point p4={a.p1.x+(a.p2.x-a.p1.x)/5*4,a.p1.y+(a.p2.y-a.p1.y)/5*4};
double d=sqrt((double)len_line_pow({p1,p4}));
double d1=sqrt((double)len_line_pow({p,p1}));
double d4=sqrt((double)len_line_pow({p,p4}));
return fabs(d-d1-d4)<1e-1;
}
bool check(line l,line r,line m){
//条件1:两线有唯一共同端点
int x=check_same_point(l.p1,r.p1);
if(check_same_point(l.p1,r.p2)){
x++;
swap(r.p1,r.p2);
}
if(check_same_point(l.p2,r.p1)){
x++;
swap(l.p1,l.p2);
}
if(check_same_point(l.p2,r.p2)){
x++;
swap(l.p1,l.p2);
swap(r.p1,r.p2);
}
if(x!=1){
return false;
}
//条件2:夹角不是钝角,可以是直角
if(len_line_pow(l)+len_line_pow(r)<len_line_pow({l.p2,r.p2})){
return false;
}
//条件3:第3线两端点与前两线共线
if(check_one_line(l,m.p1)&&check_one_line(r,m.p2)){
;
}else if(check_one_line(l,m.p2)&&check_one_line(r,m.p1)){
swap(m.p1,m.p2);
}else{
return false;
}
//条件4:第3线两端点必须在两线分别的1/5点和4/5线之间
if(check_5_point(l,m.p1)&&check_5_point(r,m.p2)){
return true;
}else{
return false;
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin>>T;
while(T--){
for(int i=1;i<=3;i++){
cin>>a[i].p1.x>>a[i].p1.y>>a[i].p2.x>>a[i].p2.y;
}
bool flag=false;
for(int i=1;i<=3&&!flag;i++){
for(int j=1;j<=3&&!flag;j++){
if(i==j){
continue;
}
for(int k=1;k<=3&&!flag;k++){
if(k==j||k==i){
continue;
}
flag|=check(a[i],a[j],a[k]);
}
}
}
cout<<(flag?"YES":"NO")<<"\n";
}
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"
] | // LUOGU_RID: 102518717
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
//#define int long long
//#define endl '\n'
const int N=200009;
const int INF=0x3f3f3f3f;
const int mod=998244353;
inline int read(){
int s=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
while(ch>='0'&&ch<='9'){s=(s<<1)+(s<<3)+(ch^48); ch=getchar();}
return s*=f;
}
inline void write(int x){
if(x>9)write(x/10);
putchar(x%10+48);
}
inline void print(int x){
if(x<0){putchar('-'); x=-x;}
write(x);
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T> T rnd(T l,T r){return uniform_int_distribution<T>(l,r)(rng);}
inline void file(){
freopen(".in","r",stdin);
freopen(".out","w",stdout);
}
int n,m,B,b[N],k[N],f[N],nxt[N];
inline void update(int id){
int l=(b[id]-1)*B+1;
int r=min(b[id]*B,n);
for(int i=id;i>=l;i--){
int pos=i+k[i];
if(pos>r){
f[i]=1;
nxt[i]=pos;
}
else{
f[i]=f[pos]+1;
nxt[i]=nxt[pos];
}
}
}
signed main(){
n=read(); m=read(); B=sqrt(n);
for(int i=1;i<=n;i++)k[i]=read();
for(int i=1;i<=n;i++)b[i]=(i-1)/B+1;
for(int i=n;i>=1;i--){
int pos=i+k[i];
int r=min(b[i]*B,n);
if(pos>r){
f[i]=1;
nxt[i]=pos;
}
else{
f[i]=f[pos]+1;
nxt[i]=nxt[pos];
}
}
for(int i=1;i<=m;i++){
int op=read(),id=read();
if(op==0){
k[id]=read();
update(id);
continue;
}
int ans=0;
while(nxt[id]<=n){
ans+=f[id];
id=nxt[id];
}
while(id+k[id]<=n)id+=k[id],ans++;
cout<<id<<' '<<ans+1<<'\n';
}
return 0;
}
//luogu | cpp |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | #pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
#include <array>
// #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using lld = long double;
using ull = unsigned long long;
using vll = vector<ll>;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x<<" "; _print(x); cerr << endl;
#else
#define debug(x) ((void)0);
#endif
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define loop(i,k,n) for(ll i = k; i < n;i++)
#define MOD 1000000007
#define MOD1 998244353
#define nl "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define UNIQUE(X) X.erase(unique(all(X)),X.end())
const ll INF = 1e18;
template<class A> void read(vector<A>& v);
template<class T> void read(T& x) {
cin >> x;
}
template<class H, class... T> void read(H& h, T&... t) {
read(h);
read(t...);
}
template<class A> void read(vector<A>& x) {
for (auto& a: x)
read(a);
}
template<class A> void read1(vector<A>& x) {
for(ll i = 1; i <= sz(x) - 1; i++){
read(x[i]);
}
}
void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
template<class T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
void google(int t) {cout << "Case #" << t << ": ";}
ll mul(ll a, ll b, ll m) {
if (a < (1 << 14)) {
return (a * b) % m;
}
ll c = mul(a >> 14, b, m);
c <<= 14;
c %= m;
c = (c + (a % (1 << 14)) * b) % m;
return c;
}
ll fast_power(ll p, ll e, ll m) {
if (e == 0) {
return 1 % m;
}
if (e % 2 == 0) {
return fast_power(mul(p, p, m), e / 2, m);
}
else {
return mul(fast_power(p, e - 1, m), p, m);
}
}
// #define N 200005 // change N here
// vector<vll> adjl(N);
// vll visited(N);
// ll n, m;
// vector<ll> adj[N];
// void dfs(ll u){
// visited[u] = 1;
// for(ll v: adj[u]){
// if(!visited[v]){
// dfs(v);
// }
// }
// }
// vll dist;
// void bfs(ll s) {
// dist.assign(n + 1, -1); // n must be defined(i.e global)
// queue<ll> q;
// dist[s] = 0; q.push(s);
// while (q.size()) {
// ll u = q.front(); q.pop();
// for (ll v : adj[u]) {
// if (dist[v] == -1) {
// dist[v] = dist[u] + 1;
// q.push(v);
// }
// }
// }
// }
// const ll maxn = 1000; // set maxn accordingly
// ll C[maxn + 1][maxn + 1];
// void makenCr(){
// C[0][0] = 1;
// for (ll n = 1; n <= maxn; ++n) {
// C[n][0] = C[n][n] = 1;
// for (ll k = 1; k < n; ++k)
// C[n][k] = C[n - 1][k - 1] + C[n - 1][k];
// // C[n][k] %= MOD;
// }
// }
void solve(){
ll n; cin >> n;
string s; cin >> s;
ll x = 0, y = 0;
map<pll,ll> ump;
ump[{x, y}] = -1;
auto f = [&](char c) -> void{
if(c == 'L') x --;
if(c == 'R') x ++;
if(c == 'U') y ++;
if(c == 'D') y --;
};
ll ans = INF, idx = -1;
loop(i, 0, n){
f(s[i]);
if(ump.count({x, y}))
if(ckmin(ans, i - ump[mp(x, y)] )) idx = i;
ump[mp(x, y)] = i;
}
if(ans == INF) {cout << -1 << nl; return;}
cout << idx - ans + 2 << " " << idx + 1 << nl;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
cout << "---------------------" << nl;
cout << "OUTPUT:" << nl;
freopen("error.txt", "w", stderr);
#endif
int t = 1;
cin>>t;
for(ll i = 1; i <= t; i ++)
{
// google(i);
solve();
// cout << "\n";
}
return 0;
}
| 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"
] | #include<bits/stdc++.h>
#define F(i,l,r) for(int i=(l),i##end=(r);i<=i##end;++i)
#define f(i,r,l) for(int i=(r),i##begin=(l);i>=i##begin;--i)
using namespace std;
const int N=105;
int n,a[N],b[N],c[N];
string s,st;
template<typename T>inline void readmain(T &n){T sum=0,x=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-')x=-1;ch=getchar();}while (ch>='0'&&ch<='9'){sum=sum*10+ch-'0';ch=getchar();}n=sum*x;}
template<typename T>inline T& read(T &x){readmain(x);return x;}
template<typename T,typename ...Tr>inline void read(T &x,Tr&... r){readmain(x);read(r...);}
template<typename T>inline void write(T x){if (x<0){putchar('-');x=-x;}if (x>9)write(x/10);putchar(x%10+'0');return;}
template<typename T>inline void writesc(T x){write(x);putchar(' ');}
template<typename T>inline void writeln(T x){write(x);putchar('\n');}
inline void query(int l,int r,auto &a)
{
cout<<"? "<<l<<" "<<r<<endl;
F(i,l,r)F(j,i,r)
{
cin>>st;
for (char c:st)a[st.size()]+=c;
}
}
int main()
{
read(n);s.resize(n+1);
if (n<=3)
{
F(i,1,n)query(i,i,a),s[i]=a[1]-=s[i-1];
cout<<"! "<<s.substr(1);return 0;
}
query(1,n+1>>1,a);query(2,n+1>>1,b);query(1,n,c);
F(i,1,(n+1)>>1)s[i]=(a[i]-=b[i])-a[i-1];
int j=s[n/2+1];f(i,n>>1,1)s[n-i+1]=c[i]-c[i-1]-j-s[i],j=c[i]-c[i-1];
cout<<"! "<<s.substr(1);return 0;
} | cpp |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | #include <bits/stdc++.h>
#define ll long long
using namespace std;
ll gcd_sum(ll num) {
ll t = num, d= 0;
while (t > 0) {
d += t % 10;
t /= 10;
}
ll gcd = __gcd(num, d);
return gcd;
}
void Void(){
ll n, s = 0, p = 1, c = 0, ans = 0;
cin >> n;
vector <ll> a(n);
for(ll i = 0; i < n; i++)
{
cin >> a[i];
if(a[i] == 0)
c++, a[i] = 1;
s += a[i];
}
ans = (s == 0);
if(c == 0)
cout << ans << endl;
else
cout << ans + c << endl;
}
int main(){
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
ll t = 1;
cin >> t;
while(t--)Void();
}
| cpp |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | #include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T, a, b, c, ans, tmp, aa, bb, cc;
cin>>T;
while(T--)
{
cin>>a>>b>>c;
ans = 2e9;
for(int i=1;i<=20000;++i)
{
for(int j=i;j<=20000;j+=i)
{
for(int k=j;k<=20000;k+=j)
{
tmp = fabs(i-a)+fabs(j-b)+fabs(k-c);
if(ans>tmp)
{
ans = tmp;
aa = i;
bb = j;
cc = k;
}
}
}
}
cout<<ans<<"\n"<<aa<<" "<<bb<<" "<<cc<<"\n";
}
return 0;
} | cpp |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | #include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
#define vi vector<int>
int main()
{
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int a[2*n];
for(int i=0;i<2*n;i++){
cin>>a[i];
}
sort(a,a+(2*n));
//
// cout<<a[n]<<" "<<a[n+1]<<endl;
cout<<abs(a[n-1]-a[n])<<endl;;
}
return 0;
} | cpp |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX = 2e5 + 5;
#define checkBit(n, i) ((n) & (1LL << (i)))
void solve() {
ll n, m; cin >> n >> m;
ll sum = 0;
vector<ll> a, bc(65);
for (int i = 0; i < m; i++) {
ll x;
cin >> x;
if (n & x) n -= x;
else {
a.push_back(x);
bc[__lg(x)]++;
sum += x;
}
}
if (!n) {
cout << "0\n";
return;
}
if (sum < n) {
cout << "-1\n";
return;
}
ll ans = 0;
for (int i = 0; i < 62; i++) {
if (!checkBit(n, i)) {
bc[i + 1] += bc[i] / 2;
bc[i] %= 2;
}
else {
if (bc[i]) {
n -= (1LL << i);
bc[i]--;
bc[i + 1] += bc[i] / 2;
bc[i] %= 2;
}
else {
for (int j = i; j < 62; j++) {
if (bc[j]) {
for (int k = j; k > i; k--) {
bc[k]--;
bc[k - 1] += 2;
ans++;
}
break;
}
}
if (bc[i]) {
n -= (1LL << i);
bc[i]--;
bc[i + 1] += bc[i] / 2;
bc[i] %= 2;
}
else {
ans = -1;
break;
}
}
}
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int tc = 1;
cin >> tc;
while (tc--)
solve();
return 0;
}
| cpp |
1290 | F | F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3
-1 0
1 1
0 -1
OutputCopy3
InputCopy3 3
-1 0
2 2
0 -1
OutputCopy1
InputCopy3 1776966
-1 0
3 3
0 -2
OutputCopy296161
InputCopy4 15
-4 -4
-1 1
-1 -4
4 3
OutputCopy1
InputCopy5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
OutputCopy0
InputCopy5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
OutputCopy9248783
NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is: | [
"dp"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 11
#define yu (998244353)
ll n,m;
ll ans=0;
inline void add(ll &x,ll y){x+=y;if(x>=yu)x-=yu;return ;}
ll xi[6],yi[6];
ll f[31][22][22][22][22][2][2];
inline ll dfs(ll pos,ll x,ll fx,ll y,ll fy,ll x1,ll x2){
if(pos==31){
return ((x==0)&(fx==0)&(y==0)&(fy==0)&(x1==0)&(x2==0));
}if(f[pos][x][fx][y][fy][x1][x2]!=-1)return f[pos][x][fx][y][fy][x1][x2];
ll an=0;
for(int i=0;i<(1<<n);i++){
ll jix=0,jifx=0,jiy=0,jify=0;
for(int j=1;j<=n;j++){
if(i&(1<<(j-1))){
if(xi[j]>0)jix+=xi[j];
else jifx-=xi[j];
if(yi[j]>0)jiy+=yi[j];
else jify-=yi[j];
}
}
jix+=x;jifx+=fx;jiy+=y;jify+=fy;
if(((jix&1)!=(jifx&1))||((jiy&1)!=(jify&1)))continue;
ll o=(m>>pos)&1;
add(an,dfs(pos+1,jix>>1,jifx>>1,jiy>>1,jify>>1,((o==(jix&1))?x1:(o<(jix&1))),((o==(jiy&1))?x2:(o<(jiy&1)))));
}return f[pos][x][fx][y][fy][x1][x2]=an;
}
int main()
{
// freopen("test1.in","r",stdin);
//freopen(".in","r",stdin);
//freopen("test1.out","w",stdout);
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>xi[i]>>yi[i];
}memset(f,-1,sizeof(f));
cout<<(dfs(0,0,0,0,0,0,0)-1+yu)%yu;
return 0;
}
| cpp |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44. | [
"brute force",
"data structures",
"implementation"
] | #include<iostream>
#include<algorithm>
#include<string>
#define int long long
#define endl '\n'
using namespace std;
int t, n, m, k;
int x, y;
int a[100010];
int l, r;
signed main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> t;
while (t--) {
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
int ans = 0;
k = min(k, m-1);
for (int i = 0; i <= k; i++) {
l = i + 1;
r = n - k + i;
int res = 1e9;
for (int j = 0; j <= m - k - 1; j++) {
res = min(res, max(a[l + j], a[r - (m - k - 1) + j]));
}
ans = max(ans, res);
}
cout << ans << endl;
}
return 0;
}
| cpp |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33 | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,
tree_order_statistics_node_update> indexed_set;
#define endl '\n'
#define ilihg ios_base::sync_with_stdio(false);cin.tie(NULL)
void dfs(int i,int par,vector<int> v[],vector<int> &p,int d,vector<int> &depth){
depth[i]=d;
p[i]=par;
for(auto u:v[i]){
if(u!=par){
dfs(u,i,v,p,d+1,depth);
}
}
}
void eval(int n,vector<int> v[],vector<vector<int>> &dp,vector<int> &depth){
vector<int> p(n+1);
int r=log2(n);
dp.resize(n+1,vector<int>(r+2));
depth.resize(n+1);
dfs(1,0,v,p,1,depth);
for(int i=1;i<=n;i++){
dp[i][0]=p[i];
}
for(int i=1;i<=r+1;i++){
for(int j=1;j<=n;j++){
dp[j][i]=dp[dp[j][i-1]][i-1];
}
}
}
int lca(int x,int y,vector<vector<int>> &dp,vector<int> &depth){
int ans=0;
if(depth[x]<depth[y]){
swap(x,y);
}
int c=depth[x]-depth[y];
while(c){
int p=log2(c);
x=dp[x][p];
c-=(1<<p);
ans+=(1<<p);
}
int g=log2(depth[x]);
while(g>=0){
if(dp[x][g]!=dp[y][g]){
ans+=(1<<(g+1));
x=dp[x][g];
y=dp[y][g];
}
g--;
}
if(x!=y){
ans+=2;
x=dp[x][0];
}
return ans;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
clock_t time_req=clock();
ilihg;
int t=1;
// cin>>t;
while(t--){
int n;
cin>>n;
vector<int> v[n+1];
for(int i=0;i<n-1;i++){
int c,d;
cin>>c>>d;
v[c].push_back(d);
v[d].push_back(c);
}
vector<vector<int>> dp;
vector<int> depth;
eval(n,v,dp,depth);
int q;
cin>>q;
while(q--){
int x,y,a,b,k;
cin>>x>>y>>a>>b>>k;
int z=0;
int a1=lca(a,b,dp,depth),a2=lca(a,x,dp,depth)+lca(b,y,dp,depth)+1,a3=lca(b,x,dp,depth)+lca(a,y,dp,depth)+1;
if(a1<=k&&a1%2==k%2){
z=1;
}
if(a2<=k&&a2%2==k%2){
z=1;
}
if(a3<=k&&a3%2==k%2){
z=1;
}
if(z){
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}
}
}
#ifndef ONLINE_JUDGE
cout<<"Time : "<<fixed<<setprecision(6)<<((double)(clock()-time_req))/CLOCKS_PER_SEC<<endl;
#endif
} | cpp |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement. | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | #include <bits/stdc++.h>
#pragma optimization_level 3
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
#pragma GCC optimize("Ofast")//Comment optimisations for interactive problems (use endl)
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
using namespace std;
struct PairHash {inline std::size_t operator()(const std::pair<int, int> &v) const { return v.first * 31 + v.second; }};
// speed
#define Code ios_base::sync_with_stdio(false);
#define By ios::sync_with_stdio(0);
#define Sumfi cout.tie(NULL);
// alias
using ll = long long;
using ld = long double;
using ull = unsigned long long;
// constants
const ld PI = 3.14159265358979323846; /* pi */
const ll INF = 1e18;
const ld EPS = 1e-6;
const ll MAX_N = 202020;
const ll mod = 998244353;
// typedef
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
typedef array<ll,3> all3;
typedef array<ll,4> all4;
typedef array<ll,5> all5;
typedef vector<all3> vall3;
typedef vector<all4> vall4;
typedef vector<all5> vall5;
typedef pair<ld, ld> pld;
typedef vector<pld> vpld;
typedef vector<ld> vld;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<vll> vvll;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef deque<ll> dqll;
typedef deque<pll> dqpll;
typedef pair<string, string> pss;
typedef vector<pss> vpss;
typedef vector<string> vs;
typedef vector<vs> vvs;
typedef unordered_set<ll> usll;
typedef unordered_set<pll, PairHash> uspll;
typedef unordered_map<ll, ll> umll;
typedef unordered_map<pll, ll, PairHash> umpll;
// macros
#define rep(i,m,n) for(ll i=m;i<n;i++)
#define rrep(i,m,n) for(ll i=n;i>=m;i--)
#define all(a) begin(a), end(a)
#define rall(a) rbegin(a), rend(a)
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define INF(a) memset(a,0x3f3f3f3f3f3f3f3fLL,sizeof(a))
#define ASCEND(a) iota(all(a),0)
#define sz(x) ll((x).size())
#define BIT(a,i) (a & (1ll<<i))
#define BITSHIFT(a,i,n) (((a<<i) & ((1ll<<n) - 1)) | (a>>(n-i)))
#define pyes cout<<"YES\n";
#define pno cout<<"NO\n";
#define endl "\n"
#define pneg1 cout<<"-1\n";
#define ppossible cout<<"Possible\n";
#define pimpossible cout<<"Impossible\n";
#define TC(x) cout<<"Case #"<<x<<": ";
#define X first
#define Y second
// utility functions
template <typename T>
void print(T &&t) { cout << t << "\n"; }
template<typename T>
void printv(vector<T>v){ll n=v.size();rep(i,0,n){cout<<v[i];if(i+1!=n)cout<<' ';}cout<<endl;}
template<typename T>
void printvv(vector<vector<T>>v){ll n=v.size();rep(i,0,n)printv(v[i]);}
template<typename T>
void printvln(vector<T>v){ll n=v.size();rep(i,0,n)cout<<v[i]<<endl;}
void fileIO(string in = "input.txt", string out = "output.txt") {freopen(in.c_str(),"r",stdin); freopen(out.c_str(),"w",stdout);}
void readf() {freopen("", "rt", stdin);}
template <typename... T>
void in(T &...a) { ((cin >> a), ...); }
template<typename T>
void readv(vector<T>& v){rep(i,0,sz(v)) cin>>v[i];}
template<typename T, typename U>
void readp(pair<T,U>& A) {cin>>A.first>>A.second;}
template<typename T, typename U>
void readvp(vector<pair<T,U>>& A) {rep(i,0,sz(A)) readp(A[i]); }
void readvall3(vall3& A) {rep(i,0,sz(A)) cin>>A[i][0]>>A[i][1]>>A[i][2];}
void readvall5(vall5& A) {rep(i,0,sz(A)) cin>>A[i][0]>>A[i][1]>>A[i][2]>>A[i][3]>>A[i][4];}
void readvvll(vvll& A) {rep(i,0,sz(A)) readv(A[i]);}
struct Combination {
vll fac, inv;
ll n, MOD;
ll modpow(ll n, ll x, ll MOD = mod) { if(!x) return 1; ll res = modpow(n,x>>1,MOD); res = (res * res) % MOD; if(x&1) res = (res * n) % MOD; return res; }
Combination(ll _n, ll MOD = mod): n(_n + 1), MOD(MOD) {
inv = fac = vll(n,1);
rep(i,1,n) fac[i] = fac[i-1] * i % MOD;
inv[n - 1] = modpow(fac[n - 1], MOD - 2, MOD);
rrep(i,1,n - 2) inv[i] = inv[i + 1] * (i + 1) % MOD;
}
ll fact(ll n) {return fac[n];}
ll nCr(ll n, ll r) {
if(n < r or n < 0 or r < 0) return 0;
return fac[n] * inv[r] % MOD * inv[n-r] % MOD;
}
};
struct Matrix {
ll r,c;
vvll matrix;
Matrix(ll r, ll c, ll v = 0): r(r), c(c), matrix(vvll(r,vll(c,v))) {}
Matrix(vvll m) : r(sz(m)), c(sz(m[0])), matrix(m) {}
Matrix operator*(const Matrix& B) const {
Matrix res(r, B.c);
rep(i,0,r) rep(j,0,B.c) rep(k,0,B.r) {
res.matrix[i][j] = (res.matrix[i][j] + matrix[i][k] * B.matrix[k][j] % mod) % mod;
}
return res;
}
Matrix copy() {
Matrix copy(r,c);
copy.matrix = matrix;
return copy;
}
ll get(ll y, ll x) {
return matrix[y][x];
}
Matrix pow(ll n) {
assert(r == c);
Matrix res(r,r);
Matrix now = copy();
rep(i,0,r) res.matrix[i][i] = 1;
while(n) {
if(n & 1) res = res * now;
now = now * now;
n /= 2;
}
return res;
}
};
// geometry data structures
template <typename T>
struct Point {
T y,x;
Point(T y, T x) : y(y), x(x) {}
Point(pair<T,T> p) : y(p.first), x(p.second) {}
Point() {}
void input() {cin>>y>>x;}
friend ostream& operator<<(ostream& os, const Point<T>& p) { os<<p.y<<' '<<p.x<<'\n'; return os;}
Point<T> operator+(Point<T>& p) {return Point<T>(y + p.y, x + p.x);}
Point<T> operator-(Point<T>& p) {return Point<T>(y - p.y, x - p.x);}
Point<T> operator*(ll n) {return Point<T>(y*n,x*n); }
Point<T> operator/(ll n) {return Point<T>(y/n,x/n); }
bool operator<(const Point &other) const {if (x == other.x) return y < other.y;return x < other.x;}
Point<T> rotate(Point<T> center, ld angle) {
ld si = sin(angle * PI / 180.), co = cos(angle * PI / 180.);
ld y = this->y - center.y;
ld x = this->x - center.x;
return Point<T>(y * co - x * si + center.y, y * si + x * co + center.x);
}
ld distance(Point<T> other) {
T dy = abs(this->y - other.y);
T dx = abs(this->x - other.x);
return sqrt(dy * dy + dx * dx);
}
T norm() { return x * x + y * y; }
};
template<typename T>
struct Line {
Point<T> A, B;
Line(Point<T> A, Point<T> B) : A(A), B(B) {}
Line() {}
void input() {
A = Point<T>();
B = Point<T>();
A.input();
B.input();
}
T ccw(Point<T> &a, Point<T> &b, Point<T> &c) {
T res = a.x * b.y + b.x * c.y + c.x * a.y;
res -= (a.x * c.y + b.x * a.y + c.x * b.y);
return res;
}
bool isIntersect(Line<T> o) {
T p1p2 = ccw(A,B,o.A) * ccw(A,B,o.B);
T p3p4 = ccw(o.A,o.B,A) * ccw(o.A,o.B,B);
if (p1p2 == 0 && p3p4 == 0) {
pair<T,T> p1(A.y, A.x), p2(B.y,B.x), p3(o.A.y, o.A.x), p4(o.B.y, o.B.x);
if (p1 > p2) swap(p2, p1);
if (p3 > p4) swap(p3, p4);
return p3 <= p2 && p1 <= p4;
}
return p1p2 <= 0 && p3p4 <= 0;
}
pair<bool,Point<ld>> intersection(Line<T> o) {
if(!this->intersection(o)) return {false, {}};
ld det = 1. * (o.B.y-o.A.y)*(B.x-A.x) - 1.*(o.B.x-o.A.x)*(B.y-A.y);
ld t = ((o.B.x-o.A.x)*(A.y-o.A.y) - (o.B.y-o.A.y)*(A.x-o.A.x)) / det;
return {true, {A.y + 1. * t * (B.y - A.y), B.x + 1. * t * (B.x - A.x)}};
}
//@formula for : y = ax + fl
//@return {a,fl};
pair<ld, ld> formula() {
T y1 = A.y, y2 = B.y;
T x1 = A.x, x2 = B.x;
if(y1 == y2) return {1e9, 0};
if(x1 == x2) return {0, 1e9};
ld a = 1. * (y2 - y1) / (x2 - x1);
ld b = -x1 * a + y1;
return {a, b};
}
};
template<typename T>
struct Circle {
Point<T> center;
T radius;
Circle(T y, T x, T radius) : center(Point<T>(y,x)), radius(radius) {}
Circle(Point<T> center, T radius) : center(center), radius(radius) {}
Circle() {}
void input() {
center = Point<T>();
center.input();
cin>>radius;
}
bool circumference(Point<T> p) {
return (center.x - p.x) * (center.x - p.x) + (center.y - p.y) * (center.y - p.y) == radius * radius;
}
bool intersect(Circle<T> c) {
T d = (center.x - c.center.x) * (center.x - c.center.x) + (center.y - c.center.y) * (center.y - c.center.y);
return (radius - c.radius) * (radius - c.radius) <= d and d <= (radius + c.radius) * (radius + c.radius);
}
bool include(Circle<T> c) {
T d = (center.x - c.center.x) * (center.x - c.center.x) + (center.y - c.center.y) * (center.y - c.center.y);
return d <= radius * radius;
}
};
ll __gcd(ll x, ll y) { return !y ? x : __gcd(y, x % y); }
all3 __exgcd(ll x, ll y) { if(!y) return {x,1,0}; auto [g,x1,y1] = __exgcd(y, x % y); return {g, y1, x1 - (x/y) * y1}; }
ll __lcm(ll x, ll y) { return x / __gcd(x,y) * y; }
ll modpow(ll n, ll x, ll MOD = mod) { if(x < 0) return modpow(modpow(n,-x,MOD),MOD-2,MOD); n%=MOD; if(!x) return 1; ll res = modpow(n,x>>1,MOD); res = (res * res) % MOD; if(x&1) res = (res * n) % MOD; return res; }
ll solve(ll n, ll m) {
ll res = n * (n + 1) / 2, z = n - m;
ll buc = m + 1;
if(buc > z) return res - z;
ll d = z / buc, r = z % buc;
return res - (r * (d + 1) * (d + 2) / 2) - (d * (d + 1) / 2 * (buc - r));
}
int main() {
Code By Sumfi
cout.precision(12);
ll tc = 1;
in(tc);
rep(i,1,tc+1) {
ll n,m;
in(n,m);
print(solve(n,m));
}
return 0;
} | cpp |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | /*
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⣋⣯⡀⠀⣠⣿⠿⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠰⣤⡙⣿⡄⠀⣷⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⣠⡾⠙⠟⣩⡤⢾⠉⡿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⣼⣿⡷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⢀⣾⠿⠶⠶⠚⠉⡀⢰⣤⢳⠧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⢿⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⢸⠃⠀⣿⡄⠀⠀⣷⡘⡿⠟⠃⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠠⠀⢸⣀⡀⠟⠉⣟⣛⣿⡴⠶⠛⠋⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠁⠀⠀⠀⣩⣥⡴⠞⠋⠉⠀⠀⣀⣠⣤⣤⣶⣶⣶⣶⣶⠶⠶⢶⣶⣶⣦⣤⣤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠁⠀⠀⠶⠛⠉⠀⠀⠀⠀⣶⣶⣿⣿⣿⡿⠿⡿⣿⣿⣀⡀⠿⣦⡀⠀⠈⠉⠙⠛⠛⠿⣿⣯⣰⢤⣄⡀⠀⠀⠀⠀⠀⠘⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⣀⣴⣶⠿⠋⠉⠁⠀⠀⠀⠀⠀⠈⠻⣿⣷⡀⠙⠿⣦⡀⠀⠀⠀⠀⠀⠀⠉⠙⠻⢶⣧⣹⣦⣀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⢠⣴⠿⡛⣁⡀⠀⠀⠀⠀⢀⣀⡀⠀⠀⠀⠀⠈⠻⣷⡀⠀⠈⠳⡄⠀⠀⠀⠀⢲⡀⠀⠀⠀⠈⠉⠀⠙⣧⡀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⢠⣾⣶⡿⣧⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⠀⠀⠀⢀⣬⣿⡀⠀⠀⠘⢦⡀⠀⢀⣄⠻⣄⠀⠀⠀⠀⠀⠀⠸⠿⣦⡀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⠀⢴⣿⣿⣿⣿⠟⠛⠛⠛⠛⣿⣛⣛⠛⠛⠋⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣦⣀⡀⠈⠻⣷⣌⢻⣷⣭⣑⠀⠀⠀⠸⣦⡀⠀⠸⣧⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡟⠰⣿⣿⣿⠋⣡⣴⣾⣿⣷⣶⣶⣯⣙⠿⣷⣦⡀⠀⠀⠀⠀⣼⣿⣿⣿⣉⣬⣿⣿⣶⣾⣿⣿⣷⣝⢿⣿⣿⣶⣀⣄⠙⢿⣦⡀⠀⡆⢸⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡀⢰⣿⣿⣿⠟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣮⣻⡏⠀⠀⠀⠀⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣜⠿⢿⣿⣿⣦⣄⠙⣇⣤⣀⣸⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⠿⣿⣿⣟⣻⣿⣿⣿⣿⣟⣿⣿⣶⣀⣤⣄⣀⣰⣿⠟⠹⠿⢯⡿⣿⣿⣿⡿⠿⠿⢿⣿⣿⣷⣌⣻⣿⣿⣿⣿⣿⣿⢉⣛⢿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠈⠉⠉⠉⠉⠉⠉⠉⠉⢻⣿⡿⠛⠛⢿⣿⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⠙⢿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⠋⢻⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⠇⠀⠀⢸⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⠟⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠘⢻⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⠀⢸⣿⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⡿⠀⠀⠀⠀⣿⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠠⣾⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡀⢸⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⣿⢁⣤⣤⣤⣄⡈⢿⣷⡀⠀⠀⠀⠀⠀⠀⠀⢀⢀⣴⣿⠏⠀⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⣰⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣧⠈⣿⣿⣿⣿⣶⣄⣀⣀⣀⣀⣤⣶⡿⠟⠹⣿⣻⣿⣿⣻⣿⡿⠻⢿⣦⣄⣀⡀⢀⣀⣠⣼⣿⡿⠃⠀⠀⣿⣿⣿⣿⣿⣿⡟⢿⣧⣰⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⣿⣿⣿⡆⠉⠛⠛⠛⠛⠛⠛⠉⠀⠀⠀⠉⠉⠛⡿⠉⠁⠀⠀⠀⠉⠛⠛⠿⠿⠿⠛⠋⠁⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣇⣠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡶⠶⠶⠒⠒⢦⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⣿⣿⣿⣿⣿⣿⣿⢻⣿⣿⡋⠉⠉⠙⠷⢿⣯⡙
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⣥⣤⣤⣶⣶⣶⣦⣽⣷⣶⣤⣴⠆⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⢸⣿⡟⠀⠀⠀⠀⠀⢸⣿⠁
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠻⠾⠿⠿⠷⠶⢾⣛⠉⠁⠀⢀⣤⡼⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⢸⣿⠁⠀⠀⠀⠀⠀⣾⠃⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠛⠛⠛⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⢿⡿⠀⠀⠀⠀⢀⣾⠃⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣟⣾⠃⠀⠀⠀⢠⡿⠁⠀⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⣿⣿⣿⣿⣿⣿⡿⠃⠀⠀⠀⢨⡟⠀⠀⠀⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣯⠀⠀⠀⠀⢠⡿⠀⠀⠀⠀⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡴⠾⠛⠁⠘⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⠟⠁⠀⠀⠀⢀⡞⢀⠄⠀⠀⠀⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠙⣃⠉⠛⠻⠶⣾⣿⣿⣿⣿⣶⣷⡶⠖⠒⠀⠀⠀⠀⠀⠀⣸⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⠀⡼⠁⡼⠀⠀⠀⠀⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠁⢠⣿⣷⣤⠀⠄⠈⠉⠿⣿⣿⣿⠿⠄⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⠁⠀⠀⠀⠀⣼⠃⡼⠁⠀⠀⠀⠀⠀⠀
⣿⣿⣿⣿⣿⣿⣿⡿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⢸⣿⣿⣿⣧⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⢰⠇⡼⠁⠀⠀⠀⠀⠀⠀⠀
⣿⣿⣿⣿⣿⣿⢋⣴⣿⣭⣭⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠈⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⣴⣿⣿⣿⣿⡟⠀⠀⠀⠀⢰⡟⠸⠁⠀⠀⠀⠀⠀⠀⠀⠀
⣿⣿⣿⣿⠟⣡⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠙⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡴⢆⣠⣾⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⣸⡇
*/
#include <bits/stdc++.h>
using namespace std;
#define fo(i, a, n) for (i = a; i < n; i++)
#define ll long long
#define si(x) scanf("%d", &x)
#define sl(x) scanf("%lld", &x)
#define ss(s) scanf("%s", s)
#define pi(x) printf("%d\n", x)
#define pl(x) printf("%lld\n", x)
#define ps(s) printf("%s\n", s)
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define clr(x) memset(x, 0, sizeof(x))
#define sortall(x) sort(all(x))
#define tr(it, a) for (auto it = a.begin(); it != a.end(); it++)
#define PI 3.1415926535897932384626
typedef pair<int, int> pii;
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vpii;
typedef vector<pl> vpl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
/////////////////////////////////////////////////////////////////////////////////////////
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V> &x)
{
cerr << '{';
__print(x.first);
cerr << ',';
__print(x.second);
cerr << '}';
}
template <typename T>
void __print(const T &x)
{
int f = 0;
cerr << '{';
for (auto &i : x)
cerr << (f++ ? "," : ""), __print(i);
cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v)
{
__print(t);
if (sizeof...(v))
cerr << ", ";
_print(v...);
}
#ifndef ONLINE_JUDGE
#define debug(x...) \
cerr << "[" << #x << "] = ["; \
_print(x)
#else
#define debug(x...)
#endif
////////////////////////////////////////CONST////////////////////////////////////////////
const int mod = 1'000'000'007;
const int N = 3e5, M = N;
///////////////////////////////////////FUNCTION//////////////////////////////////////////
int mpow(int base, int exp)
{
base %= mod;
int result = 1;
while (exp > 0)
{
if (exp & 1)
result = ((ll)result * base) % mod;
base = ((ll)base * base) % mod;
exp >>= 1;
}
return result;
}
ll mod_mul(ll a, ll b, ll m)
{
a = a % m;
b = b % m;
return (((a * b) % m) + m) % m;
}
int ncr(int n, int r)
{
vector<int> c(n + 1);
c[0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = min(i, r); j > 0; j--)
{
c[j] = (c[j] + c[j - 1]) % mod;
}
}
return c[r];
}
///////////////////////////////////////////////CODE////////////////////////////////////////////////////////////////////////
void solve()
{
int n, k;
cin >> n >> k;
vector<string> vec(n);
unordered_map<string, int> mpp;
for (int i = 0; i < n; i++)
{
cin >> vec[i];
mpp[vec[i]]++;
}
int count = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
string s = "";
for (int z = 0; z < k; z++)
{
if (vec[i][z] == vec[j][z])
s += vec[i][z];
else
{
if (vec[i][z] == 'S' && vec[j][z] == 'E' || vec[i][z] == 'E' && vec[j][z] == 'S')
s += 'T';
if (vec[i][z] == 'S' && vec[j][z] == 'T' || vec[i][z] == 'T' && vec[j][z] == 'S')
s += 'E';
if (vec[i][z] == 'T' && vec[j][z] == 'E' || vec[i][z] == 'E' && vec[j][z] == 'T')
s += 'S';
}
}
/* debug(s); */
if (mpp[s])
{
count++;
}
mpp[vec[j]]--;
}
for (int t = i + 1; t < n; t++)
mpp[vec[t]]++;
mpp[vec[i]]--;
}
cout << count;
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
/* cin >> t; */
while (t--)
{
solve();
}
return 0;
}
| cpp |
1284 | E | E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213 | [
"combinatorics",
"geometry",
"math",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,b) FOR(i,0,b)
#define pb push_back
const long double pi = acos(-1.0L);
signed main() {
int n;
cin >> n;
long double x[n], y[n];
F0R(i,n) cin >> x[i] >> y[i];
int ans = 0;
F0R(i,n) {
vector<long double> v;
F0R(j,n) if (j != i) {
v.pb(atan2(y[j]-y[i],x[j]-x[i]));
}
sort(v.begin(), v.end());
int f[n-1], s[n-1];
int k = 0;
F0R(j,n-1) {
while (k < n-1 && v[k] < v[j]+pi) ++k;
f[j] = k;
s[j] = (j?s[j-1]:0)+f[j];
}
F0R(j,n-1) {
ans += (s[f[j]-1]-s[j])-(f[j])*(f[j]-j-1);
}
}
cout << ans*(n-4)/2 << endl;
}
| cpp |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] | #include<bits/stdc++.h>
using namespace std;
#define ll long long
void solve()
{
ll n;
cin>>n;
double ans=1;
for(ll i=n;i>=2;i--){
ans+=(double)(1/(double)i);
// cout<<double(1/(double)i)<<endl;
}
cout<<fixed<<setprecision(12)<<ans<<endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t=1;
// cin>>t;
while(t--)
{
solve();
}
return 0;
}
| cpp |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
| [
"math"
] | /*Pash_Mak*/
#include <bits/stdc++.h>
using namespace std;
[[maybe_unused]] const bool Tests = true;
class Pash
{
public:
int t;
static void B()
{
int n , ans = 0 , res = 1e9;
cin >> n;
while (n > 0) {while (n < res) res /= 10;ans += res , n -= res - res / 10;}
cout << ans << '\n';
}
};
int main()
{
ios_base::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);
Pash Mak;
if (Tests) cin >> Mak.t;
else Mak.t = 1;
while(Mak.t --)
Pash::B();
return 0;
}/*.
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣶⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡄⠀⠀⠀⠀⠀⠀⢀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣤⣤⣄⠀⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣄⣤⣶⣷⣿⣿⣿⣻⠿⣦⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡾⢛⣯⣽⣿⣿⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣮⡻⣧⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠜⢣⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣮⣳⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠌⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡷⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀ ⠀⠀⠀⠀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣡⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡰⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⢦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠅⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡜⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡌⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢱⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢐⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡆⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡜⢀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⢱⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠁⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡆⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠘⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⠀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠉⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡄⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⠀⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠁⢸⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠐⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⣸⡏⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⣿⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⣀⣠⣤⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠷⠾⠛⠛⠛⠉⠉⠁⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠈⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣇⠙⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⡆⠈⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠤⠽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡾⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡸⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠻⣿⣿⡄⠈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⠛⠙⠁⣀⣠⣤⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢹⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⠒⠲⠶⢦⣬⣿⣿⣄⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠀⢀⣤⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣤⣶⣶⣶⣶⣶⣶⣶⣶⣶⣦⣤⣀⣀⠈⠙⠳⠍⠂⠀⠈⠻⣿⣧⡙⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⠛⠻⢿⣿⢷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⡀⠀⠀⠀⠀⠀⠈⠓⢄⠀⠈⠙⠿⢿⣿⣿⠻⠿⠿⠿⠟⠿⠀⠀⠀⢠⣾⣿⡿⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠈⠂⠀⠀⠀⠈⠉⠑⠀⠀⠀⠀⠀⠀⠀⠀⠉⠀⠀⠀⢸⣿⣿⣿⡿⠟⠛⠿⠿⡿⣿⣿⣿⣿⠀⠀⠈⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⡟⠀⠀⠀⠀⠀⠀⢘⣿⣿⠃⠀⠀⠠⠾⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠉⠀⢙⣿⣿⣿⣿⡟⠉⠉⠛⠛⠿⢿⣿⡿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠉⠉⠉⠉⠉⠙⠛⠛⠛⠛⠛⠒⠂⠁⠀⠀⠀⠀⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠉⠙⠿⣧⡀⠀⠀⠀⠻⣿⣿⡟⠁⠀⢀⡀⠤⠶⠾⠛⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠰⠲⠀⠀⠀⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀⠈⠁⠀⠀⢀⣀⣭⠿⠗⠚⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠄⡀⢀⡠⢠⠂⣠⠀⢀⠀⠀⠀⠀⠄⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠀⠄⠐⢁⠁⣣⢣⢢⠃⠀⢊⡾⢠⡦⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀⠀⣠⠀⠀⠠⢀⢆⢄⡜⣸⢠⡔⡴⠠⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀⠁⠠⠃⠀⠀⠠⠁⠅⣿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⡆⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠈⠀⠀⠠⣡⣯⠎⡸⣿⢳⠇⠏⢀⠂⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠠⠡⠁⠐⠁⠏⠎⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢸⠃⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠞⠁⢸⣿⣿⣿⣿⣿⣿⠟⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⡀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠔⠃⠀⠀⠀⠀⣿⣿⣿⡿⠟⠁⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢻⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠙⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⢢⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⢀⣿⠋⣽⡇⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⣼⠀⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠛⢿⣿⣿⣿⣿⣿⣿⠀⠈⠁⠀⠁⠒⠂⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⡏⠀⡿⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡇⢰⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠈⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢱⠀⠀⠀⠈⠙⠿⠿⠿⢿⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⡿⠀⣸⠇⠀⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠀⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡆⣇⠀⠀⠀⠀⠀⠀⠀⠀⢻⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⡴⠖⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⡿⠁⠀⡿⠀⠀⠀⠀⠀⣸⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠘⡄⠀⠀⠀⠀⠀⠀⠀⠀⢹⣧⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢤⣤⣤⠤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠁⢀⠔⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⡟⠀⠀⣸⠃⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⡿⣸⣿⣿⣿⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠘⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⡎⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⢨⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⢳⡀⠀⠀⠀⠀⠀⠀⠀⠀⠘⢷⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠓⠀⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡼⠋⠀⠀⢰⡟⠀⠀⠀⠀⠀⢰⣿⣿⣿⣿⣿⣿⣿⠇⣿⣿⣿⣿⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⢰⠁⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⢸⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⢳⡀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠻⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠞⠁⠀⠀⢀⡞⠀⠀⠀⠀⠀⠀⣸⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⢸⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⢸⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠈⢧⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⠞⠁⠀⠀⠀⠀⡞⠁⠀⠀⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⠇⢠⣿⣿⣿⡟⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠇⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⢸⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠘⢷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠓⢦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠊⠀⠀⠀⠀⠀⢀⠞⠀⠀⠀⠀⠀⠀⠀⣸⢿⣿⣿⣿⣿⣿⡿⠀⣼⣿⣿⣿⡇⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⢿⡇⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⡘⠀⢸⣿⡟⢻⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⢸⠀⢸⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠀⠈⢻⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠣⢄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⠔⠉⠀⠀⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⢰⡿⣼⣿⣿⣿⣿⣿⠁⢀⣿⣿⣿⣿⣧⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠸⡇⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⡅⠀⣾⣿⠇⢸⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⡾⠀⢸⣿⣿⣿⣿⡟⣿⣿⣿⣿⣿⣿⣿⡷⠀⠀⠀⠀⠙⢦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠓⠤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣶⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡾⢱⣿⣿⣿⣿⣿⠇⠀⣼⡇⣿⣿⣿⣿⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢰⠀⣀⣿⣿⠀⢸⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⡇⠀⣿⣿⣿⣿⣿⣷⢻⣿⣿⣿⣿⣿⣿⣷⡁⠀⠀⠀⠀⠀⠉⠂⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⣦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣾⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⠃⣾⣿⣿⣿⣿⡏⠀⢸⡿⠀⣿⣿⣿⣿⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠸⡇⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠇⢀⣿⣿⡿⠀⢸⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⠀⢀⠃⢀⣿⣿⣿⣿⣿⣿⠀⢿⣿⣿⣿⣿⣿⣿⣯⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣦⣤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣴⣾⣿⣿⣿⣿⣿⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡾⠃⣸⣿⣿⣿⣿⡏⠀⣰⡿⠁⠀⣿⣿⣿⣿⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⣇⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⡼⠀⠸⣿⣿⠇⠀⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⢸⠀⣼⣿⣿⣿⣿⣿⣿⣇⠈⣿⣿⣿⣿⣷⢿⣿⣖⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣷⣤⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣶⡤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠞⠀⣰⣿⣿⣿⣿⠏⠀⣴⠟⠀⠀⠀⣿⣿⣿⣿⡀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⢹⡄⠀⠀⠀⠀⠀⠀
⠀⠀⢠⠃⠀⣶⣿⣿⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⠀⠀⡏⢰⣿⣿⣿⣿⠁⢻⣿⣿⡄⠘⢿⣿⣿⣿⡇⠻⣿⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣶⣤⣀⣀⣤⣶⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⣟⣿⣿⠋⢀⠌⠃⠀⠀⠀⠀⣿⣿⣿⣿⡇⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠈⡇⠀⠀⠀⠀⠀⠀
⠀⠀⡏⠀⡸⣾⣿⡟⠀⠀⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠁⠀⠀⢸⢱⣿⣿⣿⣿⡏⠀⠈⣿⣿⣷⡀⠈⢿⣿⣿⣿⡄⠙⢿⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⡿⢫⣾⠟⠁⠀⠁⠀⠀⠀⠀⠀⠀⢻⣿⢸⣿⣿⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⢹⡄⠀⠀⠀⠀⠀
⠀⡜⠀⠀⣧⣿⣿⠃⠀⠀⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠀⠀⠀⣴⣿⣿⣿⣿⣿⠇⠀⠀⣿⠈⢿⣧⠀⠀⠹⣿⣿⣷⡀⠀⠙⢷⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡾⠋⣠⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⡟⣿⣿⡄⠀⠀⠀⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠸⣇⠀⠀⠀⠀⠀
⠘⠁⠀⣸⣾⣿⡟⠀⠀⢰⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⣼⣿⣿⣿⣿⣿⡟⠀⠀⢀⣿⠀⠈⢻⣧⠀⠀⠈⢿⣿⣷⡀⠀⠀⠙⢷⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠤⠔⠛⠉⡠⠞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣇⠸⣿⣷⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡆⢻⡆⠀⠀⠀⠀
⠁⠀⠀⣿⣿⣿⡇⠀⠀⣸⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠁⠀⠀⣼⣿⣿⣿⣿⣿⣿⠃⠀⠀⢸⣿⠀⠀⠀⠙⠷⣄⠀⠀⠙⢿⣷⡄⠀⠀⠀⠀⠉⠒⠀⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⡄⠹⣿⣆⠀⠀⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠘⣿⡀⠀⠀⠀
⠀⠀⣸⣿⣿⣿⠀⠀⠀⠇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⢀⣾⣿⣿⣿⣿⣿⣿⠏⠀⠀⠀⣿⡏⠀⠀⠀⠀⠀⠈⠑⠄⠀⠀⠉⠳⢤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣤⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣧⠀⠹⣿⣆⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠸⣿⣿⣿⣿⣇⠘⣷⠀⠀⠀
⠀⢀⣿⣿⣿⡇⠀⠀⢀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣤⣤⣤⣼⣿⣄⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⠠⠀⠀⠀⠀⣀⣀⣀⣀⣀⣤⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢿⣧⠀⠙⣿⣧⡀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿⣿⣿⣿⣿⠀⢻⣆⠀⠀
⢀⣾⣿⣿⣿⠁⠀⠀⡌⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⣠⣾⣿⣿⣿⡿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣼⣿⣶⣶⡶⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣤⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣆⠀⠙⢿⣿⣦⡀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠸⣿⣿⣿⣿⣇⠀⢿⡂⠀
⣼⣿⣹⣿⡇⠀⠀⠰⠁⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⣾⣿⣿⣿⣿⣿⣿⣷⣤⣀⠙⠛⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣤⣴⣶⣶⣶⣶⣶⣶⣶⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⣿⣿⣿⣿⣿⡀⠈⣷⡀
⣿⣿⣿⡿⠀⠀⠀⡘⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠋⠉⠀⠈⠈⠙⠿⢿⣿⣿⣿⣷⣴⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠘⣿⣿⣿⣿⣧⠀⠘⣧
⣿⣾⣿⠃⠀⠀⢰⠁⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠀⢿⣿⣿⣿⣿⡄⠀⠸
⣿⣿⡿⠀⠀⠀⡀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠛⠋⠉⠀⠀⠀⠀⠀⠉⠙⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠘⣿⣿⣿⣿⣿⡀⠀
⣿⣿⠁⠀⠀⠰⢁⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⢻⣿⣿⣿⣿⣧⠀
⣿⡟⠀⠀⢠⠇⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣏⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠧⠹⣿⣿⣿⣿⣿⡄⠀⠀⢸⡿⣿⣿⣿⣿⡇
⡟⠀⠀⢀⡞⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⢫⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡸⣿⣿⣿⡿⠟⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣧⠀⠀⠈⣿⠸⣿⣿⣿⣿
⠃⠀⢀⡾⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⡀⠀⠀⢹⡆⠹⣿⣿⣿
⠀⢀⣞⢡⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⣿⣿⣿⣇⠀⠀⢸⣧⠀⠻⣿⣿
⢀⢼⢃⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⡄⠀⠈⣿⠀⠀⠻⣿
⢮⢏⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢹⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣇⠀⠀⢹⡆⠀⠀⠹
⢊⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⣸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⡄⠀⠀⣷⠀⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣧⠀⠀⢻⡄⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣿⣿⣿⣿⣿⣇⠀⠘⣧⠀⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⡄⠀⢿⡂⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⢸⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢢⠀⠀⠀⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣷⠀⠘⣧⠀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣹⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⡇⠀⠀⠀⠀⠀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠀⠀⠀⠀⠀⠀⢠⣞⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣇⠀⢻⡆
⣿⣿⣿⣿⣿⣿⣿⣿⠏⣿⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢷⡀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⢠⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⡀⠘⣷
⣿⣿⣿⣿⣿⣿⣿⣿⢠⡇⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣧⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡆⠀⠀⠀⠀⢠⣿⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⢹
⣿⣿⣿⣿⣿⣿⣿⡏⢸⠁⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⡆⠀⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠀⠀⠀⢺⡿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⢸*/ | cpp |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
while(n--){
int m;
string s;
int ans=0,count=0;
cin>>m;
cin>>s;
for(int i=m-1;i>=0;i--){
if(s[i]=='P'){
count++;
}
else{
ans = max(ans, count);
count=0;
}
}
cout<<ans<<"\n";
}
}
| cpp |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | //ANY TIME YOU SEE OPTIMIZATION PROBLEM -> BINARY SEARCH THE ANSWER!!!
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define No cout<<"No"<<endl;
#define NO cout<<"NO"<<endl;
#define Yes cout<<"Yes"<<endl;
#define YES cout<<"YES"<<endl;
#define MOD 1000000007
void solve()
{
ll n, m, i, j, cnt=0;
string s;
cin>>n>>s;
for(i=0;i<=n;i++)
{
vector<pair<char,ll>> v;
for(j=0;j<n;j++)
{
if((j>0 && s[j]==s[j-1]+1) || (j<n-1 && s[j]==s[j+1]+1))
{
v.push_back({s[j], j});
}
}
if(v.size()==0)
{
//cout<<cnt<<endl;
break;
}
sort(v.rbegin(),v.rend());
s.erase(v[0].second, 1);
cnt++;
}
//cout<<s<<endl;
cout<<n-s.size()<<endl;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(nullptr);
//int t; cin>>t;
//while(t--)
solve();
} | cpp |
1284 | E | E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213 | [
"combinatorics",
"geometry",
"math",
"sortings"
] | #include <bits/stdc++.h>
using namespace std;
struct pt {
int x, y;
};
int quadrant(pt a) {
if (a.y >= 0 && a.x > 0) return 0;
else if (a.x <= 0 && a.y > 0) return 1;
else if (a.y <= 0 && a.x < 0) return 2;
else return 3;
}
bool operator < (pt& a, pt& b) {
// for the purposes we need it for, a and b are nonzero and at different angles
int qa = quadrant(a);
int qb = quadrant(b);
if (qa != qb) return qa < qb;
return 1LL*a.x*b.y > 1LL*b.x*a.y;
}
bool within_half_rotation(pt& a, pt& b) {
return (1LL*a.x*b.y >= 1LL*b.x*a.y);
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int n;
cin >> n;
vector<pt> pts(n);
for (pt& p: pts) cin >> p.x >> p.y;
// for each point, calculate how many triangles enclose it
long long ans = 0;
for (int i = 0; i < n; i++) {
vector<pt> rel;
rel.reserve(n-1);
for (int j = 0; j < n; j++) {
if (j == i) continue;
rel.emplace_back(pt{pts[j].x-pts[i].x, pts[j].y-pts[i].y});
}
sort(rel.begin(), rel.end());
long long triangles = 1LL*(n-1)*(n-2)*(n-3)/6;
int r = 0;
for (int l = 0; l < n-1; l++) {
while (within_half_rotation(rel[l], rel[r])) {
r++;
if (r == n-1) r = 0;
if (r == l) break;
}
int k = r-l-1;
if (k < 0) k += n-1;
triangles -= k*(k-1)/2;
if (r == l) r++;
if (r == n-1) r = 0;
}
ans += triangles;
}
ans = (n-4)*ans/2;
cout << ans << '\n';
}
| cpp |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | #include <bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);
#define test fast int t;cin>>t;while(t--)
#define test2 int t;scanf("%d",&t);while(t--)
#define pb push_back
#define fs first
#define sc second
#define mp make_pair
#define loop(i,n) for(int i=0;i<n;i++)
#define lt(i) ((i<<1)+1)
#define rt(i) ((i<<1)+2)
#define par(i) ((i-1)>>1)
#define f(k,n) k*(2*n-k-1)
#define all(v) v.begin(), v.end()
#define sz(v) v.size()
#define vc vector
using ll = long long int;
using ull = unsigned ll;
using vi = vc<int>;
using vb = vc<bool>;
using vl = vc<ll>;
using pii = pair<int,int>;
ll mod = 1e9+7;
ll inf = 2e18;
const ll constant = 1e5;
// input/output
template <typename T> ostream& operator<<(ostream&os,const vector<T>&v){
loop(i,v.size()){
os<<v[i]<<" ";
}
os<<',';
return os;
}
template <typename T> istream& operator>>(istream&is,vector<T>&v){
loop(i,v.size())is>>v[i];
return is;
}
template <typename T, typename S> ostream& operator<<(ostream&os,const pair<T,S>&p){
os<<"("<<p.fs<<", "<<p.sc<<")";
return os;
}
template <typename T> ostream& operator<<(ostream&os,const set<T>&s){
os<<"{";
for(auto it:s){
os<<it<<",";
}
os<<"}";
return os;
}
template <typename T, typename S> ostream& operator<<(ostream&os, const map<T,S>&h){
os<<"{";
for(auto i:h){
os<<i.fs<<":"<<i.sc;
if(i!=*h.end())os<<",";
}
os<<"}";
return os;
}
template <typename T> ostream& operator<<(ostream&os,const deque<T>&d){
os<<"{";
for(auto i:d){
os<<i<<",";
}
os<<'}';
return os;
}
void print(){cout<<"\n";}
template <typename T, typename... types>void print(T var,types... vars){
cout<<var<<" ";
print(vars...);
}
// debug
vector<string> vcsplit(string s){
s += ",";
string temp = "";
vc<string> v;
loop(i,sz(s)){
if(s[i]==','){
v.pb(temp);
temp="";
}
else temp+=s[i];
}
return v;
}
void debug_out(
vc<string> __attribute__ ((unused)) args,
int __attribute__ ((unused)) idx,
int __attribute__ ((unused)) LINE) {
cerr<<endl;
}
template<typename H,typename... T> void debug_out(vc<string>args,int idx,int LINE,H h,T... t){
cerr<<((idx)?", ":"Line("+to_string(LINE)+") ");
stringstream ss; ss<<h;
cerr<<args[idx]<<" = "<<ss.str();
debug_out(args,idx+1,LINE,t...);
}
#ifdef XOX
#define debug(...) debug_out(vcsplit(#__VA_ARGS__),0,__LINE__,__VA_ARGS__);
#else
#define debug(...) 42;
#endif
// template classes
//code
ll cnt = 0;
void fill_bits(vi&v,ll cur){
loop(i,63){
if(cur&(1ll<<i))v[i]++;
}
}
void split(vi&v, int idx, int cur){
while(idx>cur){
v[idx]--;
v[idx-1]+=2;
cnt++;
idx--;
}
}
int find_smallest(vi&v){
loop(i,63){
if(v[i])return i;
}
return 63;
}
int find_upper(vi&v,int cur){
for(int i=cur;i<63;i++){
if(v[i]) return i;
}
return 63;
}
void group(vi&v,int cur){
loop(i,cur){
v[i+1]+=v[i]>>1;
v[i] = v[i]&1;
}
}
void solve(){
vi c(63,0); // count
vi b(63,0); // input
ll n;
int m;
cin>>n>>m;
cnt = 0;
fill_bits(b,n);
loop(i,m){
ll a;
cin>>a;
fill_bits(c,a);
}
debug(n,m,b,c);
loop(cur,63){
if(b[cur]){
int s = find_smallest(c);
debug(s,cur,cnt);
if(s==63){
cnt=-1;
break;
}
if(s>=cur){
split(c,s,cur);
c[cur]--;
debug(s,cur,c);
}
else{
group(c,cur);
debug(c,cur);
if(c[cur]){
c[cur]--;
debug(c,cur);
}
else{
s = find_upper(c,cur);
debug(s);
if(s==63){
cnt=-1;
break;
}
split(c,s,cur);
c[cur]--;
}
}
}
}
cout<<cnt<<"\n";
}
int main(){
test solve();
} | cpp |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | #include <iostream>
#include <vector>
#include <algorithm>
#define ll long long
using namespace std;
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
vector <int> x;
vector <int> sum;
int SUM = 0;
int numerator = 0;
int demnator = 0;
int A;
int B;
float remainder;
cin >> A;
B = A;
int C;
for (int i = 2; i < A ; i++)
{
C = B;
SUM = 0;
while (C != 0)
{
remainder = C%i;
C=C/i;
x.push_back(remainder);
}
for ( int j = 0; j < x.size(); j++)
{
SUM+= x[j];
}
sum.push_back(SUM);
demnator++;
x.clear();
}
for (int i = 0; i < sum.size(); i++)
{
numerator += sum[i];
}
cout << numerator/ gcd(numerator, demnator) << "/" << demnator/ gcd(numerator, demnator) << "\n";
}
| cpp |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | #include <bits/stdc++.h>
using namespace std;
#include <ext/rope>
using namespace __gnu_cxx;
// #pragma comment(linker, "/stack:2000000000")
// #pragma GCC optimize("Ofast")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pll;
#define precise(a) cout<<fixed<<setprecision(a)
#define sz size()
#define ff first
#define ss second
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(), a.rend()
#define pb push_back
// t1
const ll mod = ll(1e9)+7; //(b + (a%b)) % b (to mod -1%(10^9+7) correctly in c++ its -1 but its suppose to be 10^9+6
const ll MOD = 998244353; // (a%mod)*(binpow(b,mod-2,mod) = (a/b)%mod
const ll N = ll(3e5)+10;
const ll K = 17;
const ll inf = 1e18;
const ld eps = 1e-15L;
//const ll B = 316;
ll lcm(ll a, ll b){ return (a / __gcd(a,b)) * b; }
//const ld P = acos(-1.0);
// ll binpow(ll a, ll b, ll m){ ll res=1;a%=m; while(b>0){ if(b&1)res=(res*a)%m; a=(a*a)%m; b/=2; } return res%m;}
ld binpow(ld a, ll b){ ld res=1; while(b>0){ if(b&1)res=(res*a); a=(a*a); b/=2; } return res;}
void Freopen(string Key){ freopen((Key+".in").c_str(), "r", stdin); freopen((Key+".out").c_str(), "w", stdout); }
void precalc() {
}
ll fact[N];
void Baizho()
{
ll n, m; cin>>n>>m;
fact[0] = 1;
for(ll i=1; i<N; i++) fact[i] = (fact[i-1]*i)%m;
ll ans = 0;
for(ll len = 1; len<=n; len++) {
ans = (((fact[len]*fact[n-len+1])%m)*(n-len+1)+ans)%m;
}
cout<<ans;
}
int main() {
// Freopen("div7");
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
precalc();
int ttt = 1;
// cin>>ttt;
for(int i=1; i<=ttt; i++) { Baizho();}
} | 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"
] |
// Depressed boy Bhaskor Roy
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define forn(i,n) for(int i=0;i<n;i++)
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
using namespace std;
#define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
void s1(){
int n,m;
cin>>n>>m;
string s[n],t[m];
forn(i,n)
cin>>s[i];
forn(i,m)
cin>>t[i];
int q;
cin>>q;
while(q--){
int y;
cin>>y;
int i=y%n;
if(i==0)
i=n-1;
else
i=i-1;
int j=y%m;
if(j==0)
j=m-1;
else
j=j-1;
//cout<<i<<" "<<j<<endl;
cout<<s[i]<<t[j]<<endl;
}
}
int main(){
optimize();
int t;
s1();
return 0;
}
| cpp |
1307 | C | C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l. | [
"brute force",
"dp",
"math",
"strings"
] | /*********************************
* Author -> Puspendra yadav *
**********************************/
#include<bits/stdc++.h>
using namespace std;
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define idx(x) find_by_order(x)
#define less_then(x) order_of_key(x)
template<class T> using pbds = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update> ;
#define int long long int
#define endl '\n'
#define all(a) (a).begin(),(a).end()
#define mod 1000000007
/************************************************************/
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(float 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 << "]";}
/*************************************************************/
void solve() {
string s;
cin >> s;
int n = s.size();
map<char, int> mp;
map<int, int> m;
for (auto &i : s) m[i]++;
for (char ch = 'a'; ch <= 'z'; ch++) {
mp[ch] = 0;
}
vector<vector<int>> a(26 , vector<int>(n , 0));
for (int i = 0; i < n; i++) {
mp[s[i]]++;
for (int j = 0; j < 26; j++) {
a[j][i] = mp[j + 'a'];
}
}
int maxi = 0;
for (char firstch = 'a'; firstch <= 'z'; firstch++) {
for (char secondch = 'a'; secondch <= 'z'; secondch++) {
// if (firstch == secondch) continue;
vector<int> l = a[firstch - 'a'];
vector<int> r = a[secondch - 'a'];
int currSum = 0;
for (int i = 0; i < n; i++) {
if (s[i] == firstch) {
currSum += (r[n - 1] - r[i]);
}
}
maxi = max(maxi , currSum);
}
}
for (auto &i : m) maxi = max(maxi , i.second);
vector<int> temp;
for (char ch = 'a'; ch <= 'z'; ch++) {
vector<int> temp;
for (int i = 0; i < n; i++) {
if (s[i] == ch) {
int j = i;
while (j < n and s[i] == s[j]) {
j++;
}
temp.push_back(j - i);
i = j - 1;
}
}
sort(all(temp));
if (temp.size() > 1) {
maxi = max(maxi , temp[temp.size() - 1] * temp[temp.size() - 2]);
}
}
cout << maxi << endl;
}
main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("Error.txt", "w", stderr);
#endif
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
/*
Sorting using cmp --> return boolen in which order
order you want to Sort
using pbds
using only less --> normal set
using less_equal --> lower_bound gives result like upper
bound in multiset and vice versa
eg -> for in desecnding order --> return (a > b);
*/
} | 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"
] | /* 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 mod=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],inv[fac_size+1];
void Cal_Factorial(){
fac[0]=1;
for(ll i=1;i<=fac_size;i++)
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){
return 1LL*(fac[n]*inv[r]%M*inv[n-r]%M);
}
// nCr --> 1LL*(fac[a]*inv[b]%M*inv[a-b]%M)
// Euler Totient
ll phi(ll n) {
ll result = n;
for (ll i = 2; i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0)
n /= i;
result -= result / i;
}
}
if (n > 1)
result -= result / n;
return result;
}
void solve(){
ll a,m;
cin >> a >> m;
ll val = gcd(a,m);
a/=val;
m/=val;
ll M = phi(m);
ll A = phi(a);
ll Val = phi(val);
dbg(mkp(A,M));
dbg(val)
cout << M << endl;
}
int main(){
fast;
int t=1;
cin>>t;
while(t--){
#ifndef ONLINE_JUDGE
freopen("error.txt", "w", stderr);
#endif
solve();
}
return 0;
} | cpp |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | #include <bits/stdc++.h>
#define int long long
#define all(x) x.begin(), x.end()
#define pb push_back
#define pop pop_back
#define vi vector <int>
#define NHI {cout<<"NO"<<endl; return;}
#define F first
#define S second
#define mod(x) (x%M+M)%M
#define in(x) int x; cin >> x;
#define st(x) string x; cin >> x;
#define foit(it, v) for(auto it = v.begin(); it != v.end(); it++)
#define fo(i, n) for(int i = 0; i < n; i++)
#define fot(i, k, n) for(int i = k; i < n; i++)
#define endl "\n";
#define deb(x) cout << #x << "=" << x << endl
#define vp vector<pair <int, int>>
#define mi map <int, int>
#define PI 3.1415926535897932384626
using namespace std;
void printvec(vi &v){
for (auto e : v)
cout << e << ' ';
cout << endl;
}
int M = INT64_MAX;
int T = 0;
int po(int a, int b){
int ans = 1;
while (b > 0){
if (b & 1)
ans = (ans * a) % M;
a = (a * a) % M;
b >>= 1;
}
return ans;
}
void solve()
{
in(u);in(v);
if(v<u||((v-u)&1)){cout<<-1;return;}
if(v==u){
if(v==0) cout<<0;
else cout<<"1 \n"<<u;
return;
}
v-=u;
if((u^(v/2))==u+v/2){cout<<"2 \n"<<u+v/2<<" "<<v/2;return;}
cout<<"3 \n"<<u<<" "<<v/2<<" "<<v/2<<endl;
}
signed main () {
ios::sync_with_stdio(0);
cin.tie(0);
// cin>>T;
// while(T--)
solve();
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>
using namespace std;
int n;
string s;
int main() {
int t; cin >> t;
while (t--)
{
int d = 0;
cin >> s;
n = s.size();
int len = 0;
for (int i = 0; i < n; i++)
{
int j = i + 1;
if (s[i] == 'R')
{
d = max(d, j - len);
len = j;
}
}
d = max(d, n + 1 - len);
cout << d << "\n";
}
return 0;
} | 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;
const long long mod = 1000000007;
int n, a[65], f[65], ind[65], nidx[65], imsk[65], pfxs[65536];
long long dp[65536][65], fac[65], ifac[65];
vector <int> wcc[65], nod;
inline int GetRoot(int v) {
if (f[v] == v) return v;
return f[v] = GetRoot(f[v]);
}
inline void Merge(int x, int y) {
int u = GetRoot(x), v = GetRoot(y);
if (u != v) f[v] = u;
}
inline void Read() {
cin >> n;
for (int i = 1;i <= n;i++) cin >> a[i];
}
inline void Prefix() {
for (int i = 1;i <= n;i++) f[i] = i;
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= n;j++) {
if (a[i] % a[j] == 0) Merge(i, j);
}
}
for (int i = 1;i <= n;i++) wcc[GetRoot(i)].push_back(a[i]);
ifac[1] = ifac[0] = fac[1] = fac[0] = 1;
for (int i = 2;i <= n;i++) ifac[i] = (mod - mod / i) * ifac[mod % i] % mod;
for (int i = 2;i <= n;i++) {
fac[i] = fac[i - 1] * i % mod;
ifac[i] = ifac[i - 1] * ifac[i] % mod;
}
}
inline pair <int, long long> Work(int idx) {
nod.clear(); nod.shrink_to_fit();
sort(wcc[idx].begin(), wcc[idx].end());
for (int i = 0;i < wcc[idx].size();i++) {
for (int j = i + 1;j < wcc[idx].size();j++) {
if (wcc[idx][j] % wcc[idx][i] == 0) ind[wcc[idx][j]]++;
}
}
for (int x : wcc[idx]) {
if (!ind[x]) {
nidx[x] = nod.size();
nod.push_back(x);
}
}
memset(imsk, 0, sizeof(imsk));
memset(pfxs, 0, sizeof(pfxs));
for (int x : wcc[idx]) {
for (int y : nod) {
if (x % y == 0) imsk[x] |= (1 << nidx[y]);
}
if (ind[x]) pfxs[imsk[x]]++;
}
for (int i = 0;i < nod.size();i++) {
for (int j = 0;j < (1 << nod.size());j++) {
if (j & (1 << i)) pfxs[j] += pfxs[j ^ (1 << i)];
}
}
memset(dp, 0, sizeof(dp));
for (int x : wcc[idx]) {
if (ind[x]) dp[imsk[x]][1]++;
}
for (int i = 1;i < (1 << nod.size());i++) {
for (int j = 1;j <= n;j++) {
dp[i][j + 1] = (dp[i][j + 1] + dp[i][j] * (pfxs[i] - j)) % mod;
for (int k = 1;k <= n;k++) {
if ((imsk[a[k]] & i) != 0 && (imsk[a[k]] & i) != imsk[a[k]]) {
dp[i | imsk[a[k]]][j + 1] = (dp[i | imsk[a[k]]][j + 1] + dp[i][j]) % mod;
}
}
}
}
return make_pair(pfxs[(1 << nod.size()) - 1] - 1, dp[(1 << nod.size()) - 1][pfxs[(1 << nod.size()) - 1]]);
}
inline void Solve() {
long long ans = 1;
int fcnt = 0;
for (int i = 1;i <= 60;i++) {
if (wcc[i].size() > 1) {
pair <int, long long> res = Work(i);
ans = ans * res.second % mod * ifac[res.first] % mod;
fcnt += res.first;
}
}
cout << ans * fac[fcnt] % mod << endl;
}
int main() {
std::ios::sync_with_stdio(0);
Read();
Prefix();
Solve();
return 0;
} | cpp |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pint;
#define MP make_pair
#define MAXN 5069
pint p[MAXN]; vector<int> adj[MAXN];
vector<pint> edges;
vector<pair<pint,int>> updates;
int h[MAXN];
void dfs(int x, int par) {
p[x] = MP(par, INT_MIN);
for(auto i: adj[x]) if(i != par) {
h[i] = h[x] + 1;
dfs(i, x);
}
}
void update(int a, int b, int val) {
if(h[b] < h[a]) swap(a, b);
while(h[b] > h[a]) {
p[b].second = max(p[b].second, val);
b = p[b].first;
}
while(a != b) {
p[a].second = max(p[a].second, val);
p[b].second = max(p[b].second, val);
a = p[a].first; b = p[b].first;
}
}
int check(int a, int b) {
if(h[b] < h[a]) swap(a, b);
int ans = INT_MAX;
while(h[b] > h[a]) {
ans = min(ans, p[b].second);
b = p[b].first;
}
while(a != b) {
ans = min(min(p[a].second, p[b].second), ans);
a = p[a].first; b = p[b].first;
}
return ans;
}
int main() {
int n, m, a, b, g; cin >> n;
for(int i = 1; i < n; i++) {
cin >> a >> b; edges.push_back(MP(a, b));
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1, -1);
cin >> m;
while(m--) {
cin >> a >> b >> g;
updates.push_back(MP(MP(a, b),g));
update(a, b, g);
}
bool valid = true;
for(auto i: updates) {
if(check(i.first.first, i.first.second) != i.second) {
valid = false; break;
}
}
if(valid) {
for(auto i: edges) {
int child = max(i.first, i.second);
if(p[child].second == INT_MIN) cout << "69420\n";
else cout << p[child].second << "\n";
}
} else {
cout << -1;
}
} | cpp |
1310 | D | D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
OutputCopy2
InputCopy3 2
0 1 1
2 0 1
2 2 0
OutputCopy3
| [
"dp",
"graphs",
"probabilities"
] | #include <bits/stdc++.h>
using namespace std;
const int N = 600+10;
const int MOD = 1e9 + 7;
typedef long long ll;
int n, k;
int dis[N], e[N][N], tmp[N];
int c[N];
void dp() {
memset(dis, 0x3f, sizeof dis);
dis[1] = 0;
for (int turns = 1; turns <= k; turns++) {
memset(tmp, 0x3f, sizeof tmp);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (c[i] == c[j]) continue;
tmp[j] = min(tmp[j], dis[i] + e[i][j]);
// cout << e[i][j] << " \n" [j==n];
}
}
for (int i = 1; i <= n; i++) {
dis[i] = tmp[i];
}
}
}
void solve() {
cin >> n >> k;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> e[i][j];
}
e[i][i] = 1e9;
}
int cnt = 0, ans = 1e9;
while (++cnt <= 512 * 10) {
for (int i = 1; i <= n; i++) {
c[i] = rand() % 2;
}
dp();
ans = min(ans, dis[1]);
}
cout << ans << endl;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t = 1;
srand(time(0));
while (t--) solve();
}
| cpp |
1295 | E | E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
| [
"data structures",
"divide and conquer"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int maxn = 2e5 + 7;
int n,m, a[maxn], b[maxn], pos[maxn], val[maxn];
struct segment_tree {
struct tree {
int l, r, lazy, mi;
}tr[maxn * 4];
inline void build(int p, int l, int r) {
tr[p].l = l, tr[p].r = r;
if (l == r) {
tr[p].mi = a[l];
tr[p].lazy = 0;
return;
}
int mid = (l + r) >> 1;
build(p * 2, l, mid);
build(p * 2 + 1, mid + 1, r);
tr[p].mi = min(tr[p * 2].mi, tr[p * 2 + 1].mi);
return;
}
inline void push_down(int p) {
if (tr[p].lazy != 0) { //如果父节点lazy标记不为0,既让lazy标记下传
tr[p * 2].lazy += tr[p].lazy;
tr[p * 2 + 1].lazy += tr[p].lazy;
int mid = (tr[p].l + tr[p].r) >> 1;
tr[p * 2].mi += tr[p].lazy;//改变两个子节点的maxv
tr[p * 2 + 1].mi += tr[p].lazy;
tr[p].lazy = 0;//下传后自己的lazy标记变为0
}
}
inline void add(int p, int l, int r, int k) {
if (tr[p].l >= l && tr[p].r <= r) {
tr[p].mi += k;
tr[p].lazy += k; //完全包含就将lazy标记加上k用来之后传给子节点
return;
}
push_down(p); //如果没有完全找到就往下找,同时下传lazy和子节点的maxv;
if (tr[p * 2].r >= l) add(p * 2, l, r, k); //哪边有交集就往哪边走;
if (tr[p * 2 + 1].l <= r) add(p * 2 + 1, l, r, k);
tr[p].mi = min(tr[p * 2].mi , tr[p * 2 + 1].mi);//自下向上更新maxv
return;
}
inline int search(int p, int l, int r) {
if (tr[p].l >= l && tr[p].r <= r) { //如果完全包含就返回maxv,并加在s上
return tr[p].mi;
}
if (tr[p].l > r || tr[p].r < l) return 0;
push_down(p);////如果没有完全找到就往下找,同时下传lazy和子节点的maxv;
int s = 0;
if (tr[p * 2].r >= l) s = min(s, search(p * 2, l, r));
if (tr[p * 2 + 1].l <= r) s = min(s, search(p * 2 + 1, l, r));
return s;
}
}ST;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n;
for(int i = 1; i <= n; i++){
cin >> b[i];
pos[b[i]] = i;
}
for(int i = 1, x; i <= n; i++){
cin >> x;
val[b[i]] = x;
a[i] = a[i - 1] + x;
}
ST.build(1, 1, n - 1);
ll ans = ST.tr[1].mi;
for(int i = 1; i <= n; i++){
// cout << ST.tr[1].mi << '\n';
if(1 <= pos[i] - 1)ST.add(1, 1, pos[i] - 1, val[i]);
if(pos[i] <= n - 1)ST.add(1, pos[i], n - 1, -val[i]);
ans = min(ans, ST.tr[1].mi);
}
cout << ans << '\n';
} | cpp |
13 | C | C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1 | [
"dp",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
#define int long long int
#define fio ios_base::sync_with_stdio(0);cin.tie(NULL)
#define endl '\n'
#define MAXN ((int)(5e5 + 5))
typedef vector<int> vi;
typedef pair<int,int> pii;
signed main()
{
int n,res = 0;
priority_queue<int> pq;
cin >> n;
for(int i=1;i<=n;++i)
{
int x; cin >> x;
if(!pq.empty() && pq.top() > x)
{
res += pq.top() - x;
pq.pop();
pq.push(x);
}
pq.push(x);
}
cout << res;
}
| cpp |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"implementation"
] | #pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#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;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> p32;
typedef pair<ll, ll> p64;
typedef pair<double, double> pdd;
typedef vector<ll> v64;
typedef vector<int> v32;
typedef vector<vector<int>> vv32;
typedef vector<vector<ll>> vv64;
typedef vector<vector<p64>> vvp64;
typedef vector<p64> vp64;
typedef vector<p32> vp32;
ll MOD = 998244353;
double eps = 1e-12;
#define forn(i, e) for (ll i = 0; i < e; i++)
#define forsn(i, s, e) for (ll i = s; i < e; i++)
#define rforn(i, s) for (ll i = s; i >= 0; i--)
#define rforsn(i, s, e) for (ll i = s; i >= e; i--)
#define ln "\n"
#define dbg(x) cout << #x << " = " << x << ln
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define INF 2e18
#define fast_cin() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((ll)(x).size())
bool dfs(int vertex, v64 graph[], vector <bool> &visited, int parent) {
bool isLoopExists = false;
// cout<<vertex<<" ";
visited[vertex] = true;
for(auto child : graph[vertex]) {
if((visited[child]) && (child == parent)) continue;
if(visited[child]) return true;
isLoopExists |= dfs(child, graph, visited, vertex);
}
return isLoopExists;
}
void dfs1(ll node, ll par, v64 g[], v64 &ans) {
ans.pb(node);
for(auto child : g[node]) {
if(child == par) continue;
dfs1(child, node, g, ans);
}
}
void solve()
{
string s;
cin>>s;
ll n = sz(s);
if(n == 1) {
cout<<"YES\n";
cout<<"abcdefghijklmnopqrstuvwxyz\n";
return;
}
set <p64> st;
v64 g[26];
forn(i, n-1) {
p64 p = {(s[i] - 'a'), (s[i+1] - 'a')};
p64 p1 = {p.se, p.fi};
if(st.find(p) == st.end()) {
st.insert(p);
st.insert(p1);
g[p.fi].pb(p.se);
g[p.se].pb(p.fi);
}
}
vector <bool> vis(26, false);
if(dfs((s[0] - 'a'), g, vis, -1)) {
cout<<"NO\n";
return;
}
ll flag = 0;
for(ll i = 0; i < 26; i++) {
if(g[i].size() > 2) {
flag = 1;
break;
}
}
if(flag) {
cout<<"NO\n";
return;
}
else {
cout<<"YES\n";
ll x = 1;
for(ll i = 0; i < 26; i++) {
if(g[i].size() == 1) {
x = i;
break;
}
}
v64 ans;
dfs1(x, -1, g, ans);
for(auto it : ans) {
cout<<(char)('a' + it);
}
for(ll i = 0; i < 26; i++) {
if(vis[i] == 0) cout<<(char)('a' + i);
}
cout<<ln;
}
}
int main()
{
fast_cin();
ll t;
cin >> t;
for (int it = 1; it <= t; it++)
{
// cout << "Case #" << it+1 << ": ";
solve();
}
return 0;
} | cpp |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | #include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
typedef long long ll;
void slove() {
ll n, v;
cin >> n >> v;
if(n > v) {
cout << "-1\n";
return;
}
if(n == v) {
if(n != 0) {
cout << 1 << "\n";
cout << n << "\n";
} else {
cout << "0\n";
}
return;
}
if((v - n) % 2 == 1) {
cout << "-1\n";
} else {
if((((v - n) / 2) & n) == 0) {
cout << 2 << "\n";
cout << (v - n) / 2 << " " << (((v - n) / 2) ^ n) << "\n";
} else {
cout << 3 << "\n";
cout << (v - n) / 2 << " " << (v - n) /2 << " " << n << "\n";
}
}
return;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
slove();
return 0;
}
| 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;
//#define int long long
#define pb push_back
#define mp make_pair
constexpr int N = (int)1e5 + 111;
constexpr int INF = (int)1e9 + 11;
constexpr int md = (int)1e9+7;
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx2,popcnt")
void solve(){
string s1,s2;
cin >> s1 >> s2;
int n = s1.size();
int m = s2.size();
short cnt[256];
memset(cnt,0,sizeof cnt);
for(int i = 0; i < s1.size(); i++) cnt[s1[i]]++;
for(int i = 0; i < s2.size(); i++) cnt[s2[i]]--;
for(auto& y : cnt){
if(y < 0){
cout << "NO\n";
return;
}
}
bool dp[m+1][m+1];
int pos = 0;
int C = 0;
int ptr = 0;
for(int j = 0; j < s2.size(); j++){
while(ptr < s1.size() && s1[ptr] != s2[j])
ptr++;
if(ptr == s1.size())
break;
// cerr << "ptr: " << ptr << "\n";
C = j+1;
ptr++;
}
// cerr << "C: " << C << "\n";
#pragma GCC ivdep
for(int s = max(0,C/2-1); s <= C; s++){
memset(dp,0,sizeof dp);
dp[0][0] = true;
bool can = false;
for(int i = 0; i < n; i++){
for(int j = min(i,s); j >= 0; j--){
for(int t = min(i,m-s); t >= 0; t--){
if(j + 1 <= s && s2[j] == s1[i])
dp[j+1][t] |= dp[j][t];
if(t + 1 <= m - s && s2[t+s] == s1[i])
dp[j][t+1] |= dp[j][t];
}
}
// for(int j = 0; j <= min(i+1,s); j++){
// for(int t = 0; t <= min(i+1,m - s); t++){
// dp[0][j][t] = dp[1][j][t];
//// dp[1][j][t] = 0;
// }
// }
}
for(int j = 0; j <= m-s; j++)
can |= dp[s][j];
if(dp[s][m-s]){
// cerr << "s: " << s << "\n";
cout << "YES\n";
return;
}
// if(!can)
// break;
}
cout << "NO\n";
return;
}
signed main(){
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
int tests = 1;
cin >> tests;
for(int test = 1; test <= tests; test++){
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;
#define fast \
ios_base::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
#define ll long long
#define all(v) v.begin(), v.end()
#define pb push_back
#define vl vector<ll>
#define vp vector<pair<ll, ll>>
#define in(a) \
for (auto &x : a) \
cin >> x;
#define out(a) \
for (auto x : a) \
cout << x << ' '; \
cout << endl;
#define pr(a) cout << a << endl
const ll mod = 1e9 + 7;
const double pi = acos(-1);
void solve()
{
string a;
cin >> a;
vl ob, cb;
ll l = 0, r = a.size() - 1;
while (l < r)
{
while (l < a.size() and a[l] == ')')
{
l++;
}
while (r >= 0 and a[r] == '(')
{
r--;
}
if (l < a.size() and r >= 0 and l < r)
{
ob.push_back(l + 1);
cb.push_back(r + 1);
l++;
r--;
}
}
if (ob.empty())
{
pr(0);
return;
}
reverse(all(cb));
pr(1);
pr(2 * ob.size());
for (ll x : ob)
{
cout << x << " ";
}
for (auto x : cb)
{
cout << x << " ";
}
pr("");
}
int main()
{
fast;
int t = 1;
// cin >> t;
while (t--)
solve();
} | cpp |
1316 | F | F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212. | [
"data structures",
"divide and conquer",
"probabilities"
] | #line 1 "/home/maspy/compro/library/my_template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) \
vector<vector<vector<type>>> name( \
h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name( \
a, vector<vector<vector<type>>>( \
b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
#define FOR_(n) for (ll _ = 0; (_) < (ll)(n); ++(_))
#define FOR(i, n) for (ll i = 0; (i) < (ll)(n); ++(i))
#define FOR3(i, m, n) for (ll i = (m); (i) < (ll)(n); ++(i))
#define FOR_R(i, n) for (ll i = (ll)(n)-1; (i) >= 0; --(i))
#define FOR3_R(i, m, n) for (ll i = (ll)(n)-1; (i) >= (ll)(m); --(i))
#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define stoi stoll
template <typename T>
T SUM(vector<T> &A) {
T sum = T(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())
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 : 31 - __builtin_clz(x)); }
int lowbit(u32 x) { return (x==0 ? -1 : 31 - __builtin_clz(x)); }
int lowbit(ll x) { return (x==0 ? -1 : 63 - __builtin_clzll(x)); }
int lowbit(u64 x) { return (x==0 ? -1 : 63 - __builtin_clzll(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};
}
ll binary_search(function<bool(ll)> check, ll ok, ll ng) {
assert(check(ok));
while (abs(ok - ng) > 1) {
auto x = (ng + ok) / 2;
if (check(x))
ok = x;
else
ng = x;
}
return ok;
}
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);
}
vi s_to_vi(string S, char first_char = 'a') {
vi A(S.size());
FOR(i, S.size()) { A[i] = S[i] - first_char; }
return A;
}
template <typename T>
vector<T> cumsum(vector<T> &A, int off = 1) {
int N = A.size();
vector<T> B(N + 1);
FOR(i, N) { B[i + 1] = B[i] + A[i]; }
if (off == 0) B.erase(B.begin());
return B;
}
template <typename T, typename CNT = int>
vc<CNT> bincount(vc<T> &A, int size) {
vc<CNT> C(size);
for (auto &&x: A) { ++C[x]; }
return C;
}
template <typename T>
vector<int> argsort(vector<T> &A) {
// stable
vector<int> ids(A.size());
iota(all(ids), 0);
sort(all(ids),
[&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
return ids;
}
#line 1 "/home/maspy/compro/library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>
namespace detail {
template <typename T, decltype(&T::is_modint) = &T::is_modint>
std::true_type check_value(int);
template <typename T>
std::false_type check_value(long);
} // namespace detail
template <typename T>
struct is_modint : decltype(detail::check_value<T>(0)) {};
template <typename T>
using is_modint_t = enable_if_t<is_modint<T>::value>;
template <typename T>
using is_not_modint_t = enable_if_t<!is_modint<T>::value>;
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 <class T, is_modint_t<T> * = nullptr>
bool read_single(T &ref) {
long long val = 0;
bool f = read_single(val);
ref = T(val);
return f;
}
bool read_single(double &ref) {
string s;
if (!read_single(s)) return false;
ref = std::stod(s);
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 <class A, class B, class C>
bool read_single(tuple<A, B, C> &p) {
return (read_single(get<0>(p)) && read_single(get<1>(p))
&& read_single(get<2>(p)));
}
template <class A, class B, class C, class D>
bool read_single(tuple<A, B, C, D> &p) {
return (read_single(get<0>(p)) && read_single(get<1>(p))
&& read_single(get<2>(p)) && read_single(get<3>(p)));
}
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 << setprecision(12) << x;
string s = oss.str();
write(s);
}
template <class T, is_modint_t<T> * = nullptr>
void write(T &ref) {
write(ref.val);
}
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);
}
};
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...);
}
#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 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/mod/modint.hpp"
template <int mod>
struct modint {
static constexpr bool is_modint = true;
int val;
constexpr modint(const ll val = 0) noexcept
: val(val >= 0 ? val % mod : (mod - (-val) % mod) % mod) {}
bool operator<(const modint &other) const {
return val < other.val;
} // To use std::map
modint &operator+=(const modint &p) {
if ((val += p.val) >= mod) val -= mod;
return *this;
}
modint &operator-=(const modint &p) {
if ((val += mod - p.val) >= mod) val -= mod;
return *this;
}
modint &operator*=(const modint &p) {
val = (int)(1LL * val * p.val % mod);
return *this;
}
modint &operator/=(const modint &p) {
*this *= p.inverse();
return *this;
}
modint operator-() const { return modint(-val); }
modint operator+(const modint &p) const { return modint(*this) += p; }
modint operator-(const modint &p) const { return modint(*this) -= p; }
modint operator*(const modint &p) const { return modint(*this) *= p; }
modint operator/(const modint &p) const { return modint(*this) /= p; }
bool operator==(const modint &p) const { return val == p.val; }
bool operator!=(const modint &p) const { return val != p.val; }
modint inverse() const {
int a = val, b = mod, u = 1, v = 0, t;
while (b > 0) {
t = a / b;
swap(a -= t * b, b), swap(u -= t * v, v);
}
return modint(u);
}
modint pow(int64_t n) const {
modint ret(1), mul(val);
while (n > 0) {
if (n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
static constexpr int get_mod() { return mod; }
};
struct ArbitraryModInt {
static constexpr bool is_modint = true;
int val;
ArbitraryModInt() : val(0) {}
ArbitraryModInt(int64_t y)
: val(y >= 0 ? y % get_mod()
: (get_mod() - (-y) % get_mod()) % get_mod()) {}
bool operator<(const ArbitraryModInt &other) const {
return val < other.val;
} // To use std::map<ArbitraryModInt, T>
static int &get_mod() {
static int mod = 0;
return mod;
}
static void set_mod(int md) { get_mod() = md; }
ArbitraryModInt &operator+=(const ArbitraryModInt &p) {
if ((val += p.val) >= get_mod()) val -= get_mod();
return *this;
}
ArbitraryModInt &operator-=(const ArbitraryModInt &p) {
if ((val += get_mod() - p.val) >= get_mod()) val -= get_mod();
return *this;
}
ArbitraryModInt &operator*=(const ArbitraryModInt &p) {
unsigned long long a = (unsigned long long)val * p.val;
unsigned xh = (unsigned)(a >> 32), xl = (unsigned)a, d, m;
asm("divl %4; \n\t" : "=a"(d), "=d"(m) : "d"(xh), "a"(xl), "r"(get_mod()));
val = m;
return *this;
}
ArbitraryModInt &operator/=(const ArbitraryModInt &p) {
*this *= p.inverse();
return *this;
}
ArbitraryModInt operator-() const { return ArbitraryModInt(-val); }
ArbitraryModInt operator+(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) += p;
}
ArbitraryModInt operator-(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) -= p;
}
ArbitraryModInt operator*(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) *= p;
}
ArbitraryModInt operator/(const ArbitraryModInt &p) const {
return ArbitraryModInt(*this) /= p;
}
bool operator==(const ArbitraryModInt &p) const { return val == p.val; }
bool operator!=(const ArbitraryModInt &p) const { return val != p.val; }
ArbitraryModInt inverse() const {
int a = val, b = get_mod(), u = 1, v = 0, t;
while (b > 0) {
t = a / b;
swap(a -= t * b, b), swap(u -= t * v, v);
}
return ArbitraryModInt(u);
}
ArbitraryModInt pow(int64_t n) const {
ArbitraryModInt ret(1), mul(val);
while (n > 0) {
if (n & 1) ret *= mul;
mul *= mul;
n >>= 1;
}
return ret;
}
};
template<typename mint>
tuple<mint, mint, mint> get_factorial_data(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
static vector<mint> fact = {1, 1};
static vector<mint> fact_inv = {1, 1};
static vector<mint> inv = {0, 1};
while(len(fact) <= n){
int k = len(fact);
fact.eb(fact[k - 1] * mint(k));
auto q = ceil(mod, k);
int r = k * q - mod;
inv.eb(inv[r] * mint(q));
fact_inv.eb(fact_inv[k - 1] * inv[k]);
}
return {fact[n], fact_inv[n], inv[n]};
}
template<typename mint>
mint fact(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n);
if(n >= mod) return 0;
return get<0>(get_factorial_data<mint>(n));
}
template<typename mint>
mint fact_inv(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
return get<1>(get_factorial_data<mint>(n));
}
template<typename mint>
mint inv(int n){
static constexpr int mod = mint::get_mod();
assert(0 <= n && n < mod);
return get<2>(get_factorial_data<mint>(n));
}
template<typename mint>
mint C(ll n, ll k, bool large = false) {
assert(n >= 0);
if (k < 0 || n < k) return 0;
if (!large) return fact<mint>(n) * fact_inv<mint>(k) * fact_inv<mint>(n - k);
k = min(k, n - k);
mint x(1);
FOR(i, k) {
x *= mint(n - i);
}
x *= fact_inv<mint>(k);
return x;
}
using modint107 = modint<1000000007>;
using modint998 = modint<998244353>;
using amint = ArbitraryModInt;
#line 2 "/home/maspy/compro/library/ds/segtree.hpp"
template <class Monoid>
struct SegTree {
using X = typename Monoid::value_type;
using value_type = X;
vc<X> dat;
int n, log, size;
SegTree() : SegTree(0) {}
SegTree(int n) : SegTree(vc<X>(n, Monoid::unit)) {}
SegTree(vc<X> v) : n(len(v)) {
log = 1;
while ((1 << log) < n) ++log;
size = 1 << log;
dat.assign(size << 1, Monoid::unit);
FOR(i, n) dat[size + i] = v[i];
FOR3_R(i, 1, size) update(i);
}
X operator[](int i) { return dat[size + i]; }
void update(int i) { dat[i] = Monoid::op(dat[2 * i], dat[2 * i + 1]); }
void set(int i, X x) {
assert(i < n);
dat[i += size] = x;
while (i >>= 1) update(i);
}
X prod(int L, int R) {
assert(L <= R);
assert(R <= n);
X vl = Monoid::unit, vr = Monoid::unit;
L += size, R += size;
while (L < R) {
if (L & 1) vl = Monoid::op(vl, dat[L++]);
if (R & 1) vr = Monoid::op(dat[--R], vr);
L >>= 1, R >>= 1;
}
return Monoid::op(vl, vr);
}
X prod_all() { return dat[1];}
template <class F>
int max_right(F &check, int L) {
assert(0 <= L && L <= n && check(Monoid::unit));
if (L == n) return n;
L += size;
X sm = Monoid::unit;
do {
while (L % 2 == 0) L >>= 1;
if (!check(Monoid::op(sm, dat[L]))) {
while (L < size) {
L = 2 * L;
if (check(Monoid::op(sm, dat[L]))) {
sm = Monoid::op(sm, dat[L]);
L++;
}
}
return L - size;
}
sm = Monoid::op(sm, dat[L]);
L++;
} while ((L & -L) != L);
return n;
}
template <class F>
int min_left(F &check, int R) {
assert(0 <= R && R <= n && check(Monoid::unit));
if (R == 0) return 0;
R += size;
X sm = Monoid::unit;
do {
--R;
while (R > 1 && (R % 2)) R >>= 1;
if (!check(Monoid::op(dat[R], sm))) {
while (R < size) {
R = 2 * R + 1;
if (check(Monoid::op(dat[R], sm))) {
sm = Monoid::op(dat[R], sm);
R--;
}
}
return R + 1 - size;
}
sm = Monoid::op(dat[R], sm);
} while ((R & -R) != R);
return 0;
}
void debug() { print("segtree", dat); }
};
#line 2 "/home/maspy/compro/library/nt/primetable.hpp"
vc<ll>& primetable(int LIM) {
++LIM;
const int S = 32768;
static int done = 2;
static vc<ll> primes = {2}, sieve(S + 1);
if(done >= LIM) return primes;
done = LIM;
primes = {2}, sieve.assign(S + 1, 0);
const int R = LIM / 2;
primes.reserve(int(LIM / log(LIM) * 1.1));
vc<pi> cp;
for (int i = 3; i <= S; i += 2) {
if (!sieve[i]) {
cp.eb(i, i * i / 2);
for (int j = i * i; j <= S; j += 2 * i) sieve[j] = 1;
}
}
for (int L = 1; L <= R; L += S) {
array<bool, S> block{};
for (auto& [p, idx]: cp)
for (int i = idx; i < S + L; idx = (i += p)) block[i - L] = 1;
FOR(i, min(S, R - L)) if (!block[i]) primes.eb((L + i) * 2 + 1);
}
return primes;
}
#line 3 "/home/maspy/compro/library/mod/powertable.hpp"
template<typename mint>
vc<mint> powertable_1(mint a, ll N) {
// table of a^i
vc<mint> f(N, 1);
FOR(i, N - 1) f[i + 1] = a * f[i];
return f;
}
template<typename mint>
vc<mint> powertable_2(ll e, ll N) {
// table of i^e. N 以下の素数テーブルを利用する.
auto& primes = primetable(N);
vc<mint> f(N, 1);
f[0] = mint(0).pow(e);
for(auto&& p : primes){
if(p > N) break;
mint xp = mint(p).pow(e);
ll pp = p;
while(pp < N){
ll i = pp;
while(i < N){
f[i] *= xp;
i += pp;
}
pp *= p;
}
}
return f;
}
#line 6 "main.cpp"
using mint = modint107;
struct T {
mint cnt, ans, min_sum, max_sum;
};
struct Mono {
using value_type = T;
using X = value_type;
static X op(X x, X y) {
if (x.cnt == mint(0)) return y;
if (y.cnt == mint(0)) return x;
T z;
z.cnt = x.cnt * y.cnt;
z.ans = x.ans * y.cnt + y.ans * x.cnt + x.max_sum * y.min_sum;
z.max_sum = y.max_sum * x.cnt + x.max_sum;
z.min_sum = x.min_sum * y.cnt + y.min_sum;
return z;
}
static constexpr X unit = X{0, 0, 0, 0};
static constexpr bool commute = false;
};
void solve() {
LL(N);
VEC(ll, A, N);
LL(Q);
VEC(pi, query, Q);
vc<pi> X;
FOR(i, N) X.eb(A[i], i);
FOR(i, Q) X.eb(query[i].se, i + N);
UNIQUE(X);
vi last_time(N, -1);
SegTree<Mono> seg(N + Q);
mint coef = mint(2).pow(N).inverse();
auto upd = [&](ll time, ll i, ll x) -> void {
if (last_time[i] != -1) {
ll idx = LB(X, mp(A[i], last_time[i]));
seg.set(idx, {0, 0, 0, 0});
}
A[i] = x;
last_time[i] = time;
ll idx = LB(X, mp(x, time));
seg.set(idx, {2, 0, x, x});
};
auto out = [&]() -> void {
auto e = seg.prod_all();
// print(e.cnt, e.ans, e.max_sum, e.min_sum);
print(e.ans * coef);
};
FOR(i, N) upd(i, i, A[i]);
out();
FOR(q, Q) {
auto [i, x] = query[q];
--i;
upd(N + q, i, x);
out();
}
}
signed main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << setprecision(15);
ll T = 1;
// LL(T);
FOR(_, T) solve();
return 0;
}
| cpp |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5
| [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | #include <iostream>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <cstring>
#define int long long
#define ll long long
#define II pair<int, int>
#define fs first
#define sc second
#define endl '\n'
const double PI = 3.141592653589793238;
const long long LINF = 1ll << 60;
const int INF = 1 << 30;
const int N = 8e5 + 10;
using namespace std;
int n, m = 0;
II a[N];
int c[N], pre[N];
int nxt[N], cum[N];
void compress() {
m = 0;
for(int i = 1; i <= n; i++) {
c[++m] = a[i].fs;
c[++m] = a[i].sc;
}
sort(c + 1, c + m + 1);
m = unique(c + 1, c + m + 1) - c - 1;
for(int i = 1; i <= n; i++) {
a[i].fs = lower_bound(c + 1, c + m + 1, a[i].fs) - c;
a[i].sc = lower_bound(c + 1, c + m + 1, a[i].sc) - c;
a[i].fs *= 2;
a[i].sc *= 2;
}
m = m * 2;
}
void solve() {
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> a[i].fs >> a[i].sc;
}
compress();
for(int i = 1; i <= max(n, m) + 10; i++) {
pre[i] = nxt[i] = cum[i] = 0;
}
int mn = INF, mx = 0;
for(int i = 1; i <= n; i++) {
pre[a[i].fs]++;
pre[a[i].sc + 1]--;
mn = min(mn, a[i].fs);
mx = max(mx, a[i].sc);
}
for(int i = 1; i <= m; i++) pre[i] += pre[i - 1];
int last = m + 1;
for(int i = m; i >= 1; i--) {
if(pre[i] == 1) {
if(last > i + 1) cum[i]++;
nxt[i] = last;
last = i;
}
}
for(int i = 1; i <= m; i++) cum[i] += cum[i - 1];
int cnt = 1;
for(int i = mn; i <= mx; i++) {
if(pre[i] != pre[i - 1] && pre[i] == 0) cnt++;
}
int ans = 0;
for(int i = 1; i <= n; i++) {
int val = cum[a[i].sc] - cum[a[i].fs - 1];
if(pre[a[i].fs] == 1 && pre[a[i].fs - 1] == 0) val--;
if(pre[a[i].sc] == 1 && pre[a[i].sc + 1] == 0) val--;
ans = max(ans, val);
}
cout << min(ans + cnt, n - 1) << endl;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int t;
cin >> t;
while(t--) solve();
return 0;
} | cpp |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | /**
* Author: nicksms
* Created: 02.01.2023 22:18:10
**/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
vector<int> b(n);
for (auto &&p : b) cin >> p;
vector<int> c(n);
for (int i = 0; i < n; i++) {
c[i] = b[i]-i;
}
vector<ll> d(800001);
ll m = 0;
for (int i = 0; i < n; i++) {
d[200000+c[i]] += b[i];
m = max(d[200000+c[i]], m);
}
cout << m << "\n";
return 0;
} | cpp |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | //****************************Template Begins****************************//
// Header Files
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<utility>
#include<set>
#include<unordered_set>
#include<list>
#include<iterator>
#include<deque>
#include<stack>
#include<set>
#include<bitset>
#include<map>
#include<unordered_map>
#include<stdio.h>
#include<complex>
#include<math.h>
#include<chrono>
#include<cstring>
#include<string>
// Header Files End
using namespace std;
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define ll long long
#define umap unordered_map
#define uset unordered_set
#define lb loresr_bound
#define ub upper_bound
#define fo(i,a,b) for(i=a;i<b;i++)
#define all(v) (v).begin(),(v).end()
#define all1(v) (v).begin()+1,(v).end()
#define allr(v) (v).rbegin(),(v).rend()
#define allr1(v) (v).rbegin()+1,(v).rend()
#define sort0(v) sort(all(v))
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
#define max3(a,b,c) max(max((a),(b)),(c))
#define max4(a,b,c,d) max(max((a),(b)),max((c),(d)))
#define min3(a,b,c) min(min((a),(b)),(c))
#define min4(a,b,c,d) min(min((a),(b)),min((c),(d)))
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define inf 9999999999999
#define endl '\n'
#include "ext/pb_ds/assoc_container.hpp"
#include "ext/pb_ds/tree_policy.hpp"
using namespace __gnu_pbds;
template<class T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update> ;
template<class key, class value, class cmp = std::less<key>>
// find_by_order(k) returns iterator to kth element starting from 0;
// order_of_key(k) returns count of elements strictly smaller than k;
using ordered_map = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>;
const ll mod = 998244353;
const ll mod1 = 1e9 + 7;
const ll MOD = 1e18 + 1e16;
ll mod_mul(ll a, ll b) {a = a % mod; b = b % mod; return (((a * b) % mod) + mod) % mod;}
ll inv(ll i) {if (i == 1) return 1; return (mod - ((mod / i) * inv(mod % i)) % mod) % mod;}
ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b);}
ll pwr(ll a, ll b) {a %= mod; ll res = 1; while (b > 0) {if (b & 1) res = res * a % mod; a = a * a % mod; b >>= 1;} return res;}
//****************************Template Ends*******************************//
//****************************Functions*******************************//
// const ll M = 4 * 1e5 + 1;
// ll parent[M];
// ll size1[M];
// void make_set(ll v) {
// parent[v] = v;
// size1[v] = 1;
// }
// ll find_set(ll v) {
// if (v == parent[v])
// return v;
// return parent[v] = find_set(parent[v]);
// }
// // DSU
// bool union_sets(ll a, ll b) {
// a = find_set(a);
// b = find_set(b);
// if (a == b) {
// return false;
// }
// if (a != b) {
// if (size1[a] < size1[b])
// swap(a, b);
// parent[b] = a;
// size1[a] += size1[b];
// }
// return true;
// }
//sparse table
class STable
{
public:
ll LOG = 0;
ll n;
vector<vector<ll>> T;
STable(vector<ll> &a)
{
n = (ll)a.size();
while (1 << (LOG + 1) <= n)
LOG++;
T.resize(LOG + 1);
for (ll i = 0; i <= LOG; i++)
T[i].resize(n);
for (ll i = 0; i < n; i++)
T[0][i] = a[i];
for (ll i = 1; i <= LOG; i++)
{
for (ll j = 0; j < n - (1 << i) + 1; j++)
{
T[i][j] = combine(T[i - 1][j], T[i - 1][j + (1 << (i - 1))]);
}
}
}
ll combine(ll a, ll b)
{
return max(a, b);
}
ll qry(ll l, ll r)
{
ll exp = 0;
while (1 << (exp + 1) <= r - l + 1)
exp++;
return combine(T[exp][l], T[exp][r - (1 << exp) + 1]);
}
};
// vector<vll> dp(n + 1, vll(k + 1, 99999999999));
// dp[0][0] = 0;
// for (ll i = 0; i <= n; i++)
// for (ll j = 0; j < k; j++) {
// dp[i][j + 1] = min(dp[i][j + 1], dp[i][j]);
// MCMF (hungarian algo) flows,graph matching,dp
// if (i < n)
// dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(a[i] - (j + 1)));
// }
ll findMinNumber(ll n)
{
ll count = 0, ans = 1;
// Since 2 is only even prime, compute its
// poresr seprately.
while (n % 2 == 0)
{
count++;
n /= 2;
}
// If count is odd, it must be removed by dividing
// n by prime number.
if (count % 2)
ans *= 2;
for (ll i = 3; i <= sqrt(n); i += 2)
{
count = 0;
while (n % i == 0)
{
count++;
n /= i;
}
// If count is odd, it must be removed by
// dividing n by prime number.
if (count % 2)
ans *= i;
}
if (n > 2)
ans *= n;
return ans;
}
// ll fact(ll n , ll mod)
// {
// ll p=1;
// if (n == 0)
// return 1;
// else
// {
// for(ll i=1;i<=n;i++)
// {p*=i;
// p=p%mod;}
// return p;
// }
// }
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// vll fact(300005, 1);
// fo(i, 2, 300005)
// {
// fact[i] = mod_mul(fact[i - 1], i); //include the loop inside ll main()
// }
// ll C(ll n, ll r)
// {
// ll ans = 1;
// ans = fact[n];
// ans = mod_mul(ans, pwr(fact[r], mod - 2));
// ans = mod_mul(ans, pwr(fact[n - r], mod - 2));
// return ans;
// }
// vector<bool>isprime(10000001, true);
// vll primes;
// void sieve()
// {
// ll i, j;
// fo(i, 2, 10000001)
// {
// if (isprime[i])
// {
// for (j = i * i; j <= 10000000; j += i)
// {
// isprime[j] = false;
// }
// }
// }
// fo(i, 2, 10000001)if (isprime[i])primes.pb(i);
// }
// -------------- DIJKSTRA --------------
// ll INF = 1e16;
// void disp(vll v)
// {
// for(auto u:v)
// cout<<u<<" ";
// cout<<"\n";
// }
// vll p(200001),d(200001);
// map<pll,ll>m1;
// vector<pair<ll,ll>> adj[100005];
// ll n;
// void dijkstra(ll s,vll d, vll p, ll f)
// {
// d .assign(n+1,INF);
// p .assign(n+1,-1);
// priority_q<pll> q;
// d[s]=0;
// q .push({0,s});
// while(!q.empty())
// {
// ll v =q.top().second;
// ll d_v = -(q.top().first);
// q .pop();
// if(d_v!=d[v])continue;
// for(auto edge:adj[v])
// {
// auto to = edge.first;
// auto len = edge.second;
// if(d[v] + len < d[to])
// {
// d[to] = d[v] + len;
// p[to]=v;
// q .push({-d[to],to});
// }
// }
// }
// ll v=f;
// if(d[f]==INF)
// {
// cout<<-1;
// return ;
// }
// vll path;
// while(v!=-1)
// {
// path .pb(v);
// v=p[v];
// }
// reverse(all(path));
// disp(path);
// }
// -------------- SEGMENT TREE ----------
// vll dx = {1, -1, 0, 0};
// vll dy = {0, 0, 1, -1};
const auto start_time = chrono::high_resolution_clock::now();
void output_run_time() {
// will work for ac,cc&&cf.
#ifndef ONLINE_JUDGE
auto end_time = chrono::high_resolution_clock::now();
chrono::duration<double> diff = end_time - start_time;
cout << "\n\n\nTime Taken : " << diff.count();
#endif
}
int main() {
fio;
ll n, x, y, i, j;
cin >> n;
bool res = 1;
bool vis[n][n];
pii dest[n][n];
queue<pii> q;
char ans[n][n];
memset(vis, 0, sizeof(vis));
fo(i, 0, n)
{
fo(j, 0, n)
{
cin >> x >> y;
if (x == -1)
{
x = 0;
y = 0;
}
x--;
y--;
dest[i][j] = {x, y};
if (x == i && y == j)
{
ans[i][j] = 'X';
q.push({i, j});
}
}
}
fo(i, 0, n)
{
fo(j, 0, n) {
if (dest[i][j].first == -1) {
vis[i][j] = 1;
if (i) {
if (dest[i - 1][j].first == -1) {
ans[i][j] = 'U';
continue;
}
}
if (i != n - 1) {
if (dest[i + 1][j].first == -1) {
ans[i][j] = 'D';
continue;
}
}
if (j) {
if (dest[i][j - 1].first == -1) {
ans[i][j] = 'L';
continue;
}
}
if (j != n - 1) {
if (dest[i][j + 1].first == -1) {
ans[i][j] = 'R';
continue;
}
}
res = 0;
}
}
}
while (!q.empty()) {
auto s = q.front();
q.pop();
if (vis[s.first][s.second])
continue;
vis[s.first][s.second] = 1;
int i = s.first, j = s.second;
if (i) {
if (dest[i - 1][j] == dest[i][j] && !vis[i - 1][j]) {
ans[i - 1][j] = 'D';
q.push({i - 1, j});
}
}
if (i != n - 1) {
if (dest[i + 1][j] == dest[i][j] && !vis[i + 1][j]) {
ans[i + 1][j] = 'U';
q.push({i + 1, j});
}
}
if (j) {
if (dest[i][j - 1] == dest[i][j] && !vis[i][j - 1]) {
ans[i][j - 1] = 'R';
q.push({i, j - 1});
}
}
if (j != n - 1) {
if (dest[i][j + 1] == dest[i][j] && !vis[i][j + 1]) {
ans[i][j + 1] = 'L';
q.push({i, j + 1});
}
}
}
fo(i, 0, n)
{
fo(j, 0, n)
{
// cout << vis[i][j] << ' ';
res &= vis[i][j];
}
}
if (res) {
cout << "VALID" << endl;
fo(i, 0, n)
{
fo(j, 0, n)
cout << ans[i][j];
cout << endl;
}
}
else {
cout << "INVALID" << endl;
}
return 0;
}
//remove #define endl '\n' for lleractive problems | cpp |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
set<int> s;
for (int i = 0; i < n; ++i) {
int current;
cin >> current;
s.insert(current);
}
cout << s.size() << '\n';
}
return 0;
} | 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>
#define Cn const
#define CI Cn int&
#define N 60
#define X 1000000007
using namespace std;
int n,a[N+5],C[N+5][N+5],c,s[N+5],tt,ans=1;
int vis[N+5];void dfs(int x)
{
vis[x]=1,s[++c]=a[x];for(int i=1;i<=n;++i) !vis[i]&&(!(a[i]%a[x])||!(a[x]%a[i]))&&(dfs(i),0);
}
int w[N+5],q[N+5],g[1<<N/4],f[N+5][1<<N/4];void Solve()
{
if(c==1) return;sort(s+1,s+c+1);
int i,j,k,c_=0,ct=0;for(i=1;i<=c;++i) {j=1;for(j=1;j<=ct&&s[i]%q[j];++j);(j>ct?q[++ct]:s[++c_])=s[i];}c=c_;
for(i=1;i<=c;++i) {w[i]=0;for(j=1;j<=ct;++j) !(s[i]%q[j])&&(w[i]|=1<<j-1);++g[w[i]];}
int l=1<<ct;for(i=1;i<=n;++i) for(j=0;j^l;++j) f[i][j]=0;for(j=0;j^l;++j) g[j]=0;
for(i=1;i<=c;++i) ++f[1][w[i]],++g[w[i]];
for(i=0;i^ct;++i) for(j=0;j^l;++j) j>>i&1&&(g[j]+=g[j^(1<<i)]);
for(i=1;i^c;++i) for(j=0;j^l;++j) if(f[i][j])
{
f[i+1][j]=(f[i+1][j]+1LL*f[i][j]*(g[j]-i))%X;
for(k=1;k<=c;++k) w[k]&j&&(w[k]|j)^j&&(f[i+1][w[k]|j]=(f[i+1][w[k]|j]+f[i][j])%X);
}
ans=1LL*ans*f[c][l-1]%X*C[tt+c-1][tt]%X,tt+=c-1;
}
int main()
{
int i,j;for(scanf("%d",&n),i=1;i<=n;++i) scanf("%d",a+i);
for(C[0][0]=i=1;i<=n;++i) for(C[i][0]=j=1;j<=i;++j) C[i][j]=(C[i-1][j-1]+C[i-1][j])%X;
for(i=1;i<=n;++i) !vis[i]&&(c=0,dfs(i),Solve(),0);return printf("%d\n",ans),0;
} | cpp |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | #include<bits/stdc++.h>
using namespace std;
long long n,cnt,k,num,ans;
priority_queue<int>q;
struct ono{
int x,y;
bool operator <(const ono &W)const
{
return x<W.x;
}
}a[1000000];
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i].x;
for(int i=1;i<=n;i++)
cin>>a[i].y;
sort(a+1,a+1+n);
while(q.size()||cnt<n)
{
k++;
if(!q.size())
{
k=a[cnt+1].x;
while(k==a[cnt+1].x&&cnt<n)
{
cnt++;
num+=a[cnt].y;
q.push(a[cnt].y);
}
}
else
{
while(k==a[cnt+1].x&&cnt<n)
{
cnt++;
num+=a[cnt].y;
q.push(a[cnt].y);
}
}
num-=q.top();
q.pop();
ans+=num;
}
cout<<ans;
return 0;
}
| cpp |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | #include <bits/stdc++.h>
#define ll long long
#define ld long double
#define vi vector<int>
#define vll vector<long long>
#define pii pair<int,int>
#define pll pair<ll , ll>
#define pb push_back
#define mp make_pair
#define FAST ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define INF INT_MAX
#define ff first
#define ss second
#define all(v) v.begin(),v.end()
#define pr(v) for(int i=0;i<v.size();i++)cout << v[i] << " "
#define nar ll n;cin >> n; ll a[n] ; for(int i=0;i<n;i++)cin >> a[i]
#define oar for(int i=0;i<n;i++)cout << a[i] << " "
#define nl "\n"
#define yes cout << "YES\n"
#define no cout << "NO\n"
using namespace std;
const ll MOD = 1000000007 ;
const int mxN = 1e5+1;
const ld PI = 4.0 * atan(1);
int main(){
FAST
//==================
ll t = 1;
cin >> t;
while(t--){
ll n,m; cin >> n>>m;
ll a[n],b[n],a2[n];
map<ll,bool> mm ;
for(int i=0;i<n;i++){
cin >> a[i];
a2[i] = a[i];
}
for(int i=0;i<m;i++){
cin >> b[i];
mm[b[i]-1] = 1;
}
sort(a2,a2+n);
bool done[n];
for(int i=0;i<n;i++)done[i] =0 ;
bool is =1;
for(int i=0;i<n;i++){
ll st = i , en ;
for(int j=0;j<n;j++){
if(a2[j] == a[i] && !done[j]){
done[j] = 1 ;
en = j;
break;
}
}
if(en < st)swap(en,st);
for(int j=st;j<en;j++){
if(!mm[j]){
is =0 ;
//cout << a[i] << " ==\n";
break;
}
}
}
if(is)yes;
else no;
}
}
| cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.