D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will:   Tell you if acac is in SS;  Add acac at the back of SS;  If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:  fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.

#include<bits/stdc++.h>

using namespace std;

#define ll long long

#define N 100001

ll n,k;

inline bool gt(ll x){

	cout<<"? "<<x<<'\n';

	char tem;

	cout.flush();cin>>tem;

	if(tem=='N')return 0;

	return 1;

}

inline void clear(){

	cout<<'R'<<'\n';

	return ;

}

ll an[N];

int main()

{

//	freopen("test1.in","r",stdin);

	//freopen(".in","r",stdin);

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

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

	cin>>n>>k;

	if(k==1){

		ll ans=n;

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

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

				gt(j);ll o=gt(i);an[i]|=o;

			}

			if(an[i])ans--;

		}cout<<"! "<<ans;

		return 0;

	}

	ll ji=k/2,g=n/ji,ans=n;

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

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

			if(j>g-i)continue;

			for(int k=j;k<=g;k+=i){

				for(int p=(k-1)*ji+1;p<=k*ji;p++)an[p]|=gt(p);

			}clear();

		}

	}

	for(int i=1;i<=n;i++)if(an[i])ans--;

	cout<<"! "<<ans;

	return 0;

}


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
using vi = vector<int>;
using pi = pair<int, int>;

#define FAST_IO                     \
  ios_base::sync_with_stdio(false); \
  cin.tie(NULL)

bool is_prime(ll x) {
  if (x <= 1) return 0;
  for (ll y = 2; y * y <= x; ++y)
    if (x % y == 0) return 0;
  return 1;
}

using std::gcd;  // Computes the greatest common divisor of the integers m and
                 // n.
using std::lcm;  // Computes the least common multiple of the integers m and n.

int popcnt(uint x) { return __builtin_popcount(x); }
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(ull x) { return __builtin_popcountll(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int bsr(uint x) { return 31 - __builtin_clz(x); }
int bsr(ull x) { return 63 - __builtin_clzll(x); }
int ctz(int x) { return __builtin_ctz(x); }
int ctz(ll x) { return __builtin_ctzll(x); }
int ctz(ull x) { return __builtin_ctzll(x); }

template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;

#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())

#define SUM(v) accumulate(all(v), 0LL)
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))

#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())

ll ceil(ll x, ll y) {
  assert(y >= 1);
  return (x > 0 ? (x + y - 1) / y : x / y);
}

ll floor(ll x, ll y) {
  assert(y >= 1);
  return (x > 0 ? x / y : (x - y + 1) / y);
}

ll mod(ll x, ll y) { return x - y * floor(x, y); }

#line 74 "library/ds/unionfind.hpp"
struct UnionFind {
  int n;
  int n_comp;
  std::vector<int> size, par;
  UnionFind(int n) : n(n), n_comp(n), size(n, 1), par(n) {
    std::iota(par.begin(), par.end(), 0);
  }
  int find(int x) {
    assert(0 <= x && x < n);
    while (par[x] != x) {
      x = par[x] = par[par[x]];
    }
    return x;
  }

  int operator[](int x) { return find(x); }

  bool merge(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) {
      return false;
    }
    n_comp--;
    if (size[x] < size[y]) std::swap(x, y);
    size[x] += size[y];
    size[y] = 0;
    par[y] = x;
    return true;
  }

  std::vector<int> find_all() {
    std::vector<int> A(n);
    for (int i = 0; i < n; ++i) A[i] = find(i);
    return A;
  }

  void reset() {
    n_comp = n;
    size.assign(n, 1);
    std::iota(par.begin(), par.end(), 0);
  }
};

/**************************** debug utils begin *******************************/

#line 121 "debug_utils.cpp"

#ifdef OJ_DEBUG
#define LOG std::cerr << "line: " << __LINE__ << ", "
#else
struct NonFunctioningLogger {
 public:
  template <typename T>
  NonFunctioningLogger& operator<<(const T& obj) {
    return *this;
  }
};
NonFunctioningLogger LOG;
#endif  // OJ_DEBUG

#define DEFINE_CONTAINER_PRINTER(CONTAINER_TYPE)                   \
  template <typename T>                                            \
  ostream& operator<<(ostream& ostr, const CONTAINER_TYPE<T>& a) { \
    ostr << "{";                                                   \
    for (auto it = a.begin(); it != a.end(); it++) {               \
      if (it != a.begin()) ostr << ", ";                           \
      ostr << *it;                                                 \
    }                                                              \
    ostr << "}";                                                   \
    return ostr;                                                   \
  }

DEFINE_CONTAINER_PRINTER(std::vector)
DEFINE_CONTAINER_PRINTER(std::deque)
DEFINE_CONTAINER_PRINTER(std::list)
DEFINE_CONTAINER_PRINTER(std::set)
DEFINE_CONTAINER_PRINTER(std::unordered_set)

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

template <typename T, typename Y>
auto operator<<(std::ostream& os, const std::vector<std::pair<T, Y>>& a)
    -> std::ostream& {
  os << "{";
  int i;
  for (i = 0; i < a.size() - 1; i++) {
    os << "(" << a[i].first << ", " << a[i].second << "), ";
  }
  if (i < a.size()) {
    os << a[i];
  }
  os << "}";
  return os;
}

template <class T, class S>
inline bool chmin(T& a, const S& b) {
  return (a > b ? a = b, 1 : 0);
}

/**************************** debug utils end *******************************/

#line 182 "main.cpp"

