E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2
1 2
OutputCopy? 1 2
? 1 1
! 1 2

// Fresh Peach Heart Shower

#include <bits/stdc++.h>

#define reg

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

#define mem(x,y) memset(x,y,sizeof x)

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

#define ln putchar('\n')

#define lsp putchar(32)

#define pb push_back

#define MP std::make_pair

#define MT std::make_tuple

#ifdef _LOCAL_

#define dbg(x) std::cerr<<__func__<<"\tLine:"<<__LINE__<<' '<<#x<<": "<<x<<"\n"

#define dprintf(x...) std::fprintf(stderr,x)

#else

#define dbg(x) 42

#define dprintf(x...) 42

#endif

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

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

typedef std::pair<int,int> pii;

typedef std::vector<int> poly;

template <class t> inline void read(t &s){s=0;

signed f=1;char c=getchar();while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}

while(isdigit(c))s=(s<<3)+(s<<1)+(c^48),c=getchar();;s*=f;}

template<class t,class ...A> inline void read(t &x,A &...a){read(x);read(a...);}

template <class t> inline void write(t x){if(x<0)putchar('-'),x=-x;

static int buf[50],top=0;while(x)buf[++top]=x%10,x/=10;if(!top)buf[++top]=0;

while(top)putchar(buf[top--]^'0');}

inline void setIn(std::string s){freopen(s.c_str(),"r",stdin);return;}

inline void setOut(std::string s){freopen(s.c_str(),"w",stdout);return;}

inline void setIO(std::string s=""){setIn(s+".in");setOut(s+".out");return;}

template <class t>inline bool ckmin(t&x,t y){if(x>y){x=y;return 1;}return 0;}

template <class t>inline bool ckmax(t&x,t y){if(x<y){x=y;return 1;}return 0;}

inline int lowbit(int x){return x&(-x);}

const int MaxN=805;

int a[MaxN],pos[MaxN],f[MaxN],n,p;

inline int ask(poly a)

{

	std::printf("? %d",(int)a.size());

	for(auto i:a)lsp,write(i);

	ln,fflush(stdout);

	int x;read(x);

	return x;

}

inline poly del(poly a,int x){return a.erase(std::find(ALL(a),x)),a;}

inline void solve(int l,int r)

{

	poly al;

	rep(i,1,n)if(!a[i])al.pb(i);

	rep(i,1,n)if(!a[i]&&f[i]==l%p&&ask(del(al,i)))

	{

		pos[a[i]=l]=i;

		break;

	}

	rep(i,1,n)if(!a[i]&&f[i]==r%p&&ask(del(al,i)))

	{

		pos[a[i]=r]=i;

		break;

	}

}

signed main(void)

{

	read(n);

	if(n==2)return std::cout<<"! 1 2"<<std::endl,0;

	p=1,solve(1,n);

	p=2;

	rep(i,1,n)if(!a[i])f[i]=ask(poly{pos[1],i});

	rep(i,2,n/2)

	{

		solve(i,n-i+1);

		if(i==(p<<1))

		{

			rep(j,1,n)if(!a[j])

			{

				poly al;

				rep(k,1,p<<1)if(k%(p<<1)!=f[j])al.pb(pos[k]);

				al.pb(j);

				if(ask(al))f[j]+=p;

			}

			p<<=1;

		}

	}

	if(a[1]>n/2)rep(i,1,n)a[i]=n-a[i]+1;

	std::printf("!");

	rep(i,1,n)lsp,write(a[i]);

	ln,fflush(stdout);

	return 0;

}

/*

 * Check List:

 * 1. Input / Output File (OI)

 * 2. long long

 * 3. Special Test such as n=1

 * 4. Array Size

 * 5. Memory Limit (OI) int is 4 and longlong is 8

 * 6. Mod (a*b%p*c%p not a*b*c%p  ,  (a-b+p)%p not a-b )

 * 7. Name ( int k; for(int k...))

 * 8. more tests , (T=2 .. more)

 * 9. blank \n after a case

*/


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<bits/stdc++.h>

#define f first
#define s second
#define pii pair<int,int>
using namespace std;
const int N = 1005, mod = 1e9 + 7; // !
int t, a[N][N], n,m,k,f[N],d[44][N][N], dx[] = {1, -1, 0, 0}, dy[] = {0, 0, -1, 1};
vector<pii> c[44];
bool ok(int x,int y) {
if(min(x,y) < 1 || x > n || y > m) return 0;
return 1;
}
main() {
cin >> n >> m >> k;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin >> a[i][j];
c[a[i][j]].push_back({i,j});
}
}
for(int cl = 1; cl <= k; cl++) {
queue<pii> q;
for(int j = 1; j <= k; j++) f[j] = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
if(a[i][j] == cl) d[cl][i][j] = 0, q.push({i,j});
else d[cl][i][j] = n + m + 5;
}
}
while(q.size()) {
int i = q.front().f;
int j = q.front().s;
q.pop();

if(!f[a[i][j]]) {
f[a[i][j]] = 1;
for(int k = 0; k < c[a[i][j]].size(); k++) {
int i_ = c[a[i][j]][k].f;
int j_ = c[a[i][j]][k].s;
if(d[cl][i_][j_] > n + m) {
d[cl][i_][j_] = d[cl][i][j] + 1;
q.push({i_,j_});
}
}
}
for(int k = 0; k < 4; k++) {
if(ok(i + dx[k], j + dy[k]) && d[cl][i + dx[k]][j + dy[k]] > n + m) {
d[cl][i + dx[k]][j + dy[k]] = d[cl][i][j] + 1;
q.push({i + dx[k], j + dy[k]});
}
}
}
}
int q;
cin >> q;
while(q--) {
int x,y,i,j;
cin >> x >> y >> i >> j;
int ans = abs(i - x) + abs(j - y);
for(int c = 1; c <= k; c++) ans = min(ans, d[c][x][y] + d[c][i][j] + 1);
cout << ans << endl;
}
}


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

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

typedef unsigned long long uLL;

typedef pair<LL,LL> pii;

#define MAXN 100005

#define pb push_back

#define mkpr make_pair

#define fir first

#define sec second

#define lson (rt<<1)

#define rson (rt<<1|1)

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

const int mo=998244353;

const int inv2=5e8+4;

const int jzm=2333;

const int zero=15;

const int INF=0x3f3f3f3f;

const double Pi=acos(-1.0);

const double eps=1e-9;

const int orG=3,ivG=332748118;

template<typename _T>

_T Fabs(_T x){return x<0?-x:x;}

template<typename _T>

void read(_T &x){

    _T f=1;x=0;char s=getchar();

    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}

    while('0'<=s&&s<='9'){x=(x<<3)+(x<<1)+(s^48);s=getchar();}

    x*=f;

}

int add(int x,int y,int p){return x+y<p?x+y:x+y-p;}

void Add(int &x,int y,int p){x=add(x,y,p);}

int qkpow(int a,int s,int p){int t=1;while(s){if(s&1)t=1ll*a*t%p;a=1ll*a*a%p;s>>=1;}return t;}

int n,m,TT,id[25][25],idx,col[405],cnt,head[1005],tot;

int dis[1005],cntp,S,T,deg[405],fa[405],pre[405];

char maze[25][25],ans[45][45];bool used[1005];queue<int>q;

struct ming{int u,v,x,y;}s[1005];

