C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:   fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

#include "bits/stdc++.h"

using namespace std;

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

template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }

template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = " "; return os; }

#define debug(a) cerr << "(" << #a << ": " << a << ")\n";

typedef long long ll;

typedef vector<int> vi;

typedef vector<vi> vvi;

typedef pair<int,int> pi;

const int mxN = 1e5+1, oo = 1e9;

string str;

vector<array<int,3>> es;

string hidden = "xasdungo";

void query(int l, int r) {

    cout << "? " << l+1 << ' ' << r+1 << endl;

    int len = r-l+1;

    vector<int> v(len+1);

    for(int i=0;i<len*(len+1)/2;++i) {

        string s; cin >> s;

        auto& w = v[s.size()];

        for(auto c : s) w+=c;

    }

    // for(int i=l;i<=r;++i) for(int j=i;j<=r;++j) {

    //     string s = hidden.substr(i,j-i+1);

    //     auto& w = v[s.size()];

    //     for(auto c : s) w+=c;

    // }

    // take biggest string, do it times two, subtract out those two?

    vi res = {};

    for(int i=0;i<(len+1)/2;i++) {

        int ans=-v[len-i-1];

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

            ans+=res[j]*(j+1 - (i+2));

        }

        ans += v[len]*(i+2);

        res.push_back(ans);

    }

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

        es.push_back({l+i,r-i,res[i]});

    }

    if(len%2==1) {

        str[(l+r)/2]=res.back()/2;

    }

}

int main() {

    int n; cin >> n;

    str.resize(n,'?');

    if(n==1) {

        query(0,0);

    } else if(n==2) {

        query(0,0);

        query(0,1);

    } else {

        query(0,(n+1)/2 -1);

        query(0,(n+1)/2 -2);

        query(0,n-1);

    }

    vector<vector<pi>> adj(n);

    for(auto& [u,v,w] : es) adj[u].push_back({v,w}),adj[v].push_back({u,w});

    for(int i=0;i<n;++i) if(str[i]!='?') {

        auto dfs = [&](auto&& self, int at) -> void {

            for(auto [to,w] : adj[at]) if(str[to]=='?') {

                str[to]=w-str[at];

                self(self,to);

            }

        };

        dfs(dfs,i);

        break;

    }

    cout << "! " << str << endl;

}


C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way:  At 00-th minute, change the state to heating (the temperature is 0).  At 22-nd minute, change the state to off (the temperature is 2).  At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied).  At 66-th minute, change the state to off (the temperature is 3).  At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied).  At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

#include<bits/stdc++.h>

using namespace std;

#define int long long

#define pb push_back

#define F first

#define S second

#define endl "\n"

const int N=1e2+2 , inf=2e9;

pair<int,int> dp[N];

bool solve (int num , int cur)

{

	bool c=true;

	int time[N];

	dp[0]={cur,cur};

	time[0]=0;

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

	{

		int l,r;

		cin >> time[i] >> l >> r;

		int dif=time[i]-time[i-1];

		int a,b;

		a=dp[i-1].F-dif;

		b=dp[i-1].S+dif;

		if (a>r || b<l)	c=false;

		dp[i].F = max (a,l);

		dp[i].S = min (b,r);

	}

	return c;

}

int32_t main()

{

	ios_base::sync_with_stdio(0);

	cin.tie(NULL);

	cout.tie(NULL);

	int test;	cin >> test;

	while (test--)

	{

		int num;	cin >> num;

		int cur;		cin >> cur;

		if (solve (num,cur))	cout << "YES" << endl;

		else cout << "NO" << endl;

	}

	return 0;

}


C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

// Problem: C2. Skyscrapers (hard version)

// Contest: Codeforces - Codeforces Round #622 (Div. 2)

// URL: https://codeforces.com/problemset/problem/1313/C2

// Memory Limit: 512 MB

// Time Limit: 3000 ms

// User: milan0027

#include <bits/stdc++.h>

using namespace std;

//#include <ext/pb_ds/assoc_container.hpp>

//#include <ext/pb_ds/tree_policy.hpp>

//using namespace __gnu_pbds;

#define pb push_back

#define int long long

#define lld long double

#define fi first

#define se second

#define vi vector<int>

#define vb vector<bool>

#define vs vector<string>

#define vvi vector<vector<int>>

#define vpii vector<pair<int,int>>

#define vvpii vector<vector<pair<int,int>>>

#define mii map<int,int>

#define pii pair<int,int>

#define pq priority_queue

#define setbits(a) __builtin_popcountll(a)

#define ctz(a) __builtin_ctzll(a)

#define clz(a) __builtin_clzll(a)

#define loop(n) for(int i=0;i<n;i++)

#define fo(i,s,e) for(int i=s;i<e;i++)

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

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

#define out(a) for(auto x9: a) cout<<x9<<" "; cout<<"\n";

#define test int _; cin>>_; for(int tt=1;tt<=_;tt++)

#define en "\n"

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

#define sortf(a) sort(a.begin(),a.end())

#define sortr(a) sort(a.rbegin(),a.rend())

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

#define gsum(a) accumulate(a.begin(),a.end(),0LL)

#define gmax(a) *max_element(a.begin(),a.end())

#define gmin(a) *min_element(a.begin(),a.end())

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

const int mod = 1000000007;

//const int mod = 998244353;

const int inf = 2100000000;

const lld pi = 3.1415926535897932;

const long long INF = 1e18+5;

//typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;

// ans val flag temp fin fish eye kill stat tic tac time cnt cost

void yesno(bool xxx)

{

    if(xxx)

    cout<<"YES\n";

    else

    cout<<"NO\n";

}

void NGE(vi &arr,vi &ans)

{

    int n=sz(arr);

    stack<int> s;

    s.push(arr[0]);

    // iterate for rest of the elements

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

        if (s.empty()) {

            s.push(arr[i]);

            continue;

        }

        while (s.empty() == false && arr[s.top()] > arr[i]) {

            ans[s.top()]=i;

            s.pop();

        }

        s.push(i);

    }

    while (s.empty() == false) {

        ans[s.top()]=0;

        s.pop();

    }

}

int32_t main()