int main() {
  FAST_IO;
  int n;
  cin >> n;
  vc<ll> a(n);
  vc<ll> b(n);
  for (int i = 0; i < n; i++) cin >> a[i];
  for (int i = 0; i < n; i++) cin >> b[i];
  for (int i = 0; i < n; i++) {
    a[i] -= b[i];
  }
  sort(all(a));
  ll cnt{0};
  for (int i = 0; i < n - 1; i++) {
    if (a[i] <= 0) {
      cnt += distance(lower_bound(a.begin() + i + 1, a.end(), 1LL - a[i]),
                      a.end());
    } else {
      cnt += (n - 1 - i);
    }
  }
  cout << cnt << "\n";
  return 0;
}


C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823


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

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using ld = long double;

constexpr int N = int(4e2) + 5;

constexpr int inf = 0x7f7f7f7f;

constexpr int MOD = int(1e9) + 7;

void solve(){

    int n, m, k = 0, l;

    cin >> n >> m;

    vector<int> v;

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

        if(k + (i - 1 >> 1) <= m){

            k += i - 1 >> 1;

            v.push_back(i);

            l = v.back() + 1;

        }

        else if(k < m){

            v.push_back(2 * (i - m + k) - 1);

            k = m;

            l = v.back() + 1;

        }

        else v.push_back(int(1e9) - l * (n - i));

    }

    if(k != m) cout << -1;

    else for(auto& i : v) cout << i << ' ';

}

int main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    int t = 1;

    //cin >> t;

    while(t--){

        solve();

    }

}


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

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

#define endl '\n';

void solve()

{

    int n; cin >> n;

    if (n % 2 != 0)

    {

        cout << "7";

        n -= 3;

    }

    while (n)

    {

        cout << 1;

        n -= 2;

    }

    cout << "\n";

}

int main()

{

	ios_base::sync_with_stdio(0);

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

	int t;

	cin >> t;

	while(t--)

	{

		solve();

	}

	return 0;

}


B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0

InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.

/* ______ Defines _____ */

#pragma GCC optimize("O3")

#pragma GCC optimize("unroll-loops")

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

#define ordered_set tree<pair<ll,ll>, null_type,less<pair<ll,ll>>, rb_tree_tag,tree_order_statistics_node_update>

#define Time cerr << "Time Taken: " << (float)clock() / CLOCKS_PER_SEC << " Secs" << "\n";

#include <bits/stdc++.h>

#define Num_of_Digits(n) ((int)log10(n)+1)

using namespace std;

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

double pi=3.141592653590;

typedef long long ll;

typedef long double ld;

typedef unsigned long long ull;

typedef long double ld;

#define yes cout<<"YES\n";return;

#define no cout<<"NO\n";return;

#define F first

#define S second

#define el '\n'

#define INF 1e18

#define PI 3.1415926535

#define L00 0x3f3f3f3f3f3f3f3f

#define I00 0x3f3f3f3f

#define NL00 -0x3f3f3f3f3f3f3f3f

#define popcount __builtin_popcount

ll MOD = 1e18+5;

int TEST_CASE = 1;

void file(){

#ifndef ONLINE_JUDGE

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

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

#endif

}

int

di[] = {1, 0, -1, 0,  1, -1, -1, 1},

dj[] = {0, 1, 0, -1, 1,  1, -1, -1},

dx[] = {0, 1, 0 , -1},

dy[] = {1, 0, -1,  0};

//right, down, left, up

int const N = 1e5 + 5, M = 2*N + 9 ,SQRT=1e6+10 ,mod = 1e9 + 7, oo = 1e9 + 10;

//------------start solve-------------------

void solve() {

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

    map<string, int> mp;

    string s, res = "";

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

        cin>>s;

        //check if there plaindrome

        string rev = s;

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

        if(mp.find(rev) != mp.end()) {

            res += s;

            mp.erase(rev);

        }else mp[s]++;

    }

    string mid = "";

    for(auto mm:mp) {

        string tmp = mm.F;

        string rev = tmp;

        std::reverse(rev.begin(), rev.end());

        if(tmp == rev) mid = tmp;

    }

    cout<<res.size() * 2 + mid.size()<<el;

    cout<<res<<mid;

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

    cout<<res;

}

int main() {

    file();

    Lion_Heart

    /** ______ IF YOU HAVE ANY BUG IN YOUR CODE,JUST ERASE IT _____ goooddd **/

    cout<<fixed<<setprecision(10);

    int tt=1;

//    cin>>tt;

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

        solve();

//      TEST_CASE++;

    }

    return 0;

}


A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here:  After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5).  After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3).  After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal.  After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.

#include <bits/stdc++.h>

typedef long long ll;

#define vi     vector <int>

#define vll    vector <long long>

#define vs     vector <string>

#define vc     vector <char>

#define PII    pair<int,int>

#define MII    map<int,int>

#define UMII   unordered_map<int,int>

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

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

#define ff     first

#define ss     second

#define int    long long

#define endl   "\n"

#define TxtIO   freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);

using namespace std;

const int  M  = 1e9+7;

const int  N  = 1e5+7;

signed main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    cout.tie(0);

        int n,q;

        cin >> n >> q;

        vector<vector<int>> v(2,vector<int>(n+1));

        int locks{};

        while(q--){

            int a,b; cin >> a >> b;

            a--; b--;

            if(v[a][b] == 0){

                v[a][b] = 1;

                locks += v[a^1][b];

                if(b-1 >= 0) locks += v[a^1][b-1];

                if(b+1 < n) locks += v[a^1][b+1];

            }else{

                v[a][b] = 0;

                locks -= v[a^1][b];

                if(b-1 >= 0) locks -= v[a^1][b-1];

                if(b+1 < n) locks -= v[a^1][b+1];

            }

            if(!locks){

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

            }else{

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

            }

        }

    return 0;

}