struct edge{int to,nxt;}e[MAXN*10];

void addEdge(int u,int v){e[++tot]=(edge){v,head[u]};head[u]=tot;}

void makeSet(int x){for(int i=1;i<=x;i++)fa[i]=i;}

int findSet(int x){return x==fa[x]?x:fa[x]=findSet(fa[x]);}

void unionSet(int x,int y){int u=findSet(x),v=findSet(y);if(fa[u]^v)fa[u]=v;}

int main(){

    read(TT);int allTT=TT;

    while(TT--){

        read(n);read(m);

        for(int i=1;i<=n;i++)scanf("%s",maze[i]+1);

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

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

                if(maze[i][j]=='O')

                    id[i][j]=++idx,col[idx]=(i+j)&1;

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

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

                if(id[i][j]&&id[i][j+1])

                    s[++cntp]=(ming){id[i][j],id[i][j+1],i+i-1,j+j};

                if(id[i][j]&&id[i+1][j])

                    s[++cntp]=(ming){id[i][j],id[i+1][j],i+i,j+j-1};

            }

        cnt=cntp;S=++cnt;T=++cnt;

        while(1){

            for(int i=1;i<=cnt;i++)head[i]=0;tot=0;

            for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);

            for(int i=1;i<=cntp;i++)if(used[i])

                unionSet(s[i].u,s[i].v),deg[s[i].u]++,deg[s[i].v]++;

            for(int i=1;i<=cntp;i++)if(!used[i]){

                int u=s[i].u,v=s[i].v;if(findSet(u)!=findSet(v))addEdge(S,i);

                if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2)&&u!=1)addEdge(i,T);

            }

            for(int i=1;i<=cntp;i++)if(used[i]){

                makeSet(idx);deg[s[i].u]--;deg[s[i].v]--;

                for(int j=1;j<=cntp;j++)if(used[j]&&i!=j)unionSet(s[j].u,s[j].v);

                for(int j=1;j<=cntp;j++)if(!used[j]){

                    int u=s[j].u,v=s[j].v;if(u==1)continue;

                    if(findSet(u)!=findSet(v))addEdge(i,j);

                    if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2))addEdge(j,i);

                }

                deg[s[i].u]++;deg[s[i].v]++;

            }

            for(int i=1;i<=cnt;i++)dis[i]=pre[i]=0;dis[S]=1;

            while(!q.empty())q.pop();q.push(S);

            while(!q.empty()){

                int u=q.front();q.pop();

                for(int i=head[u];i;i=e[i].nxt){

                    int v=e[i].to;if(dis[v])continue;

                    q.push(v);dis[v]=dis[u]+1;pre[v]=u;

                }

            }

            if(!dis[T])break;int now=pre[T];

            while(now^S)used[now]^=1,now=pre[now];

        }

        for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);

        for(int i=1;i<=cntp;i++)if(used[i])

            deg[s[i].u]++,deg[s[i].v]++,unionSet(s[i].u,s[i].v);

        bool flag=0;for(int i=2;i<=idx;i++)if(!col[i])flag|=(deg[i]<2);

        if(flag)puts("NO");

        else{

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

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

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

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

                    ans[i+i-1][j+j-1]=maze[i][j];

            for(int i=1;i<=cntp;i++)if(findSet(s[i].u)^findSet(s[i].v))

                used[i]=1,unionSet(s[i].u,s[i].v);

            for(int i=1;i<=cntp;i++)if(used[i])

                ans[s[i].x][s[i].y]='O';

            puts("YES");

            for(int i=1;i<n+n;i++,puts(""))

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

                    printf("%c",ans[i][j]),ans[i][j]=0;

        }

        for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)id[i][j]=maze[i][j]=0;

        for(int i=1;i<=cntp;i++)used[i]=0;

        for(int i=1;i<=idx;i++)col[i]=0;idx=cntp=cnt=0;

    }

    return 0;

}


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

#include<bits/stdc++.h>

using namespace std;

int n,m,k;

int a[55][20200];

int f[55][200200];

int tree[55][20200];

int lowbit(int x)

{

	return x&(-x);

}

int get(int x,int y,int i)

{

	if (x>y) return 0;

	int sum=0;

	while(y>=x)

	{

		sum=max(sum,f[i][y]);

		y--;

		for (;y-lowbit(y)>=x;y-=lowbit(y)) sum=max(sum,tree[i][y]);

	}

	return sum;

}

void push(int x,int i,int j)

{

	for (;j<=m;j+=lowbit(j)) tree[i][j]=max(tree[i][j],x);

}

int main()

{

	int x;

	cin>>n>>m>>k;

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

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

		{

			cin>>x;

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

		}

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

	{

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

		{

			f[i][j]=max(get(k,j-k,i-1),get(j+k,m,i-1));

			for (int ii=max(j-k+1,k);ii<=j+k-1;ii++)

			f[i][j]=max(f[i][j],f[i-1][ii]-(a[i-1][min(ii,j)]-a[i-1][max(j-k,ii-k)]));

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

			push(f[i][j],i,j);

		}

	}

	int ans=0;

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

		ans=max(ans,f[n+1][j]);

	cout<<ans<<endl;

 }


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

#include <bits/stdc++.h>

#define Fast()  ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);cin>>t;while(t--)

#define up(a,x) (upper_bound(a.begin(),a.end(),x)-a.begin())

#define lp(a,x) (lower_bound(a.begin(),a.end(),x)-a.begin())

#define tol(s)  transform(s.begin(),s.end(),s.begin(),::tolower);

#define tou(s)  transform(s.begin(),s.end(),s.begin(),::toupper);

#define MNE(c)  *min_element(c.begin(),c.end())

#define MXE(c)   max_element(c.begin(),c.end())

#define upn(a,n,x) (upper_bound(a,a+n,x)-a)

#define lpn(a,n,x) (lower_bound(a,a+n,x)-a)

#define YON(f) cout<<(f?"YES":"NO")<<Endl;

#define pas {cout<<-1<<Endl;continue;}

#define bitsN(n)  __builtin_popc(n);

#define MAX(a,b) a=max(a,b)

#define PB(a) push_back(a)

#define sz(a) a.size()

#define ll long long

#define Endl '\n'

using namespace std;

const double eps=1e-6;

ll t,n;

int main(){

    Fast(){

        cin>>n;

        if(n%2){cout<<7;n-=3;};

        while(n>0){

            cout<<1;

            n-=2;

        }

        cout<<Endl;

    }

}


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

// Problem: D. Pair of Topics

// Contest: Codeforces - Codeforces Round #627 (Div. 3)

// URL: https://codeforces.com/problemset/problem/1324/D

// Memory Limit: 256 MB

// Time Limit: 2000 ms

//

// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>

#define int long long

#pragma GCC optimize("Ofast")

#define mod (int)(1e9+7)

using namespace std;

const int N=1e5+5;

void solve(){

	int n;

	cin >> n;

	vector<int> v(n), a(n);

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

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

		int x;

		cin >> x;

		a[i]=v[i]-x;

	}

	sort(begin(a),end(a));

	int ans=0;

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

		if ( a[i]<=0 ) continue;

		int l=-1, r=a.size();

		int x=-a[i]+1;

		while ( r>l+1 ){

			int m=(l+r)/2;

			if ( a[m]<x ){

				l=m;

			}else r=m;

		}

		//cout << l << " " << r << '\n';

		ans+=i-l-1;

	}

	cout << ans;

}

