C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment:  With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment:  With this assignment, all non-zero mex value are listed below:   mex(1,3)=1mex(1,3)=1  mex(1,5)=2mex(1,5)=2  mex(2,3)=1mex(2,3)=1  mex(2,5)=2mex(2,5)=2  mex(3,4)=1mex(3,4)=1  mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.

//0 1 1 0 1

//0 1 0 0 1

//1 0 0 1 1

//0 1 1 0 1

//uoy kcuf;

#include <bits/stdc++.h>

#pragma GCC optimize("Ofast")

#pragma GCC optimize("unroll-loops")

using namespace std;

#define F 			first

#define S 			second

#define pb 			push_back

#define sze			size()

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

#define wall__		cout << "--------------------------------------\n";

#define node		int mid = (tl + tr) >> 1, cl = v << 1, cr = v << 1 | 1

#define file_io		freopen("input.cpp", "r", stdin) ; freopen("output.cpp", "w", stdout);

typedef long long ll;

typedef long double dl;

typedef pair < int , int > pii;

typedef pair < int , ll > pil;

typedef pair < ll , int > pli;

typedef pair < ll , ll > pll;

typedef pair < int , pii > piii;

typedef pair < ll, pll > plll;

const ll N = 3e3 + 10;

const ll mod = 1e9 + 7;

const ll inf = 2e16;

const ll rinf = -2e16;

const ll INF = 1e9 + 10;

const ll rINF = -1e9 - 10;

const ll lg = 12;

ll n, subtree[N], val[N][N], dp[N][N], st[N], en[N], timer, parent[N], par[lg][N], lca[N][N], dis[N][N], h[N], ppp[N][N];

vector < int > g[N];

vector < pii > len[N];

void dfs (int v, int p) {

	st[v] = ++timer;

	parent[v] = p;

	par[0][v] = p;

	h[v] = h[p] + 1;

	for (int i = 1; i < lg; i++) par[i][v] = par[i - 1][par[i - 1][v]];

	subtree[v] = 1;

	for (auto u : g[v]) {

		if (p == u) continue;

		dfs (u, v);

		subtree[v] += subtree[u];

	}

	en[v] = ++timer;

}

bool be_anc (int v, int u) {

	if (st[v] <= st[u] && en[u] <= en[v]) return 1;

	return 0;

}

int get_par (int v, int u) {

	if (be_anc(u, v)) swap(v, u);

	for (int i = lg - 1; i >= 0; --i) {

		if (!be_anc(par[i][u], v)) u = par[i][u];

	}

	return u;

}

void solve() {

	cin >> n;

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

		int v, u; cin >> v >> u;

		g[v].pb(u);

		g[u].pb(v);

	}

	st[0] = -1;

	en[0] = INF;

	dfs (1, 0);

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

		val[i][i] = subtree[i] * (n - subtree[i] + 1);

		lca[i][i] = i;

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

			int pp = get_par(i, j);

			ppp[i][j] = ppp[j][i] = pp;

			int lc = par[0][pp];

			if (i == lc) val[i][j] = subtree[j] * (n - subtree[pp]);

			else if (j == lc) val[i][j] = subtree[i] * (n - subtree[pp]);

			else {

				val[i][j] = subtree[i] * subtree[j];

			}

			lca[i][j] = lca[j][i] = lc;

			dis[i][j] = h[i] + h[j] - (2 * h[lc]);

			len[dis[i][j]].pb({i, j});

			val[j][i] = val[i][j];

		}

		dp[i][i] = 0;

	}

	// cout << "lca = \n";

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

	// 	cout << i << " : ";

	// 	for (int j = 1; j <= n; j++) cout << j << " = " << lca[i][j] << " , " << val[i][j] << " | ";

	// 	cout << '\n';

	// }

	// wall__

	// cout << "subtree = ";for (int i = 1; i <= n; i++) cout << i << " , " << subtree[i] << " | "; cout << '\n';

	// wall__

	ll ans = 0;

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

		if (len[i].sze == 0) continue;

		for (auto e : len[i]) {

			int v = e.F;

			int u = e.S;

			if (lca[v][u] == v)

				dp[v][u] = max(dp[v][parent[u]] + val[v][u], dp[ppp[v][u]][u] + val[v][u]);

			else if (lca[v][u] == u)

				dp[v][u] = max(dp[parent[v]][u] + val[v][u], dp[v][ppp[u][v]] + val[v][u]);

			else

				dp[v][u] = max(dp[parent[v]][u] + val[v][u], dp[v][parent[u]] + val[v][u]);

			dp[u][v] = dp[v][u];

			ans = max(ans, dp[v][u]);

		}

	}

	cout << ans;

}

int main() {

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

	int t = 1;

	// cin >> t;

	while (t--) {solve();}

    return 0;

}

/*

*/


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;

typedef long long int ll;

typedef vector<ll> vll;

typedef pair<ll, ll> pll;

typedef vector<pll> vpll;

typedef map<ll, ll> mll;

#define N 200'006

#define MOD 1000000007

#define FOR(i, n) for (i = 0; i < n; i++)

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

#define FASTIO                        \

    ios_base::sync_with_stdio(false); \

    cin.tie(NULL);

#define FREOPEN                  \

    freopen("i.in", "r", stdin); \

    freopen("o.out", "w", stdout);

#define gohome      \

    cout << "NO\n"; \

    return;

#define arprt(x)           \

    for (auto it : x)      \

        cout << it << " "; \

    cout << "\n";

int main()

{

    FASTIO

    ll i, j, n, m, p = -1;

    cin >> n >> m;

    ll a[n];

    ll trips = 0;

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

    {

        trips += i / 2;

        if (trips > m)

        {

            trips -= i / 2;

            p = i - 1;

            break;

        }

    }

    if (p == -1)

    {

        if (trips == m)

        {

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

                cout << i << " ";

        }

        else

            cout << -1;

        return 0;

    }

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

        a[i] = i + 1;

    ll t = m - trips;

    a[p + 1] = 2 * (p + 1) - 2 * t + 1;

    for (i = p + 2; i < n; i++)

    {

        a[i] = N * i + 1;

    }

    arprt(a);

    return 0;

}


B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

#define endl '\n'

const int maxn=2*1e5+11;

const int Maxx=1e5+11;

const int mod=1e9+7;

int t;

int n;

int p[2005],c[2005];

vector<int>son[2005];

int ans[2005];

int f;

vector<int> dfs(int x)

{

    vector<int>tmp;

    for(auto P:son[x])

    {

        vector<int>res=dfs(P);

        tmp.insert(tmp.end(),res.begin(),res.end());

    }

    if(c[x]>int(tmp.size())) {f=1;return tmp;}

    tmp.insert(tmp.begin()+c[x],x);

    return tmp;

}

void solve()