A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands:  'L' (Left) sets the position x:=x−1x:=x−1;  'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully):   "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00;  "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well;  "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.

#include<bits/stdc++.h>

using namespace std;

int main(){

int n;

cin>>n;

string s;

cin>>s;

cout<<s.size()+1<<"\n";

return 0;

}


E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can:  choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously.  Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this:  In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.

#include <bits/stdc++.h>

int main() {
int n, m; scanf("%d%d", &n, &m);
int a{n * m}, C[a]{};
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) {
int x; scanf("%d", &x);
if (--x % m == j and x < a)
C[j * n + (i - x / m + n) % n]--;
C[j * n + i] += i;
}
for (int k = 0; k < n * m; k += n)
a += *std::min_element(C + k, C + k + n);
printf("%d", a);
}


B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs:  buy one bus ticket to get from 11 to 33,  buy one tram ticket to get from 33 to 66,  buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6

#include <bits/stdc++.h>

using namespace std;

#define fast                          \

    ios_base::sync_with_stdio(false); \

    cin.tie(0);                       \

    cout.tie(0)

#define ll long long

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

#define pb push_back

#define vl vector<ll>

#define vp vector<pair<ll, ll>>

#define in(a)         \

    for (auto &x : a) \

        cin >> x;

#define out(a)            \

    for (auto x : a)      \

        cout << x << ' '; \

    cout << endl;

#define pr(a) cout << a << endl

const ll mod = 1e9 + 7;

const double pi = acos(-1);

void solve()

{

    ll i, a, b, p, ans;

    string s;

    cin >> a >> b >> p >> s;

    char c = 'X';

    for (i = s.size() - 2; i >= 0; i--)

    {

        if (c != s[i])

        {

            c = s[i];

            p -= (c == 'A' ? a : b);

            if (p < 0)

            {

                break;

            }

        }

    }

    pr(i + 2);

}

int main()

{

    fast;

    int t;

    cin >> t;

    while (t--)

        solve();

}


G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk.  The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 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 = 2e5+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 > > ;

vector < vector <pair <int , int > > > g;

vector <int > dep(N);

void dfs(int node , int par){

    for (auto &ch : g[node]){

        if (par == ch.first) continue;

        dep[ch.first] = 1 + dep[node];

        dfs(ch.first , node);

    }

}

void hi(int tc) {

    ll n , k; cin >>n >> k;

    g = vector < vector <pair <int , int > > > (n+5);

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

        cin >> u >> v;

        g[u].emplace_back(v , i);

        g[v].emplace_back(u , i);

    }

    vector <pair <int , int > > bad;

    for (int i = 1; i <= n; ++i) bad.emplace_back((int)g[i].size() , i);

    sort(all(bad) , [&](pair <int , int > & a , pair <int , int > & b) {

        return a.first > b.first;

    });

    dfs(1 , 1);

    cout << bad[k].first <<nd;

    int u = bad[k].first;

    vector <pair <int , int > > order;

    vector <int > col(n+5 , -1);

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

       // for (auto &ch : g[bad[i].second])

            //col[ch.second] = 1;

    for (int i = k; i < n; ++i)order.emplace_back(dep[bad[i].second] , bad[i].second);

    sort(all(order));

    for (auto &p : order){

        int node = p.second;

        set <int > st;

      //  cout << node <<" "<<p.first <<" "<<(int)g[node].size()<< nd;

        for (int i = 1; i <= (int)g[node].size(); ++i) st.emplace(i);

        for (auto &ch : g[node]) st.erase(col[ch.second]);

        for (auto &ch : g[node]){

            if (col[ch.second] != -1) continue;

            col[ch.second] = *st.begin();

            st.erase(st.begin());

        }

    }

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

        if (col[i] == -1) col[i] = 1;

        cout << col[i] <<" ";

    }

}

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;

}

/*

 * greedy

 * if k == 0 thw answer is equal to the maximum degree of a vertex

 * cuz if it was less/ then there at least two edges out of me with the same color

 */


B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].

#include <bits/stdc++.h>

using namespace std;

int main()

{

    ios_base::sync_with_stdio(false);

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

    int32_t test; cin >> test;

    int32_t n, tmp;

    while (test--)

    {

        cin >> n;

        set <int32_t> st;

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

        {

            cin >> tmp; st.insert(tmp);

        }

        cout << st.size() << '\n';

    }

    return 0;

}


B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.

/**

 *      Author:  Richw818

 *      Created: 02.10.2023 15:06:35

**/

#include <bits/stdc++.h>

using namespace std;

template<typename T>

struct Point2D{

    using P2 = Point2D;

    T x, y;

    Point2D(T _x = 0, T _y = 0){ x = _x, y = _y; }

    bool operator<(P2 p) const { return tie(x, y) < tie(p.x, p.y); }

    bool operator==(P2 p) const { return tie(x, y) == tie(p.x, p.y); }

    bool operator!=(P2 p) const { return !(tie(x, y) == tie(p.x, p.y)); }

    P2 operator+(P2 p) const { return P2(x + p.x, y + p.y); }

    P2 operator-(P2 p) const { return P2(x - p.x, y - p.y); }

    P2 operator*(T d) const { return P2(x * d, y * d); }

    P2 operator/(T d) const { return P2(x / d, y / d); }

    T cross(P2 p) const { return x * p.y - y * p.x; }

    T cross(P2 a, P2 b) const { return (a - *this).cross(b - *this); }

    T dot(P2 p) const { return x * p.x + y * p.y; }

    T dist2() const { return x * x + y * y; }

    double dist() const { return sqrt(dist2()); }

    P2 unit() const { return *this / dist(); }

    P2 perp() const { return P2(-y, x); }

    P2 normal() const { return perp().unit(); }