{

   fastio;

   //code goes here

   int n;

   cin>>n;

   vi a(n+2,0);

   fo(i,1,n+1)

   cin>>a[i];

   vi fans(n+2,0),bans(n+2,0);

   NGE(a,fans);

   vi b=a;

   reverse(all(b));

   NGE(b,bans);

   reverse(all(bans));

   vi fdp(n+2,0),bdp(n+2,0);

  // out(fans)

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

   {

       fdp[i]=(fans[i]-i)*a[i]+fdp[fans[i]];

       bans[i]=n-bans[i]+1;

   }

   //out(bans)

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

   {

       bdp[i]=(i-bans[i])*a[i]+bdp[bans[i]];

   }

   int note=1;

   int ans=0;

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

   {

       int val = bdp[i]+fdp[i+1];

       if(val > ans)

       {

           if(a[i]>a[i+1])

           note=i;

           else

           note=i+1;

           ans=val;

       }

   }

   vi fin(n+2,0);

   fin[note]=a[note];

   int r=note;

   while(r<=n)

   {

       int p=r;

       int to=fans[p];

       while(p<to)

       {

           fin[p]=a[r];

           p++;

       }

       r=to;

   }

   int l=note;

   while(l>=1)

   {

       int p=l;

       int to=bans[p];

       while(p>to)

       {

           fin[p]=a[l];

           p--;

       }

       l=to;

   }

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

   cout<<fin[i]<<" ";

}

/*

*/


F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4
1 2
2 3
4 3
1 3
2 4
1 4
OutputCopy3
3 2 4 2
2 1 1 3
4 3 1 4
InputCopy5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
OutputCopy4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
InputCopy9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
OutputCopy8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3

#include<bits/stdc++.h>

const int N = 2e6 + 101;

int n, m;

int dep[N], f[N][25], du[N], belong[N], vis[N];

std::vector<int> e[N], t[N];

std::queue<int> q;

void dfs(int u, int fa) {
	dep[u] = dep[fa] + 1;
	f[u][0] = fa;
	for (int i = 0; i <= 22; ++i) f[u][i + 1] = f[f[u][i]][i];
	for (auto v : e[u]) {
		if (v == fa) continue;
		dfs(v, u);
	}
}

int lca(int x, int y) {
	if (dep[x] < dep[y]) std::swap(x, y);
	for (int i = 22; i >= 0; --i) {
		if (dep[f[x][i]] >= dep[y]) x = f[x][i];
		if (x == y) return x;
	}
	for (int i = 22; i >= 0; --i) {
		if (f[x][i] != f[y][i]) {
			x = f[x][i];
			y = f[y][i];
		}
	}
	return f[x][0];
}

int find(int x) {
	if (belong[x] == x) return x;
	else return belong[x] = find(belong[x]);
}

signed main() {

	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);

	std::cin >> n;
	for (int i = 1; i <= n; ++i) belong[i] = i;
	for (int i = 1; i < n; ++i) {
		int u, v;
		std::cin >> u >> v;
		e[u].push_back(v), e[v].push_back(u);
	}
	for (int i = 1; i < n; ++i) {
		int u, v;
		std::cin >> u >> v;
		t[u].push_back(v), t[v].push_back(u);
		++du[u], ++du[v];
	}
	dfs(1, 0);
	for (int i = 1; i <= n; ++i) {
		if (du[i] == 1) q.push(i);
	}
	//for (int i = 1; i <= n; ++i) std::cout << dep[i] << '\n';
	std::cout << n - 1 << '\n';
	while (q.size() >= 2) {
		int u = q.front(), v;
		q.pop();
		vis[u] = 1;
		for (auto to : t[u]) {
			if (vis[to] == 1) continue;
			v = to;
			--du[v];
			if (du[v] == 1) q.push(v);
			break;
		}
		int k = lca(u, v);
		int a = find(u), b;
		//std::cout << "a: " << a << " u: " << u << " v: " << v << " k: " << k << '\n';
		if (dep[a] > dep[k]) {
			b = f[a][0];
			std::cout << a << " " << b << " " << u << " " << v << '\n';
			belong[a] = find(b);
		}
		else {
			b = v;
			for (int i = 22; i >= 0; --i) {
				//std::cout << "b: " << b << '\n';
				if (dep[f[b][i]] > dep[k] && find(f[b][i]) != a) b = f[b][i];
			}
			std::cout << b << " " << f[b][0] << " " << u << " " << v << '\n';
			belong[b] = a;
		}
	}

	return 0;
}


D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples.  In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11.  In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges.  In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.

#include <bits/stdc++.h>

using namespace std;

const int D = 5;

const int S = 374;

int transition[S][1<<D];

int combination[S][S];

struct linear_space {

  uint32_t x;

  linear_space(): x(1) {};

  linear_space(uint32_t _x): x(_x) {};

  bool has(int k) {

    return (x>>k)&1;

  }

  bool operator == (const linear_space& other) {

    return x == other.x;

  }

  bool operator < (const linear_space& other) {

    return x < other.x;

  }

  linear_space operator + (int k) {

    uint32_t res = x;

    for (int i = 0; i < (1<<D); i++) {

      if ((x>>i)&1) res |= 1<<(k^i);

    }

    return linear_space(res);

  }

  linear_space operator + (const linear_space& other) {

    uint32_t res = 0;

    for (int i = 0; i < (1<<D); i++) {

      for (int j = 0; j < (1<<D); j++) {

        if ((x>>i)&1 && (other.x>>j)&1) res |= 1<<(i^j);

      }

    }

    return linear_space(res);

  }

  friend ostream& operator << (ostream& os, const linear_space& l) {

    return os << bitset<32>(l.x);

  }

};

vector<linear_space> spaces(1);

int get_index(linear_space x) {

  return lower_bound(spaces.begin(), spaces.end(), x)-spaces.begin();

}

void precompute() {

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

    for (int j = 0; j < (1<<D); j++) {

      if (spaces[i].has(j)) continue;

      linear_space y = spaces[i]+j;

      if (find(spaces.begin(), spaces.end(), y) == spaces.end()) {

        spaces.push_back(y);

      }

    }

  }

  sort(spaces.begin(), spaces.end());

  assert(spaces.size() == S);

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

    for (int j = 0; j < (1<<D); j++) {

      transition[i][j] = (spaces[i].has(j) ? -1 : get_index(spaces[i]+j));

    }

  }

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

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

      combination[i][j] =

        ((spaces[i].x&spaces[j].x) == 1 ? get_index(spaces[i]+spaces[j]) : -1);

    }

  }

}

const int MOD = 1e9+7;

void add(int& x, int y) {

  x += y;

  if (x >= MOD) x -= MOD;

}

const int N = 1e5+5;

vector<pair<int, int>> G[N];