{

     cin>>n;

     int root=0;

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

     {

         cin>>p[i]>>c[i];

         if(!p[i]) root=i;

         else son[p[i]].push_back(i);

     }

     f=0;

     vector<int>res=dfs(root);

     if(f) {cout<<"NO"<<endl;return;}

     cout<<"YES"<<endl;

     for(int i=0;i<int(res.size());++i) ans[res[i]]=i+1;

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

     {

         cout<<ans[i]<<" ";

     }

     cout<<endl;

}

int main()

{

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

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

    //ios::sync_with_stdio(false);cin.tie(0);cin>>t;while(t--)

    solve();

    return 0;

}


A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.

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

using ll = long long;

int main()
{
    int n; cin >> n;
    vector<array<int, 2>> A(n);
    for (auto& [x, y] : A)
        cin >> x;
    for (auto& [x, y] : A)
        cin >> y;
    sort(A.begin(), A.end());

    multiset<array<int, 2>, std::greater<>> Q;
    int s = 0;
    ll res{};
    int i = 0;
    while (i < (int)A.size() || !Q.empty())
    {
        while (i < (int)A.size() && A[i][0] == s)
        {
            Q.insert({A[i][1], A[i][0]});
            i++;
        }

        if (Q.empty())
        {
            s = A[i][0];
            continue;
        }
        auto [cost, val] = *Q.begin();
        res += (ll)(s - val) * cost;
        Q.erase(Q.begin());
        s++;
    }
    std::cout << res << '\n';
}


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

#include <bits/stdc++.h>

using namespace std;

int main() {

    int t;

    cin >> t; // Taking the number of test case

    while (t--) {

        // Declaring and taking input in three string variable

        string str1, str2, str3;

        cin >> str1 >> str2 >> str3;

        // looping through all strings and compareing their words in same position

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

            if (str1[i] == str3[i]) {

                str2[i] = str3[i]; // if string1[i] == string3[i] then string2[i] = string3[i]

            } else if (str2[i] == str3[i]) {

                str1[i] = str3[i]; // if string2[i] == string3[i] then string1[i] = string3[i]

            } else {

                str1[i] = str3[i]; // If none of them are true then just do string1[i] = string3[i]

            }

        }

        if (str1 == str2) {

            cout << "YES" << endl;

        } else {

            cout << "NO" << endl;

        }

    }

    return 0;

}


D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7

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

typedef double ld;
typedef long long ll;
#define f first
#define s second

const int N=500;
int n,m;

struct pt{
  int x,y;
};

pt R[N], B[N];
int cnt[N][N];

int main(){
  cin.tie(0)->sync_with_stdio(0);

  cin >> n >> m;
  for(int i=0; i<n; i++){
    cin >> R[i].x >> R[i].y;
  }
  for(int i=0; i<m; i++){
    cin >> B[i].x >> B[i].y;
  }
  sort(R, R+n, [&](pt a, pt b){ return a.y<b.y; });
  sort(B, B+m, [&](pt a, pt b){ return a.y<b.y; });

  for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
      for(int k=0; k<m; k++){
        if(!(R[i].y<=B[k].y && B[k].y<R[j].y)) continue;
        pair<int,int> u={R[j].x-R[i].x, R[j].y-R[i].y};
        pair<int,int> v={B[k].x-R[j].x, B[k].y-R[j].y};
        cnt[i][j]+=ll(u.f)*v.s-ll(u.s)*v.f>0;
      }
    }
  }

  int ans=0;
  for(int i=0; i<n; i++){
    for(int j=i+1; j<n; j++){
      for(int k=j+1; k<n; k++){
        ans+=cnt[i][j]+cnt[j][k]==cnt[i][k];
      }
    }
  }
  cout << ans;
}


F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.

// CALL ME DADDY
//	Whispering makes everything sound way sexier,
//	unless you're like 'Can you pass the salt'
#include<bits/stdc++.h>
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL)
#define ll long long int
#define rep(i,n) for(ll i=0;i<n;i++)
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mod 1000000007
#define nl '\n'
#define vll vector<ll>
#define scanit(vvv,nnn) for(ll i=0; i<nnn; i++) cin>>vvv[i];
#define ff first
#define ss second
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename K, typename V, typename Comp = less<K>> using indexed_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;
template <typename K, typename Comp = less<K>> using indexed_set = indexed_map<K, null_type, Comp>;

 void solve(){
             int n;cin>>n;
             vector<int> v(n);scanit(v,n);
             vector<vector<int>> adj(n+1);
             for(int i=0;i<n-1;i++){
                 int a,b;cin>>a>>b;
                 a--;b--;
                 adj[a].pb(b);
                 adj[b].pb(a);
             }
             vector<int> dis(n,0);
             rep(i,n){
                 if(v[i]==1) v[i] = 1;
                 else v[i] = -1;
             }
             function<void(int,int)> dfs1 = [&](int x,int y){
                 dis[x] += v[x];
                 for(auto i : adj[x]){
                     if(i==y) continue;
                     dfs1(i,x);
                     dis[x] += max(0,dis[i]);
                 }
             };
             dfs1(0,-1);
            //  for(auto i : dis){
            //      cout<<i<<" ";
            //  }cout<<nl;
             function<void(int,int)> dfs = [&](int x,int y){

                 for(auto i : adj[x]){
                     if(i==y) continue;
                     dis[i] += max(dis[x] - max(0,dis[i]) ,0);
                     dfs(i,x);
                 }

             };
             dfs(0,-1);
             for(auto i : dis){
                 cout<<i<<" ";
             }cout<<nl;

    }

int main(){
    fast;
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    freopen("err.txt", "w", stderr);
#endif
    ll testcase = 1;
    // cin >> testcase;
    while (testcase--){
        solve();
    }
    return 0;
}


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

#include<bits/stdc++.h>

#include<ext/pb_ds/assoc_container.hpp>

#include<ext/pb_ds/tree_policy.hpp>

using namespace std;

using namespace __gnu_pbds;

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

#define endl '\n'

#define int long long

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

#define pb push_back

#define mod 1000000007

#define inf 1e18

#define ppb pop_back

#define ff first

#define ss second

///  order_of_key return number of elements less than x -> os.order_of_key(x)

///  cout << "oth element  : " << *os.find_by_order(0) << endl; so it returns value of index

int lcm(int x,int y)

{

    return (x * 1LL * y) / __gcd(x,y);

}

// Graph on 2D Grid

/*----------------------Graph Moves----------------*/

//const int dx[]={+1,-1,+0,+0};

//const int dy[]={+0,+0,+1,-1};

//const int dx[]={+0,+0,+1,-1,-1,+1,-1,+1};   // Kings Move

//const int dy[]={-1,+1,+0,+0,+1,+1,-1,-1};  // Kings Move