    P2 rotate(double a) const {

        return P2(x * cos(a) - y * sin(a), x * sin(a) + y * cos(a));

    }

    friend ostream& operator<<(ostream& os, P2 p){

        return os << "(" << p.x << ", " << p.y << ")\n";

    }

    friend istream& operator>>(istream& is, P2& p){

        return is >> p.x >> p.y;

    }

};

int main(){

    ios_base::sync_with_stdio(false);

    cin.tie(nullptr);

    using P2 = Point2D<int>;

    int n; cin >> n;

    if(n & 1){

        cout << "NO\n";

        return 0;

    }

    vector<P2> points(n); for(auto& P : points) cin >> P;

    P2 check = points[0] + points[n / 2];

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

        if(points[i] + points[i + n / 2] != check){

            cout << "NO\n";

            return 0;

        }

    }

    cout << "YES\n";

    return 0;

}


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

#include<bits/stdc++.h>

template <typename _Tp>void read(_Tp &x){

	char ch(getchar());bool f(false);while(!isdigit(ch))f|=ch==45,ch=getchar();

	x=ch&15,ch=getchar();while(isdigit(ch))x=x*10+(ch&15),ch=getchar();

	if(f)x=-x;

}

template <typename _Tp,typename... Args>void read(_Tp &t,Args &...args){read(t);read(args...);}

const int N=100005;typedef long long ll;

int L[N],R[N],p[N],s[N],a[N],n,m,val[N],VAL[N];ll t,lim[N],b[N],suf[N];

ll calc1(int mid){ll tot=0;for(int i=1;i<=n;++i)tot+=std::min(R[i],std::max(L[i],mid));return tot;}

bool check(int mid){

	int x=-1,y=-1;for(int i=1;i<=mid;++i)if(val[i]!=-1)(x==-1?x:y)=val[i];

	if(x!=-1&&y!=-1&&x!=y)return 0;

	if(x==-1&&y==-1){

		ll tmp=1e18,tot=0;

		for(int i=1;i<=m;++i)tot+=i>mid?VAL[i]:0,tmp=std::min(tmp,(lim[i]-tot)/std::min(i,mid));

		for(int i=1;i<=m;++i)b[i]=i<=mid?tmp:VAL[i];

	}

	else for(int i=1;i<=m;++i)b[i]=i<=mid?x:VAL[i];

	ll tot=0;for(int i=1;i<=m;++i){tot+=b[i],suf[i]=lim[i]-tot;if(tot>lim[i])return 0;}

	suf[m+1]=1e18;for(int i=m;i>=1;--i)suf[i]=std::min(suf[i],suf[i+1]);

	ll sum=0;for(int i=mid+1;i<=m;++i)if(val[i]==-1)b[i]=std::min(VAL[i]+suf[i]-sum,b[i-1]),sum+=b[i]-VAL[i];

	for(int i=1;i<m;++i)if(b[i]<b[i+1])return 0;

	return sum+tot==t;

}

int main(){

	read(n,m);

	for(int i=1;i<=n;++i)read(L[i],R[i]);

	int q;read(q);

	memset(val,-1,sizeof(val));

	for(int i=1;i<=q;++i)read(p[i],s[i]),val[p[i]]=s[i],VAL[p[i]]=s[i];

	for(int i=m;i>=1;--i)if(!VAL[i])VAL[i]=VAL[i+1];

	read(t);int l=0,r=m,mid;

	while(l<r)mid=(l+r+1)>>1,calc1(mid)<=t?l=mid:r=mid-1;

	ll tot=0;for(int i=1;i<=n;++i)a[i]=std::min(R[i],std::max(L[i],l)),tot+=a[i];

	for(int i=1;i<=n;++i)if(tot<t&&a[i]!=R[i]&&a[i]==l)++a[i],++tot;

	std::sort(a+1,a+n+1);

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

		while(j<=n&&a[j]<i)++j;

		lim[i]=std::min(t,lim[i-1]+n-j+1);

	}

	l=1,r=m;while(l<r)mid=(l+r+1)>>1,check(mid)?l=mid:r=mid-1;

	if(!check(l))return puts("-1 -1"),0;

	printf("%d %lld\n",l,b[1]);

	return 0;

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

#include<bits/stdc++.h>
using namespace std;
int a[1001];
int main()
{
	int n,t;
	cin>>t;
	while(t--)
	{
		int k=0;
		cin>>n>>k;
		int s=0;
		for(int i=1;i<=n;i++)
		{
			cin>>a[i];
		}
		for(int i=1;i<=k;i++)
		{
			for(int j=2;j<=n;j++)
			{
				if(a[j]>0)
				{
					a[j]--,a[j-1]++;
					break;
				}
			}

		}
		cout<<a[1]<<endl;
	}
    return 0;
}


B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is:  There are 44 subrectangles of size 22 consisting of only ones in it:  In second example matrix cc is:

#include <bits/stdc++.h>