int wt[N], tree_space[N], dep[N];

bool inner[N], vis[N];

vector<tuple<int, int, int>> special_edges;

void dfs(int v) {

  for (auto& [u, w]: G[v]) {

    if (inner[u] && inner[v]) {

      if (u < v) special_edges.emplace_back(u, v, w);

      continue;

    }

    if (dep[u] < dep[v] && (dep[u] > 0 || u == 1)) continue;

    if (dep[u] > dep[v]+1) {

      if (tree_space[v] != -1) {

        tree_space[v] = transition[tree_space[v]][wt[u]^wt[v]^w];

      }

      continue;

    }

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

    wt[u] = wt[v]^w;

    dfs(u);

    if (v != 1 && tree_space[v] != -1) {

      if (tree_space[u] == -1) tree_space[v] = -1;

      else tree_space[v] = combination[tree_space[v]][tree_space[u]];

    }

  }

}

void increment(array<int, S>& a, array<int, S>& b, int c) {

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

    int j = combination[i][c];

    if (j != -1) add(b[j], a[i]);

  }

}

int main () {

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

  precompute();

  int n, m;

  cin >> n >> m;

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

    int u, v, w;

    cin >> u >> v >> w;

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

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

  }

  for (auto& [v, _]: G[1]) inner[v] = 1;

  dfs(1);

  fill(vis, vis+N, 0);

  array<int, S> dp({});

  dp[0] = 1;

  for (auto& [u, v, w]: special_edges) {

    vis[u] = vis[v] = 1;

    array<int, S> _dp = dp;

    if (tree_space[u] != -1 && tree_space[v] != -1) {

      int k = combination[tree_space[u]][tree_space[v]];

      if (k != -1) {

        increment(dp, _dp, k);

        increment(dp, _dp, k);

        int l = transition[k][wt[u]^wt[v]^w];

        if (l != -1) increment(dp, _dp, l);

      }

    }

    swap(dp, _dp);

  }

  for (auto& [v, _]: G[1]) {

    if (vis[v]) continue;

    if (tree_space[v] != -1) {

      array<int, S> _dp = dp;

      increment(dp, _dp, tree_space[v]);

      swap(dp, _dp);

    }

  }

  int ans = 0;

  for (int x: dp) add(ans, x);

  cout << ans << '\n';

}


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;

}


F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way:   On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days.  On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days.  If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1:   Example 2:   Example 3:   Example 4:

/// Author : Nguyễn Thái Sơn - Ti20 - THPT chuyên Lương Thế Vinh

/// Training VOI 2023

#include<bits/stdc++.h>

//#include <ext/pb_ds/assoc_container.hpp>

//#include <ext/pb_ds/trie_policy.hpp>

//#include <ext/rope>

//#pragma GCC optimize("Ofast")

//#pragma GCC optimization("unroll-loops, no-stack-protector")

//#pragma GCC target("avx,avx2,fma")

//using namespace std;

//using namespace __gnu_pbds;

//using namespace __gnu_cxx;

#define fi first

#define se second

#define TASK "test"

#define pb push_back

#define EL cout << endl

#define Ti20_ntson int main()

#define in(x) cout << x << endl

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

#define getbit(x, i) (((x) >> (i)) & 1)

#define cntbit(x) __builtin_popcount(x)

#define FOR(i,l,r) for (int i = l; i <= r; i++)

#define FORD(i,l,r) for (int i = l; i >= r; i--)

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

using namespace std;

typedef long long ll;

typedef vector<int> vi;

typedef pair<int,int> vii;

typedef unsigned long long ull;

typedef vector<vector<int>> vvi;

int fastMax(int x, int y) { return (((y-x)>>(32-1))&(x^y))^y; }

const int N = 2e4 + 5;

const int oo = INT_MAX;

const int mod = 1e9 + 7;

const int d4x[4] = {-1, 0, 1, 0} , d4y[4] = {0, 1, 0, -1};

const int d8x[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, d8y[8] = {0, 1, 1, 1, 0, -1, -1, -1};

int n, a[55][N], m, k;

ll dp[55][N];

inline void Read_Input() {

    cin >> n >> m >> k;

    FOR(i, 1, n)

        FOR(j, 1, m) {

            cin >> a[i][j];

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

        }

}

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

    return a[xx][yy] - a[x - 1][yy] - a[xx][y - 1] + a[x - 1][y - 1];

}

struct Segment_Tree {

    ll st[4 * N + 5], lz[4 * N + 5];

    void build(int id, int l, int r, int cur) {

        lz[id] = 0;

        if (l == r) {

            st[id] = dp[cur][l];

            return;

        }

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

        build(id * 2, l, mid, cur);

        build(id * 2 + 1, mid + 1, r, cur);

        st[id] = max(st[id * 2], st[id * 2 + 1]);

    }

    void Down(int id) {

        if (lz[id] == 0)

            return;

        lz[id * 2] += lz[id];

        lz[id * 2 + 1] += lz[id];

        st[id * 2] += lz[id];

        st[id * 2 + 1] += lz[id];

        lz[id] = 0;

    }

    void update(int id, int l, int r, int u, int v, int val) {

        if (l > v || r < u)

            return;

        if (l >= u && r <= v) {

            st[id] += val;

            lz[id] += val;

            return;

        }

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

        Down(id);

        update(id * 2, l, mid, u, v, val);

        update(id * 2 + 1, mid + 1, r, u, v, val);

        st[id] = max(st[id * 2], st[id * 2 + 1]);

    }

    ll Get(int id, int l, int r, int u, int v) {

        if (l > v || r < u)

            return 0;

        if (l >= u && r <= v)

            return st[id];

        Down(id);

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

        return max(Get(id * 2, l, mid, u, v), Get(id * 2 + 1, mid + 1, r, u, v));

    }

}it;