//const int dx[]={-2, -2, -1, -1,  1,  1,  2,  2};  // Knights Move

//const int dy[]={-1,  1, -2,  2, -2,  2, -1,  1}; // Knights Move

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

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

void _print(int t) {cerr << t;}

void _print(string t) {cerr << t;}

void _print(char t) {cerr << t;}

void _print(double t) {cerr << t;}

template <class T, class V> void _print(pair <T, V> p);

template <class T> void _print(vector <T> v);

template <class T> void _print(set <T> v);

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

template <class T> void _print(multiset <T> v);

template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}

template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}

template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}

template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}

template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}

void solve()

{

    string s,ans;

    int n,i;

    cin >> n >> s;

    char mx = 'a',one = 'a';

    for(auto it : s)

    {

        if(it >= mx)

        {

            mx = it;

            ans += '0';

        }

        else if(it >= one)

        {

            one = it;

            ans += '1';

        }

        else

        {

            cout << "NO" << endl;

            return ;

        }

    }

    cout << "YES" << endl;

    cout << ans << endl;

}

int32_t main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int t= 1;

    while(t--)

    {

        solve();

    }

}

/**

Test Case :

**/


B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.

#ifdef LOCAL
    #define _GLIBCXX_DEBUG
#endif
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
#define sz(s) ((int)s.size())
#define all(v) begin(v), end(v)

typedef long double ld;
const int MOD = 1000000007;
#define ff first
#define ss second

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

// *-> KISS*
int solve() {
    ll n, g, b; cin >> n >> g >> b;
    ll num = (n + 1) / 2, leftOut = n - num;
    ll how1 = num / g, how2 = num % g;
    ll ans = 0;
    if(how2 == 0) {
        ll ok = (how1 - 1) * b;
        leftOut = max(0LL, leftOut - ok);
        ans += ok + how1 * g;
        ans += leftOut;
    }
    else {
        if(how1 == 0) {
            ans = n;
        }
        else {
            ll ok = (how1) * b;
            leftOut = max(0LL, leftOut - ok);
            ans += ok + how1 * g;
            ans += how2;
            ans += leftOut;
        }
    }
    cout << ans;
    return 0;
}
int32_t main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int TET = 1;
    cin >> TET;
    cout << fixed << setprecision(6);
    for (int i = 1; i <= TET; i++) {
        #ifdef LOCAL
            cout << "##################" << '\n';
        #endif
        if (solve()) {
            break;
        }
        cout << '\n';
    }
    #ifdef LOCAL
        cout << endl << "finished in " << clock() * 1.0 / CLOCKS_PER_SEC << " sec" << endl;
    #endif
    return 0;
}
// -> Keep It Simple Stupid!


C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10


B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:

#include <bits/stdc++.h>

#define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)

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

#define fxd(x) fixed << setprecision(x)

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

#define lwb lower_bound

#define upb upper_bound

#define dl double long

#define ll long long

#define pb push_back

#define sz() size()

#define F first

#define S second

using namespace std;

const ll N = 1e2+9;

void solve() {

	vector <char> v;

	ll n;

	cin >> n;

	pair <int , int> p[n+9];

	for (int i = 1 ; i <= n ; i++)cin >> p[i].F >> p[i].S;

	sort (p+1 , p+1+n);

	ll x1=p[1].F , x2=p[1].S;

	while (x1--)v.pb('R');

	while (x2--)v.pb('U');

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

		if (p[i].F>p[i-1].F&&p[i].S<p[i-1].S){

			cout << "NO\n";

			return;

		}

		if (p[i].F==p[i-1].F){

			ll x=p[i].S-p[i-1].S;

			while(x--)v.pb('U');

		}

		if (p[i].F>p[i-1].F&&p[i].S==p[i-1].S){

			ll x=p[i].F-p[i-1].F;

			while (x--)v.pb('R');

		}

		if (p[i].F!=p[i-1].F&&p[i].S!=p[i-1].S){

			ll x=p[i].F-p[i-1].F;

			while (x--)v.pb('R');

			x=p[i].S-p[i-1].S;

			while (x--)v.pb('U');

		}

	}

	cout << "YES\n";

	for (int i = 0 ; i < v.sz() ; i++)cout << v[i];

	cout << "\n";

}

signed main() {

    optimus_prime;

    ll t;

    cin >> t;

    while (t--)solve();

return 0;

}


A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey:  c=[1,2,4]c=[1,2,4];  c=[3,5,6,8]c=[3,5,6,8];  c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N  = 1e6 + 3;

int main()

{

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

    cout.tie(0);cout.sync_with_stdio(0);

    int n;

    cin >> n;

    map<ll , ll > fr;

    ll ans =0 ;

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

        int x;

        cin >> x;

        fr[x - i] += x;

        ans = max(ans , fr[x-i] ) ;

    }

    cout << ans ;

    return 0;

}


#include <bits/stdc++.h>

using namespace std;

//hello

#define int long long

#define inf (1ll<<60)

#define pii pair<int,int>

int32_t N = 2e6 + 5;

int32_t mod = 1e9 + 7;

void dfs1(int v, int p, vector<int> &a, vector<vector<int>> &adj, vector<int> &cnt)

{

    cnt[v] = a[v];

    for(auto u : adj[v])

    {

        if(u != p)

        {

            dfs1(u,v,a,adj,cnt);

            cnt[v] += max(0ll,cnt[u]);

        }

    }

}

void dfs2(int v, int p, vector<int> &a, vector<vector<int>> &adj, vector<int> &cnt, vector<int> &ans)

{

    ans[v] = cnt[v];

    for(auto u : adj[v])

    {

        if(u != p)

        {

            cnt[v] -= max(0ll,cnt[u]);

            cnt[u] += max(0ll,cnt[v]);

            dfs2(u,v,a,adj,cnt,ans);

            cnt[u] -= max(0ll,cnt[v]);

            cnt[v] += max(0ll,cnt[u]);

        }

    }

}

void solveCase()

{

    int n=0;

    cin >> n;

    vector<int> a(n+1);

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

    {

        cin >> a[i];

        a[i] = a[i]==0 ? -1 : a[i];

    }

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

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

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

    {

        int u=0, v=0;

        cin >> u >> v;

        adj[u].push_back(v);

        adj[v].push_back(u);

    }

    dfs1(1,-1,a,adj,cnt);

    dfs2(1,-1,a,adj,cnt,ans);

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

        cout << ans[i] << " ";

    cout << "\n";

}

int32_t main()

{

    ios::sync_with_stdio(false), cin.tie(NULL);

    int t = 1;

    // cin >> t;

    while (t--)

        solveCase();

}


D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No


E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213

#include<iostream>

#include<cstring>

#include<cmath>

#include<algorithm>

using namespace std;

using LL = long long;

using point_t = long long; //全局数据类型，可修改为 long long 等