using namespace std;
struct custom_hash
{
    static uint64_t splitmix64(uint64_t x)
    {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }
    size_t operator()(uint64_t x) const
    {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
#define endl '\n'
#define fio ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
#define incr_loop(a, n) for (int i = a; i < n; i++)
#define decr_loop(a, b) for (int i = a; i > b; i--)
#define nested_incr_loop(a, b) for (int j = a; j < b; j++)
#define nested_decr_loop(a, b) for (int j = b; j > a; --j)
typedef long long ll;
typedef double long dl;
#define pb push_back
#define ppb pop_back
#define MP make_pair
#define sort_all(v) sort(all(v));
#define PI 3.141592653589793238462
#define space cout << ' ';
typedef unordered_map<int, int, custom_hash> mp;
ll MOD = 998244353;

vector<ll> primes;
ll ans = 0;

void solve()
{
    ll n, m, k;
    cin >> n >> m >> k;
    vector<int> arr(n), brr(m);
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    for (int i = 0; i < m; i++)
    {
        cin >> brr[i];
    }
    vector<ll> mmp1(n + 1), mmp2(m + 1);
    for (int i = 0; i < n;)
    {
        if (arr[i] == 0)
        {
            i++;
            continue;
        }
        int cnt = 0;
        while (i < n && arr[i] == 1)
        {
            i++;
            cnt++;
        }
        for (int j = 1; j <= cnt; j++)
        {
            mmp1[j] += cnt + 1 - j;
        }
    }
    for (int i = 0; i < m;)
    {
        if (brr[i] == 0)
        {
            i++;
            continue;
        }
        int cnt = 0;
        while (i < m && brr[i] == 1)
        {
            i++;
            cnt++;
        }
        for (int j = 1; j <= cnt; j++)
        {
            mmp2[j] += cnt + 1 - j;
        }
    }

    ll ans = 0;
    for (int i = 1; i <= k; i++)
    {
        if (i > n)
        {
            break;
        }
        if (k % i)
        {
            continue;
        }
        if ((k / i) > m)
        {
            continue;
        }
        ans += mmp1[i] * mmp2[k / i];
    }
    cout << ans << endl;
}

int main()
{
    fio int tc = 1;
    // cin >> tc;
    // int p = 10000000;
    // vector<bool> is_prime(p, true);
    // for (int i = 2; i < p; ++i)
    // {
    //     if (!is_prime[i])
    //         continue;
    //     primes.push_back(i);
    //     for (int j = i + i; j < p; j += i)
    //     {
    //     is_prime[j] = false;
    // }
    // }

    for (int t = 1; t <= tc; t++)
    {
        // cout << "Case #" << t << ": ";
        solve();
    }
}


#include<iostream>

#include<cstring>

#include<vector>

#include<map>

#include<queue>

#include<unordered_map>

#include<cmath>

#include<cstdio>

#include<algorithm>

#include<set>

#include<cstdlib>

#include<stack>

#include<ctime>

#define forin(i,a,n) for(int i=a;i<=n;i++)

#define forni(i,n,a) for(int i=n;i>=a;i--)

#define fi first

#define se second

using namespace std;

typedef long long ll;

typedef double db;

typedef pair<int,int> PII;

const double eps=1e-7;

const int N=6e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7;

inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}

while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}

void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}

template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}

template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}

int T;

int n,m,k;

int a[N],b[N];

int la[N],lb[N];

void solve() {

    n=read(),m=read(),k=read();

    for(int i=1;i<=n;i++) a[i]=read();

    for(int i=1;i<=m;i++) b[i]=read();

    vector<int> vec;

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

        if(k%i==0) {

            vec.push_back(i);

            if(i!=k/i) vec.push_back(k/i);

        }

    }

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

    int last=0;

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

        if(a[i]==1) last++;

        else {

            int temp=last;

            for(int j=1;j<=temp;j++) la[j]+=last--;

            last=0;

        }

    }

    if(last!=0) {

        int temp=last;

        for(int j=1;j<=temp;j++) la[j]+=last--;

    }

    last=0;

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

        if(b[i]==1) last++;

        else {

            int temp=last;

            for(int j=1;j<=temp;j++) lb[j]+=last--;

            last=0;

        }

    }

    if(last!=0) {

        int temp=last;

        for(int j=1;j<=temp;j++) lb[j]+=last--;

    }

    ll ans=0;

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

        int l=vec[i],r=k/vec[i];

        if(l>=1&&l<=n&&r>=1&&r<=m) {

            ans+=(ll)la[l]*lb[r];

        }

    }

    printf("%lld\n",ans);

}

int main() {

    // init();

    // stin();

    // scanf("%d",&T);

    T=1;

    while(T--) solve();

    return 0;

}


D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules:  He starts at the top-left cell in the grid;  In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to:   in the case 'U' to the cell (i−1,j)(i−1,j);  in the case 'D' to the cell (i+1,j)(i+1,j);  in the case 'L' to the cell (i,j−1)(i,j−1);  in the case 'R' to the cell (i,j+1)(i,j+1);   He wants to run exactly kk kilometers, so he wants to make exactly kk moves;  Bashar can finish in any cell of the grid;  He can't go out of the grid so at any moment of the time he should be on some cell;  Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):

#include<bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

//#include<boost/algorithm/string.hpp>

//pragmas

#pragma GCC optimize("O3")

//types

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

#define ll long long int

#define ull unsigned long long int

#define vec vector<long long int>

#define pall pair<long long int, long long int>

#define vecpair vector<pair<long long int,long long int>>

#define vecvec(a, i, j) vector<vector<long long int>> a (i, vec (j, 0))

#define vecvecvec(a, i, j, k) vector<vector<vector<long long int>>> dp (i + 1, vector<vector<long long int>>(j + 1, vector<long long int>(k + 1, 0)))

using namespace std;

using namespace __gnu_pbds;

//random stuff

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

#define read(a) for (auto &x : a) cin >> x

#define endl "\n"

#define pb push_back

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

#define print(a) for(auto x : a) cout << x << " "; cout << endl

#define sp " "

ll INF = 9223372036854775807;

typedef tree<long long int, null_type, less<long long int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;

struct custom_hash {

    static uint64_t splitmix64(uint64_t x) {

        x += 0x9e3779b97f4a7c15;

        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;

        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;

        return x ^ (x >> 31);

    }

    size_t operator()(uint64_t x) const {

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

        return splitmix64(x + FIXED_RANDOM);

    }

};

