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.

#include <bits/stdc++.h>

using namespace std;

int ans,n;

string f(string s,char c){

	int l=s.length();

	string tmp="";

	for(int i=0;i<l;i++){

		if(s[i]==c){

			int j=i+1;

			while(j<l&&s[j]==c) j++;

			if(i>0&&s[i-1]==c-1||j<l&&s[j]==c-1){

				ans+=j-i;

				i=j-1;

				continue;

			}

		}

		tmp+=s[i];

	}

	return tmp;

}

int main(){

	cin>>n;

	string s;

	cin>>s;

	for(char c='z';c>'a';c--)

		s=f(s,c);

	cout<<ans<<endl;

	return 0;

}


E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000

#include <bits/stdc++.h>

#define N 205

#define wr cout << "Continue debugging\n";

#define all(x) (x).begin(), (x).end()

#define ll long long int

#define pii pair <int, int>

#define pb push_back

#define ff first

#define ss second

using namespace std;

int p[N];

pair<int,pii> dp[N][30][30];

int main ()

{

	ios::sync_with_stdio(false);

	cin.tie(0);

	int n;

	string s;

	cin >> n >> s;

	// char lst1 = 'a', lst2 = 'a';

	// for (int i = 0; i < n; i++){

	// 	if (s[i] >= lst1) lst1 = s[i];

	// 	else if (s[i] >= lst2){

	// 		lst2 = s[i];

	// 		p[i] = 1;

	// 	}else return cout << "NO", 0;

	// }

	// cout << "YES\n";

	// for (int i = 0; i < n; i++){

	// 	cout << p[i];

	// }

	s = '#'+s;

	dp[0][0][0].ff = 1;

	int a = -1, b = -1;

	for (int i = 1; i <= n; i++){

		int x = s[i]-'a';

		for (int j = 0; j < 26; j++){

			for (int k = 0; k < 26; k++){

				if (dp[i-1][j][k].ff){

					if (j <= x){

						dp[i][x][k].ff = 1;

						dp[i][x][k].ss.ff = j;

						dp[i][x][k].ss.ss = k;

						if (i == n){

							a = x;

							b = k;

						}

					}

					if (k <= x){

						dp[i][j][x].ff = 1;

						dp[i][j][x].ss.ff = j;

						dp[i][j][x].ss.ss = k;

						if (i == n){

							a = j;

							b = x;

						}

					}

				}

			}

		}

	}

	if (a == -1) return cout << "NO", 0;

	cout << "YES\n";

	for (int i = n; i >= 1; i--){

		if (s[i]-'a' == b) p[i] = 1;

		int olda = a, oldb = b;

		a = dp[i][olda][oldb].ss.ff;

		b = dp[i][olda][oldb].ss.ss;

	}

	for (int i = 1; i <= n; i++){

		cout << p[i];

	}

}


C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.

#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;

using ll = long long;

using ull = unsigned long long;

#ifdef LOCAL

#include "algo/debug.h"

#define TASK "inp1"

#else

#define debug(...) 42

#define TASK "printer"

#define debugArr(...) 42

#endif

#define ordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>

#define faster() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

#define fi first

#define se second

const ll MOD = 1e9+7;

const ll maxn = 1e5+5;

const ll inf = 1e18;

const ll BASE = 31;

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; }

//random

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

int Rand(int a, int b)

{

    return uniform_int_distribution<int>(a, b)(rng);

}

void solve()

{

    int n, k; cin >> n >> k;

    string s; cin >> s;

    s = '$' + s;

    vector <int> v(k), ans(26);

    vector <vector <int>> cnt(n + 1, vector <int> (26));

    for(int &x : v) cin >> x;

    v.push_back(n);

    for(int i = 1; i <= n; i++)

    {

        int x = s[i] - 'a';

        for(int j = 0; j < 26; j++) cnt[i][j] = cnt[i - 1][j] + (x == j);

    }

    for(int x : v)

    {

        for(int i = 0; i < 26; i++)

        {

            ans[i] += cnt[x][i];

        }

    }

    for(int x : ans) cout << x << ' ';

    cout << '\n';

}

signed main()

{

    faster();

    if (fopen(TASK ".inp", "r")) freopen(TASK ".inp", "r", stdin);

    int t = 1;

    cin >> t;

    while(t--)

    {

        solve();

    }

}


C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1

// #pragma GCC optimize("O3,unroll-loops")

// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

#include <bits/stdc++.h>

#include <ext/rope>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/hash_policy.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#include <ext/pb_ds/trie_policy.hpp>

#include <ext/pb_ds/priority_queue.hpp>

using namespace std;

using namespace __gnu_cxx;

using namespace __gnu_pbds;

template <class T> using Tree = tree<T, null_type, less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>;

using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>;

// template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>;

template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>;

#define ll long long

#define i128 __int128

#define ld long double

#define ui unsigned int

#define ull unsigned long long

#define pii pair<int, int>

#define pll pair<ll, ll>

#define pdd pair<ld, ld>

#define vi vector<int>

#define vvi vector<vector<int>>

#define vll vector<ll>

#define vvll vector<vector<ll>>

#define vpii vector<pii>

#define vpll vector<pll>

#define lb lower_bound

#define ub upper_bound

#define pb push_back

#define pf push_front

#define eb emplace_back

#define fi first

#define se second

#define rep(i, a, b) for(int i = a; i < b; ++i)

#define per(i, a, b) for(int i = a; i > b; --i)

#define each(x, v) for(auto& x: v)

#define len(x) (int)x.size()

#define elif else if

#define all(x) (x).begin(), (x).end()

#define rall(x) (x).rbegin(), (x).rend()

#define mst(x, a) memset(x, a, sizeof(x))

#define lowbit(x) (x & (-x))

#define bitcnt(x) (__builtin_popcountll(x))

#define endl "\n"

mt19937 rng( chrono::steady_clock::now().time_since_epoch().count() );

#define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a)

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);

    }

    size_t operator()(pair<uint64_t,uint64_t> x) const {

        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

        return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1);

    }

};

const i128 ONE = 1;

istream &operator>>(istream &in, i128 &x) {

    string s;

    in >> s;

    bool minus = false;

    if (s[0] == '-') {

        minus = true;

        s.erase(s.begin());

    }

    x = 0;

    for (auto i : s) {

        x *= 10;

        x += i - '0';

    }

    if (minus) x = -x;

    return in;

}

ostream &operator<<(ostream &out, i128 x) {

    string s;

    bool minus = false;

    if (x < 0) {

        minus = true;

        x = -x;

    }

    while (x) {

        s.push_back(x % 10 + '0');

        x /= 10;

    }

    if (s.empty()) s = "0";

    if (minus) out << '-';

    reverse(s.begin(), s.end());

    out << s;

    return out;

}

template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const set<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) {

    for(auto it = begin(v); it != end(v); ++it) {

        if(it == begin(v)) os << *it;

        else os << " " << *it;

    }

    return os;

}

template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) {

    os << p.first << " " << p.second;

    return os;

}

ll gcd(ll x,ll y) {

    if(!x) return y;

    if(!y) return x;

    int t = __builtin_ctzll(x | y);

    x >>= __builtin_ctzll(x);

    do {

        y >>= __builtin_ctzll(y);

        if(x > y) swap(x, y);

        y -= x;

    } while(y);

    return x<<t;

}

ll lcm(ll x, ll y) { return x * y / gcd(x, y); }

ll exgcd(ll a, ll b, ll &x, ll &y) {

    if(!b) return x = 1, y = 0, a;

    ll d = exgcd(b, a % b, x, y);

    ll t = x;

    x = y;

    y = t - a / b * x;

    return d;

}

ll max(ll x, ll y) { return x > y ? x : y; }

ll min(ll x, ll y) { return x < y ? x : y; }

ll Mod(ll x, int mod) { return (x % mod + mod) % mod; }

ll pow(ll x, ll y, ll mod){

    ll res = 1, cur = x;

    while (y) {

        if (y & 1) res = res * cur % mod;

        cur = ONE * cur * cur % mod;

        y >>= 1;

    }

    return res % mod;

}