signed main(){

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

    int t=1; //cin >> t;

    while ( t-- ){

        solve(); cout << '\n';

    }

}

/*

*/


B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.

#include<bits/stdc++.h>

using namespace std;

typedef long long li;

int n, x;

string s;

inline bool read() {

	if(!(cin >> n >> x >> s))

		return false;

	return true;

}

inline void solve() {

	int ans = 0;

	bool infAns = false;

	int cntZeros = (int)count(s.begin(), s.end(), '0');

	int total = cntZeros - (n - cntZeros);

	int bal = 0;

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

		if(total == 0) {

			if(bal == x)

				infAns = true;

		}

		else if(abs(x - bal) % abs(total) == 0) {

			if((x - bal) / total >= 0)

				ans++;

		}

		if(s[i] == '0')

			bal++;

		else

			bal--;

	}

	if(infAns) ans = -1;

	cout << ans << endl;

}

int main() {

#ifdef _DEBUG

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

#endif

	ios_base::sync_with_stdio(false);

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

	cout << fixed << setprecision(15);

	int tc; cin >> tc;

	while(tc--) {

		read();

		solve();

	}

	return 0;

}


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

#include <bits/stdc++.h>

using namespace std;

#define str string

int main(){

    int n; str s;

    cin >> n >> s;

    cout << n + 1;

}

// :D


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

#pragma GCC optimize("Ofast")

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

#include <bits/stdc++.h>

#define int             long long

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

#define endl            "\n"

#define fill(a,b) memset(a, b, sizeof(a))

#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))

using namespace std;

int MOD;

int power(int a, int b, int p){

    if(a==0)

    return 0;

    int res=1;

    a%=p;

    while(b>0)

    {

        if(b&1)

        res=(1ll*res*a)%p;

        b>>=1;

        a=(1ll*a*a)%p;

    }

    return res;

}

int modInverse(int n,int p)

{

	return power(n, p - 2, p);

}

vector<int>fac;

int choose(int a,int b) { //get nCr

        if(a<b) {

            return 0;

        }

        return ((fac[a]*modInverse(fac[b],MOD))%MOD*modInverse(fac[a-b],MOD))%MOD;

    }

signed main (){

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    cout.tie(NULL);

    int t=1;

    //cin>>t;

while(t--){

    fac.clear();

    int i,j,x=0,y=0,p=0,n,q=-1,u=0,v=0,k,c=0,m,z;

    cin>>n>>m;

    MOD=m;

    fac.push_back(1);

    p=1;

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

        p=(p*i)%m;

        fac.push_back(p);

    }

    //r-l=1=i...i+1...n-(i+1)...n-i

    int ansx=0;

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

        x=fac[i+1];

        y=fac[n-(i+1)];

        z=n-i;

        int ans=1;

        ans=((x*y)%m)%m;

        ans=(ans*z)%m;

        q=z;

        ans=(ans*q)%m;

        ansx+=ans;

        ansx%=m;

    }

    cout<<ansx<<endl;

    }

}


E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

namespace atcoder {

namespace internal {

// @param n `0 <= n`

// @return minimum non-negative `x` s.t. `n <= 2**x`

int ceil_pow2(int n) {

  int x = 0;

  while ((1U << x) < (unsigned int)(n))

    x++;

  return x;

}

// @param n `1 <= n`

// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`

constexpr int bsf_constexpr(unsigned int n) {

  int x = 0;

  while (!(n & (1 << x)))

    x++;

  return x;

}

// @param n `1 <= n`

// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`

int bsf(unsigned int n) {

#ifdef _MSC_VER

  unsigned long index;

  _BitScanForward(&index, n);

  return index;

#else

  return __builtin_ctz(n);

#endif

}

} // namespace internal

template <class S, S (*op)(S, S), S (*e)(), class F, S (*mapping)(F, S),

          F (*composition)(F, F), F (*id)()>

struct lazy_segtree {

public:

  lazy_segtree() : lazy_segtree(0) {}

  explicit lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}

  explicit lazy_segtree(const std::vector<S> &v) : _n(int(v.size())) {

    log = internal::ceil_pow2(_n);

    size = 1 << log;

    d = std::vector<S>(2 * size, e());

    lz = std::vector<F>(size, id());

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

      d[size + i] = v[i];

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

      update(i);

    }

  }

  void set(int p, S x) {

    assert(0 <= p && p < _n);

    p += size;

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

      push(p >> i);

    d[p] = x;

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

      update(p >> i);

  }

  S get(int p) {

    assert(0 <= p && p < _n);

    p += size;

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

      push(p >> i);

    return d[p];

  }

  S prod(int l, int r) {

    assert(0 <= l && l <= r && r <= _n);

    if (l == r)

      return e();

    l += size;

    r += size;

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

      if (((l >> i) << i) != l)

        push(l >> i);

      if (((r >> i) << i) != r)

        push((r - 1) >> i);

    }

    S sml = e(), smr = e();

    while (l < r) {

      if (l & 1)

        sml = op(sml, d[l++]);

      if (r & 1)

        smr = op(d[--r], smr);

      l >>= 1;

      r >>= 1;

    }

    return op(sml, smr);

  }

  S all_prod() { return d[1]; }

  void apply(int p, F f) {

    assert(0 <= p && p < _n);

    p += size;

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

      push(p >> i);

    d[p] = mapping(f, d[p]);

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

      update(p >> i);

  }

  void apply(int l, int r, F f) {

    assert(0 <= l && l <= r && r <= _n);

    if (l == r)

      return;

    l += size;

    r += size;

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

      if (((l >> i) << i) != l)

        push(l >> i);

      if (((r >> i) << i) != r)

        push((r - 1) >> i);

    }

    {

      int l2 = l, r2 = r;

      while (l < r) {

        if (l & 1)

          all_apply(l++, f);

        if (r & 1)

          all_apply(--r, f);

        l >>= 1;

        r >>= 1;

      }

      l = l2;

      r = r2;

    }

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

      if (((l >> i) << i) != l)

        update(l >> i);

      if (((r >> i) << i) != r)

        update((r - 1) >> i);

    }

  }

  template <bool (*g)(S)> int max_right(int l) {

    return max_right(l, [](S x) { return g(x); });

  }

  template <class G> int max_right(int l, G g) {

    assert(0 <= l && l <= _n);

    assert(g(e()));

    if (l == _n)

      return _n;

    l += size;

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

      push(l >> i);

    S sm = e();

    do {

      while (l % 2 == 0)

        l >>= 1;

      if (!g(op(sm, d[l]))) {

        while (l < size) {

          push(l);

          l = (2 * l);

          if (g(op(sm, d[l]))) {

            sm = op(sm, d[l]);

            l++;

          }

        }

        return l - size;

      }

      sm = op(sm, d[l]);

      l++;

    } while ((l & -l) != l);

    return _n;

  }

  template <bool (*g)(S)> int min_left(int r) {

    return min_left(r, [](S x) { return g(x); });

  }

  template <class G> int min_left(int r, G g) {

    assert(0 <= r && r <= _n);

    assert(g(e()));

    if (r == 0)

      return 0;

    r += size;

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

      push((r - 1) >> i);

    S sm = e();

    do {

      r--;

      while (r > 1 && (r % 2))

        r >>= 1;

      if (!g(op(d[r], sm))) {

        while (r < size) {

          push(r);

          r = (2 * r + 1);

          if (g(op(d[r], sm))) {

            sm = op(d[r], sm);

            r--;

          }

        }

        return r + 1 - size;

      }

      sm = op(d[r], sm);

    } while ((r & -r) != r);

    return 0;

  }