const point_t eps = 1e-8;

const long double PI = acosl(-1);

// 点与向量

template <typename T>

struct point{

    T x, y;

    bool operator==(const point &a) const { return (abs(x - a.x) <= eps && abs(y - a.y) <= eps); }

    bool operator<(const point &a) const{

        if (abs(x - a.x) <= eps)

            return y < a.y - eps;

        return x < a.x - eps;

    }

    bool operator>(const point &a) const { return !(*this < a || *this == a); }

    point operator+(const point &a) const { return {x + a.x, y + a.y}; }

    point operator-(const point &a) const { return {x - a.x, y - a.y}; }

    point operator-() const { return {-x, -y}; }

    point operator*(const T k) const { return {k * x, k * y}; }

    point operator/(const T k) const { return {x / k, y / k}; }

    T operator*(const point &a) const { return x * a.x + y * a.y; } // 点积

    T operator^(const point &a) const { return x * a.y - y * a.x; } // 叉积，注意优先级

    int toleft(const point &a) const

    {

        const auto t = (*this) ^ a;

        return (t > eps) - (t < -eps);

    }                                                             // to-left 测试

    T len2() const { return (*this) * (*this); }                  // 向量长度的平方

    T dis2(const point &a) const { return (a - (*this)).len2(); } // 两点距离的平方

    // 涉及浮点数

    long double len() const { return sqrtl(len2()); }                                                                      // 向量长度

    long double dis(const point &a) const { return sqrtl(dis2(a)); }                                                       // 两点距离

    long double ang(const point &a) const { return acosl(max(-1.0l, min(1.0l, ((*this) * a) / (len() * a.len())))); }      // 向量夹角

    point rot(const long double rad) const { return {x * cos(rad) - y * sin(rad), x * sin(rad) + y * cos(rad)}; }          // 逆时针旋转（给定角度）

    point rot(const long double cosr, const long double sinr) const { return {x * cosr - y * sinr, x * sinr + y * cosr}; } // 逆时针旋转（给定角度的正弦与余弦）

};

using Point = point<point_t>;

// 极角排序

struct argcmp

{

    bool operator()(const Point &a, const Point &b) const

    {

        const auto quad = [](const Point &a)

        {

            if (a.y < -eps)

                return 1;

            if (a.y > eps)

                return 4;

            if (a.x < -eps)

                return 5;

            if (a.x > eps)

                return 3;

            return 2;

        };

        const int qa = quad(a), qb = quad(b);

        if (qa != qb)

            return qa < qb;

        const auto t = a ^ b;

        // if (abs(t)<=eps) return a*a<b*b-eps;  // 不同长度的向量需要分开

        return t > eps;

    }

};

const int maxn = 5005;

Point p[maxn], v[maxn];

int main(){

#ifdef LOCAL

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

    freopen("data.out", "w", stdout);

#endif

    cin.tie(0);

    cout.tie(0);

    ios::sync_with_stdio(0);

    int n;

    cin >> n;

    LL C5 = 1;

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

        C5 = C5 * (n - i + 1) / i;

    auto C3 = [](int x){

        return 1LL * x * (x - 1) * (x - 2) / 6;

    };

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

        cin >> p[i].x >> p[i].y;

    LL cnt = 0;

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

        int tot = 0;

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

            if (i == j) continue;

            v[++tot] = p[j] - p[i];

        }

        sort(v + 1, v + tot + 1, argcmp());

        for(int j = 1; j <= tot; j++) v[j + tot] = v[j];

        for(int j = 1, k = 2; j <= tot; j++){

            while(k < j + tot && (v[j] ^ v[k]) >= 0) k++;

            int c1 = k - j - 1;

            int c2 = tot - c1 - 1;

            cnt += C3(c1) + C3(c2);

        }

    }

    cout << C5 * 5 - cnt / 2 << '\n';

}


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

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

#define gc()(xS==xTT&&(xTT=(xS=xB)+fread(xB,1,1<<20,stdin),xS==xTT)?0:*xS++)

#define pc(x)(p3-obuf<1000000)?(*p3++=x):(fwrite(obuf,p3-obuf,1,stdout),p3=obuf,*p3++=x)

using namespace std;typedef long long ll;typedef double db;typedef long double ld;typedef unsigned long long ull;typedef unsigned int ui;char xch,xB[1<<20],*xS=xB,*xTT=xB,obuf[1000000],*p3=obuf;inline ll read(){char ch=gc();ll x=0,f=1;while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}while('0'<=ch&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=gc();}return x*f;}static char cc[20];template<typename item>inline void pt( item x){ int len=0;if(!x)pc('0');if(x<0)x=-x,pc('-');while(x)cc[len++]=x%10+'0',x/=10;while(len--)pc(cc[len]);}inline void pS(string s){for(int i=0;i<s.length();i++)pc(s[i]);}inline ll read2(){char ch=gc();ll x=0,f=1;while(ch<'0'||ch>'1'){if(ch=='-')f=-1;ch=gc();}while('0'<=ch&&ch<='9'){x=(x<<1)+(ch^48);ch=gc();}return x*f;}

const int maxn=410,maxh=25;

int h,w,n,a[maxh][maxh],T,tx[4]={0,0,1,-1},ty[4]={1,-1,0,0},hd,u[maxn<<2],v[maxn<<2],cnt,du[maxn],pre[maxn<<2],rt[maxn];bool isx[maxn<<2],isy[maxn<<2],xz[maxn<<2],vis[maxn<<2];char ans[maxh<<1][maxh<<1];

int go(){char c=gc();while(c!='O'&&c!='X')c=gc();return c=='X';}

bool in(int x,int y){return x>=1&&x<=h&&y>=1&&y<=w;}

int get(int x,int y){return (x-1)*w+y;}

int fr(int p){return rt[p]==p?p:rt[p]=fr(rt[p]);}

bool mg(int x,int y)

{

	x=fr(x),y=fr(y);

	if(x==y)return 0;

	rt[y]=x;return 1;

}

bool zg()

{

	memset(isx,0,sizeof isx),memset(isy,0,sizeof isy),memset(pre,0,sizeof pre),memset(du,0,sizeof du),memset(vis,0,sizeof vis);

	queue<int>Q;

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

	for(int i=1;i<=cnt;i++)if(xz[i])du[u[i]]++,du[v[i]]++,mg(u[i],v[i]);

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

	{

		if(xz[i])continue;

		if(fr(u[i])!=fr(v[i]))isx[i]=1,Q.push(i),vis[i]=1;

		if(du[u[i]]<2)

		{

			isy[i]=1;

			if(isx[i]){xz[i]=1;return 1;}

		}

	}

	while(!Q.empty())

	{

		int p=Q.front();Q.pop();

		if(isy[p])

		{

			while(p)xz[p]^=1,p=pre[p];

			return 1;

		}

		if(xz[p])

		{

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

			for(int i=1;i<=cnt;i++)if(xz[i]&&i!=p)mg(u[i],v[i]);

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

			{

				if(xz[i]||vis[i]||fr(u[i])==fr(v[i]))continue;

				pre[i]=p,vis[i]=1,Q.push(i);

			}

		}

		else

		{

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

			{

				if(!xz[i]||vis[i]||du[u[p]]-(u[i]==u[p])>=2)continue;

				pre[i]=p,vis[i]=1,Q.push(i);

			}

		}

	}

	return 0;

}