inline void Solve() {

    const int mx = m - k + 1;

    ll Ans = 0;

    FOR(i, 1, mx)

        dp[1][i] = Get(1, i, 1, i + k - 1);

    if (n > 1)

        FOR(i, 1, mx)

            dp[1][i] += Get(2, i, 2, i + k - 1);

    FOR(i, 2, n) {

        it.build(1, 1, mx, i - 1);

        int val = Get(i, 1, i, k);

        FOR(j, 1, k) {

            it.update(1, 1, mx, j, j, -val),

            val -= Get(i, j, i, j);

        }

        FOR(j, 1, mx) {

            dp[i][j] = it.st[1] + Get(i, j, i, j + k - 1);

            if (i != n)

                dp[i][j] += Get(i + 1, j, i + 1, j + k - 1);

            if (j != mx) {

//                cout << "CHECK " << j << endl;

                int l = max(1, j - k + 1);

//                cout << "UPDATE " << l << " " << j << " " << Get(i, j, i, j) << endl;

                it.update(1, 1, mx, l, j, Get(i, j, i, j));

                int cur = j + k;

                cur = Get(i, cur, i, cur);

                int r = min(mx, j + k);

                it.update(1, 1, mx, j + 1, r, -cur);

//                cout << "UPDATE " << j + 1 << " " << r << " " << -cur << endl;

//                FOR(k, 1, mx)

//                    cout << it.Get(1, 1, mx, k, k) << " "; cout << endl;

            }

        }

//        FOR(j, 1, mx)

//            cout << dp[i][j] << " \n"[j == mx];

    }

    cout << *max_element(dp[n] + 1, dp[n] + mx + 1);

}

Ti20_ntson {

//    freopen(TASK".INP","r",stdin);

//    freopen(TASK".OUT","w",stdout);

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

    int T = 1;

//    cin >> T;

    while (T -- ) {

        Read_Input();

        Solve();

    }

}


A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int t, x;

void Solve() {
    for (int i=1; i<=t; i++) {
        cin >> x;
        cout << 1 << ' ' << x - 1 << '\n';
    }
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> t;
    Solve();
    return 0;
}


B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png   When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4];  Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]);  Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4];  Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3

#include <bits/stdc++.h>

using namespace std;

#define FOR(i, x, y) for (int i = x; i < y; i++)

const int mx = 2e5 + 5;

int n, m, k, A[mx], dst[mx], cnt[mx]; vector<int> adj[mx];

int main(){
cin >> n >> m;
FOR(i, 1, m + 1){
int u, v; cin >> u >> v;
adj[v].push_back(u);
}
cin >> k;
FOR(i, 1, k + 1) cin >> A[i];

queue<int> q; memset(dst, 0x3f, sizeof(dst));
q.push(A[k]); dst[A[k]] = 0;

while (!q.empty()){
int cur = q.front(); q.pop();
for (int nxt : adj[cur]){
if (dst[cur] + 1 < dst[nxt]){
dst[nxt] = dst[cur] + 1;
cnt[nxt] = 0;
q.push(nxt);
}
if (dst[cur] + 1 == dst[nxt]) cnt[nxt]++;
}
}
int bstMn = 0, bstMx = 0;
FOR(i, 1, k){
if (dst[A[i]] - 1 != dst[A[i + 1]]) bstMn++, bstMx++;
else if (cnt[A[i]] > 1) bstMx++;
}
cout<<bstMn<<" "<<bstMx<<"\n";
}


C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets:   a occurs at (1)(1), (2)(2), (3)(3)  b occurs at (4)(4), (5)(5)  ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5)  aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3)  bb occurs at (4,5)(4,5)  aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4)  aaa occurs at (1,2,3)(1,2,3)  abb occurs at (3,4,5)(3,4,5)  aaab occurs at (1,2,3,4)(1,2,3,4)  aabb occurs at (2,3,4,5)(2,3,4,5)  aaabb occurs at (1,2,3,4,5)(1,2,3,4,5)  Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.

// LUOGU_RID: 102570643
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
const int N = 100005;

LL a[26];
LL f[26][26];
int main() {
    string s;
    cin >> s;
    int n = s.size();
    for (int i = 0; i < n; i++) {
        int x = s[i] - 'a';
        for (int j = 0; j < 26; j++) {
            f[x][j] += a[j];
        }
        a[x]++;
    }
    LL ans = 0;
    for (int i = 0; i < 26; i++) {
        ans = max(ans, a[i]);
        for (int j = 0; j < 26; j++) {
            ans = max(ans, f[i][j]);
        }
    }
    cout << ans << endl;
    return 0;
}


C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

#define print_debug true

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

const long long MOD = 1000000007;

using namespace __gnu_pbds;

using namespace std;

typedef tree<int, null_type, less<int>, rb_tree_tag,

             tree_order_statistics_node_update>

    indexed_set;

typedef long long ll;

void fileIO(string name) {

    freopen((name + ".in").c_str(), "r", stdin);

    freopen((name + ".out").c_str(), "w", stdout);

}

template <class T>

void debug(const T& n) {

    if (print_debug) cerr << n << "\n\n";

}

template <class T>

void debug(const vector<T>& k) {

    if (print_debug) {

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

            cerr << k[i] << " ";

        }

        cerr << "\n\n";

    }

}

template <class T>

void debug(const vector<vector<T>>& k) {

    if (print_debug) {

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

            for (int j = 0; j < (int)k[i].size(); ++j) {

                cerr << k[i][j] << " ";

            }

            cerr << "\n";

        }

        cerr << "\n";

    }

}

template <class T>

int bin_upper(const vector<T>& k, const T& value) {

    return distance(k.begin(), upper_bound(k.begin(), k.end(), value));

}

template <class T>

int bin_lower(const vector<T>& k, const T& value) {

    return distance(k.begin(), lower_bound(k.begin(), k.end(), value));

}

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    int n;

    cin >> n;

    vector<ll> v(n);

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

        cin >> v[i];

    }

    ll ans = 0;

    vector<ll> vans(n);

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

        vector<ll> a(n);

        // set to max

        ll c = 0;

        a[i] = v[i];

        c += v[i];

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

            a[j] = min(a[j - 1], v[j]);

            c += a[j];

        }

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

            a[j] = min(a[j + 1], v[j]);

            c += a[j];

        }

        if (c > ans ) {

            ans = c;

            vans = a;

        }

    }

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

        cout << vans[i] << " ";

    }

    cout << "\n";

}


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


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

  MK-1311

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

#include <bits/stdc++.h>

using namespace std;

#define fi first

#define se second

#define pb push_back

#define nl '\n'

#ifdef LOCAL

#include "debug.h"

#else

#define debug(...)

#endif

/*

*/

#define int long long

void solve() {

  int n, it;

  cin >> n >> it;

  vector<int> t(n + 1, 0), l(n + 1, 0), h(n + 1, 0);

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

    cin >> t[i] >> l[i] >> h[i];

  }

  int x = it, y = it;

  l[0] = it, h[0] = it;

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

    int time = t[i] - t[i - 1];

    x = max(l[i - 1], x) - time;

    y = min(h[i - 1], y) + time;

    debug(x, y);

    if(l[i] > y || h[i] < x) {

      cout << "NO" << endl;

      return;

    }

  }

  cout << "YES" << endl;

}