private:

  int _n, size, log;

  std::vector<S> d;

  std::vector<F> lz;

  void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }

  void all_apply(int k, F f) {

    d[k] = mapping(f, d[k]);

    if (k < size)

      lz[k] = composition(f, lz[k]);

  }

  void push(int k) {

    all_apply(2 * k, lz[k]);

    all_apply(2 * k + 1, lz[k]);

    lz[k] = id();

  }

};

} // namespace atcoder

using namespace atcoder;

struct node {

  ll sum;

  ll len;

};

constexpr ll inf = 1e16;

node op(node l, node r) { return node{min(l.sum, r.sum), l.len + r.len}; }

node e() { return node{inf, 0}; }

struct F {

  ll add;

};

node mapping(F f, node x) { return node{x.sum + f.add, x.len}; }

F composition(F f, F g) {

  // f(g())

  return F{f.add + g.add};

}

F id() { return F{0}; }

auto solve() {

  int n;

  cin >> n;

  vector<ll> p(n), a(n);

  for (auto &i : p) {

    cin >> i;

    i--;

  }

  for (auto &i : a) {

    cin >> i;

  }

  lazy_segtree<node, op, e, F, mapping, composition, id> seg(n);

  ll sum = a[0];

  vector<int> pos(n);

  vector<ll> val(n);

  pos[p[0]] = 0;

  val[p[0]] = a[0];

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

    seg.set(i, {sum, 1});

    sum += a[i];

    pos[p[i]] = i;

    val[p[i]] = a[i];

  }

  ll ans = inf;

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

    // l: i, r: n-i

    ans = min(ans, seg.prod(0, n).sum);

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

    //   cout<<seg.get(j).sum<<" ";

    // }

    // cout << "\n";

    seg.apply(pos[i] + 1, n, F{-val[i]});

    seg.apply(1, pos[i] + 1, F{val[i]});

    // cout << "OP:" << pos[i] + 1 << " " << val[i] << "\n";

  }

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

  //   cout << seg.get(j).sum << " ";

  // }

  // cout << "\n";

  ans = min(ans, seg.prod(0, n).sum);

  cout << ans << "\n";

}

auto main() -> int {

  ios::sync_with_stdio(false);

  cin.tie(nullptr), cout.tie(nullptr);

  int _ = 1;

  // cin >> _;

  while (_--) {

    solve();

  }

}


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

#include<bits/stdc++.h>

#define ll long long

#define flot(n) cout << setprecision(n) << setiosflags(ios::fixed) << setiosflags(ios::showpoint)

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

#define pb push_back

#define mp make_pair

#define pii pair<int,int>

#define pll pair<ll,ll>

#define piii pair<pii,int>

#define plll pair<pll,ll>

#define R return

#define B break

#define C continue

#define SET(n , i) memset(n , i , sizeof(n))

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

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

#define repn(i , j , n) for(int i = j ; i < n ; i++)

#define repr(i,n,j) for(int i=n;i>=j;i--)

#define positive(x) ((x%mod+mod)%mod)

#define YES(f)cout<<((f)?"YES":"NO")<<endl

#define F first

#define S second

#define endl '\n'

#define vi vector<int>

//#define int ll

using namespace std;

void readFromFile(string input = "input.txt",string output="output.txt") {

    #ifndef ONLINE_JUDGE

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

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

    #endif

}

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

ll rnd(ll x, ll y) {

    return uniform_int_distribution<ll>(x, y)(rng);

}

template <typename T> void Max(T& x,T y){x=max(x,y);}

template <typename T> void Min(T& x,T y){x=min(x,y);}

const int INF = 0x3f3f3f3f;

const ll INFLL = 0x3f3f3f3f3f3f3f3f;

const long double EPS = 1e-3;

const long double pi =  acos(-1.0);

const int mod = 1e9+9;

const int N =5e5+3;

ll Mul(ll x,ll y,ll mod=mod){R((x%mod)*(y%mod))%mod;}

ll Add(ll x,ll y,ll mod=mod){R((x%mod)+(y%mod)+2ll*mod)%mod;}

int n,a[N],nxt[N],prv[N],dub[N];

ll pre[N],suf[N];

void pr() {

    rep(i,n)prv[i]=-1;

    rep(i,n)nxt[i]=n;

    stack<int> st;

    rep(i,n) {

        while(!st.empty() && a[st.top()] > a[i]) {

            nxt[st.top()] = i;

            st.pop();

        }

        st.push(i);

    }

    while(!st.empty())st.pop();

    repr(i,n-1,0) {

        while(!st.empty() && a[st.top()] > a[i]) {

            prv[st.top()] = i;

            st.pop();

        }

        st.push(i);

    }

}

/**

2 3 6 2 8 4

2 2 2 2 4 4

0:2+2+2+2+2+2 = 12

1:2+2+2+3+3+2 = 14

2:2+2+2+6+2+3 = 17

3:2+2+2+2+2+2 = 12

4:4+8+2+2+2+2 = 20

5:4+2+2+2+2+4 = 16

*/

void solve() {

    cin >> n;

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

    pr();

    rep(i,n)dub[i]=1;

    rep(i,n) {

        int z = nxt[i];

        pre[i] += 1ll*dub[i]*a[i];

        pre[z] -= 1ll*dub[i]*a[i];

        dub[z] += dub[i];

        if(i)pre[i] += pre[i-1];

    }

    rep(i,n)dub[i]=1;

    repr(i,n-1,0) {

        int z = prv[i];

        suf[i] += 1ll*dub[i]*a[i];

        if(z>=0) {

            suf[z] -= 1ll*dub[i]*a[i];

            dub[z] += dub[i];

        }

        if(i<n-1) suf[i] += suf[i+1];

    }

    ll z=0;

    rep(i,n) Max(z,pre[i] += suf[i]-a[i]);

    vector<int> ans(n);

    rep(i,n) {

        if(pre[i] == z) {

            int mn = a[i];

            repr(j,i,0) {

                Min(mn,a[j]);

                ans[j] = mn;

            }

            mn = a[i];

            repn(j,i,n) {

                Min(mn,a[j]);

                ans[j] = mn;

            }

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

            R;

        }

    }

}

int32_t main() {

    readFromFile();

    SD;

    int t = 1;

//    cin >> t;

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

    rep(i,t) {

        solve();

    }

}


#include <bits/stdc++.h>

using namespace std;

const int maxn = 810;

int T, n, m, fa[maxn], d[maxn], pre[maxn], lim[maxn], eid[22][22][2];

bool bad[maxn], mark[maxn], vis[maxn], in1[maxn], in2[maxn], ban[maxn];

vector<int> G[maxn];

char str[22][22], ans[42][42];

int id(int x, int y) {

    return (x - 1) * m + y;

}

int find(int x) {

    while (x ^ fa[x]) x = fa[x] = fa[fa[x]];

    return x;

}