ll probabilityMod(ll x, ll y, ll mod) {

    return x * pow(y, mod-2, mod) % mod;

}

vvi getGraph(int n, int m, bool directed = false) {

    vvi res(n);

    rep(_, 0, m) {

        int u, v;

        cin >> u >> v;

        u--, v--;

        res[u].emplace_back(v);

        if(!directed) res[v].emplace_back(u);

    }

    return res;

}

vector<vpii> getWeightedGraph(int n, int m, bool directed = false) {

    vector<vpii> res(n);

    rep(_, 0, m) {

        int u, v, w;

        cin >> u >> v >> w;

        u--, v--;

        res[u].emplace_back(v, w);

        if(!directed) res[v].emplace_back(u, w);

    }

    return res;

}

const ll LINF = 0x1fffffffffffffff;

const ll MINF = 0x7fffffffffff;

const int INF = 0x3fffffff;

const int MOD = 1000000007;

const int MODD = 998244353;

const int N = 1e6 + 10;

class SegmentTree {

public:

	struct STNode {

		STNode () : left(nullptr), right(nullptr), val(0), maxval(0), minval(0), lazy(0), mlazy(LINF) {}

		STNode* left;

		STNode* right;

		ll val;

		ll maxval;

		ll minval;

		ll lazy;

		ll mlazy;

	};

	STNode* root;

	SegmentTree() { root = new STNode(); }

	~SegmentTree() {}

	void assign(STNode* node, int l, int r, int start, int end, ll x) {

		if (l == start && r == end) {

			node->val = 0;

			node->maxval = 0;

			node->minval = 0;

			node->lazy = 0;

			node->mlazy = x;

			return;

		}

		pushdown(node);

		int mid = l+r>>1;

		if (end <= mid) {

			assign(node->left, l, mid, start, end, x);

		} elif (start > mid) {

			assign(node->right, mid+1, r, start, end, x);

		} else {

			assign(node->left, l, mid, start, mid , x);

			assign(node->right, mid+1, r, mid+1, end, x);

		}

		pushup(node, mid-l+1, r-mid);

	}

	void add(STNode* node, int l, int r, int start, int end, ll x){

		if (l == start && r == end) {

			node->lazy += x;

			return;

		}

		pushdown(node);

		int mid = l+r>>1;

		if (end <= mid) {

			add(node->left, l, mid, start, end, x);

		} elif (start > mid) {

			add(node->right, mid+1, r, start, end, x);

		} else {

			add(node->left, l, mid, start, mid , x);

			add(node->right, mid+1, r, mid+1, end, x);

		}

		pushup(node, mid-l+1, r-mid);

	}