int32_t main() {

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

  int tt = 1;

  cin >> tt;

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

    solve();

  }

  cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;

  return 0;

}


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

#include<iostream>

#include <bits/stdc++.h>

#include <ext/numeric>

using namespace std;

//using L = __int128;

#include<ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

using ll = long long;

using ull = unsigned long long;

using ld = long double;

#define nd "\n"

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

#define lol cout <<"i am here"<<nd;

#define py cout <<"YES"<<nd;

#define pp  cout <<"ppppppppppppppppp"<<nd;

#define pn cout <<"NO"<<nd;

#define popcount(x)  __builtin_popcount(x)

#define clz(n) __builtin_clz(n)//31 -x

const  double PI = acos(-1.0);

double EPS = 1e-9;

#define print2(x , y) cout <<x<<' '<<y<<nd;

#define print3(x , y , z) cout <<x<<' '<<y<<' '<<z<<nd;

#define watch(x) cout << (#x) << " = " << x << nd;

const ll N = 4e5+500 , LOG = 22 , inf = 1e8 , SQ= 550 , mod= 1e9+7;//998244353;

template<class container> void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;}

//template <class Type1 , class Type2>

ll fp(ll a , ll p){ if(!p) return 1; ll v = fp(a , p/2); v*=v;return p & 1 ? v*a : v;  }

template <typename T> using ordered_set =  tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;

ll mul (ll a, ll b){

    return ( ( a % mod ) * ( b % mod ) ) % mod;

}

ll add (ll a , ll b) {

    return (a + b + mod) % mod;

}

template< typename  T > using min_heap = priority_queue <T , vector <T >  , greater < T > > ;

void hi(int tc) {

    ll h , n; cin >> h >> n;

    vector <ll> a(n);

    for (ll &i : a) cin >> i;

    ll sum = 0;

    ll mn= 0;

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

        sum+=a[i];

        if (sum+h <= 0){cout << i+1 << nd;return;}

        mn = min(mn , sum);

    }

    if(sum >= 0){cout << -1 << nd; return;}

    ll temp = h + mn;

    ll nume = abs(sum);

    ll k = temp/nume + bool(temp % nume);

    h+= k * sum;

    int i = -1; ll ans = k * n;

    while (h > 0){

        ++i , ans++;

        h+=a[i % n];

    }

    cout << ans <<nd;

}

int main(){

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

    int tt = 1 , tc = 0;

  //cin >> tt;

    while(tt--) hi(++tc);

    return 0;

}


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

#include <bits/stdc++.h>

using namespace std;

#define int long long
#define endl '\n'

typedef unsigned long long ull;
typedef pair<int,int> PII;

void Dbug(string s,int x){
    cout<<"DEBUG:"<<s<<" "<<x<<"\n";
}
void Dbug(int x){
    cout<<"DEBUG:"<<x<<"\n";
}

const int N=2e5+10,mod=1e9+7;

int n,m;
string s;
int sum[N][30];

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin>>s;
    n=s.size();
    cin>>m;
    s='?'+s;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=26;j++){
            sum[i][j]=sum[i-1][j];
        }
        sum[i][s[i]-'a'+1]++;
    }
    for(int _=1,l,r,cnt;_<=m;_++){
        cin>>l>>r;
        if(l==r||s[l]!=s[r]){
            cout<<"Yes\n";
            continue;
        }
        cnt=0;
        for(int i=1;i<=26;i++){
            if(sum[l-1][i]<sum[r][i]){
                cnt++;
            }
        }
        cout<<(cnt>2?"Yes":"No")<<endl;
    }
    return 0;
}


F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following:  replace the element ax,yax,y with cc;  count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10
2 1 1
1 2 1
2 2 1
1 1 2
3 1 2
1 2 2
2 2 2
2 1 2
3 2 4
2 1 5
OutputCopy2
4
3
3
4
4
4
2
2
4

//a better implememtation: https://codeforces.com/blog/entry/73872
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef vector<int> vi;
typedef pair<int, int> pii;
#define IOS ios::sync_with_stdio(0)
#define For(i,a,b) for (int i=(a),_b=(b);i<=_b;i++)
#define FOr For
#define Iter(i,a,b) for (int i=(a),_b=(b);i<_b;i++)
#define Downto(i,a,b) for (int i=(a),_b=(b);i>=_b;i--)
#define set0(a) memset(a,0,sizeof(a))
#define set0n(a,n) memset(a,0,sizeof((a)[0])*(n+1))
#define pb push_back
#define mkp make_pair
#define all(a) (a).begin(),(a).end()
template <class T1, class T2>
inline void getmin(T1& x, const T2& y) {if (y < x) x = y;}
template <class T1, class T2>
inline void getmax(T1& x, const T2& y) {if (x < y) x = y;}
//char NY[2][10]={"NO\n","YES\n"};//capital?

#ifdef DEBUG
	#define SHOW(x) (cerr<<#x"="<<(x)<<endl,(x))
	#define MSG(s) (cerr<<"MESSAGE: "<<(s)<<endl,0)
#else
	#define SHOW(x) (x)
	#define MSG(s) 0
#endif

const int N = 303, NN = N * N, Q = 2e6 + 10;
const int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
int n, m, q;
int first[Q], last[Q];
int dt[Q];
struct Query {
	int x, y, c;
} a[Q];

vi cover[Q];
int cc[N][N];//current color
int fa[NN];
int find(int x) {return fa[x] == x ? x : (fa[x] = find(fa[x]));}
inline void merge(int x, int y) {fa[find(y)] = find(x);}
#define pt(x,y) ((x)*m+(y))
inline bool in(int x, int y) {return 1 <= x && x <= n && 1 <= y && y <= m;}
inline int add(int x, int y, int c) {
	if (!x && !y) { return 0; }
	int cnt = 0, x2, y2;
	cc[x][y] = c;
	For(d, 0, 3) if (in(x2 = x + dx[d], y2 = y + dy[d]) && cc[x2][y2] == c && find(pt(x, y)) != find(pt(x2, y2))) { cnt++, merge(pt(x, y), pt(x2, y2)); }
	return 1 - cnt;
}