signed main()

{

	T=read();

	while(T--)

	{

		cnt=0;memset(xz,0,sizeof xz),hd=0;

		h=read(),w=read();n=get(h,w);

		for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)a[i][j]=go();

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

		{

			for(int j=(i==1?2:1);j<=w;j++)

			{

				if(!(i+j&1)&&!a[i][j])

				{

					hd+=2;

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

					{

						int i2=i+tx[t],j2=j+ty[t];

						if(in(i2,j2)&&!a[i2][j2])u[++cnt]=get(i,j),v[cnt]=get(i2,j2);

					}

				}

			}

		}

		while(zg())hd--;

		if(hd)pS("NO\n");

		else

		{

			pS("YES\n");

			if(!a[1][2])u[++cnt]=get(1,1),v[cnt]=get(1,2);

			if(!a[2][1])u[++cnt]=get(1,1),v[cnt]=get(2,1);

			for(int i=1;i<h<<1;i++)for(int j=1;j<w<<1;j++)ans[i][j]=' ';

			for(int i=1;i<=h;i++)for(int j=1;j<=w;j++)if(a[i][j])ans[(i<<1)-1][(j<<1)-1]='X';else ans[(i<<1)-1][(j<<1)-1]='O';

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

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

			{

				if(!xz[i])continue;

				mg(u[i],v[i]);

				int x1=(u[i]-1)/w+1,y1=(u[i]-1)%w+1;

				int x2=(v[i]-1)/w+1,y2=(v[i]-1)%w+1;

				if(x1==x2&&y1+1==y2)ans[(x1<<1)-1][y1<<1]='O';

				else if(x1==x2&&y1-1==y2)ans[(x1<<1)-1][(y1-1)<<1]='O';

				else if(y1==y2&&x1+1==x2)ans[x1<<1][(y1<<1)-1]='O';

				else ans[(x1-1)<<1][(y1<<1)-1]='O';

			}

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

			{

				if(xz[i]||fr(u[i])==fr(v[i]))continue;

				mg(u[i],v[i]);

				int x1=(u[i]-1)/w+1,y1=(u[i]-1)%w+1;

				int x2=(v[i]-1)/w+1,y2=(v[i]-1)%w+1;

				if(x1==x2&&y1+1==y2)ans[(x1<<1)-1][y1<<1]='O';

				else if(x1==x2&&y1-1==y2)ans[(x1<<1)-1][(y1-1)<<1]='O';

				else if(y1==y2&&x1+1==x2)ans[x1<<1][(y1<<1)-1]='O';

				else ans[(x1-1)<<1][(y1<<1)-1]='O';

			}

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

			{

				for(int j=1;j<w<<1;j++)pc(ans[i][j]);

				pc('\n');

			}

		}

	}

	fwrite(obuf,p3-obuf,1,stdout);

    return 0;

}


C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that:  the length of both arrays is equal to mm;  each element of each array is an integer between 11 and nn (inclusive);  ai≤biai≤bi for any index ii from 11 to mm;  array aa is sorted in non-descending order;  array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays:   a=[1,1],b=[2,2]a=[1,1],b=[2,2];  a=[1,2],b=[2,2]a=[1,2],b=[2,2];  a=[2,2],b=[2,2]a=[2,2],b=[2,2];  a=[1,1],b=[2,1]a=[1,1],b=[2,1];  a=[1,1],b=[1,1]a=[1,1],b=[1,1].

#include<bits/stdc++.h>

using namespace std;

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

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

#define F first

#define S second

#define oo 1e18+5

#define MOD ll(1e9+7)

//#define endl '\n'

#define fvec(i,vec) for(auto i:vec)

#define pb push_back

#define mpr make_pair

#define min3(a,b,c) min(a,min(b,c))

#define max3(a,b,c) max(a,max(b,c))

# define M_PI  3.14159265358979323846

#define foor(i,a,b) for (ll i = a; i < b; i++)

#define num_ocur_insort(vec,x) equal_range(all(vec), x) /* return pair upper lower   auto r=num_ocur_insort(a,6);*/

typedef long long ll;

typedef unsigned long long ull;

typedef vector<ll> vi;

typedef vector<vi> vii;

typedef pair<ll,ll> pi;

typedef vector<pi> vip;

typedef vector<string> vss;

typedef map<ll,ll> mapi;

typedef unordered_map<ll,ll> umapi;

struct bebo {ll fir;ll sec;ll thi;ll fot;};

typedef vector<vip> viip;

ll gcd(ll a, ll b) { return ((b == 0) ? a : gcd(b, a % b)); }

const int N=8*1e5;

ll add(ll a, ll b) {

    return ((a % MOD + b % MOD) + MOD) % MOD;

}

ll multi(ll a, ll b) {

    return ((a % MOD * b % MOD) + MOD) % MOD;

}

ll fastpow(ll a, ll b) {

    if (b == 0)return ll(1);

    ll temp = fastpow(a, b / 2);

    ll total = multi(temp, temp);

    if (b % 2 == 1) {

        total = multi(total, a);

    }

    return total;

}

int fact[N], inv[N];

int nCr( ll n , ll r)

{

    return multi(fact[n],multi(inv[n-r],inv[r]));

}

void solve() {

    ll n, m;

    cin >> n >> m;

    cout << nCr(n + 2 * m - 1, 2 * m) << endl;

}

int main() {

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    ll t = 1;

     // cin >> t;

    fact[0] = inv[0] = 1;

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

        fact[i] = multi(i, fact[i - 1]);

        inv[i] = fastpow(fact[i], MOD - 2);

    }

    while (t--) {

        solve();

    }

}


A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.

#include<bits/stdc++.h>

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

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

#define ll long long

#define ull unsigned long long

#define fixed(name) fixed << setprecision(name)

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

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

#define pi  3.14159265359

#define getline(s) getline(cin >> ws, s)

#define dl "\n"

#define cin(v) for(auto &i: v)  cin>>i

#define cout(v) for(auto &i: v) cout<<i<<" "

#define Mod  1'000'000'007

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

#define OO 2'000'000'000

using namespace std;

//using namespace __gnu_pbds;

void MAI(){

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

     #ifndef ONLINE_JUDGE

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

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

     #endif

}