int main() {

    scanf("%d", &T);

    while (T--) {

        scanf("%d %d", &n, &m);

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

            scanf("%s", str[i] + 1);

            for (int j = 1; j <= m; j++) ban[id(i, j)] = str[i][j] == 'X';

        }

        memset(mark, 0, sizeof(mark));

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

        memset(lim, 0, sizeof(lim));

        memset(bad, 0, sizeof(bad));

        int cnt = 0;

        vector<array<int, 2>> E;

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

            for (int j = 1; j <= m; j++) if (str[i][j] == 'O') {

                cnt++, bad[id(i, j)] = (i + j + 1) % 2 && (i > 1 || j > 1);

                if (i < n && str[i + 1][j] == 'O') {

                    eid[i][j][0] = E.size(), E.push_back({id(i, j), id(i + 1, j)});

                    lim[id(i, j)]++, lim[id(i + 1, j)]++;

                }

                if (j < m && str[i][j + 1] == 'O') {

                    eid[i][j][1] = E.size(), E.push_back({id(i, j), id(i, j + 1)});

                    lim[id(i, j)]++, lim[id(i, j + 1)]++;

                }

            }

        }

        bool ok = 1;

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

            if (bad[i] && (lim[i] -= 2) < 0) { ok = 0; break; }

        }

        if (!ok) { puts("NO"); continue; }

        while (count(mark, mark + E.size(), 0) >= cnt) {

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

                G[i].clear();

            }

            for (int i = 0; i < E.size(); i++) if (mark[i]) {

                fill(d + 1, d + n * m + 1, 0);

                for (int j = 0; j < E.size(); j++) {

                    if (i ^ j && mark[j]) d[E[j][0]]++, d[E[j][1]]++;

                }

                for (int j = 0; j < E.size(); j++) if (!mark[j]) {

                    if (d[E[j][0]] < lim[E[j][0]] && d[E[j][1]] < lim[E[j][1]]) G[j].push_back(i);

                }

            }

            for (int i = 0; i < E.size(); i++) if (!mark[i]) {

                iota(fa + 1, fa + n * m + 1, 1);

                for (int j = 0; j < E.size(); j++) {

                    if (i ^ j && !mark[j]) fa[find(E[j][0])] = find(E[j][1]);

                }

                int num = 0;

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

                    if (!ban[j] && j == find(j)) num++;

                }

                for (int j = 0; j < E.size(); j++) if (mark[j]) {

                    if (num == 1 || num == 2 && find(E[j][0]) ^ find(E[j][1])) G[j].push_back(i);

                }

            }

            fill(in1, in1 + E.size(), 0);

            fill(in2, in2 + E.size(), 0);

            for (int i = 0; i < E.size(); i++) if (!mark[i]) {

                iota(fa + 1, fa + n * m + 1, 1);

                fill(d + 1, d + n * m + 1, 0);

                bool flag = 0;

                for (int j = 0; j < E.size(); j++) {

                    if (i ^ j && !mark[j]) fa[find(E[j][0])] = find(E[j][1]);

                    else if (++d[E[j][0]] > lim[E[j][0]] || ++d[E[j][1]] > lim[E[j][1]]) flag = 1;

                }

                int num = 0;

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

                    if (!ban[j] && j == find(j)) num++;

                }

                in1[i] = num == 1, in2[i] = !flag;

            }

            fill(vis, vis + E.size(), 0);

            queue<int> Q;

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

                if (in1[i]) Q.push(i), vis[i] = 1;

            }

            bool flag = 0;

            while (!Q.empty()) {

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

                if (in2[u]) {

                    while (1) {

                        mark[u] ^= 1;

                        if (in1[u]) break;

                        u = pre[u];

                    }

                    flag = 1; break;

                }

                for (int v : G[u]) if (!vis[v]) {

                    Q.push(v), vis[v] = 1, pre[v] = u;

                }

            }

            if (!flag) break;

        }

        if (count(mark, mark + E.size(), 0) >= cnt) {

            puts("NO"); continue;

        }

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

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

                ans[2 * i - 1][2 * j - 1] = str[i][j];

                ans[2 * i][2 * j - 1] = ~eid[i][j][0] && mark[eid[i][j][0]] ? ' ' : 'O';

                ans[2 * i - 1][2 * j] = ~eid[i][j][1] && mark[eid[i][j][1]] ? ' ' : 'O';

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

            }

        }

        puts("YES");

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

            for (int j = 1; j < 2 * m; j++) putchar(ans[i][j]);

            putchar('\n');

        }

    }

    return 0;

}


A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
int jinzhi(int n,int i)
{
	int k=n,temp=0,sum=0;
	while(k>0)
	{
		sum=sum+k%i;
		k=k/i;
	}
	return sum;
}
int gys(int n,int m)
{
	if(n%m==0) return m;
	return gys(m,n%m);
}
int main()
{
	int i,j,k,n,m,sum=0,p;
	cin>>n;
	for(i=2;i<=n-1;i++) sum=sum+jinzhi(n,i);
	n=n-2;
	if(sum<n) swap(sum,n);
	p=gys(sum,n);
	sum=sum/p;
	n=n/p;
	cout<<sum<<"/"<<n;
	return 0;
}


C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between 00 and n−2n−2 inclusive.  All the written labels are distinct.  The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample:

#define _CRT_SECURE_NO_WARNINGS

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

typedef long double ld;

typedef vector<int> vi;

typedef vector<ll> vl;

typedef pair<int, int>pi;

typedef pair<ll, ll>pl;

typedef vector<pi>vpi;

typedef vector<pl>vpl;

typedef vector<vi> vvi;

typedef vector<vl> vvl;

typedef vector<string> vs;

typedef vector<bool> vb;

typedef priority_queue<int> pqi;

typedef priority_queue<int, vi, greater<int>> pqI;

typedef priority_queue<ll> pql;

typedef priority_queue<ll, vl, greater<ll>> pqL;

const long double PI = acos(-1);

const int oo = 1e9 + 7;

const int MOD = 1e9 + 7;

const int N = 1e5 + 7;

#define endl '\n'

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

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

#define read(v) for (auto& it : v) scanf("%d", &it);

#define readL(v) for (auto& it : v) scanf("%lld", &it);

#define print(v) for (auto it : v) printf("%d ", it); puts("");

#define printL(v) for (auto it : v) printf("%lld ", it); puts("");

void solve() {

	int n;

	scanf("%d", &n);

	if (n == 2) {

		puts("0");

		return;

	}

	vvi g(n + 1);

	map<pi, int>idx;

	vi ans(n - 1, -1);

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

		scanf("%d %d", &u, &v);

		g[u].push_back(v);

		g[v].push_back(u);

		idx[{u, v}] = idx[{v, u}] = i;

	}

	int cur = 0;

	for (int i = 1; i <= n && cur <= 2; i++)

		if (g[i].size() == 1)

			ans[idx[{i, g[i][0]}]] = cur++;

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

		if (ans[i] == -1)

			ans[i] = cur++;

	for (auto& it : ans)

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

}

int t = 1;

int main() {

#ifndef ONLINE_JUDGE

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

#endif

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

	while (t--) solve();

}


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

#include<bits/stdc++.h>

#define ll long long

#define pb push_back

#define pf push_front

#define pob pop_back

#define pof pop_front

#define ff first

#define ss second

#define PLL pair<ll,ll>

#define pii pair<int,int>

#define SetBit(x, k) (x |= (1LL << k))

#define ClearBit(x, k) (x &= ~(1LL << k))

#define CheckBit(x, k) (x & (1LL << k))

#define scn(n) scanf("%d",&n)