#define safe_map unordered_map<long long, int, custom_hash>

//debug

void __print(int x) {cerr << x;}

void __print(long x) {cerr << x;}

void __print(long long x) {cerr << x;}

void __print(unsigned x) {cerr << x;}

void __print(unsigned long x) {cerr << x;}

void __print(unsigned long long x) {cerr << x;}

void __print(float x) {cerr << x;}

void __print(double x) {cerr << x;}

void __print(long double x) {cerr << x;}

void __print(char x) {cerr << '\'' << x << '\'';}

void __print(const char *x) {cerr << '\"' << x << '\"';}

void __print(const string &x) {cerr << '\"' << x << '\"';}

void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>

void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}

template<typename T>

void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}

void _print() {cerr << "]\n";}

template <typename T, typename... V>

void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}

#ifndef ONLINE_JUDGE

#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)

#define reach cerr<<"reached"<<endl

#else

#define debug(x...)

#define reach

#endif

/*---------------------------------------------------------------------------------------------------------------------------*/

ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}

ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}

void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3

ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b

ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);}

bool revsort(ll a, ll b) {return a > b;}

void swap(int &x, int &y) {int temp = x; x = y; y = temp;}

ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;}

void google(int t) {cout << "Case #" << t << ": ";}

vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (ll j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}

ll mod_add(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}

ll mod_mul(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}

ll mod_sub(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}

ll mod_div(ll a, ll b, ll m = 1000000007) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;}  //only for prime m

ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N))

void precision(int a) {cout << setprecision(a) << fixed;}

ll ceil_div(ll x, ll y){return (x + y - 1) / y;}

unsigned long long power(unsigned long long x,ll y, ll p){unsigned long long res = 1;x = x % p; while (y > 0){if (y & 1)res = (res * x) % p;y = y >> 1;x = (x * x) % p;}return res;}

unsigned long long modInverse(unsigned long long n,int p){return power(n, p - 2, p);}

ll nCr(ll n,ll r, ll p){if (n < r)return 0;if (r == 0)return 1;unsigned long long fac[n + 1];fac[0] = 1;for (int i = 1; i <= n; i++)fac[i] = (fac[i - 1] * i) % p;return (fac[n] * modInverse(fac[r], p) % p* modInverse(fac[n - r], p) % p)% p;}

ll accumulate(const vec &nums){ll sum = 0; for(auto x : nums) sum += x; return sum;}

ll tmax(ll a, ll b, ll c = 0, ll d = -INF, ll e = -INF, ll f = -INF){return max(a, max(b, max(c, max(d, max(e, f)))));}

int log2_floor(unsigned long long i) {return i ? __builtin_clzll(1) - __builtin_clzll(i) : -1;}

string bin(ll n){return bitset<32>(n).to_string();}

/*--------------------------------------------------------------------------------------------------------------------------*/

ll mod = 1000000007;

vector<pair<ll, string>> mv;

//code starts

int main()

{

    fastio();

    ll n, m, k;

    cin >> m >> n >> k;

    if(k <= 4 * n * m - 2 * (n + m))

    {

        cout << "YES" << endl;

        ll run = 0;

        if(n - 1)

        {

            mv.pb({min(k, n - 1), "R"});

            run += min(k, n - 1);

        }

        for(ll i = n; i > 1 and run < k; i --)

        {

            if((k - run)/3 == 0)

            {

                if(m - 1)

                {

                    if(k - run == 1)    mv.pb({1, "D"});

                    if(k - run == 2)    mv.pb({1, "DL"});

                    run += k - run;

                }

            }

            else if((k - run)/3 < m - 1)

            {

                ll down = (k - run)/3;  //go down by this much

                mv.pb({(k - run)/3, "DLR"});

                run += ((k - run)/3) * 3;

                if(down and run < k)

                {

                    mv.pb({1, "D"});

                    run ++;

                    if(k - run)

                    {

                        mv.pb({1, "U"});

                        run ++;

                    }

                }

            }

            else

            {

                if(m - 1)

                {

                    mv.pb({m - 1, "DLR"});

                    run += (m - 1) * 3;

                    if(run < k) //go back up

                    {

                        mv.pb({min(k - run, m - 1), "U"});

                        run += min(k - run, m - 1);

                    }

                }

            }

            if(run < k) //go left

            {

                mv.pb({1, "L"});

                run ++;

            }

        }

        if(run < k)

        {

            if(m - 1)

            {

                mv.pb({min(k - run, m - 1), "D"});

                run += min(k - run, m - 1);

                if(run < k)

                {

                    mv.pb({min(k - run, m - 1), "U"});

                    run += min(k - run, m - 1);

                }

            }

        }

        cout << size(mv) << endl;

        for(auto &x : mv)   cout << x.first << sp << x.second << endl;

    }

    else

        cout << "NO" << endl;

}

// There is an idea of a Patrick Bateman. Some kind of abstraction.

// But there is no real me. Only an entity. Something illusory.

// And though I can hide my cold gaze, and you can shake my hand and

// feel flesh gripping yours, and maybe you can even sense our lifestyles

// are probably comparable, I simply am not there.


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

/*+Rainybunny+*/

#include <bits/stdc++.h>

#define rep(i, l, r) for (int i = l, rep##i = r; i <= rep##i; ++i)
#define per(i, r, l) for (int i = r, per##i = l; i >= per##i; --i)

typedef std::pair<int, int> PII;
#define fi first
#define se second

const int MAXN = 20, IINF = 0x3f3f3f3f;
const int MOVE[4][2] = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } };
int n, m, deg[MAXN * MAXN + 5];
char maz[MAXN + 5][MAXN + 5], str[MAXN * 2 + 5][MAXN * 2 + 5];