signed main() {
	IOS;
	cin >> n >> m >> q;
	For(i, 1, q) {
		int x, y, c;
		cin >> x >> y >> c;
		if (cc[x][y] == c) {x = y = 0;}
		else { cover[cc[x][y]].pb(i); }
		a[i] = (Query) {x, y, c};
		last[cc[x][y] = c] = i;
		if (c != a[i - 1].c) { first[c] = i; }
	}

	dt[0] = 1, last[0] = -1;
	For(c, 0, a[q].c) {
		if (!last[c]) { continue; }
		if (c) {
			iota(fa, fa + 1 + (n + 1)*m, 0);
			For(i, 1, n) set0n(cc[i], m);
			For(i, first[c], last[c]) {
				dt[i] += add(a[i].x, a[i].y, c);
			}
		}
		iota(fa, fa + 1 + (n + 1)*m, 0);
		reverse(all(cover[c]));
		for (auto i : cover[c]) {
			cc[a[i].x][a[i].y] = -1;
		}
		if (c) { For(i, first[c], last[c]) if (cc[a[i].x][a[i].y] != -1) add(a[i].x, a[i].y, c); } //only merging
		else { For(x, 1, n) For(y, 1, m) if (cc[x][y] != -1) add(x, y, 0); } //beware braces!!!
		for (auto i : cover[c]) {
			dt[i] -= add(a[i].x, a[i].y, c);
		}
	}
	For(i, 1, q) dt[i] += dt[i - 1], cout << dt[i] << '\n';

	return cout << flush, 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

#pragma GCC optimize("O3")

#pragma GCC optimize("unroll-loops")

#include <bits/stdc++.h>

using namespace std;

#define int long long int

//bool prime[30007];

vector<int> fact(15);

#define INF 1e9;

#ifndef ONLINE_JUDGE

#define debug(x) cerr<< #x <<"= "; _print(x);cerr<<endl;

#else

#define debug(x)

#endif

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

#define ascending(v) sort(v.begin(),v.end());

#define descending(v) sort(v.rbegin(),v.rend());

void _print(string a) {cerr << a;} void _print(int a) {cerr << a;} void _print(char a) {cerr << a;}

void _print(bool a) {cerr << a;} void _print(double a) {cerr << a;} void _print(float a) {cerr << a;}

template<class T, class V> void _print(unordered_map<T, V> m)

{

    cerr << "\n";

    for (auto &pr : m)

    {

        cerr << pr.first << "->";

        cerr << pr.second << "\n";

    }

}

template<class T, class V> void _print(map<T, vector<V>> m)

{

    cerr << "\n";

    for (auto &pr : m)

    {

        cerr << pr.first << "->";

        for (auto i : pr.second)

        {

            _print(i);

            cerr << " ";

        }

        cerr << "\n";

    }

}

template<class T, class V> void _print(map<T, V> m)

{

    cerr << "\n";

    for (auto &pr : m)

    {

        _print(pr.first);

        cerr << "->";

        _print(pr.second);

        cerr << "\n";

    }

}

template<class T> void _print(vector<T> v1)

{

    cerr << "[";

    for (T i : v1)

    {

        _print(i);

        cerr << " ";

    }

    cerr << "]";

}

template<class T, class V> void _print(vector<pair<T, V>> v1)

{

    cerr << "[";

    for (auto &pr : v1)

    {

        cerr << "{";

        _print(pr.first);

        cerr << " ";

        _print(pr.second);

        cerr << "}";

        cerr << " ";

    }

    cerr << "]";

}

template<class T> void _print(vector<vector<T>> v1)

{

    cerr << "\n";

    for (auto &vec : v1)

    {

        for (T i : vec)

        {

            _print(i);

            cerr << " ";

        }

        cerr << "\n";

    }

}

template<class T> void _print(vector<set<T>> v1)

{

    for (auto &vec : v1)

    {

        for (T i : vec)

        {

            _print(i);

            cerr << " ";

        }

        cerr << "\n";

    }

}

template<class T> void _print(set<T> s1)

{

    cerr << "[";

    for (T i : s1)

    {

        _print(i);

        cerr << " ";

    }

    cerr << "]";

}

template<class T> void _print(queue<T> q1)

{

    cerr << "[";

    while (!q1.empty())

    {

        T i = q1.front();

        q1.pop();

        cerr << i;

        cerr << " ";

    }

    cerr << "]";

}

template<class T> void _print(stack<T> st1)

{

    cerr << "[";

    while (!st1.empty())

    {

        _print(st1.top());

        st1.pop();

        cerr << " ";

    }

    cerr << "]";

}

template<class T> void _print(list<T> lis1)

{

    cerr << "[";

    for (T i : lis1)

    {

        _print(i);

        cerr << " ";

    }

    cerr << "]";

}

template<class T> void _print(deque<T> lis1)

{

    cerr << "[";

    for (T i : lis1)

    {

        _print(i);

        cerr << " ";

    }

    cerr << "]";

}

template<class T, class V> void _print(deque<pair<T, V>> lis1)

{

    cerr << "[";

    for (auto i : lis1)

    {

        cerr << "{";

        _print(i.first);

        cerr << " ";

        _print(i.second);

        cerr << "}";

    }

    cerr << "]";

}

template<class T> void _print(priority_queue<T> pq1)

{

    cerr << "[";

    for (T i : pq1)

    {

        _print(i);

        cerr << " ";

    }

    cerr << "]";

}

int moduloMultiplication(int a, int b,

                         int  mod)

{

    // Initialize result

    int  res = 0;

    // Update a if it is more than

    // or equal to mod

    a %= mod;

    while (b) {

        // If b is odd, add a with result

        if (b & 1)

            res = (res + a) % mod;

        // Here we assume that doing 2*a

        // doesn't cause overflow

        a = (2 * a) % mod;

        b >>= 1; // b = b / 2

    }

    return res;

}

int modpower(int x, int y, int p)

{

    int res = 1;     // Initialize result

    x = x % p; // Update x if it is more than or

    // equal to p

    if (x == 0) return 0; // In case x is divisible by p;

    while (y > 0)

    {

        // If y is odd, multiply x with result

        if (y & 1)

            res = (res * x) % p;

        // y must be even now

        y = y >> 1; // y = y/2

        x = (x * x) % p;

    }

    return res;

}

int power(int x, int y)

{

    int res = 1;     // Initialize result

    if (x == 0) return 0; // In case x is divisible by p;

    while (y > 0)

    {

        if (y & 1)

            res = (res * x);

        // y must be even now

        y = y >> 1; // y = y/2

        x = (x * x);

    }

    return res;

}

// C++ function for extended Euclidean Algorithm

int gcdExtended(int a, int b,

                int* x,

                int* y);

// Function to find modulo inverse of b. It returns

// -1 when inverse doesn't exists

int modInverse( int b,  int m)

{

    int x, y; // used in extended GCD algorithm

    int g = gcdExtended(b, m, &x, &y);

    // Return -1 if b and m are not co-prime

    if (g != 1)

        return -1;

    // m is added to handle negative x

    return (x % m + m) % m;

}

// C function for extended Euclidean Algorithm (used to

// find modular inverse.

int gcdExtended(int a, int b,

                int* x,

                int* y)

{

    // Base Case

    if (a == 0) {

        *x = 0, *y = 1;

        return b;

    }

    // To store results of recursive call

    int x1, y1;

    int gcd = gcdExtended(b % a, a, &x1, &y1);

    // Update x and y using results of recursive

    // call

    *x = y1 - (b / a) * x1;

    *y = x1;

    return gcd;

}

// Function to compute a/b under modlo m

int modDivide( int a,  int b,

               int m)

{

    a = a % m;

    int inv = modInverse(b, m);

    if (inv == -1)

        // cout << "Division not defined";

        return 0;

    else

        return (inv * a) % m;

}

// Function to calculate nCr % p

// int nCr(int n, int r, int p)

// {

//     int calc1 = fact[n];

//     int calc2 = ((fact[n - r] % p) * (fact[r] % p)) % p;

//     return modDivide(calc1, calc2, p);

// }

// void SieveOfEratosthenes(int n)

// {

//     // Create a boolean array

//     // "prime[0..n]" and initialize

//     // all entries it as true.

//     // A value in prime[i] will

//     // finally be false if i is

//     // Not a prime, else true.

//     memset(prime, true, sizeof(prime));

//     for (int p = 2; p * p <= n; p++)

//     {

//         // If prime[p] is not changed,

//         // then it is a prime

//         if (prime[p] == true)

//         {

//             // Update all multiples

//             // of p greater than or

//             // equal to the square of it

//             // numbers which are multiple

//             // of p and are less than p^2

//             // are already been marked.

//             for (int i = p * p; i <= n; i += p)

//                 prime[i] = false;

//         }

//     }

// }

int binarySearch(int arr[], int l, int r, int x)

{

    if (r >= l) {

        int mid = l + (r - l) / 2;

        // If the element is present at the middle

        // itself

        if (arr[mid] == x)

            return mid;

        // If element is smaller than mid, then

        // it can only be present in left subarray

        if (arr[mid] > x)

            return binarySearch(arr, l, mid - 1, x);

        // Else the element can only be present

        // in right subarray

        return binarySearch(arr, mid + 1, r, x);

    }

    // We reach here when element is not

    // present in array

    return -1;

}

void factorial(int p)

{

    fact[0] = 1;

    fact[1] = 1;

    for (int i = 2; i < fact.size(); i++)

    {

        fact[i] = (i * fact[i - 1]) % p;

    }

}

int gcd(int a, int b)

{

    // Everything divides 0

    if (a == 0)

        return b;

    if (b == 0)

        return a;

    // base case

    if (a == b)

        return a;

    // a is greater

    if (a > b)

        return gcd(a - b, b);

    return gcd(a, b - a);

}

int ceil(int a, int x)

{

    if (a % x == 0)

        return a / x;

    else

        return a / x + 1;

}

int countBits(int n)

{

    int count = 0;

    while (n)

    {

        count++;

        n >>= 1;

    }

    return count;

}

bool isPower(int x, int y)

{

    int res1 = log2(y) / log2(x);

    double res2 = log2(y) / log2(x);

    // compare to the result1 or result2 both are equal

    return (res1 == res2);

}

bool isPerfectSquare(int x)

{

    // Find floating point value of

    // square root of x.

    if (x >= 0) {

        long long sr = sqrt(x);

        // if product of square root

        //is equal, then

        // return T/F

        return (sr * sr == x);

    }

    // else return false if n<0

    return false;

}

//--------------------------------------------------------------------------------------------------------------------------------------------

const int mod = 998244353;

const int M = 1e9 + 7;

const int inf = 1e18;

void solve()

{

    int n;

    cin >> n;

    vector<int> q;

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

    {

        int x;

        cin >> x;

        q.push_back(x);

    }

    vector<int> p(n);

    p[0] = 1;

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

    {

        p[i] = q[i - 1] + p[i - 1];

    }

    debug(p);

    int minn = INT_MAX;

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

    {

        minn = min(minn, p[i]);

    }

    int diff = 1 - minn;

    vector<int> vis(n + 1, 0);

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

    {

        p[i] += diff;

        if (p[i] <= n) vis[p[i]] = 1;

    }

    debug(vis)

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

    {

        if (!vis[i])

        {

            cout << -1 << "\n";

            return;

        }

    }

    for (int i : p)

        cout << i << " ";

    cout << "\n";

    return;

}

int32_t main() {

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    cout.tie(NULL);

#ifndef ONLINE_JUDGE

    freopen("input.txt", "r", stdin);

    freopen("output.txt", "w", stdout);

    freopen("Error2.txt", "w", stderr);

#endif//ONLINE_JUDGE

    int T = 1;

    //cin >> T;

    int t = 1;

    //SieveOfEratosthenes(100005);

    // debug(primes);

    //cout << (char)('z' - 25) << "\n";

    //factorial(inf);

    //debug(fact);

    while (T--)

    {

        cerr << T << "____________________________________" << "\n";

        //cout << "Case #" << t << ": ";

        solve();

        t++;

    }

}


B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5

#include<bits/stdc++.h>

#define ll long long int

using namespace std;

int main(){

   ll t;

   cin>>t;

   while(t--){

      ll n;

      cin>>n;

      vector<ll>v;

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

         int x;

         cin>>x;

         v.push_back(x);

      }

      sort(v.begin(),v.end());

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

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

         cout<<v[i]<<" ";

      }

      cout<<endl;

     }

  }