	ll querySum(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->val + node->lazy * (r-l+1) + \

				(node->mlazy == LINF ? 0 : node->mlazy * (r-l+1));

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = querySum(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = querySum(node->right, mid+1, r, start, end);

		} else {

			res = querySum(node->left, l, mid, start, mid) +

			querySum(node->right, mid+1, r, mid+1, end);

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	ll queryMax(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->maxval + node->lazy + \

				(node->mlazy == LINF ? 0 : node->mlazy);

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = queryMax(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = queryMax(node->right, mid+1, r, start, end);

		} else {

			res = max(queryMax(node->left, l, mid, start, mid),

			queryMax(node->right, mid+1, r, mid+1, end));

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	ll queryMin(STNode* node, int l, int r, int start, int end) {

		if (l == start && r == end) {

			return node->minval + node->lazy + \

				(node->mlazy == LINF ? 0 : node->mlazy);

		}

		pushdown(node);

		int mid = l+r>>1;

		ll res;

		if (end <= mid) {

			res = queryMin(node->left, l, mid, start, end);

		} elif (start > mid) {

			res = queryMin(node->right, mid+1, r, start, end);

		} else {

			res = min(queryMin(node->left, l, mid, start, mid),

			queryMin(node->right, mid+1, r, mid+1, end));

		}

		pushup(node, mid-l+1, r-mid);

		return res;

	}

	void pushdown(STNode* node) {

		if (node->left == nullptr) {

			node->left = new STNode();

		}

		if (node->right == nullptr) {

			node->right = new STNode();

		}

		if (node->mlazy != LINF) {

			node->left->lazy = 0;

			node->left->val = 0;

			node->left->maxval = 0;

			node->left->minval = 0;

			node->right->lazy = 0;

			node->right->val = 0;

			node->right->maxval = 0;

			node->right->minval = 0;

			node->left->mlazy = node->mlazy;

			node->right->mlazy = node->mlazy;

			node->mlazy = LINF;

		}

		if (node->lazy) {

			node->left->lazy += node->lazy;

			node->right->lazy += node->lazy;

			node->lazy = 0;

		}

	}

	void pushup(STNode* node, int ln, int rn) {

		node->val = node->left->val + node->left->lazy * ln + \

					(node->left->mlazy == LINF ? 0 : node->left->mlazy * ln) + \

					node->right->val + node->right->lazy * rn + \

					(node->right->mlazy == LINF ? 0 : node->right->mlazy * rn);

		node->maxval = max(node->left->maxval + node->left->lazy + \

						(node->left->mlazy == LINF ? 0 : node->left->mlazy),

						node->right->maxval + node->right->lazy + \

						(node->right->mlazy == LINF ? 0 : node->right->mlazy));

		node->minval = min(node->left->minval + node->left->lazy + \

						(node->left->mlazy == LINF ? 0 : node->left->mlazy),

						node->right->minval + node->right->lazy + \

						(node->right->mlazy == LINF ? 0 : node->right->mlazy));

	}

};

void solve() {

    int n, m, p;

    cin >> n >> m >> p;

    vpii a(n), b(m);

    vector<array<int, 3>> monster(p);

    rep(i, 0, n) cin >> a[i].fi >> a[i].se;

    rep(i, 0, m) cin >> b[i].fi >> b[i].se;

    rep(i, 0, p) cin >> monster[i][0] >> monster[i][1] >> monster[i][2];

    sort(all(a)), sort(all(b)), sort(all(monster));

    SegmentTree st;

    st.assign(st.root, 0, N, 0, N, -LINF);

    rep(i, 0, m) {

        ll t = st.queryMax(st.root, 0, N, b[i].fi, b[i].fi);

        st.assign(st.root, 0, N, b[i].fi, b[i].fi, max(t, -b[i].se));

    }

    ll ans = -LINF;

    for (int i = 0, j = 0; i < n; i++) {

        for ( ; j < p && monster[j][0] < a[i].fi; j++) {

            auto [x, y, z] = monster[j];

            st.add(st.root, 0, N, y + 1, N, z);

        }

        ans = max(ans, st.queryMax(st.root, 0, N, 0, N) - a[i].se);

    }

    cout << ans << endl;

}

signed main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int t = 1;

    // cin >> t;

    while (t--) {

        solve();

    }

    return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

#define sz(s) (int)(s.size())

#define all(v) v.begin(),v.end()

#define clr(d, v) memset(d,v,sizeof(d))

#define ll long long

void file() {

    std::ios_base::sync_with_stdio(0);

    cin.tie(NULL);

    cout.tie(NULL);

}

int main() {

    file();

    int n;

    cin >> n;

    vector<int> v(n - 1);

    ll sum = 0;

    int pos = 0;

    bool ok = true;

    for (auto &it: v) {

        cin >> it;

        sum += it;

        if (sum > 0)

            pos++;

    }

    vector<int> ans = {n - pos};

    vector<bool> vis(n + 1);

    vis[n - pos] = true;

    for (int i = 1; i < n; i++) {

        ans.push_back(v[i - 1] + ans.back());

        if (ans.back() > n || ans.back() <= 0 || vis[ans.back()]) {

            cout << "-1";

            return 0;

        }

        vis[ans.back()] = true;

    }

    for (auto it: ans)cout << it << " ";

}


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

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<queue>
#include<string>
#include<stack>
using namespace std;
const int maxn = 1e6 + 10;
typedef long long ll;
#define tbl ios::sync_with_stdio(false), cin.tie(0),cout.tie(0);
int main() {
	int t;
	cin >> t;
	while (t--) {
		vector<int>q(64, 0);
		ll m,n,sum=0,cnt=0;
		cin >> m >> n;
		for (int i = 0; i < n; i++) {
			int h;
			cin >> h;
			sum += h;
			q[log2(h)]++;
		}
		if (sum < m) {
			cout << "-1" << endl;
			continue;
		}
		for (int i = 0; i < 63&&m; i++) {
			if (m % 2 == 1) {
				int j = i;
				while (q[j] == 0) {
					j++;
					cnt++;
				}
				while (j != i) {
					q[j--]--;
					q[j] += 2;
				}
				q[i]--;
			}
			m /= 2;
			q[i + 1] += q[i] / 2;
		}
		cout << cnt << endl;
	}
}


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.

#include<cstdio>
#include<cctype>
#include<vector>

#define maxn 66

const int mod=1e9+7;

template<class T>

inline T read(){
	T r=0,f=0;
	char c;
	while(!isdigit(c=getchar()))f|=(c=='-');
	while(isdigit(c))r=(r<<1)+(r<<3)+(c^48),c=getchar();
	return f?-r:r;
}

inline long long qpow(long long a,int b){
	long long ans=1;
	for(;b;b>>=1){
		if(b&1)(ans*=a)%=mod;
		(a*=a)%=mod;
	}
	return ans;
}

int n,a[maxn];

bool vis[maxn],tag[maxn];

long long C[maxn][maxn],A[maxn][maxn];

inline void Add(int &x,int y){
	x+=y-mod,x+=(x>>31)&mod;
}

int sum;

long long ans;

std::vector<int> to[maxn];

namespace Solve{

	long long f[1<<15];

	int N,n,m,d[maxn],d0[maxn],T[maxn],cnt[1<<15];

	inline void FWT(){
		for(int i=1;i<N;i<<=1)
			for(int j=0,p=i<<1;j<N;j+=p)
				for(int k=0;k<i;k++)
					Add(cnt[i|j|k],cnt[j|k]);
	}

	void dfs(int u){
		vis[u]=1;
		if(tag[u])d0[++n]=u;
		else d[++m]=u;
		for(auto v:to[u])
			if(!vis[v])dfs(v);
	}

	inline void work(int s){
		n=m=0,dfs(s);
		if(!m)return;
		N=1<<n,sum+=m-1;
		(ans*=C[sum][m-1])%=mod;
		for(int i=0;i<N;i++)
			cnt[i]=0,f[i]=0;
		for(int i=1;i<=m;i++){
			T[i]=0;
			for(int j=1;j<=n;j++)
				if(!(a[d[i]]%a[d0[j]]))
					T[i]|=1<<(j-1);
			cnt[T[i]]++;
		}
		FWT();
		for(int i=1;i<=m;i++)
			(f[T[i]]+=A[m-1][cnt[T[i]]-1])%=mod;
		for(int S=1;S<N-1;S++){
			if(!f[S])continue;
			int tot=cnt[S];
			long long val=f[S];
			for(int i=1;i<=m;i++)
				if((S&T[i])&&(S&T[i])!=T[i]){
					int S1=S|T[i];
					(f[S1]+=val*A[m-tot-1][cnt[S1]-tot-1])%=mod;
				}
		}
		(ans*=f[N-1])%=mod;
	}

}

int main(){
	n=read<int>();
	for(int i=1;i<=n;i++)
		a[i]=read<int>();
	for(int i=1;i<=n;i++){
		tag[i]=1;
		for(int j=1;j<=n;j++)
			if((i^j)&&!(a[i]%a[j]))
				tag[i]=0,to[i].push_back(j),to[j].push_back(i);
	}
	for(int i=0;i<=n;i++){
		C[i][0]=A[i][0]=1;
		for(int j=1;j<=i;j++){
			C[i][j]=(C[i-1][j-1]+C[i-1][j])%mod;
			A[i][j]=A[i-1][j-1]*i%mod;
		}
	}
	ans=1;
	for(int i=1;i<=n;i++)
		if(!vis[i])Solve::work(i);
	printf("%lld\n",ans);
	return 0;
}//


D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.

#include<bits/stdc++.h>
using namespace std;
#define taskname ""
struct line{
int l,r;
bool operator < (const line &p)const{
return l<p.l;
}
};
struct suzy{
int id,pos;
};
line a[100009];
int vis[8];
int dp[200009][1<<8];
int dp2[200009][1<<8];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    //freopen(taskname".INP","r",stdin);
    //freopen(taskname".OUT","w",stdout);
    int n,m,k;
    cin>>n>>m>>k;
    vector<int>pos;
    map<int,int>dm;
    pos.push_back(m);
    dm[m]=1;
    for (int i=1;i<=n;i++){
        cin>>a[i].l>>a[i].r;
        if (dm[a[i].l]==0){
            pos.push_back(a[i].l);
            dm[a[i].l]=1;
        }
        if (dm[a[i].r+1]==0){
            dm[a[i].r+1]=1;
            pos.push_back(a[i].r+1);
        }
    }
    if (dm[m+1]==0)pos.push_back(m+1);
    sort(pos.begin(),pos.end());
    sort(a+1,a+1+n);
    int p=0;
    int mask=0;
    vector<suzy>last;
    int ans=0;
    for (int i=0;i<(int)pos.size()-1;i++){
        for (int j=0;j<k;j++){
            vis[j]=0;
        }
        mask=0;
        for (auto v:last){
            if (a[v.id].r<pos[i])continue;
            vis[v.pos]=v.id;
            //cout<<i<<" "<<v.pos<<'\n';
            mask+=(1<<v.pos);
        }
        vector<int>newline;
        for (int j=p+1;j<=n;j++){
            if (a[j].l==pos[i]){
                p=j;
                newline.push_back(j);
            }
            else break;
        }
        //cout<<newline.size()<<'\n';
        last.clear();
        int newmask=0,nmask=0;;
        for (int j=0;j<k;j++){
            if (vis[j]==0){
                if (newline.empty())continue;
                vis[j]=newline.back();
                newline.pop_back();
                last.push_back({vis[j],j});
                if (a[vis[j]].r>=pos[i+1])newmask+=(1<<j);
                nmask|=(1<<j);
            }
            else {
                last.push_back({vis[j],j});
                if (a[vis[j]].r>=pos[i+1])newmask+=(1<<j);
                nmask|=(1<<j);
                //cout<<i<<" "<<j<<'\n';
            }
        }
        //cout<<pos[i]<<" "<<last.size()<<'\n';
        //cout<<pos[i]<<" "<<nmask<<'\n';
        for (int j=0;j<(1<<k);j++){
            //beforemask
            if ((j&nmask)!=j)continue;
            int huhu=(j&mask);
            int sum=0;
            if (i>0)sum=dp2[i-1][huhu];
            if (__builtin_popcount(j)%2==1){
                sum+=(pos[i+1]-pos[i]);
            }
            dp[i][j]=sum;
            ans=max(ans,sum);
            //cout<<pos[i]<<" "<<j<<" "<<sum<<'\n';
        }
        //cout<<mask<<" "<<pos[i]<<'\n';
        //cout<<pos[i]<<" "<<newmask<<'\n';
        for (int j=0;j<(1<<k);j++){
            dp2[i][(j&newmask)]=max(dp2[i][(j&newmask)],dp[i][j]);
        }
        //cout<<i<<" "<<last.size()<<'\n';
    }
    cout<<ans;

}


///******* In the name of ALLAH, Who is Most Gracious, Most Merciful *******///

///******* There is no God but ALLAH, MUHAMMAD(S.A.W) is the Messenger of ALLAH. *******///

///******* Every soul shall taste death.*******///

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

/**************************************************************************************

    ___  _          _   _  ___ ___  ________ _   _ _    _____ _     _      ___  _   _

   / _ \| |        | | | |/ _ \|  \/  |  _  | | | | |  |_   _| |   | |    / _ \| | | |

  / /_\ | |  ____  | |_| / /_\ | .  . | | | | | | | |    | | | |   | |   / /_\ | |_| |

  |  _  | | |____| |  _  |  _  | |\/| | | | | | | | |    | | | |   | |   |  _  |  _  |

  | | | | |____    | | | | | | | |  | | |/ /| |_| | |____| |_| |___| |___| | | | | | |

  \_| |_\_____/    \_| |_\_| |_\_|  |_|___/  \___/\_____\___/\_____\_____\_| |_\_| |_/

***************************************************************************************/

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//  AL-HAMDULILLAH    //  AL-HAMDULILLAH     //  AL-HAMDULILLAH    //  AL-HAMDULILLAH

//#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<iostream>

#include<algorithm>

#include<vector>

#include<stdlib.h>

#include<string.h>

#include<math.h>

#define 	ll              long long

#define 	size1           1000001

#define 	bm              1000000007   //bigmod

#define		reset(arr,n,i)  fill(arr,arr+n,i)  //cbrt(n) means cube root

#define		rset(arr,x)  	memset(arr,x,sizeof(arr))

#define		_ceil(x,y)      ((x)/(y))+(((x)%(y))>0)

#define		INF             1e18 + 10

#define		mod             1e9 + 7//998244353;

#define 	endl            "\n"

#define		_cpy(c,a,n)     for(int i=0;i<n;i++) c.push_back(a[i]);

#define 	_iin(a,n)       int a[n]; for(int i=0;i<n;i++) cin>>a[i]

#define 	_lin(a,n)       ll a[n]; for(int i=0;i<n;i++) cin>>a[i]

#define 	_in(a,n)        for(int i=0;i<n;i++) cin>>a[i]

#define 	_out(a,n)       for(int i=0;i<n;i++) cout<<a[i]<<" "; cout<<endl

#define		_celi(x,y)      (x+y-1)/(y)  //use this version of _ceil [note: ceil is risky]

#define     eps             0.0000000001

#define 	fopr()          freopen("input.txt", "r", stdin)

#define 	fopw()          freopen("output.txt", "w", stdout)

#define 	FastIO          ios_base::sync_with_stdio(false), cin.tie(0)

// Math :

void		mns(int *x, int *y)		{if(*x>=*y) *x-=*y, *y=0; else *y-=*x, *x=0;}

int			log_2(ll n)				{int cnt=0; while(n/2) cnt++, n/=2; return cnt;}

// Debuging :

#define		_dbg(_x,_y,_z)  cout<<_x<<" "<<_y<<" "<<_z<<endl

#define		_dbl			cout<<"_________________ "<<endl

#define		_db(_x,_y)      cout<<_x<<" "<<_y<<endl

#define     OK              cout<<"Ok"<<endl;

using namespace std;

void solve()

{

	int n;

	cin>>n;

	string str;

	cin>>str;

	int cnt=0;

	vector<char>tr,vec;

	for(int i=0;i<n;i++){

		vec.push_back(str[i]);

		if(tr.empty() || tr.back()!=str[i])

			tr.push_back(str[i]);

	}

	sort(tr.rbegin(),tr.rend());

	for(int i=0;i<tr.size()-1;i++){

		vector<char>v;

		if(vec.empty()) break;

		for(int k=0;k<vec.size();){

			if(vec[k]==tr[i] && !v.empty() && v.back()==tr[i]-1) cnt++,k++;

			else if(vec[k]==tr[i]-1 && !v.empty() && v.back()==tr[i]) v.pop_back(),cnt++;

			else v.push_back(vec[k++]);

		}

		vec.clear();

		_cpy(vec,v,v.size());

	}

	cout<<cnt<<endl;

}

int main()

{

	FastIO;

	int n=1;

	while(n--)

	{

		solve();

	}

	return 0;

}

//written by MAMUN

/*  Cautions:

	1.array out of bound!!! [check array size and last accessed index]

	2.signed integer overflow!!! [int*int!=ll @typecast(ll) one of them or, multiply with 1LL]

	3.floating point numbers numbers are equal if the difference between them is less than 1e-9 [better way to compare floating point numbers]

	4.any square number when divided by 4 must have a remainder of either 0 or 1.

*/

/********************************************************************************************************************************************************

 _   _            _   _       _____          _     _   _       _                    _ _          ______                   _           _           _

| \ | |          | | | |     |  ___|        | |   | | | |     (_)                  (_) |         | ___ \                 | |         | |         | |

|  \| | ___  _ __| |_| |__   | |__  __ _ ___| |_  | | | |_ __  ___   _____ _ __ ___ _| |_ _   _  | |_/ / __ _ _ __   __ _| | __ _  __| | ___  ___| |__

| . ` |/ _ \| '__| __| '_ \  |  __|/ _` / __| __| | | | | '_ \| \ \ / / _ \ '__/ __| | __| | | | | ___ \/ _` | '_ \ / _` | |/ _` |/ _` |/ _ \/ __| '_ \

| |\  | (_) | |  | |_| | | | | |__| (_| \__ \ |_  | |_| | | | | |\ V /  __/ |  \__ \ | |_| |_| | | |_/ / (_| | | | | (_| | | (_| | (_| |  __/\__ \ | | |

\_| \_/\___/|_|   \__|_| |_| \____/\__,_|___/\__|  \___/|_| |_|_| \_/ \___|_|  |___/_|\__|\__, | \____/ \__,_|_| |_|\__, |_|\__,_|\__,_|\___||___/_| |_|

                                                                                __/ |                     __/ |

                                                                                |___/                     |___/

*********************************************************************************************************************************************************/


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

ll lcm(ll a,ll b) { return a/gcd(a,b)*b; }

void yes() { cout<<"YES\n"; }

void no() { cout<<"NO\n"; }

#define yes yes();

#define no no();

#define endl '\n';

void solve()

{

	int n; cin>>n;

    set<int> st;

    for (int i = 0; i < n; i++)

    {

        int temp; cin>>temp;

        st.insert(temp%2);

    }

    if (st.size()>1) no

    else yes;

}

int main()

{

	ios_base::sync_with_stdio(0);

    cin.tie(0); cout.tie(0);

	int t;

	cin >> t;

	while(t--)

	{

		solve();

	}

	return 0;

}


E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.

// LUOGU_RID: 102254356
#include <bits/stdc++.h>

#define int long long

using namespace std;

const int INF=505;

int n,m,q;

char a[INF][INF];

mt19937 rnd(chrono::system_clock().now().time_since_epoch().count());

int gen(int l,int r) {return rnd()%(r-l+1);}

int vis[INF],p[INF],b[INF][INF],ans[INF][INF];

int f[INF][INF][13][13];

int Get(int x,int y,int xx,int yy) {

//	cout<<x<<" "<<y<<" "<<xx<<" "<<yy<<" qweijqwej\n";

	return b[xx][yy]-b[x][yy]-b[xx][y]+b[x][y];

}

int solve2(int l,int r,int ll,int rr) {

	if (ll-l+1<2) return 0;

	if (rr-r+1<2) return 0;

	if (l<1 || r<1 || ll>n || rr>m) return 0;

	for (int i=0;i<=5;i++) vis[i]=0;

	int Mid1=(l+ll)>>1,Mid2=(r+rr)>>1;

	int kk=Get(l-1,r-1,Mid1,Mid2);

	for (int i=0;i<=0;i++)

		if (kk%p[i]==0) {vis[i]++;break;}

	kk=Get(Mid1,r-1,ll,Mid2);

	for (int i=2;i<=2;i++)

		if (kk%p[i]==0) {vis[i]++;break;}

	kk=Get(Mid1,Mid2,ll,rr);

	for (int i=3;i<=3;i++)

		if (kk%p[i]==0) {vis[i]++;break;}

	kk=Get(l-1,Mid2,Mid1,rr);

	for (int i=1;i<=1;i++)

		if (kk%p[i]==0) {vis[i]++;break;}

	for (int i=0;i<4;i++)

		if (vis[i]!=1) return 0;

	return 1;

}

int query(int l,int r,int ll,int rr) {

	if (l>ll || r>rr) return -1e9;

	int xx=__lg(ll-l+1),yy=__lg(rr-r+1);

	return max({f[l][r][xx][yy],f[ll-(1ll<<xx)+1][r][xx][yy],

			f[l][rr-(1ll<<yy)+1][xx][yy],f[ll-(1ll<<xx)+1][rr-(1ll<<yy)+1][xx][yy]});

}

signed main()

{

	ios::sync_with_stdio(false);

	cin>>n>>m>>q;

	for (int i=0;i<4;i++) p[i]=rnd();

	for (int i=1;i<=n;i++)

		for (int j=1;j<=m;j++) {

			cin>>a[i][j];

			if (a[i][j]=='R') b[i][j]=p[0];

			else if (a[i][j]=='G') b[i][j]=p[1];

			else if (a[i][j]=='Y') b[i][j]=p[2];

			else b[i][j]=p[3];

		}

	for (int i=1;i<=n;i++)

		for (int j=1;j<=m;j++)

			b[i][j]+=b[i-1][j]+b[i][j-1]-b[i-1][j-1];

	for (int i=1;i<=n;i++) {

		for (int j=1;j<=m;j++) {

			int l=1,r=min(n,m),ans2=0;

			while (l<=r) {

				int Mid=(l+r)>>1;

				if (solve2(i-Mid+1,j-Mid+1,i+Mid,j+Mid)) l=(ans2=Mid)+1;

				else r=Mid-1;

			}

			ans[i][j]=ans2;

			f[i][j][0][0]=ans2;

		}

	}

	for (int i=1;i<21;i++) {

		if ((1ll<<i)>n) break;

		for (int j=1;j+(1ll<<i)-1<=n;j++)

			for (int k=1;k<=m;k++)

				f[j][k][i][0]=max(f[j][k][i-1][0],f[j+(1ll<<(i-1))][k][i-1][0]);

	}

	for (int i=1;i<21;i++) {

		if ((1ll<<i)>m) break;

		for (int j=1;j<=n;j++)

			for (int k=1;k+(1ll<<i)-1<=m;k++)

				f[j][k][0][i]=max(f[j][k][0][i-1],f[j][k+(1<<(i-1))][0][i-1]);

	}

	for (int i=1;i<21;i++) {

		if ((1ll<<i)>n) break;

		for (int p=1;p<21;p++) {

			if ((1ll<<p)>m) break;

			for (int j=1;j+(1ll<<i)-1<=n;j++) {

				for (int k=1;k+(1ll<<p)-1<=m;k++) {

					f[j][k][i][p]=max({f[j][k][i-1][p-1],f[j+(1ll<<(i-1))][k][i-1][p-1],

									f[j][k+(1ll<<(p-1))][i-1][p-1],f[j+(1ll<<(i-1))][k+(1ll<<(p-1))][i-1][p-1]});

				}

			}

		}

	}

	for (int i=1;i<=q;i++) { //123123

		int x=0,y=0,xx=0,yy=0;

		cin>>x>>y>>xx>>yy;

		int l=1,r=min(yy-y+1,xx-x+1),ans2=-1;

		while (l<=r) {

			int Mid=(l+r)>>1;

			if (query(x+Mid-1,y+Mid-1,xx-Mid,yy-Mid)>=Mid) l=(ans2=Mid)+1;

			else r=Mid-1;

		}

		if (ans2==-1) cout<<"0\n";

		else cout<<ans2*ans2*4<<"\n";

	}

	return 0;

}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

#include<bits/stdc++.h>

using namespace std;

int main()

{

    int test;

    cin >> test;

    while(test--){

        int a, b;

        cin >> a >> b;

        if(a == b) cout << 0 << endl;

        else if(a<b){

            if(a%2 != 0 && b%2 == 0) cout << 1 << endl;

            else if(a%2 != 0 && b%2 != 0) cout << 2 << endl;

            else if(a%2 == 0 && b%2 != 0) cout << 1 << endl;

            else if(a%2 == 0 && b%2 == 0) cout << 2 << endl;

        }

        else{

            if(a%2 != 0 && b%2 == 0) cout << 2 << endl;

            else if(a%2 != 0 && b%2 != 0) cout << 1 << endl;

            else if(a%2 == 0 && b%2 != 0) cout << 2 << endl;

            else if(a%2 == 0 && b%2 == 0) cout << 1 << endl;

        }

    }

    return 0;

}


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.

#include <bits/stdc++.h>

using namespace std;

using llong = int64_t;

#define len(c) int((c).size())

#define file_name "test"

#ifdef DAT

#include "debug.hpp"

#else

#define debug(x...) 12

#endif

namespace Task {

const int MAX_N = 150001;

const int MAX_LOG = 18;

const llong INF = 1e18;

vector<vector<int>> adj;

typedef class CentroidTree {

public:

  int size_tree;

  int root;

  vector<vector<int>> tree;

  vector<vector<int>> lev;

  vector<vector<int>> child;

  vector<bool> removed;

  vector<int> cnt_child;

  CentroidTree(){};

  CentroidTree(int init_size_tree) : size_tree(init_size_tree) {

    tree.resize(size_tree + 1, vector<int>());

    child.resize(size_tree + 1, vector<int>());

    lev.resize(MAX_LOG + 1, vector<int>());

    removed.resize(size_tree + 1, false);

    cnt_child.resize(size_tree + 1, 0);

  }

  void compute_size(int u, int par) {

    cnt_child[u] = 1;

    for (int v : adj[u]) {

      if (v != par and !removed[v]) {

        compute_size(v, u);

        cnt_child[u] += cnt_child[v];

      }

    }

  }

  int find_centroid(int u, int par, int cur_size) {

    while (true) {

      pair<int, int> best(-1, -1);

      for (int v : adj[u]) {

        if (v != par and !removed[v]) {

          if (cnt_child[v] > best.first) {

            best = {cnt_child[v], v};

          }

        }

      }

      if ((best.first << 1) <= cur_size) {

        return u;

      }

      par = u;

      u = best.second;

    }

  }

  void decompose(int u, int par, int cur_lev) {

    compute_size(u, -1);

    int cen_ver = find_centroid(u, -1, cnt_child[u]);

    removed[cen_ver] = true;

    if (par == -1) {

      root = cen_ver;

    }

    lev[cur_lev].emplace_back(cen_ver);

    child[cen_ver].emplace_back(cen_ver);

    if (par != -1) {

      tree[par].emplace_back(cen_ver);

    }

    for (int v : adj[cen_ver]) {

      if (!removed[v]) {

        decompose(v, cen_ver, cur_lev + 1);

      }

    }

    if (par != -1) {

      for (const int &v : child[cen_ver]) {

        child[par].emplace_back(v);

      }

    }

  }

  void decompose() { decompose(1, -1, 0); }

} td_centroid_tree;

typedef class Tree {

public:

  int size_tree;

  vector<vector<int>> jump;

  vector<int> euler_tour;

  vector<int> st;

  vector<llong> sum[2];

  vector<llong> sum_mult;

  vector<int> dep;

  vector<int> values;

  vector<int> dad;

  function<int(int, int)> comp = [&](const int &u, const int &v) {

    return (dep[u] <= dep[v] ? u : v);

  };

  Tree(){};

  Tree(int init_size_tree) : size_tree(init_size_tree) {

    jump.resize(MAX_LOG + 1, vector<int>(2 * size_tree + 1, 0));

    sum[0].resize(size_tree + 1, 0);

    sum[1].resize(size_tree + 1, 0);

    sum_mult.resize(size_tree + 1, 0);

    st.resize(size_tree + 1, 0);

    dep.resize(size_tree + 1, 1);

    dad.resize(size_tree + 1, 0);

    dep[0] = 0;

  }

  void add_edge(int u, int v) {

    adj[u].emplace_back(v);

    adj[v].emplace_back(u);

  }

  void dfs(int u, int par) {

    dad[u] = par;

    sum[0][u] = sum[0][par] + llong(values[u]);

    sum[1][u] = sum[1][par] + sum[0][u];

    sum_mult[u] = sum_mult[par] + llong(dep[u]) * llong(values[u]);

    st[u] = len(euler_tour);

    euler_tour.emplace_back(u);

    for (int v : adj[u]) {

      if (v != par) {

        dep[v] = dep[u] + 1;

        dfs(v, u);

        euler_tour.emplace_back(u);

      }

    }

  }

  void build_lca() {

    for (int u = 0; u < len(euler_tour); ++u) {

      jump[0][u] = euler_tour[u];

    }

    for (int j = 1; j <= MAX_LOG; ++j) {

      for (int u = 0; u + (1 << j) - 1 < len(euler_tour); ++u) {

        jump[j][u] = comp(jump[j - 1][u], jump[j - 1][u + (1 << (j - 1))]);

      }

    }

  }

  int get_lca(int u, int v) const {

    int l, r;

    tie(l, r) = pair<int, int>{st[u], st[v]};

    if (l > r) {

      swap(l, r);

    }

    int x = int(log2(r - l + 1));

    return comp(jump[x][l], jump[x][r - (1 << x) + 1]);

  }

  int get_dist(int u, int v) const {

    return dep[u] + dep[v] - 2 * dep[get_lca(u, v)] + 1;

  }

  llong get_sum(int u, int v) const {

    int R = get_lca(u, v);

    return sum[0][u] + sum[0][v] - 2 * sum[0][R] + llong(values[R]);

  }

  llong sum_to_root(int u, int R) const {

    int p = (R == 1 ? 0 : dad[R]);

    return sum_mult[u] - sum_mult[p] - llong(dep[p]) * (sum[0][u] - sum[0][p]);

  }

  llong sum_from_root(int u, int R) const {

    int p = (R == 1 ? 0 : dad[R]);

    return sum[1][u] - sum[1][p] - llong(dep[u] - dep[p]) * sum[0][p];

  }

  llong prefix_sums(int u, int v) const {

    int R = get_lca(u, v);

    int p = (R == 1 ? 0 : dad[R]);

    if (u == R) {

      return sum_from_root(v, R);

    } else if (v == R) {

      return sum_to_root(u, R);

    } else {

      llong lhs = sum_to_root(u, R) +

                  llong(dep[v] - dep[p] - 1) * (sum[0][u] - sum[0][p]);

      llong rhs =

          sum_from_root(v, R) - llong(dep[v] - dep[p]) * llong(values[R]);

      return lhs + rhs;

    }

  }

} td_tree;

class Line {

public:

  llong m, b;

  Line() : m(0), b(-INF){};

  Line(llong init_m, llong init_b) : m(init_m), b(init_b){};

  llong operator()(const int &x) { return m * llong(x) + b; }

};

vector<Line> lichao_tree;

vector<bool> clean;

void insert_line(Line upd_line, int l, int r, int node = 1) {

  if (l == r) {

    clean[node] = false;

    if (lichao_tree[node](l) < upd_line(l)) {

      lichao_tree[node] = upd_line;

    }

    return;

  }

  int mid = (l + r) >> 1;

  if (lichao_tree[node].m > upd_line.m) {

    swap(lichao_tree[node], upd_line);

  }

  if (lichao_tree[node](mid) > upd_line(mid)) {

    insert_line(upd_line, mid + 1, r, node << 1 | 1);

  } else {

    swap(lichao_tree[node], upd_line);

    insert_line(upd_line, l, mid, node << 1);

  }

  clean[node] = clean[node << 1] & clean[node << 1 | 1];

}

llong get_max(int pos, int l, int r, int node = 1) {

  if (l > r or r < pos or l > pos) {

    return -INF;

  }

  if (l == r) {

    return lichao_tree[node](l);

  }

  int mid = (l + r) >> 1;

  if (pos <= mid) {

    return max(lichao_tree[node](pos), get_max(pos, l, mid, node << 1));

  } else {

    return max(lichao_tree[node](pos), get_max(pos, mid + 1, r, node << 1 | 1));

  }

}

void delete_lichao_tree(int l, int r, int node = 1) {

  if (l > r or clean[node]) {

    return;

  }

  clean[node] = true;

  lichao_tree[node] = Line();

  if (l < r) {

    int mid = (l + r) >> 1;

    delete_lichao_tree(l, mid, node << 1);

    delete_lichao_tree(mid + 1, r, node << 1 | 1);

  }

}

void solve() {

  int n;

  cin >> n;

  adj.resize(n + 1, vector<int>());

  lichao_tree.resize((MAX_N << 2) + 10, Line());

  clean.resize((MAX_N << 2) + 10, true);

  td_tree tree_gr(n);

  for (int i = 1; i < n; ++i) {

    int u, v;

    cin >> u >> v;

    tree_gr.add_edge(u, v);

  }

  {

    vector<int> values(n + 1);

    for (int u = 1; u <= n; ++u) {

      cin >> values[u];

    }

    tree_gr.values = values;

  }

  tree_gr.dfs(1, 1);

  tree_gr.build_lca();

  td_centroid_tree cen_tree(n);

  cen_tree.decompose();

  llong ans = -INF;

  function<void(int, int)> dfs = [&](int u, int cen_root) -> void {

    vector<Line> lines;

    for (const int &v : cen_tree.child[u]) {

      int x = tree_gr.get_dist(v, cen_root);

      ans = max({ans,

                 get_max(x - 1, 0, MAX_N) + tree_gr.prefix_sums(cen_root, v) -

                     llong(x) * tree_gr.values[cen_root],

                 tree_gr.prefix_sums(cen_root, v),

                 tree_gr.prefix_sums(v, cen_root)});

      llong m = tree_gr.get_sum(v, cen_root);

      llong b = tree_gr.prefix_sums(v, cen_root);

      lines.emplace_back(Line(m, b));

    }

    for (const Line &line : lines) {

      insert_line(line, 0, n);

    }

  };

  auto go = [&](int u, auto it_st, auto it_en) {

    for (; it_st != it_en; ++it_st) {

      dfs(*it_st, u);

    }

  };

  for (int cur_lev = 0; cur_lev <= MAX_LOG; ++cur_lev) {

    for (const int &u : cen_tree.lev[cur_lev]) {

      go(u, ranges::rbegin(cen_tree.tree[u]), ranges::rend(cen_tree.tree[u]));

      delete_lichao_tree(0, MAX_N);

      go(u, ranges::begin(cen_tree.tree[u]), ranges::end(cen_tree.tree[u]));

      delete_lichao_tree(0, MAX_N);

    }

  }

  cout << ans << '\n';

  //// CLEAR

  auto clearData = [&]() -> void { adj.clear(); };

  clearData();

}

} // namespace Task

int main(int argc, char **argv) {

  ios_base::sync_with_stdio(false);

  cin.tie(0);

  int nTest = 1;

#ifdef DAT

  freopen(file_name ".inp", "r", stdin);

  // freopen(file_name".out","w",stdout);

  freopen(".log", "w", stderr);

  nTest = (argc > 1 ? stoi(argv[1]) : 1);

  auto rand_range = [&](int l, int r) -> int { return l + rand(r - l + 1); };

  auto generate_tree = [&](int size_tree) {

    ofstream cout("test.inp");

    cout << size_tree << '\n';

    for (int i = 2; i <= size_tree; ++i) {

      int p = rand_range(1, i - 1);

      cout << i << ' ' << p << '\n';

    }

    for (int i = 1; i <= size_tree; ++i) {

      cout << rand_range(1, 1000000) << ' ';

    }

    cout.close();

  };

#endif

  // cin >> nTest;

  for (int _ = 1; _ <= nTest; ++_) {

#ifdef DAT

    cout << "Test #" << _ << ":\n";

    // generate_tree(150000);

#endif

    Task::solve();

  }

}


B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6].  |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0;  |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3;  |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3;  |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3;  |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.


E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements:  The score of each problem should be a positive integer not exceeding 109109.  A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109.  The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution.   (1,2,3)(1,2,3)  (1,3,4)(1,3,4)  (2,4,5)(2,4,5)

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;

constexpr int N = int(4e2) + 5;
constexpr int inf = 0x7f7f7f7f;
constexpr int MOD = int(1e9) + 7;

void solve(){
    int n, m, k = 0, l;
    cin >> n >> m;

    vector<int> v;
    for(int i = 1; i <= n; i++){
        if(k + (i - 1 >> 1) <= m){
            k += i - 1 >> 1;
            v.push_back(i);
            l = v.back() + 1;
        }
        else if(k < m){
            v.push_back(2 * (i - m + k) - 1);
            k = m;
            l = v.back() + 1;
        }
        else v.push_back(int(1e9) - l * (n - i));
    }
    if(k != m) cout << -1;
    else for(auto& i : v) cout << i << ' ';
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
}


A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.

#include<bits/stdc++.h>

#define sortall(v) sort(v.begin(), v.end())

#define reverse(allv) reverse(v.begin(), v.end())

#define rall(v) sort(v.rbegin(), v.rend())

#define ll long long

#define pb push_back

#define pob pop_back

#define ff first

#define ss second

#define mk make_pair

using namespace std;

void d1zzaster1(){

	string a, b, c;

    cin >> a >> b >> c;

    for(int i = 0; i < (int)a.size(); i++){

    	if(c[i] != a[i] && c[i] != b[i]){

    		cout << "NO\n";

    		return;

		}

	}

	cout << "YES\n";

	return;

}

int main()

{

	ios_base::sync_with_stdio(0);

	cin.tie(0);

    cout.tie(0);

    int q;

    cin >> q;

    while(q--){

    	d1zzaster1();

	}

}


A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  0≤ai≤m0≤ai≤m  The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.

#include "bits/stdc++.h"

using namespace std;

#define ll long long

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  int t; cin >> t;
  while (t--) {

    int n, m; cin >> n >> m;

    int tot = 0;
    while (n--) {
      int x; cin >> x;
      tot += x;
    }

    cout << min(tot, m) << "\n";

  }

}

// ~ BucketPotato


G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace):   O: A free cell.  X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base.  For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1).  For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters.  For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1)  For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
  O