#define scnll(n) scanf("%lld",&n)

#define nl cout<<"\n"

#define YES cout<<"YES\n"

#define Yes cout<<"Yes\n"

#define yes cout<<"yes\n"

#define NO cout<<"NO\n"

#define No cout<<"No\n"

#define no cout<<"no\n"

#define mod 1000000007LL

#define mod1 1000000007LL

#define mod2 1000000009LL

#define inf 1000000000000000LL

#define N 200000

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

using namespace std;

int main()

{

    fastio;

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

    int a[n+2][m+2];

    map<int,int> cnt[m+2];

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

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

            cin>>a[i][j];

            if(a[i][j]%m==j){

                int x=a[i][j]/m;

                if(x>=n) continue;

                x=i-x;

                if(x<0){

                    x+=n;

                }

                cnt[j][x]++;

            }

            if(j==m&&(a[i][j]%m==0)){

                int x=a[i][j]/m;

                x--;

                if(x>=n) continue;

                x=i-x;

                if(x<0){

                    x+=n;

                }

                cnt[j][x]++;

            }

        }

    }

    int ans=0;

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

        int res=n;

        for(auto x:cnt[j]){

            ///cout<<x.ff<<" "<<x.ss<<"\n";

            int r=n-x.ss+x.ff;

            res=min(res,r);

        }

        ///nl;nl;

        ans+=res;

    }

    cout<<ans<<"\n";

}


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

#include <bits/stdc++.h>

using namespace std;

using LL = long long;

#define endl '\n'

using db = double;

template <class T>

using max_heap = priority_queue<T>;

template <class T>

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

void solve()

{

    int n;

    cin >> n;

    string s;

    cin >> s;

    auto work = [&](string s) -> vector<int>

    {

        s += '>';

        vector<int> a;

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

        {

            if (s[i] == '>')

            {

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

                    a.push_back(j);

                last = i;

            }

        }

        return a;

    };

    auto ans = work(s);

    for (auto x : ans)

        cout << x << " ";

    cout << endl;

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

        s[i] = '>' + '<' - s[i];

    ans = work(s);

    for (auto x : ans)

        cout << n - x + 1 << " ";

    cout << endl;

}

int main()

{

    ios::sync_with_stdio(false);

    cin.tie(nullptr);

    int T;

    cin >> T;

    while (T--)

        solve();

    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;

// #include <ext/pb_ds/assoc_container.hpp>   // everything related to pbds

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

// using namespace __gnu_pbds;

// typedef int node; // change type here

// typedef tree<node, null_type, less<node>,

//              rb_tree_tag, tree_order_statistics_node_update> // this is push_backds

//     ordered_set;

using ll = long long;

using vi = vector<long long>;

using vpi = vector<pair<ll, ll>>;

typedef long double ld;

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

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

#define lb lower_bound

#define ps(x, y) fixed << setprecision(y) << x

#define int long long

ll INF = 1e18;

ll MOD = 1000000007;

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

int dy[] = {-1, 1, 0, 0}; // useful when dealing with points

ll maxx(vi &a)

{

    return (*max_element(a.begin(), a.end()));

}

ll minn(vi &a)

{

    return (*min_element(a.begin(), a.end()));

}

long long gcd(ll a, ll b)

{

    if (b == 0)

        return a;

    return gcd(b, a % b);

}

// Function to return LCM of two numbers

long long lcm(ll a, ll b)

{

    return (a / gcd(a, b)) * b;

}

bool isPrime(ll n)

{

    for (ll i = 2; i * i <= n; i++)

    {

        if (n % i == 0)

        {

            return false;

        }

    }

    return true;

}

long long mod(long long x)

{

    return ((x % MOD + MOD) % MOD);

}

long long add(long long a, long long b)

{

    return mod(mod(a) + mod(b));

}

long long mul(long long a, long long b)

{

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

}

void input(vi &a)

{

    int n = a.size();

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

    {

        cin >> a[i];

    }

}

void print(vi &a)

{

    for (auto x : a)

    {

        cout << x << " ";

    }

    cout << endl;

}

int stringToInt(string s)

{

    stringstream geek(s);

    int x = 0;

    geek >> x;

    return x;

}

bool isPowerOfTwo(ll n)

{

    if (n == 0)

        return false;

    return (ceil(log2(n)) == floor(log2(n)));

}

bool isPalindrome(string s)

{

    int n = s.size();

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

    {

        if (s[i] != s[n - i - 1])

        {

            return false;

        }

    }

    return true;

}

string binaryTransformation(long long x)

{

    if (x == 0)

        return "";

    else

    {

        string s = binaryTransformation(x / 2);

        s.push_back(char('0' + x % 2));

        return s;

    }

}

ll power(ll a, ll b, ll mod)

{

    if (b == 0)

    {

        return 1;

    }

    ll ans = power(a, b / 2, mod);

    ans *= ans;

    ans %= mod;

    if (b % 2)

    {

        ans *= a;

    }

    return ans % mod;

}

double power(double a, int b)

{

    if (b == 0)

    {

        return 1;

    }

    double t = power(a, b / 2);

    if (b & 1)

    {

        return t * t * a;

    }

    else

    {

        return t * t;

    }

}

int modularInverse(int number, int mod)

{

    return power(number, mod - 2, mod);

}

// it should be 1LL and not 1

// write more tests

// google if stuck

// take a walk if stuck

// precompute first

const int N = 2000;

int fact[N], invfact[N];

int pow(int a, int b, int m)

{

    int ans = 1;

    while (b)

    {

        if (b & 1)

            ans = (ans * a) % m;

        b /= 2;

        a = (a * a) % m;

    }

    return ans;

}

int modinv(int k)

{

    return pow(k, MOD - 2, MOD);

}

void precompute()

{

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

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

    {

        fact[i] = fact[i - 1] * i;

        fact[i] %= MOD;

    }

    invfact[N - 1] = modinv(fact[N - 1]);

    for (int i = N - 2; i >= 0; i--)

    {

        invfact[i] = invfact[i + 1] * (i + 1);

        invfact[i] %= MOD;

    }

}

int nCr(int x, int y)

{

    if (y > x)

        return 0;

    int num = fact[x];

    num *= invfact[y];

    num %= MOD;

    num *= invfact[x - y];

    num %= MOD;

    return num;

}

void solve()

{

    // learned a lot from this problem ,lol

    // relearned stars and bars

    // basically we have 2*m positions and n candidates for each position

    // this can be rewritten as x1 + x2+x3+...xn= 2*m, here xi>=0

    // so when we place a bar it means that many positions for that number

    int n, m;

    cin >> n >> m;

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

}

// you should look down sometimes

// https://github.com/Manjunath0408/CPSnippets

int32_t main()

{

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

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

    /* stuff you should look for

     * int overflow, array bounds

     * special cases (n==1?)

     * do smth instead of nothing and stay organized

     * WRITE STUFF DOWN

     * DON'T GET STUCK ON ONE APPROACH

     * IF STUCK ON A QUESTION, MOVE TO THE NEXT ONE

     */

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int t = 1;

    precompute();

    // cin >> t;

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

    {

        solve();

    }

    return 0;

}


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

/*

        ফেরা হলো না ঘরে, নাহি ফিরলো ঘর দিকে আমার,

        এসে পথেরই মাঝে,

        পেছনে তাকিয়ে ফিরে আবার

        হেঁটে যাই আমি খুঁজতে কিছু, আমি আজও জানিনা কিসেরি পিছু!

*/

#include <bits/stdc++.h>

using namespace std;

#ifdef ONLINE_JUDGE

#define fast ios_base::sync_with_stdio(0); cin.tie(0);  // fast IO! but only when online_judge

#define debug 0

#else

#define fast ;

#define debug 1

#endif

// some typedefs for my convenience

#define int long long int

#define pii pair<int, int>

#define vi vector<int>

#define si set<int>

#define mi map<int, int>

// some speedup macros

#define gap ' '

#define endl '\n'

#define print(str) cout << str << endl

#define YES print("YES")

#define NO print("NO")

#define loop(i, begin, end) for(__typeof(end)i=begin-(begin>end); i!=end-(begin>end); i+=1-2*(begin>end))

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

void solve(int cases);

int32_t main()

{

    fast

    int total_cases = 1;

    // cin >> total_cases;

    loop(cases, 1, total_cases+1) solve(cases);

    return 0;

}

// SOLVE STARTS HERE

int dc(vi &v, int bit, int cases)

{

    if (bit == -1) return 0;

    vi ones, zeros;

    int ocount = 0, zcount = 0, out = 0;

    for (auto x: v){

        if ((x>>bit) & 1) ocount++, ones.push_back(x);

        else zcount++, zeros.push_back(x);

    }

    if (ocount && zcount){

        out = 1 << bit;

        out |= min(dc(zeros, bit-1, cases), dc(ones, bit-1, cases));

    }

    else if (ocount) out = dc(ones, bit-1, cases);

    else if (zcount) out = dc(zeros, bit-1, cases);

    return out;

}

void solve(int cases)

{

    int n, q, out=0, sum=0, flag=0, maxi=LLONG_MIN, mini=LLONG_MAX;

    int in;

    cin >> n;

    vi v(n);

    #define printp(p) cout << '(' << p.F << ',' << gap << p.S << ')' << endl;

    #define printx(array) { for (auto x : array) cout << x << gap; cout << endl; }

    #define scanx(array) { for (auto &x: array) cin >> x; }

    #define printxp(array) { for (auto x : array) cout << '(' << x.first << ',' << gap << x.second << ')' << gap; cout << endl; }

    scanx(v);

    print(dc(v, 31 - __builtin_clz(*max_element(all(v))), n));

END:;

}

/*

        Fihad arRahman

        hellofihad@gmail.com

        18-02-2023 20:32

*/


E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times:   choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|;  erase the chosen subsequence from ss (ss can become empty);  concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using ld = long double;

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

constexpr int inf = 0x7f7f7f7f;

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

short dp[N][N][N];

string s, t;

void solve(){

    cin >> s >> t;

    for(short i = 0; i <= s.size(); i++){

        for(short j = 0; j <= t.size(); j++){

            for(short k = 0; k < t.size(); k++){

                dp[i][j][k] = 0;

            }

            dp[s.size()][j][t.size()] = j;

        }

    }

    for(short i = s.size() - 1; ~i; i--){

        for(short j = t.size(); ~j; j--){

            for(short k = t.size(); ~k; k--){

                auto& r = dp[i][j][k] = dp[i + 1][j][k];

                if(s[i] == t[j]) r = max(r, dp[i + 1][j + 1][k]);

                if(s[i] == t[k]) r = max(r, dp[i + 1][j][k + 1]);

            }

        }

    }

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

        if(dp[0][0][i + 1] > i){

            cout << "YES\n";

            return;

        }

    }

    cout << "NO\n";

}