#include<bits/stdc++.h>

using namespace std;

int main(){

	int t,n;

	cin>>t;

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

		cin>>n;

		cout<<n-1<<" "<<1<<endl;

	}

}


B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES

#include <bits/stdc++.h>

using namespace std;

#define ll long long

#define int long long

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

#define yes cout << "YES" << endl;

#define no cout << "NO" << endl;

vector<int> dx8 = {0, 1, -1, 0, 1, -1, -1, 1},

        dy8 = {1, 0, 0, -1, 1, -1, 1, -1},

        dx4 = {0, 1, -1, 0},

        dy4 = {1, 0, 0, -1};

signed main() {

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    cout.tie(NULL);

    int n, m, k;

    int t;

    cin >> t;

    while (t--) {

        cin >> n >> m;

        vector<int> a(n), b(m);

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

            cin >> a[i];

        }

        vector<bool> vis(101);

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

            cin >> b[i];

            vis[b[i] - 1] = 1;

        }

        sort(all(b));

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

            int j = b[i];

            while (1) {

                if (a[b[i] - 1] > a[j]) {

                    swap(a[b[i] - 1], a[j]);

                }

                if (vis[j]) {

                    j++;

                } else {

                    break;

                }

            }

        }

        if (is_sorted(all(a))) {

            yes

        } else {

            no

        }

    }

    return 0;

}