OOO
NO
YES
OOOOO X
  O O
X O O X
  O
OOO X O
O O   O
O OOOOO
YES
OOOOOOOOOOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO

#include <bits/stdc++.h>

using namespace std;

const int NN = 2000;

struct T {

  bool rr;

  T *son[2], *pf, *fa;

} f1[NN], *ff = f1, *f[NN], *null;

void downdate(T *x) {

  if (x -> rr) {

    x -> son[0] -> rr = !x -> son[0] -> rr;

    x -> son[1] -> rr = !x -> son[1] -> rr;

    swap(x -> son[0], x -> son[1]);

    x -> rr = false;

  }

  // add stuff

}

void update(T *x) {

  // add stuff

}

void rotate(T *x, bool t) { /// start-hash

  T *y = x -> fa, *z = y -> fa;

  if (z != null)  z -> son[z -> son[1] == y] = x;

  x -> fa = z;

  y -> son[t] = x -> son[!t];

  x -> son[!t] -> fa = y;

  x -> son[!t] = y;

  y -> fa = x;

  update(y);

} /// end-hash

void xiao(T *x) {

  if (x -> fa != null)  xiao(x -> fa), x -> pf = x -> fa -> pf;

  downdate(x);

}

void splay(T *x) { /// start-hash

  xiao(x);

  T *y, *z;

  while (x -> fa != null) {

    y = x -> fa; z = y -> fa;

    bool t1 = (y -> son[1] == x), t2 = (z -> son[1] == y);

    if (z != null) {

      if (t1 == t2) rotate(y, t2), rotate(x, t1);

      else  rotate(x, t1), rotate(x, t2);

    }else rotate(x, t1);

  }

  update(x);

} /// end-hash