inline bool inside(const int i, const int j) {
    return 1 <= i && i <= n && 1 <= j && j <= m;
}

inline int id(const int i, const int j) {
    return (i - 1) * m + j;
}

struct DSU {
    int fa[MAXN * MAXN + 5], siz[MAXN * MAXN + 5];
    inline void init() { rep (i, 1, n * m) siz[fa[i] = i] = 1; }
    inline int find(const int x) {
        return x == fa[x] ? x : fa[x] = find(fa[x]);
    }
    inline bool unite(int x, int y) {
        if ((x = find(x)) == (y = find(y))) return false;
        if (siz[x] < siz[y]) x ^= y ^= x ^= y;
        return siz[fa[y] = x] += siz[y], true;
    }
};

namespace MI { // Matroid Intersection.

// M1: deg>=2; M2: no circle.

std::vector<PII> U;
std::vector<int> ans, dis, L, R, T;
std::queue<int> que;
DSU dsu;

inline void initInd() {
    dsu.init();
    rep (i, 1, n) rep (j, 1, m) deg[id(i, j)] = (i + j) & 1 ? -IINF : 0;
    deg[1] = -IINF;
    rep (i, 0, int(U.size()) - 1) if (ans[i]) {
        dsu.unite(U[i].fi, U[i].se), ++deg[U[i].fi], ++deg[U[i].se];
    }
}

inline void build() {
    initInd();
    L.clear(), R.clear();
    T.clear(), T.resize(U.size());
    dis.clear(), dis.resize(U.size(), IINF);
    rep (i, 0, int(U.size()) - 1) {
        if (ans[i]) L.push_back(i);
        else {
            R.push_back(i);
            if (deg[U[i].fi] < 2 && deg[U[i].se] < 2) T[i] = true;
            if (dsu.find(U[i].fi) != dsu.find(U[i].se)) {
                que.push(i), dis[i] = 0;
            }
        }
    }
}

inline std::vector<int> augment() {
    int fin = -1;
    std::vector<int> pre(U.size(), -1);
    while (!que.empty()) {
        int u = que.front(); que.pop();
        if (T[u]) { fin = u; break; }
        if (ans[u]) {
            dsu.init();
            for (int x: L) if (x != u) dsu.unite(U[x].fi, U[x].se);
            for (int v: R) {
                if (dis[v] == IINF && dsu.find(U[v].fi) != dsu.find(U[v].se)) {
                    dis[v] = dis[u] + 1, pre[v] = u, que.push(v);
                }
            }
        } else {
            for (int v: L) if (dis[v] == IINF) {
                ++deg[U[u].fi], ++deg[U[u].se];
                --deg[U[v].fi], --deg[U[v].se];
                if (deg[U[u].fi] <= 2 && deg[U[u].se] <= 2
                  && deg[U[v].fi] <= 2 && deg[U[v].se] <= 2) {
                    dis[v] = dis[u] + 1, pre[v] = u, que.push(v);
                }
                --deg[U[u].fi], --deg[U[u].se];
                ++deg[U[v].fi], ++deg[U[v].se];
            }
        }
    }
    if (!~fin) return {};
    while (!que.empty()) que.pop();
    std::vector<int> ret;
    ret.push_back(fin);
    while (~pre[fin]) ret.push_back(fin = pre[fin]);
    return ret;
}

inline void solve() {
    ans.clear(), ans.resize(U.size());
    while (true) {
        build();
        auto&& res(augment());
        if (res.empty()) break;
        for (int id: res) ans[id] ^= 1;
    }
}

} // namespace MI.

int main() {
    int T; scanf("%d", &T);
    while (T--) {
        scanf("%d %d", &n, &m);
        rep (i, 1, n) scanf("%s", maz[i] + 1);

        MI::U.clear();
        rep (i, 1, n) rep (j, 1, m) {
            if (~(i + j) & 1 && id(i, j) != 1 && maz[i][j] == 'O') {
                rep (k, 0, 3) {
                    int x = i + MOVE[k][0], y = j + MOVE[k][1];
                    if (inside(x, y) && maz[x][y] == 'O') {
                        MI::U.emplace_back(id(i, j), id(x, y));
                    }
                }
            }
        }

        MI::solve();
        MI::initInd();
        rep (i, 1, n) rep (j, 1, m) {
            if (~(i + j) & 1 && id(i, j) != 1
              && maz[i][j] == 'O' && deg[id(i, j)] != 2) {
                puts("NO"); goto FIN;
            }
        }
        rep (i, 1, 2 * n - 1) {
            rep (j, 1, 2 * m - 1) {
                str[i][j] = i & 1 && j & 1 ? maz[i + 1 >> 1][j + 1 >> 1] : ' ';
            }
            str[i][2 * m] = '\0';
        }

        if (maz[1][2] == 'O') {
            MI::U.emplace_back(id(1, 1), id(1, 2)), MI::ans.push_back(0);
        }
        if (maz[2][1] == 'O') {
            MI::U.emplace_back(id(1, 1), id(2, 1)), MI::ans.push_back(0);
        }
        rep (i, 0, int(MI::U.size()) - 1) {
            if (MI::dsu.find(MI::U[i].fi) != MI::dsu.find(MI::U[i].se)) {
                MI::dsu.unite(MI::U[i].fi, MI::U[i].se);
                MI::ans[i] = true;
            }
        }
        rep (i, 1, n) rep (j, 1, m) {
            if (maz[i][j] == 'O' && MI::dsu.find(id(i, j))
              != MI::dsu.find(id(1, 1))) {
                puts("NO"); goto FIN;
            }
        }

        rep (i, 0, int(MI::U.size()) - 1) if (MI::ans[i]) {
            int b = (MI::U[i].fi - 1) % m + 1, a = (MI::U[i].fi - b) / m + 1;
            int d = (MI::U[i].se - 1) % m + 1, c = (MI::U[i].se - d) / m + 1;
            str[a + c - 1][b + d - 1] = 'O';
        }
        puts("YES");
        rep (i, 1, 2 * n - 1) puts(str[i] + 1);
        FIN: ;
    }
    return 0;
}