// template <typename K, typename V, typename Comp = std::less<K>>

// using ordered_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;

// template <typename K, typename Comp = std::less<K>>

// using ordered_set = ordered_map<K, null_type, Comp>;

// template <typename K, typename V, typename Comp = std::less_equal<K>>

// using ordered_multimap = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>;

// template <typename K, typename Comp = std::less_equal<K>>

// using ordered_multiset = ordered_multimap<K, null_type, Comp>;

template < typename T = int > istream& operator >> (istream &in, vector < T > &v) {

    for (auto &x : v) in >> x;

    return in;

}

template < typename T = int > ostream& operator << (ostream &out, const vector < T > &v) {

    for (const T &x : v) out << x << ' ';

    return out;

}

// summation n*(n+1)/2 -> (-1+ sqrt(1+8*x))/2

// 2D vector vector<vector<ll>>v(n,vector<ll>(m, -1)) ;

bool is_vowel (char c){

    if(c == 'a' || c=='u' || c=='i' || c=='e' || c=='o' ) return true;

    else return false;

}

void solve(){

    int n, sum=0, c=0, i=0; cin>>n;

    vector<int>v(n); cin>>v;

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

        if(v[i]%2 == 0) {cout<<"1\n"<<i+1; return;}

        else if(sum > 0 && sum%2 == 0) break;

        else {sum+=v[i]; c++;}

    }

    if(sum > 0 && sum%2 == 0){

        cout<<i<<dl;

        for(int j=0; j<i; j++) cout<<j+1<<" ";

    }

    else cout<<"-1";

}

int main()

{   MAI();

    int t=1;

    cin>>t;

    while(t--){

        solve();

        if(t) cout << dl ;

    }

}


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;

int main()

{

    ios::sync_with_stdio(0);

    cin.tie(0);

    long long  t,i,j,p=0,q=0;

        int n;

        cin >> n;

        long long a[n], b[n] ,d[n],c[200005]={0};

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

        {

            cin >> a[i];

        }

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

        {

            cin >> b[i];

            c[i] = a[i] - b[i];

            d[i] = c[i];

        }

       sort (c,c+n);

          q = 0;

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

       {

      p =  upper_bound(c,c+n,(d[i]*(-1)))-c;

      if (d[i]<=0)  q+= (n-p); else q+= n-p-1;

       }   cout << q/2 << endl;

    return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using iii = tuple<ll, ll, ll>;

using viii = vector<iii>;

int main() {

  cin.tie(0), ios::sync_with_stdio(0);

  ll q, n, m, t, l, h;

  cin >> q;

  while (q--) {

    cin >> n >> m;

    viii a(n);

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

      cin >> t >> l >> h;

      a[i] = {t, l, h};

    }

    ll t0 = 0, mn = m, mx = m;

    bool ok = 1;

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

      tie(t, l, h) = a[i];

      mn -= (t-t0);

      mx += (t-t0);

      if (l > mx || h < mn) { ok = 0; break; }

      mn = max(mn, l);

      mx = min(mx, h);

      t0 = t;

    }

    cout << (ok?"YES\n":"NO\n");

  }

}


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:

//Made By Phuong Nam PROPTIT <3//

#pragma GCC Optimize("O3")

#include<bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/rope>

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

#define f1(i,n) for(int i=1;i<=n;i++)

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

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

#define el cout<<'\n'

#define fi first

#define se second

#define pb push_back

#define pk pop_back

#define vi vector<int>

#define vl vector<ll>

#define pii pair<int,int>

#define pll pair<ll,ll>

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

#define oset tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>

using namespace __gnu_pbds;

using namespace __gnu_cxx;

using namespace std;

typedef long long ll;

const int N=1e6+3;

const int MOD=1e9+7;

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

ll dem=0;

set<pii>s;

ll tinh(int x,int y)

{

    ll s1=0,s2=0;

    f1(i,n)

    {

        if(a[i])

        {

            int j=i;

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

            j--;

            s1+=max(0,((j-i+1)-x+1));

            i=j;

        }

    }

    f1(i,m)

    {

        if(b[i])

        {

            int j=i;

            while(j<=m&&b[j]==1) j++;

            j--;

            s2+=max(0,((j-i+1)-y+1));

            i=j;

        }

    }

    return s1*s2;

}

void xuly()

{

    cin>>n>>m>>k;

    f1(i,n) cin>>a[i];

    f1(i,m) cin>>b[i];

    s.insert({1,k});

    f(i,2,sqrt(k))

    {

        if(k%i==0) s.insert({min(i,k/i),max(i,k/i)});

    }

    for(auto i:s)

    {

        int x=i.fi,y=i.se;

        dem+=tinh(x,y);

        if(x!=y) dem+=tinh(y,x);

    }

    cout<<dem;

}

int main()

{

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

  int t=1;

  //cin>>t;

  while(t--) xuly();

}

//-----YEU CODE HON CRUSH-----//


F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105)  — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m)  — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example:  mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total);  mission 22: Jaber already starts in the finishing cell. In the second example:  mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2);  mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4);  mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4);  mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4).

#include<iostream>

#include <bits/stdc++.h>

#include <ext/numeric>

using namespace std;

using L = __int128;

#include<ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

using ll = long long;

using ull = unsigned long long;

using ld = long double;

#define nd "\n"

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

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

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

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

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

#define popcount(x)  __builtin_popcount(x)

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

const  double PI = acos(-1.0);

double EPS = 1e-9;

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

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

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

template<class container>

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

//template <class Type1 , class Type2>

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

ll inf = 1e9+5 , mod= 1e9+7;//998244353;//

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

const int N = 1e6,LOG = 12;

ll mul (ll a, ll b){

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

}

ll add (ll a , ll b){

    return (a + b + mod) % mod;

}

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

// m n

ll f (ll a ,ll b){

    return (a + b - 1)/ b;

}

ll Fp (ll x  , ll p){

    if (!p) return 1;

    ll v = Fp(x , p/2);

    v = mul(v , v);

    if (p & 1)

        v = mul(x , v);

    return v;

}

int dx [] {0 , 0 , 1 ,-1};

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