void access(T *x) {/// start-hash

  splay(x);

  x -> son[1] -> pf = x;

  x -> son[1] -> fa = null;

  x -> son[1] = null;

  update(x);

  while (x -> pf != null) {

    splay(x -> pf);

    x -> pf -> son[1] -> pf = x -> pf;

    x -> pf -> son[1] -> fa = null;

    x -> pf -> son[1] = x;

    x -> fa = x -> pf;

    splay(x);

  }

  x -> rr = true;

} /// end-hash

bool Cut(T *x, T *y) { /// start-hash

  access(x);

  access(y);

  downdate(y);

  downdate(x);

  if (y -> son[1] != x || x -> son[0] != null)

    return false;

  y -> son[1] = null;

  x -> fa = x -> pf = null;

  update(x);

  update(y);

  return true;

} /// end-hash

bool Connected(T *x, T *y) {

  access(x);

  access(y);

  return x == y || x -> fa != null;

}

bool Link(T *x, T *y) {

  if (Connected(x, y))

    return false;

  access(x);

  access(y);

  x -> pf = y;

  return true;

}

void solve(){

	int n, m;

	cin >> n >> m;

	vector<string> s(n);

	for(int i = 0; i < n; i++) cin >> s[i];

	ff = f1;

	null = new T; null -> son[0] = null -> son[1] = null -> fa = null -> pf = null;

	for (int i = 0; i < n * m; i++) {

		f[i] = ++ff;

		f[i] -> son[0] = f[i] -> son[1] = f[i] -> fa = f[i] -> pf = null;

		f[i] -> rr = false;

	}

	vector<int> dx = {1, 0, -1, 0};

	vector<int> dy = {0, 1, 0, -1};

	vector<set<int> > used(n * m);

	for(int i = 0; i < n; i++){

		for(int j = 0; j < m; j++){

			if(i == 0 && j == 0) continue;

			if(s[i][j] == 'X') continue;

			if(((i + j) & 1) == 0){

				int a = m * i + j;

				for(int d = 0; d < 4; d++){

					if(used[a].size() == 2) continue;

					int ni = i + dx[d];

					int nj = j + dy[d];

					if(ni < 0 || nj < 0 || ni >= n || nj >= m || s[ni][nj] == 'X') continue;

					int b = m * ni + nj;

					while(true){

						if(!Connected(f[a], f[b])){

							used[a].insert(b);

							used[b].insert(a);

							Link(f[a], f[b]);

							break;

						}

						bool done = false;

						for(int v = 0; v < n; v++){

							for(int w = 0; w < m; w++){

								if(((v + w) & 1) != 0) continue;

								int c = m * v + w;

								if(!Connected(f[a], f[c])) continue;

								for(int d1 = 0; d1 < 4; d1++){

									int nv = v + dx[d1];

									int nw = w + dy[d1];

									if(nv < 0 || nw < 0 || nv >= n || nw >= m || s[nv][nw] == 'X') continue;

									int nc = nv * m + nw;

									if(Connected(f[a], f[nc])) continue;

									done = true;

									for(int bc : used[c]){

										assert(Cut(f[c], f[bc]));

										if(!Connected(f[a], f[c])){

											used[c].erase(bc);

											used[bc].erase(c);

											break;

										}

										Link(f[c], f[bc]);

									}

									used[c].insert(nc);

									used[nc].insert(c);

									Link(f[c], f[nc]);

									goto found;

								}

							}

						}

						found:;

						if(!done) break;

					}

				}

				if(used[a].size() < 2){

					cout << "NO" << '\n';

					return;

				}

			}

		}

	}

	cout << "YES" << '\n';

	vector<string> ans(2*n-1, string(2*m-1, ' '));

	for(int i = 0; i < n; i++){

		for(int j = 0; j < m; j++){

			ans[2*i][2*j] = s[i][j];

			if(s[i][j] == 'X') continue;

			if(((i + j) & 1) == 0){

				int a = m * i + j;

				for(int d = 0; d < 4; d++){

					int ni = i + dx[d];

					int nj = j + dy[d];

					if(ni < 0 || nj < 0 || ni >= n || nj >= m || s[ni][nj] == 'X') continue;

					int b = m * ni + nj;

					if(!Connected(f[a], f[b])){

						used[a].insert(b);

						used[b].insert(a);

						Link(f[a], f[b]);

					}

					if(used[a].count(b)){

						ans[2*i + dx[d]][2*j + dy[d]] = 'O';

					}

				}

			}

		}

	}

	for(string z : ans){

		cout << z << '\n';

	}

}