D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns.   You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6

/*
"THE STONE THAT THE BUILDERS REJECTED HAS BECOME THE CORNERSTONE.
THIS IS THE LORD'S DOING , THIS IS MARVELOUS IN OUR EYES ." (118 :22-23 ) ❤

Dear online judge:
I have not failed. I've just found 10,000 ways that won't work.
                    _Thomas A. Edison
"لكن بالنسبة لكَ كُن قويًا ولا تستسلم لأنَّ عملَك سيُكافأ"
*/
#include <bits/stdc++.h>
#include <iostream>
#include <chrono>
#include <vector>
#include <set>
#include <map>
#include<math.h>
#include <stack>
#include <cmath>
#include <unordered_map>
#include <algorithm>
#include <iomanip>
#include <bitset>
#include <utility>
#include <string>
#include <cctype>
#include <iomanip>
#include <numeric> // for NTH
#define bye return;
#define endl '\n'
#define ll long long
#define li long int
#define lli long long int
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define Number_of_leading_zeroes_l(num) __builtin_clz(num)
#define Number_of_leading_zeroes_ll(num) __builtin_clzll(num)
#define Number_of_trailing_zeroes_ll(num) __builtin_ctz(num)
#define pop_count_int(num) __builtin_popcount(num)
#define pop_count_l(num) __builtin_popcountl(num)
#define pop_count_ll(num) __builtin_popcountll(num)
#define ison(num, bit) (num & (1 << bit))
#define setoffif(num, bit) (num ^= (1 << bit)) // iff (num &(1<<bit))
#define setoff(num, bit) (num &= ~(1 << bit))
#define seton(num, bit) (num |= (1 << bit))
#define flipbit(num, bit) (num ^= (1 << bit))
#define LSB(num) (num & (-num))
#define indx_of_MSB(n)  _lg(n) // zero based from right
#define Num_of_Digits(n) ((ll)log10(n) + 1)
#define ceill(n, m) (((n) / (m)) + (((n) % (m) ) ? 1 : 0))
#define lastOne(x) (__builtin_clzll(x))
#define fixed(n) fixed << setprecision(n)
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define Time cerr << "Time Taken: " << (float)clock() / CLOCKS_PER_SEC << " Secs" << "\n";
#define Pi  3.14159265358979323846264
#define INF_LL 0x3f3f3f3f3f3f3f3f
#define INF_INT 0x3f3f3f3f
#define sin(a) sin((a)*PI/180)
#define cos(a) cos((a)*PI/180)
#define yes cout << "YES" << endl;
#define no cout << "NO" << endl;
#define M 64    //the size of the bitset must be a constant number. You can't read n and then declare bitset<n>
#define bitset(n) bitset<M>(n) // zero based , indexing beginning from the right not left
// #define ordered_set tree<pair<int, int>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update>
// #define ordered_map tree<int, int, less<>, rb_tree_tag, tree_order_statistics_int_update>
ll sgn(ll x){ if(x > 0) return 1; if(x < 0) return -1; return 0;}
ll mod = 1e9 + 7;
ll mul(ll a, ll b) { return ((a % mod) * (b % mod)) % mod; }
ll add(ll a, ll b) { return ((a % mod) + (b % mod)) % mod; }
ll sub(ll a, ll b) { return ((a % mod) - (b % mod) + mod) % mod; }
const ll   llmin  = -1e18 ;
const ll   llmax  =  1e18 ;
const int  imin   = -1e9  ;
const int  imax   =  1e9  ;
const int  N      = 2e5   ;
using namespace std;
void AC() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); // or cin.tie(NULL)
    cout.tie(nullptr);  // or cout.tie(0)
}
void file_set(){ //string& file_name
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
    // freopen((file_name+".in").c_str(), "r", stdin);
    // freopen((file_name+".out").c_str(), "w", stdout);
}
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b)
{
    return (a.second < b.second);
}
    // THOSE WHO CAN'T REMEMBER THE PAST'RE CONDEMNED TO REPEAT IT (USE DP -_-) - George Santayana
    // PUSH HARDER THAN YESTERDAY IF YOU WANT A DIFFERENT TOMORROW !
    //YOU DON'T HAVE TO BE A GENIUS , YOU NEED TO BE DETERMINED .
const  ll MAX = 1e5+2;
ll vis[MAX];
//   n = ~(int)0; // test for possible overflow
ll MSB(ll x ){
    ll k = Number_of_leading_zeroes_ll(x);
    return (63-k) ;
}
void LELLO(){
    ll n , a , b , k  ; cin >> n >> a >> b >> k ;
    vector<ll> vc(n)  , ans(n);
    for (int i = 0; i < n; i++)
    {
        cin >> vc[i];
    }
    // NOTE : (r/a) == ((r+a-1 )/ a) == ((r-1 / a )+1)
    // to make (r/a -1) == (r-1 / a )+1) - 1 == (r-1 / a )
    for (int i = 0; i < n; i++)
    {
        vc[i] %=(a+b);
        if(vc[i] == 0 ) vc[i] = (a+b);
        ans[i] = (vc[i] - 1) / a ;
    }
    sort(all(ans)) ;
    ll co(0);
    for (int i = 0; i < n; i++)
    {
        if(ans[i] <= k){
            k -=ans[i];
            co++;
        }
    }
    cout<< co <<endl;
}
void driver(ll t=1)
{

    while (t--) LELLO();
    Time
}
signed main()
{
    AC();
    // file_set();
    // ll test ; cin >> test ;
    driver();
}