void main_(int tc){

    ll n , m , k;scanf("%lli%lli%lli" , &n , &m , & k);

    vector < vector <int > > grid(n , vector <int > (m));

    vector < vector <pair <int , int > > > nodes (k+5);

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

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

            scanf("%d" , &grid[i][j]);

            nodes[grid[i][j]].emplace_back(i , j);

        }

    }

    vector < vector < vector <int > > > dist(40+5 , vector <  vector <int > > (n+5 , vector <int > (m+5 , inf)));

    auto v =[&] (pair <int , int > p)-> bool{

        return p.first >=0 && p.second >=0 && p.first <n && p.second < m;

    };

    auto bfs =[&](int c){

       deque <pair <int , int > > q;

       vector < bool > mark(k+5);

       for (auto &i : nodes[c])

           q.emplace_back(i.first , i.second) ,dist[c][i.first][i.second] = 0;

       mark[c] = 1;

       while (!q.empty()){

            auto top = q.front(); q.pop_front();

            if (!mark[grid[top.first][top.second]]){

                mark[grid[top.first][top.second]] =1;

                for (auto &i : nodes[grid[top.first][top.second]]){

                    if (dist[c][i.first][i.second] > dist[c][top.first][top.second]+ 1) {

                        dist[c][i.first][i.second] = 1 + dist[c][top.first][top.second];

                        q.emplace_back(i.first, i.second);

                    }

                }

            }

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

                int nr = top.first + dx[i];

                int nc = top.second + dy[i];

                if (!v({nr , nc})) continue;

                if (dist[c][nr][nc] > dist[c][top.first][ top.second]+1){

                    q.emplace_back( nr , nc);

                    dist[c][nr][nc] =dist[c][top.first][top.second]+1;

                }

            }

       }

    };

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

    int q ,r1 , c1 , r2 , c2;

    scanf("%d" , &q);

    while (q--){

        scanf("%d%d%d%d" , &r1 , &c1 , &r2 , &c2);--r1 , --r2 , --c1 , --c2;

        int ans = abs(r1-r2) + abs(c1-c2);

        for (int i = 1; i <= k; ++i) ans = min(ans , 1 + dist[i][r1][c1] + dist[i][r2][c2]);

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

        ///cout << ans << nd;

    }

}

int main(){

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

    //the_best_is_still_yet_to_come();

    //freopen("red2.in ","r",stdin);//  freopen("output.txt","w",stdout);

    int tt = 1 , tc = 0;

   // cin>>tt;

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

#ifndef ONLINE_JUDGE

    cout << "Running Time: " << 1.0 * clock() / CLOCKS_PER_SEC << " s .\n";

#endif

    return 0;

}

/*

 * if we dont use cells from the same color the ans = manhattan distance

 * else we will see for from each color what is the min  distance to reach this cell by bfs

 * and  add edge between the two cells from the same color with cost one

 *

 */


#include<bits/stdc++.h>

#define pb push_back

#define mk make_pair

using namespace std;

int const M=1010,inf=1e9,dx[]={-1,1,0,0},dy[]={0,0,-1,1};

vector<pair<int,int>>g[42];queue<pair<int,int>>q;bool vis[42];

int i,j,n,m,k,c,r1,c1,r2,c2,x,y,T,X,Y,Min,col[M][M],dis[42][M][M];

int read(){

	int x=0;char ch=getchar();

	while (ch<'0'||ch>'9') ch=getchar();

	while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();

	return x;

}

int main(){

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

	memset(dis,63,sizeof(dis));

	for (i=1;i<=n;i++) for (j=1;j<=m;j++)

		g[col[i][j]=read()].pb(mk(i,j));

	for (T=1;T<=k;T++){ memset(vis,0,sizeof(vis));

		for (i=0;i<g[T].size();i++)	q.push(g[T][i]),

			dis[T][g[T][i].first][g[T][i].second]=0;

		while (!q.empty()){

			int x=q.front().first,y=q.front().second;

			q.pop();for (i=0;i<4;i++){

				X=x+dx[i];Y=y+dy[i];

				if (X&&Y&&X<=n&&Y<=m&&dis[T][X][Y]>inf)

					dis[T][X][Y]=dis[T][x][y]+1,q.push(mk(X,Y));

			} c=col[x][y];

			if (vis[c]) continue;vis[c]=1;

			for (i=0;i<g[c].size();i++)

				if (dis[T][g[c][i].first][g[c][i].second]>inf)

					dis[T][g[c][i].first][g[c][i].second]=dis[T][x][y]+1,q.push(g[c][i]);

		}

	}

	T=read();while (T--){

		r1=read();c1=read();r2=read();c2=read();Min=abs(r1-r2)+abs(c1-c2);

		for (i=1;i<=k;i++) Min=min(Min,dis[i][r1][c1]+dis[i][r2][c2]+1);

		printf("%d\n",Min);

	}

	return 0;

}


#include <bits/stdc++.h>

#include <string>

#include <ext/pb_ds/assoc_container.hpp>

using namespace __gnu_pbds;

using namespace std;

typedef long long ll;

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

        tree_order_statistics_node_update> indexed_set;

typedef priority_queue<int,vector<int>,greater<int>> min_priority_queue;

const int MOD = 1e9 + 7;

const ll INF = 1e18;

const string YES = "YES";

const string NO = "NO";

void solve() {

    ll n, m;

    cin >> n >> m;

    ll low = m, high = m;

    vector<array<ll, 3>> A(n);

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

        cin >> A[i][0] >> A[i][1] >> A[i][2];

    }

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

    ll prev = 0;

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

        ll t =A[i][0], l = A[i][1], r = A[i][2];

        ll d =  t - prev;

        if (low - d > r || high + d < l) {

            cout << NO << endl;

            return;

        }

        prev = t;

        low = max(l, low - d);

        high = min(r, high + d);

    }

    cout << YES << endl;

}

int main() {

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    int T = 1;

    cin >> T;

    while (T--) {

        solve();

    }

    return 0;

}


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

#include <iostream>

#include <iomanip>

#include <cstdio>

#include <vector>

#include <math.h>

#include <algorithm>

#include <map>

using namespace std;

int main()

{

     cout.tie(nullptr);

    std::ios::sync_with_stdio(false);

int t; cin >> t;

while(t--){

int n,s,k;

cin >> n >> s >> k;

vector<int> v;

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

    int a; cin >> a;

    v.push_back(a);

}

int ans=0;

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

		if (s+i<=n) {

                if(find(v.begin(),v.end(),s+i)==v.end()){

                ans=i; break;

                }

        }

        if (s-i>=1){

            if(find(v.begin(),v.end(),s-i)==v.end()){

               ans=i; break;

        }

		}

	}

cout << ans << '\n';

}

 return 0;

}


#include <bits/stdc++.h>

#include <ext/rope>

#include <ext/pb_ds/assoc_container.hpp>

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

#define endl "\n"                               //                 ██╔════╝╚══██╔══╝██╔════╝██║   ██║

#define F first                                 //                 ███████╗   ██║   █████╗  ██║   ██║

#define S second                            //                     ╚════██║   ██║   ██╔══╝  ╚██╗ ██╔╝

#define For(i, x , n) for(ll i=x ;x==0?i<n :i<=n;i++)          // ███████║   ██║   ███████╗ ╚████╔╝

#define Forn(i , x , n )for(int i = n-x ; x==1?i>=0:i>0;i--)     //╚══════╝   ╚═╝   ╚══════╝  ╚═══╝