int main(){

	ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

	int T;

	cin >> T;

	while(T--) solve();

}


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.

#include<bits/stdc++.h>

using ll = long long;

using namespace std;

ll del(ll n, ll m) {ll a=0;if(n%m>0)a++;a+=n/m;return a;}

#define endl '\n'

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

#define pb push_back

#define all(v) (v.begin(), v.end())

#define inf 1e9 + 1e5

#define watch(x) cout << (#x) << " => " << (x) << endl

void solve(){

ll n, m;

cin >> n >> m;

ll ans = 0;

if(m % n != 0)

{

    cout<<-1;

    return;

}

m/=n;

while(m % 2 == 0)

{

    ans++;

    m/=2;

}

while(m % 3 == 0)

{

    ans++;

    m/=3;

}

if(m != 1)

{

    cout<<ans / ans * -1;

    return;

}

cout<<ans;

}

int main()

{

IOS

//ll _; cin>>_; while(_--)

solve();

return 0;

}


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


H. Kuroni the Private Tutortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a professional private tutor; Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.The exam consists of nn questions, and mm students have taken the exam. Each question was worth 11 point. Question ii was solved by at least lili and at most riri students. Additionally, you know that the total score of all students is tt.Furthermore, you took a glance at the final ranklist of the quiz. The students were ranked from 11 to mm, where rank 11 has the highest score and rank mm has the lowest score. Ties were broken arbitrarily.You know that the student at rank pipi had a score of sisi for 1≤i≤q1≤i≤q.You wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students.InputThe first line of input contains two integers (1≤n,m≤1051≤n,m≤105), denoting the number of questions of the exam and the number of students respectively.The next nn lines contain two integers each, with the ii-th line containing lili and riri (0≤li≤ri≤m0≤li≤ri≤m).The next line contains a single integer qq (0≤q≤m0≤q≤m). The next qq lines contain two integers each, denoting pipi and sisi (1≤pi≤m1≤pi≤m, 0≤si≤n0≤si≤n). It is guaranteed that all pipi are distinct and if pi≤pjpi≤pj, then si≥sjsi≥sj.The last line contains a single integer tt (0≤t≤nm0≤t≤nm), denoting the total score of all students.OutputOutput two integers: the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students. If there is no valid arrangement that fits the given data, output −1−1 −1−1.ExamplesInputCopy5 4
2 4
2 3
1 1
0 1
0 0
1
4 1
7
OutputCopy3 2
InputCopy5 6
0 6
0 6
2 5
6 6
4 6
1
3 3
30
OutputCopy-1 -1
NoteFor the first sample; here is one possible arrangement that fits the data:Students 11 and 22 both solved problems 11 and 22.Student 33 solved problems 22 and 33.Student 44 solved problem 44.The total score of all students is T=7T=7. Note that the scores of the students are 22, 22, 22 and 11 respectively, which satisfies the condition that the student at rank 44 gets exactly 11 point. Finally, 33 students tied for first with a maximum score of 22, and it can be proven that we cannot do better with any other arrangement.