C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.

#include <bits/stdc++.h>
using namespace std;

void solve() {

	int n;
	cin >> n;
	vector<int>f(n);
	for(auto &i : f) cin >> i;
	vector<pair<double , int>>a;

	for(int i = 0 ; i < n ; i++) {
		pair<double , long long> kur = make_pair(f[i] , 1);

		while(!a.empty()) {
			if((a.back().first + kur.first) / (a.back().second + kur.second) < a.back().first / a.back().second) {
				kur.first += a.back().first , kur.second += a.back().second;
				a.pop_back();
			} else {
				break;
			}
		}

		a.push_back(kur);
	}

	for(auto [sum , knt] : a) {
		for(int i = 0 ; i < knt ; i++)
			cout << fixed << setprecision(10) << sum / knt << '\n';
	}

	return;
}

int main() {

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

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

    return 0;
}


B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)).  Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).

#include<bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        int n,m,x,mx=0;
        bool flag=0;
        cin>>n>>x;
        for(int i=1;i<=n;i++){
            cin>>m;
            if(m==x){
                flag=1;
            }
            mx=max(mx,m);
        }
        if(flag){
            cout<<1<<endl;
        }
        else{
            cout<<max(2,(mx+x-1)/mx)<<endl;//向下取整
        }
    }
    return 0;
}


E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
OutputCopy1 2
1 1
1 1 1

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

struct LCA {

    vi par,d,jmp,in,out;

    vector<basic_string<int>> adj;

    LCA(int n) : par(n),d(n),jmp(n),in(n),out(n),adj(n) {}

    void add(int i) {

        int p = par[i];

        d[i]=1+d[p];

        if(d[p] - d[jmp[p]] == d[jmp[p]] - d[jmp[jmp[p]]]) jmp[i] = jmp[jmp[p]];

        else jmp[i] = p;

    }

    int jump(int a, int k) {

        int D = max(0,d[a]-k);

        while(d[a]>D) {

            if(d[jmp[a]]>=D) a = jmp[a];

            else a = par[a];

        }

        return a;

    }

    int lca(int a, int b) {

        if(d[a]<d[b]) swap(a,b);

        a = jump(a,d[a]-d[b]);

        while(a!=b) {

            if(jmp[a]!=jmp[b]) a=jmp[a],b=jmp[b];

            else a=par[a],b=par[b];

        }

        return a;

    }

    void addE(int u, int v) {

        adj[u].push_back(v);

        adj[v].push_back(u);

    }

    int cnt=0;

    void dfs(int at) {

        in[at]=cnt++;

        for(int to: adj[at]) if(to!=par[at])  {

            par[to]=at;

            add(to);

            dfs(to);

        }

        out[at]=cnt;

    }

    void init() {

        dfs(0);

    }

};

struct virtualtree { // gives weighted subtree that connects all the nodes in vv in O(|vv| log(n))

    vector<vector<pi>> adj;

    vi v;

    int n;

    int size() {return n;}

    virtualtree (const vi& vv, LCA& lca) : v(vv) {

        sort(all(v),[&](int i, int j) {return lca.in[i]<lca.in[j];});

        n = v.size();

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

            v.push_back(lca.lca(v[i],v[i+1]));

        }

        sort(all(v),[&](int i, int j) {return lca.in[i]<lca.in[j];});

        v.erase(unique(all(v)),v.end());

        n=v.size();

        adj.resize(n);

        vi st;

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

            int at = v[i];

            while(!st.empty() and lca.out[v[st.back()]]<=lca.in[at]) {

                st.pop_back();

            }

            if(!st.empty()) {

                int par = st.back(), w = lca.d[at]-lca.d[v[st.back()]];

                adj[par].push_back({i,w});

                adj[i].push_back({par,w});

            }

            st.push_back(i);

        }

    }

};

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int n; cin >> n;

    LCA lca(n);

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

        int x,y; cin >> x >> y;

        --x,--y;

        lca.addE(x,y);

    }

    lca.init();

    int q; cin >> q;

    vi who(n),ans(n);

    while(q--) {

        int k,m; cin >> k >> m;

        vi s(k);

        vi v(k+m);

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

            cin >> v[i];

            v[i]--;

            cin >> s[i];

        }

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

            cin >> v[i];

            --v[i];

        }

        virtualtree vt(v,lca);

        for(int i=0;i<vt.n;++i) who[vt.v[i]]=i;

        struct event {

            int time, at,virusid,extra;

            bool operator<(const event& o) const {

                return make_pair(time,virusid)>make_pair(o.time,o.virusid);

            }

        };

        priority_queue<event> pq;

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

            pq.push({0,who[v[i]],i,0});

        }

        vector<bool> vis(vt.n);

        while(!pq.empty()) {

            auto e = pq.top(); pq.pop();

            if(vis[e.at]) continue;

            vis[e.at]=1;

            ans[vt.v[e.at]]=e.virusid+1;

            for(auto [to,w] : vt.adj[e.at]) {

                int need = max(0, (w-e.extra + s[e.virusid]-1)/s[e.virusid]); // ceil division

                pq.push({e.time+need,to,e.virusid,e.extra+need*s[e.virusid]-w});

            }

        }

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

            cout << ans[v[i]] << ' ';

        } cout << '\n';

    }

}