#define cin(v,x,n) For(i,x,n) cin>>v[i]

#define Insert(v,x,n) For(i,x,n){int in;cin>>in;v.insert(in);}

#define Cin    long long n ; cin>>n ; long long arr[n] ; cin(arr,0,n) ;

#define Cin2     LL arr2[n] ; cin(arr2,n) ;

#define r0 return 0

#define B begin()

#define E end()

#define RB rbegin()

#define RE rend()

#define pow 1LL*pow

#define Back(s) *s.rbegin()

#define Front(s) *s.begin()

#define PF(x) push_front(x)

#define PB(x) push_back(x)

#define POF pop_front()

#define POB pop_back()

#define Digits(n) (n==0?1:(int)log10(n)+1)

#define Bits(n) (ll)log2(n)+1

#define pof(n) ((n&(n-1))==0)

#define smaller(n) order_of_key(n)

#define bigger(cont , n , x) ( (n) - cont.smaller( x + 1) )

// #define bigger(cont , x) distance(cont.upper_bound(x) , cont.E)

#define At(n) find_by_order(n)

#define Idx(cont , x) (int)( L(ms)-(distance(cont.lower_bound(x), cont.E))) // linear time for set...

#define Sigma(n) (1LL)*( n%2==0?((ll)n/2)*((ll)n+1) :(((ll)n+1)/2)*(ll)n ) // use bracket Sigma(n -+\*)

#define Modx(a,b,c) ((a%c)*(b%c))%c

#define Modp(a,b,c) ((a%c)+(b%c))%c

#define Edis(X1 , X2 , Y1 , Y2)  (double) sqrt(   pow( abs( X1 - X2 ) , 2) +  pow(  abs ( Y1 - Y2 )  , 2 ))

#define intersect(l , r , l2 , r2) (l<=r2 and r >=l2)

#define lcm(a , b) a*b / __gcd(a , b)

#define uniq(x)   sort(All(x)); x.erase(unique(All(x)),x.E)

#define L(s) (int) s.size()    // لا تحاول ان تتخطي قدراتك  //

#define IDX(fnd,s) fnd-s.B    // بل اصنع اليوم بما تستطع  //

#define MAX INT_MAX          //       ستجد في الغد        //

#define MIN INT_MIN         //          ++قدراتك         //

#define uMAX 0xffffffff

#define LA(a) (int)(sizeof(a)/sizeof(a[0]))

#define full(x) !(x.empty())

#define All(v) v.B,v.E

#define Allr(v) v.rbegin(),v.rend()

#define getName(x)  #x

#define debug(x) cout<<getName(x)<<" = "<<x<<endl

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

#define lambda  auto x =[](const Pair &x, const Pair &y) {if (x.second != y.second) {return x.second < y.second;} return x.first < y.first;}

#define lambdaSTEV  [](const Pair &x, const Pair &y) {if (x.F != y.F) {return x.F < y.F;} return x.S < y.S;}

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

// #pragma GCC optimize("Ofast")

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

// #pragma GCC target ("sse4.2")

#define oSet tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>

#define oMap tree<int, int ,less<int>, rb_tree_tag,tree_order_statistics_node_update>

#define Acc accumulate

// lower_bound and upper_bound work oppositely

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

#define tests int tt  ; cin >> tt  ; while(tt--)

 void judge (){

      #ifndef ONLINE_JUDGE

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

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

      #endif

      }

int rnd(int a, int b){ return a + rand() % (b - a + 1);}

int generator(){int w = rnd(0, 10);return w; }

using namespace std ;

using namespace __gnu_pbds;

using namespace __gnu_cxx;

typedef long long ll ;

typedef unsigned long long ull ;

typedef pair<ll,ll> Pair ;

const int N = 200005 ;

const ll MOD  = 1e9+7 ;

const double PI =3.141592653589793238462643383279502884;

const int INF = MAX  ;

const ll  INFl = LLONG_MAX ;

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

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

char dc [] = {'D','U','R','L'} ;

int knightX[]  = { 2, 1, -1, -2, -2, -1, 1, 2 };

int knightY[] = { 1, 2, 2, 1, -1, -2, -2, -1 };

ll n  , m , components  , k ;

// bool f ;

bool Salka(int x, int y) { return x > 0 && y > 0 && x <= n && y <= m; } // 1 based

/*equal_less

 auto it = ms.upper_bound(k-i+1) ;

if((it!=ms.E and it!=ms.B)or (it==ms.E and full(ms)))

it-- ;

*/

template <typename T1 , typename T2>void dabt_el_masna3(T1 &v , T2 &v2){ v =T1(n+1) ; v2 =T2(n+1) ; }

struct point{public : double x , y ;} ;

struct triple{public : ll a , b , c ;} ;

template <typename T>void debugcont(T&v){for(auto i : v)debug(i);}

template <typename T>void debugcont2(T&v){for(auto [l ,r] : v)debug(l) ,debug(r) ; }

template<typename T> auto equal_less(T&v  , int value){ //return iterator needed or end when fail

auto it = upper_bound(All(v) , value) ;

if((it!=v.E and it!=v.B) or (it==v.E and full(v)))

it-- ;

else it=v.E;

return it; }

                                /*     “You just keep pushing. You just keep pushing.

                                           I made every mistake that could be made.

                                                But I just kept pushing.”

                                                     — René Descartes              */

                        /*                         Steven's Golden Rules ❤

                                            ❏ if you feel so dumb you didnt work enough

                                        ❏ give it more time more effort you will be better

                                        ❏ if it gives WA that means you will learn something

        ❏ every problem either teach you something or make you better in something other than that you didnt realy solve it .  */

                                                //*

                                                    main(){

                                                    judge() ;

                                                    Mo_Salah ;

                                                    tests{

                                                        int n ; cin>> n ;

                                                        vector<vector<int>> v(1001);

                                                        string s ="" ;

                                                        For(i,0,n){

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

                                                            v[x].push_back(y);

                                                        }

                                                        int x = 0 , y = 0 , ans  = 0 ;

                                                        while(x<=1000){

                                                            if( full(v[x]) ){

                                                                sort(v[x].B , v[x].E) ;

                                                                for(auto i : v[x]) {

                                                                    if(i>=y) s.append(i-y,'U') , y= i , ans++;

                                                                    else break ;

                                                                }

                                                            }

                                                              if( ans == n )break;

                                                                x++ ;

                                                                s.push_back('R') ;

                                                        }

                                                        if( ans == n ) cout<<"YES"<<endl<<s<<endl;

                                                        else cout<<"NO"<<endl;

                                                    }

                                                    }


D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2
1 1 100
3 1 0
OutputCopy1
InputCopy3
7 10 0
9 4 86
14 5 100
OutputCopy0
InputCopy4
6 4 50
11 25 50
13 16 50
15 8 50
OutputCopy150902884