#include<bits/stdc++.h>

template <typename _Tp>void read(_Tp &x){
char ch(getchar());bool f(false);while(!isdigit(ch))f|=ch==45,ch=getchar();
x=ch&15,ch=getchar();while(isdigit(ch))x=x*10+(ch&15),ch=getchar();
if(f)x=-x;
}
template <typename _Tp,typename... Args>void read(_Tp &t,Args &...args){read(t);read(args...);}
const int N=100005;typedef long long ll;
int L[N],R[N],p[N],s[N],a[N],n,m,val[N],VAL[N];ll t,lim[N],b[N],suf[N];
ll calc1(int mid){ll tot=0;for(int i=1;i<=n;++i)tot+=std::min(R[i],std::max(L[i],mid));return tot;}
bool check(int mid){
int x=-1,y=-1;for(int i=1;i<=mid;++i)if(val[i]!=-1)(x==-1?x:y)=val[i];
if(x!=-1&&y!=-1&&x!=y)return 0;
if(x==-1&&y==-1){
ll tmp=1e18,tot=0;
for(int i=1;i<=m;++i)tot+=i>mid?VAL[i]:0,tmp=std::min(tmp,(lim[i]-tot)/std::min(i,mid));
for(int i=1;i<=m;++i)b[i]=i<=mid?tmp:VAL[i];
}
else for(int i=1;i<=m;++i)b[i]=i<=mid?x:VAL[i];
ll tot=0;for(int i=1;i<=m;++i){tot+=b[i],suf[i]=lim[i]-tot;if(tot>lim[i])return 0;}
suf[m+1]=1e18;for(int i=m;i>=1;--i)suf[i]=std::min(suf[i],suf[i+1]);
ll sum=0;for(int i=mid+1;i<=m;++i)if(val[i]==-1)b[i]=std::min(VAL[i]+suf[i]-sum,b[i-1]),sum+=b[i]-VAL[i];
for(int i=1;i<m;++i)if(b[i]<b[i+1])return 0;
return sum+tot==t;
}
int main(){
read(n,m);
for(int i=1;i<=n;++i)read(L[i],R[i]);
int q;read(q);
memset(val,-1,sizeof(val));
for(int i=1;i<=q;++i)read(p[i],s[i]),val[p[i]]=s[i],VAL[p[i]]=s[i];
for(int i=m;i>=1;--i)if(!VAL[i])VAL[i]=VAL[i+1];
read(t);int l=0,r=m,mid;
while(l<r)mid=(l+r+1)>>1,calc1(mid)<=t?l=mid:r=mid-1;
ll tot=0;for(int i=1;i<=n;++i)a[i]=std::min(R[i],std::max(L[i],l)),tot+=a[i];
for(int i=1;i<=n;++i)if(tot<t&&a[i]!=R[i]&&a[i]==l)++a[i],++tot;
std::sort(a+1,a+n+1);
for(int i=1,j=1;i<=m;++i){
while(j<=n&&a[j]<i)++j;
lim[i]=std::min(t,lim[i-1]+n-j+1);
}
l=1,r=m;while(l<r)mid=(l+r+1)>>1,check(mid)?l=mid:r=mid-1;
if(!check(l))return puts("-1 -1"),0;
printf("%d %lld\n",l,b[1]);
return 0;
}


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.