int main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    int t = 1;

    cin >> t;

    while(t--){

        solve();

    }

}


G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions:  if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second;  use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier.

#include<bits/stdc++.h>

#define endl '\n'

#define iloveds std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);

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

using namespace std;

typedef long long ll ;

const int N = 1e6 + 100;

int n, ch[N][26], k, a[N], b[N], dfn[N], ans[N], f[N];

int tot, dp[N], val;

void dfs(int x){

	if(f[x]) {

		dfn[x] = ++ tot;

	}

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

		if(ch[x][i]){

			dfs(ch[x][i]);

			dfn[x] = min(dfn[x], dfn[ch[x][i]]);

		}

	}

}

void dfs2(int x){

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

		int tmp = val;

		if(ch[x][i]) {

			if(f[ch[x][i]]){

				dp[ch[x][i]] = min(dp[x] + 1, dfn[ch[x][i]] + val);

			}else{

				dp[ch[x][i]] = dp[x] + 1;

			}

			val = min(val, dp[ch[x][i]] - dfn[ch[x][i]] + 1);

			dfs2(ch[x][i]);

		}

		val = tmp;

	}

}

// dp[fa] - dfn[fa] + 1 + dfn[x];

int main(){

	iloveds;

	cin >> n;

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

		int x;

		char c;

		cin >> x >> c;

		ch[x][c - 'a'] = i;

	}

	cin >> k;

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

		cin >> a[i];

		f[a[i]] = 1;

	}

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

		dp[i] = 0x3f3f3f3f;

		dfn[i] = 0x3f3f3f3f;

	}

	dfs(0);

	val = 0;

	dfs2(0);

	for(int i = 1; i <= k ; i ++) cout << dp[a[i]] << " ";

}


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

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

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

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

#define st first

#define nd second

using namespace __gnu_pbds;

using namespace std;

template <typename T>

using ordered_set =

	tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define sim template <class c

#define ris return *this

#define dor > debug &operator<<

#define eni(x)                                                                    \

	sim > typename enable_if<sizeof dud<c>(0) x 1, debug &>::type operator<<(c i) \

	{

sim > struct rge

{

	c b, e;

};

sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }

sim > auto dud(c *x) -> decltype(cerr << *x, 0);

sim > char dud(...);

#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

#define shandom_ruffle random_shuffle

#define PB push_back

#define MP make_pair

#define LL long long

// #define int LL

#define VI vector<int>

#define PII pair<int, int>

#define LD long double

#define st first

#define nd second

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

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

using ll = long long;

using pii = pair<int, int>;

using pll = pair<ll, ll>;

using vi = vector<int>;

using vll = vector<ll>;

struct Matroid

{

	int n;

	Matroid(int size) : n(size) {}

	virtual ~Matroid() {}

	// Returns any circuit as the subset of [X]. Returns an empty vector

	// if [X] is independent.

	virtual VI FindCircuit(const vector<int> &)

	{

		throw nullptr;

	}

	bool IsIndependent(const vector<int> &X)

	{

		return FindCircuit(X).empty();

	}

};

int H, W;

string board[30];

vector<pii> verts;

vector<pii> edges;

int ids[30][30];

vector<pii> adj[1000];

int num_edges, nverts;

bool is_in[1000];

int out_bound[1000];

vector<pair<vi, int>> bounds;

int bound_mapping[1000];

struct FU

{

	vi pnt;

	FU(int n) : pnt(n)

	{

		iota(ALL(pnt), 0);

	}

	int Find(int v)

	{

		if (pnt[v] == v)

		{

			return v;

		}

		return pnt[v] = Find(pnt[v]);

	}

};

struct CographicMatroid : public Matroid

{

	CographicMatroid() : Matroid(num_edges) {}

	virtual ~CographicMatroid() {}

	VI FindCircuit(const vector<int> &X) override