/*                                                     لا اله الا الله محمد رسول الله                                              */

#include <bits/stdc++.h>

#ifndef ONLINE_JUDGE

#include "Debug.cpp"

#else

#define debug(...) 1

#define Time(i, x...) x

#endif

using namespace std;

#define sad ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

#define el '\n'

#define all(x) x.begin(), x.end()

#define LL  long long

#define int LL

#define ld long double

#define un unsigned

#define Test unsigned int TC; cin >> TC; while(TC--)

#define sz(s) int(s.size())

#define NO cout<<"NO";

#define YES cout<<"YES";

#define FILE freopen("Input.txt", "r", stdin);

set<int>ans;

void fun() {

    for (int i = 1; i < 10001; ++i) {

        ans.insert(i*i*i);

    }

}

void Solve() {

    int n;

    cin >> n;

    string s;

    cin >> s;

    int c = 0;

    bool x = 1;

    while (x){

        bool y = 0;

    for (int i = 0; i < s.size() - 1; ++i) {

        if (s[i] == 'A' && s[i+1] == 'P')

            s[i+1] = 'A', y = 1, i++;

    }

        if (!y)x = !x;

        c++;

    }

    cout << c-1;

}

signed main() {

    sad;

//    FILE

    Test

    Solve(), cout << el;

}