	{

		memset(is_in, 0, sizeof(bool) * num_edges);

		for (int v : X)

		{

			is_in[v] = true;

		}

		FU fu(nverts);

		int ncomp = nverts;

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

		{

			if (!is_in[i])

			{

				int a = fu.Find(edges[i].st);

				int b = fu.Find(edges[i].nd);

				if (a != b)

				{

					fu.pnt[a] = b;

					--ncomp;

				}

			}

		}

		if (ncomp == 1)

		{

			return {};

		}

		vi indep;

		for (int v : X)

		{

			int a = fu.Find(edges[v].st);

			int b = fu.Find(edges[v].nd);

			if (a != b && ncomp == 2)

			{

				indep.push_back(v);

				continue;

			}

			if (a != b)

			{

				fu.pnt[a] = b;

				--ncomp;

			}

		}

		return indep;

	}

};

struct MaxChoiceMatroid : public Matroid

{

	MaxChoiceMatroid() : Matroid(num_edges) {}

	virtual ~MaxChoiceMatroid() {}

	VI FindCircuit(const vector<int> &X) override

	{

		vector<vi> lists(SZ(bounds));

		for (int v : X)

		{

			const int where = bound_mapping[v];

			if (where == -1)

			{

				continue;

			}

			lists[where].push_back(v);

			if (SZ(lists[where]) > bounds[where].nd)

			{

				return lists[where];

			}

		}

		return {};

	}

};

VI IntersectMatroids(Matroid *A, Matroid *B)

{

	assert(A->n == B->n);

	const int n = A->n;

	vector<VI> graph;

	VI X;

	while (true)

	{

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

		{

			if (count(ALL(X), i))

			{

				continue;

			}

			auto Y = X;

			Y.PB(i);

			if (A->IsIndependent(Y) && B->IsIndependent(Y))

			{

				X = Y;

			}

		}

		//~ debug(X);

		vector<bool> is_x(n), is_a(n), is_b(n);

		for (int x : X)

		{

			is_x[x] = true;

		}

		graph.clear();

		graph.resize(2 * n);

		queue<int> Q;

		VI dist(2 * n, 1e9), prv(2 * n, -1);

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

		{

			if (is_x[y])

			{

				continue;

			}

			auto Y = X;

			Y.PB(y);

			auto circ_a = A->FindCircuit(Y);

			if (circ_a.empty())

			{

				is_a[y] = true;

				Q.push(y + n);

				dist[y + n] = 0;

			}

			else

			{

				for (int x : circ_a)

				{

					graph[x].PB(y + n);

				}

			}

			auto circ_b = B->FindCircuit(Y);

			if (circ_b.empty())

			{

				is_b[y] = true;

			}

			else

			{

				for (int x : circ_b)

				{

					graph[y + n].PB(x);

				}

			}

			//~ debug(y, circ_a, circ_b);

		}

		int dest = -1;

		while (!Q.empty())

		{

			int v = Q.front();

			Q.pop();

			if (v >= n && is_b[v - n])

			{

				dest = v;

				break;

			}

			for (int s : graph[v])

			{

				if (dist[s] > dist[v] + 1)

				{

					dist[s] = dist[v] + 1;

					prv[s] = v;

					Q.push(s);

				}

			}

		}

		if (dest == -1)

		{

			break;

		}

		while (dest != -1)

		{

			const int p = dest % n;

			//~ debug(p);

			is_x[p] = !is_x[p];

			dest = prv[dest];

		}

		assert(count(ALL(is_x), true) == SZ(X) + 1);

		X.clear();

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

		{

			if (is_x[i])

			{

				X.PB(i);

			}

		}

	}

	return X;

}

void Test()

{

	cin >> H >> W;

	int cnt = 0;

	verts.clear();

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

	{

		cin >> board[i];

		for (int j = 0; j < W; ++j)

		{

			ids[i][j] = -1;

			if (board[i][j] == 'O')

			{

				verts.emplace_back(i, j);

				ids[i][j] = cnt;

				++cnt;

			}

		}

	}

	edges.clear();

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

	{

		adj[i].clear();

	}

	int eid = 0;

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

	{

		for (int j = 0; j < W; ++j)

		{

			if (j < W - 1 && board[i][j] == 'O' && board[i][j + 1] == 'O')

			{

				int a = ids[i][j];

				int b = ids[i][j + 1];

				adj[a].emplace_back(b, eid);

				adj[b].emplace_back(a, eid);

				edges.emplace_back(a, b);

				eid++;

			}

			if (i < H - 1 && board[i][j] == 'O' && board[i + 1][j] == 'O')

			{

				int a = ids[i][j];

				int b = ids[i + 1][j];

				adj[a].emplace_back(b, eid);

				adj[b].emplace_back(a, eid);

				edges.emplace_back(a, b);

				eid++;

			}

		}

	}

	num_edges = SZ(edges);

	nverts = cnt;

	bounds.clear();

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

	{

		bound_mapping[i] = -1;

	}

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

	{

		for (int j = 0; j < W; ++j)

		{

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

			{

				continue;

			}

			if (board[i][j] == 'O')

			{

				const int v = ids[i][j];

				out_bound[v] = SZ(adj[v]) - 1;

				if ((i + j) % 2 == 0)

				{

					--out_bound[v];

				}

				if (out_bound[v] < 0)

				{

					cout << "NO\n";

					return;

				}

				if ((i + j) % 2 == 0)

				{

					vi eids;

					for (auto &e : adj[v])

					{

						eids.push_back(e.nd);

						bound_mapping[e.nd] = SZ(bounds);

					}

					bounds.emplace_back(eids, out_bound[v]);

				}

			}

		}

	}

	Matroid *cographic = new CographicMatroid();

	Matroid *max_choice = new MaxChoiceMatroid();

	auto inter = IntersectMatroids(cographic, max_choice);

	const int num_blocked = SZ(inter);

	const int need_blocked = num_edges - (nverts - 1);

	if (num_blocked < need_blocked)

	{

		delete cographic;

		delete max_choice;

		cout << "NO\n";

		return;

	}

	vector<string> ans(2 * H - 1, string(2 * W - 1, ' '));

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

	{

		for (int j = 0; j < W; ++j)

		{

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

		}

	}

	for (auto &E : edges)

	{

		int a = E.st;

		int b = E.nd;

		auto [r1, c1] = verts[a];

		auto [r2, c2] = verts[b];

		if (r1 == r2)

		{

			ans[2 * r1][2 * min(c1, c2) + 1] = 'O';

		}

		else

		{

			ans[2 * min(r1, r2) + 1][2 * c1] = 'O';

		}

	}

	for (int v : inter)

	{

		int a = edges[v].st;

		int b = edges[v].nd;

		auto [r1, c1] = verts[a];

		auto [r2, c2] = verts[b];

		if (r1 == r2)

		{

			ans[2 * r1][2 * min(c1, c2) + 1] = ' ';

		}

		else

		{

			ans[2 * min(r1, r2) + 1][2 * c1] = ' ';

		}

	}

	cout << "YES\n";

	for (auto s : ans)

	{

		cout << s << "\n";

	}

	delete cographic;

	delete max_choice;

}

int main()

{

	ios_base::sync_with_stdio(0);

	cin.tie(0);

	cout << fixed << setprecision(11);

	cerr << fixed << setprecision(6);

	int t;

	cin >> t;

	while (t--)

	{

		Test();

	}

}