#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define fi first
#define se second
#define PII pair<int,int>
#define PIC pair<int,char>
#define PCI pair<char,int>
#define PCC pair<char,char>
int fx[8]={1,-1,0,0,1,-1,-1,1};
int fy[8]={0,0,-1,1,1,-1,1,-1};
const int inf=1e16;
const int N=1e6+10;
const int INF=9e18;
const int mod=1e9+7;
//括号最短匹配问题，记录左括号的数量，按需匹配即可，如果需要计算，则用栈计算。
//a =" " + a, 判断a字符串要加" ";
//a*b=n,跑两层循环不会爆，调和级数,埃式塞法
//log2 (1e9) = 30
// &,|的优先级比！=低要注意。
// i % 4 + 1//范围1~~4循环
//一个有序数组，upper_bound(r)-lower_bound(l)为区间[l,r]的个数。
//vector<map<string,map<string,int>>>p(n+10);再用一个map<string,int>
//即可达成p[i][sa][sb]三个字符串来确定一条边的个数。
//选择max(l,fi)和min(r,se)即可让重复的区间减少最多。
//需要考虑分配问题的时候，可以直接判断阈值，然后再进行平均分配即可。
//遇到最值问题直接考虑二分
//前缀积要爆，遇到l,r就要考虑前缀和。
//遇到不等式，把相同变量移到同一边。
//遇到两个数要满足某个条件，则可以用map<条件，int>的方式算出组合数。
//long long 7e18
//遇到消除字符串特定字符，用栈堆实现
//遇到一段长度求区间个数，利用左右区间前缀和，相减即可。
//遇到迷宫就改建筑,end!=make_pair(1ll,1ll)
//当遇到环形问题的时候，我们可以在后面接一个数组从而达成环形条件。
//如果遇到只能转移到后面，则我们考虑挨个转移即可。
//质数在2e5范围内大概15间隔一个。
//当遇到两种状态，其中一种最优，但是最后需要另一种优化，可以用dp优化一下
//当需要进行整体最大值递归的时候，只需要定义一个全局变量进行比较即可

int n,m   ;
int a[N];

void solve(){
	string s;
	cin>>s;
	for (int k=1;k<=50;k++){
		for (int i=0;i<s.size()-1;i++){
			if(s[i]<s[i+1]-1) {
				swap(s[i],s[i+1]);
				s[i]-=1;
			}
		}
	}
	for (int i=0;i<s.size();i++){
		cout<<s[i];
	}
	cout<<endl;

}
signed main(){
	ios::sync_with_stdio(false),cin.tie(0);
	int _=1;
	cin>>_;
	while(_--){
		solve();

	}

	return 0;
}
/*

 */

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define fi first
#define se second
#define PII pair<int,int>
#define PIC pair<int,char>
#define PCI pair<char,int>
#define PCC pair<char,char>
int fx[8] = {1, -1, 0, 0, 1, -1, -1, 1};
int fy[8] = {0, 0, -1, 1, 1, -1, 1, -1};
const int inf = 1e16;
const int N = 1e6 + 10;
const int INF = 9e18;
const int mod = 1e9 + 7;
//括号最短匹配问题，记录左括号的数量，按需匹配即可，如果需要计算，则用栈计算。
//a =" " + a, 判断a字符串要加" ";
//a*b=n,跑两层循环不会爆，调和级数,埃式塞法
//log2 (1e9) = 30
// &,|的优先级比！=低要注意。
// i % 4 + 1//范围1~~4循环
//一个有序数组，upper_bound(r)-lower_bound(l)为区间[l,r]的个数。
//vector<map<string,map<string,int>>>p(n+10);再用一个map<string,int>
//即可达成p[i][sa][sb]三个字符串来确定一条边的个数。
//选择max(l,fi)和min(r,se)即可让重复的区间减少最多。
//需要考虑分配问题的时候，可以直接判断阈值，然后再进行平均分配即可。
//遇到最值问题直接考虑二分
//前缀积要爆，遇到l,r就要考虑前缀和。
//遇到不等式，把相同变量移到同一边。
//遇到两个数要满足某个条件，则可以用map<条件，int>的方式算出组合数。
//long long 7e18
//遇到消除字符串特定字符，用栈堆实现
//遇到一段长度求区间个数，利用左右区间前缀和，相减即可。
//遇到迷宫就改建筑,end!=make_pair(1ll,1ll)
//当遇到环形问题的时候，我们可以在后面接一个数组从而达成环形条件。
//如果遇到只能转移到后面，则我们考虑挨个转移即可。
//质数在2e5范围内大概15间隔一个。
//当遇到两种状态，其中一种最优，但是最后需要另一种优化，可以用dp优化一下
//当需要进行整体最大值递归的时候，只需要定义一个全局变量进行比较即可

int n, m   ;
char s[N];

void solve()
{
	string s;
	cin >> s;
	int sum = 0, cnt = 0, kk = 0;
	for (int i = 0; i < s.size(); i++)
	{
		sum += s[i] - '0';
		if (s[i] == '2') cnt++;
		else if (s[i] == '3') kk++;
	}
	if (sum % 9 == 0) cout << "Yes" << endl;
	else
	{
		for (int i = 0; i <= min((int)25, cnt); i++)
		{
			for (int j = 0; j <= kk; j++)
			{
				int  sum1 = sum + 2 * i + j * 6;
				if (sum1 % 9 == 0)
				{
					cout << "Yes" << endl;
					return ;
				}
			}
		}
		cout << "No" << endl;
	}
}
signed main()
{
	ios::sync_with_stdio(false), cin.tie(0);
	int _ = 1;
	cin >> _;
	while (_--)
	{
		solve();

	}

	return 0;
}
/*

 */

Answer: 1


// I AM NOT HERE TO PARTICIPATE, I AM HERE TO DOMINATE

#define JAI ios::sync_with_stdio(false);

#define SHREE cin.tie(NULL);

#define RAM cout.tie(NULL);

#include <bits/stdc++.h>

#define f(i, n, k) for (int i; i < n; i += k)

#define pb push_back

#define ppb pop_back

#define int long long

#define mp make_pair

using namespace std;

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

using pi = pair < int, int > ;

using vi = vector < int > ;

using mapi = map < int, int > ;

using vvi = vector < vector < int >> ;

#define ff first

#define ss second

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

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

const int inf = 9e17;

const int mod = 1e9 + 7;

#define DEBUG(x) cerr << #x << ": " << x << '\n'

template < typename T, typename Y >

istream & operator >> (istream & is, pair < T, Y > & p)

{

is >> p.first >> p.second;

return is;

}

template < typename T, typename Y >

ostream & operator << (ostream & os, pair < T, Y > p)

{

os << p.first << ' ' << p.second << ' ';

return os;

}

template < typename T >

istream & operator >> (istream & is, vector < T > & v)

{

for (auto & i: v)

is >> i;

return is;

}

template < typename T >

ostream & operator << (ostream & os, vector < T > v)

{

for (auto & i: v)

os << i << ' ';

return os;

}

int power(int base, int ex, int mod) {

int res = 1;

while (ex > 0) {

if (ex % 2 == 1) {

res = (res * base) % mod;

}

base = (base * base) % mod;

ex /= 2;

}

return res;

}

void sol() {

string str;

cin>>str;

int n = str.length();

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

int x1 = 0;

int max_x1 = str[i] - '0';

int ind1 = i;

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

x1 = (str[j] - '0') - (j-i);

if(x1 > str[i] - '0'){

if(x1 > max_x1){

max_x1 = x1;

ind1 = j;

}

}

}

while(ind1 > i){

swap(str[ind1],str[ind1-1]);

ind1--;

}

str[i] =char( max_x1 + '0');

}

cout<<str;

}

signed main() {

JAI SHREE RAM

int t;

cin >> t;

while (t--) {

sol();

cout<<endl;

}

}

// I AM NOT HERE TO PARTICIPATE, I AM HERE TO DOMINATE

#define JAI ios::sync_with_stdio(false);

#define SHREE cin.tie(NULL);

#define RAM cout.tie(NULL);

#include <bits/stdc++.h>

#define f(i, n, k) for (int i; i < n; i += k)

#define pb push_back

#define ppb pop_back

#define int long long

#define mp make_pair

using namespace std;

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

using pi = pair < int, int > ;

using vi = vector < int > ;

using mapi = map < int, int > ;

using vvi = vector < vector < int >> ;

#define ff first

#define ss second

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

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

const int inf = 9e17;

const int mod = 1e9 + 7;

#define DEBUG(x) cerr << #x << ": " << x << '\n'

template < typename T, typename Y >

istream & operator >> (istream & is, pair < T, Y > & p)

{

is >> p.first >> p.second;

return is;

}

template < typename T, typename Y >

ostream & operator << (ostream & os, pair < T, Y > p)

{

os << p.first << ' ' << p.second << ' ';

return os;

}

template < typename T >

istream & operator >> (istream & is, vector < T > & v)

{

for (auto & i: v)

is >> i;

return is;

}

template < typename T >

ostream & operator << (ostream & os, vector < T > v)

{

for (auto & i: v)

os << i << ' ';

return os;

}

int power(int base, int ex, int mod) {

int res = 1;

while (ex > 0) {

if (ex % 2 == 1) {

res = (res * base) % mod;

}

base = (base * base) % mod;

ex /= 2;

}

return res;

}

void sol() {

string str;

cin>>str;

int n = str.length();

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

int x = 0;

int max_x = -1;

int ind = i;

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

if(j>=n) break;

x = (str[j] - '0') - (j-i);

if(x > str[i] - '0'){

if(x > max_x){

max_x = x;

ind = j;

}

}

}

str[ind] = (str[ind] - '0') -ind+i +'0';

swap(str[i],str[ind]);

}

cout<<str;

}

signed main() {

JAI SHREE RAM

int t;

cin >> t;

while (t--) {

sol();

cout<<endl;

}

}

Answer: 1


def solve():
    s = input()
    s = list(s)
    for i in range(len(s)):
        best = int(s[i])
        pos = i

        for j in range(i, min(i + 10, len(s))):
            if int(s[j]) - (j - i) > best:
                best = int(s[j]) - (j - i)
                pos = j

        while pos > i:
            s[pos], s[pos - 1] = s[pos - 1], s[pos]
            pos -= 1

        s[i] = str(best)

    print(''.join(s))

if __name__ == "__main__":
    TESTS = int(input())
    for _ in range(TESTS):
        solve()
        print()

n = int(input())
for _ in range(n):
    n1 = list(input())  # Convert input to a list for mutability
    length = len(n1)

    for i in range(length):
        best = int(n1[i])
        pos = i

        # Optimize the inner loop to minimize recalculations
        for j in range(i, min(i + 9, length)):
            value = int(n1[j]) - (j - i)
            if value > best:
                best = value
                pos = j

        # Perform swaps to bring the best element to the correct position
        while pos > i:
            n1[pos], n1[pos - 1] = n1[pos - 1], n1[pos]
            pos -= 1

        n1[i] = str(best)

    print("".join(n1))

Answer: 2


def Sieve(num):
    l2=[]
    prime = [True for i in range(num+1)]
    p = 2
    while (p * p <= num):
        if (prime[p] == True):
            for i in range(p * p, num+1, p):
                prime[i] = False
        p += 1
    for p in range(2, num+1):
        if prime[p]:
            l2.append(p)
    return((l2))
# s = Sieve(50)

def op(x,y):
    # print("X==",x)
    # print("Y==",y)
    return(x+y)
class segtree():
  def __init__(self,init,func,ide):
    self.n=len(init)
    self.func=func
    self.ide=ide
    self.size=1<<(self.n-1).bit_length()
    self.tree=[self.ide for i in range(2*self.size)]
    for i in range(self.n):
      self.tree[self.size+i]=init[i]
    for i in range(self.size-1,0,-1):
      self.tree[i]=self.func(self.tree[2*i], self.tree[(2*i)|1])

  def update(self,k,x):
    k+=self.size
    self.tree[k]=x

    k>>=1
    while k:
      self.tree[k]=self.func(self.tree[2*k],self.tree[k*2|1])
      k>>=1

  def get(self,i):
    return self.tree[i+self.size]

  def query(self,l,r):
    # Include left index but not right
    l+=self.size
    r+=self.size
    ans=0
    while l<r:
      if l&1:
        ans+= self.tree[l]
        l+=1
      if r&1:
        r-=1
        ans+= self.tree[r]
      l>>=1
      r>>=1
    return ans

  def debug(self,s=10):
    print([self.get(i) for i in range(min(self.n,s))])

class sortedlist:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """Build a fenwick tree instance."""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """Update `fen_tree[index] += value`."""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(range(len(_fen_tree).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -= _fen_tree[idx]
        return idx + 1, k

    def _delete(self, pos, idx):
        """Delete value at the given `(pos, idx)`."""
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1

        if _list_lens[pos]:
            _mins[pos] = _lists[pos][0]
        else:
            del _lists[pos]
            del _list_lens[pos]
            del _mins[pos]
            self._rebuild = True

    def _loc_left(self, value):
        """Return an index pair that corresponds to the first position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        lo, pos = -1, len(_lists) - 1
        while lo + 1 < pos:
            mi = (lo + pos) >> 1
            if value <= _mins[mi]:
                pos = mi
            else:
                lo = mi

        if pos and value <= _lists[pos - 1][-1]:
            pos -= 1

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value <= _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def _loc_right(self, value):
        """Return an index pair that corresponds to the last position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        pos, hi = 0, len(_lists)
        while pos + 1 < hi:
            mi = (pos + hi) >> 1
            if value < _mins[mi]:
                hi = mi
            else:
                pos = mi

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value < _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def add(self, value):
        """Add `value` to sorted list."""
        _load = self._load
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len += 1
        if _lists:
            pos, idx = self._loc_right(value)
            self._fen_update(pos, 1)
            _list = _lists[pos]
            _list.insert(idx, value)
            _list_lens[pos] += 1
            _mins[pos] = _list[0]
            if _load + _load < len(_list):
                _lists.insert(pos + 1, _list[_load:])
                _list_lens.insert(pos + 1, len(_list) - _load)
                _mins.insert(pos + 1, _list[_load])
                _list_lens[pos] = _load
                del _list[_load:]
                self._rebuild = True
        else:
            _lists.append([value])
            _mins.append(value)
            _list_lens.append(1)
            self._rebuild = True

    def discard(self, value):
        """Remove `value` from sorted list if it is a member."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_right(value)
            if idx and _lists[pos][idx - 1] == value:
                self._delete(pos, idx - 1)

    def remove(self, value):
        """Remove `value` from sorted list; `value` must be a member."""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """Remove and return value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        value = self._lists[pos][idx]
        self._delete(pos, idx)
        return value

    def bisect_left(self, value):
        """Return the first index to insert `value` in the sorted list."""
        pos, idx = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """Return the last index to insert `value` in the sorted list."""
        pos, idx = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """Return number of occurrences of `value` in the sorted list."""
        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __contains__(self, value):
        """Return true if `value` is an element of the sorted list."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_left(value)
            return idx < len(_lists[pos]) and _lists[pos][idx] == value
        return False

    def __iter__(self):
        """Return an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return 'SortedList({0})'.format(list(self))

from collections import deque,defaultdict
g = defaultdict()
def bfs(g, start):
    queue, enqueued = deque([(None, start)]), set([start])
    while queue:
        parent, n = queue.popleft()
        yield parent, n
        # Can use a variable fin, and break if n==fin
        new = set(g[n]) - enqueued
        enqueued |= new
        queue.extend([(n, child) for child in new])
# list(bfs(dict,initial pt)) gives ==> [(None,start),(start,x1),(x1,x2),(x1,x3),(x2,finish)]

class dsu:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1 for i in range(n)]
        self.num_sets = n
    def find(self, a):
        acopy = a
        while a != self.parent[a]:
            a = self.parent[a]
        while acopy != a:
            self.parent[acopy], acopy = a, self.parent[acopy]
        return a
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a != b:
            if self.size[a] < self.size[b]:
                a, b = b, a
            self.num_sets -= 1
            self.parent[b] = a
            self.size[a] += self.size[b]

# Initialize with u = dsu(No. of ele)[No.+1 for index out of range]
# Use while acopy != a loop to find tree-like properties

# Custom HashMap and Set for Anti-hash-table test
class CustomHashMap:
    def __init__(self, type = dict, arr = []):
        self.RANDOM = random.randrange(2**62)
        self.dict = type([self.wrapper(i) for i in arr])
    def wrapper(self,num):
        return num ^ self.RANDOM
    def __setitem__(self, key, value):
        self.dict[self.wrapper(key)] = value
    def __getitem__(self, key):
        return self.dict[self.wrapper(key)]
    def __contains__(self, key):
        return self.wrapper(key) in self.dict
    def __iter__(self):
        return iter(self.wrapper(i) for i in self.dict)
    def items(self):
        return [(self.wrapper(i),j) for i,j in self.dict.items()]
    def __repr__(self):
        return repr({self.wrapper(i):j for i,j in self.dict.items()})
#Use akin: a = CustomHashMap(Counter,a)  : {a is a LIST})
#          a.items() is a number of tuples like (2,3); len(a.items()) to get len(a)

from random import randint
# Random number from 1 to 10^9
RANDOM = randint(1, 10 ** 9)
class h(int):
    def __init__(self, x):
        int.__init__(x)

    def __hash__(self):
        return super(h, self).__hash__() ^ RANDOM
# h(x) gives a changed value of x which wont hash-collide

def pfactor(n):
    ans=defaultdict(int)
    s = Sieve(ceil(n**0.5))
    # print(s)
    for i in s:
        x = divmod(n,i)
        # print("X==",x)
        while(x[1]==0):
            ans[i]+=1
            n = x[0]
            x = divmod(n,i)
        if(n==1):
            break
    if(n!=1):
        ans[n]+=1
    return(ans)
# Returns a defaultdict of prime factorization

# Calculate nCr%p
def ncr(n, r, p):
    num = den = 1
    for i in range(r):
        num = (num * (n - i)) % p
        den = (den * (i + 1)) % p
    return (num * pow(den,p - 2, p)) % p

def factor(n):
  lower,upper=[],[]
  i=1
  while i*i<=n:
    if n%i==0:
      lower.append(i)
      if i!=n//i:
        upper.append(n//i)
    i+=1
  return lower+upper[::-1]

import random
from sys import stdin,stdout
input=lambda :stdin.readline()[:-1]
from collections import defaultdict, Counter, deque, OrderedDict
import itertools;from itertools import permutations as perms, combinations as combs,combinations_with_replacement
from bisect import bisect_left, bisect_right
from heapq import heapify, heappush, heappop, nlargest, nsmallest
import math
from functools import reduce
from math import inf,floor,ceil,comb,lcm,gcd,log2
from operator import itemgetter

def solve():
    a = list(map(int,list(str(input()))))
    n = len(a)
    # print("A==",a)
    ans = [-1 for i in range(n)]
    c = []
    f= 0
    for i in range(n):
        if(i==0):
            for j in range(min(11,n)):
                c.append([a[f],f])
                f+=1
        else:
            if(f<n):
                c.append([a[f],f])
                f+=1
        t =  0; v=  -1
        for j in range(len(c)):
            if(c[j][1]<i):
                if(c[j][0]>v):
                    t= j
                    v = c[j][0]
            else:
                if(c[j][0]-c[j][1]+i>v):
                    t = j
                    v = c[j][0]-c[j][1]+i
        x = c.pop(t)
        ans[i] = v

    # print("ANS==",ans)
    print(*ans,sep="")
for _ in range(int(input())):
    solve()

def Sieve(num):
    l2=[]
    prime = [True for i in range(num+1)]
    p = 2
    while (p * p <= num):
        if (prime[p] == True):
            for i in range(p * p, num+1, p):
                prime[i] = False
        p += 1
    for p in range(2, num+1):
        if prime[p]:
            l2.append(p)
    return((l2))
# s = Sieve(50)

def op(x,y):
    # print("X==",x)
    # print("Y==",y)
    return(x+y)
class segtree():
  def __init__(self,init,func,ide):
    self.n=len(init)
    self.func=func
    self.ide=ide
    self.size=1<<(self.n-1).bit_length()
    self.tree=[self.ide for i in range(2*self.size)]
    for i in range(self.n):
      self.tree[self.size+i]=init[i]
    for i in range(self.size-1,0,-1):
      self.tree[i]=self.func(self.tree[2*i], self.tree[(2*i)|1])

  def update(self,k,x):
    k+=self.size
    self.tree[k]=x

    k>>=1
    while k:
      self.tree[k]=self.func(self.tree[2*k],self.tree[k*2|1])
      k>>=1

  def get(self,i):
    return self.tree[i+self.size]

  def query(self,l,r):
    # Include left index but not right
    l+=self.size
    r+=self.size
    ans=0
    while l<r:
      if l&1:
        ans+= self.tree[l]
        l+=1
      if r&1:
        r-=1
        ans+= self.tree[r]
      l>>=1
      r>>=1
    return ans

  def debug(self,s=10):
    print([self.get(i) for i in range(min(self.n,s))])

class sortedlist:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """Build a fenwick tree instance."""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """Update `fen_tree[index] += value`."""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(range(len(_fen_tree).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -= _fen_tree[idx]
        return idx + 1, k

    def _delete(self, pos, idx):
        """Delete value at the given `(pos, idx)`."""
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1

        if _list_lens[pos]:
            _mins[pos] = _lists[pos][0]
        else:
            del _lists[pos]
            del _list_lens[pos]
            del _mins[pos]
            self._rebuild = True

    def _loc_left(self, value):
        """Return an index pair that corresponds to the first position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        lo, pos = -1, len(_lists) - 1
        while lo + 1 < pos:
            mi = (lo + pos) >> 1
            if value <= _mins[mi]:
                pos = mi
            else:
                lo = mi

        if pos and value <= _lists[pos - 1][-1]:
            pos -= 1

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value <= _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def _loc_right(self, value):
        """Return an index pair that corresponds to the last position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        pos, hi = 0, len(_lists)
        while pos + 1 < hi:
            mi = (pos + hi) >> 1
            if value < _mins[mi]:
                hi = mi
            else:
                pos = mi

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value < _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def add(self, value):
        """Add `value` to sorted list."""
        _load = self._load
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len += 1
        if _lists:
            pos, idx = self._loc_right(value)
            self._fen_update(pos, 1)
            _list = _lists[pos]
            _list.insert(idx, value)
            _list_lens[pos] += 1
            _mins[pos] = _list[0]
            if _load + _load < len(_list):
                _lists.insert(pos + 1, _list[_load:])
                _list_lens.insert(pos + 1, len(_list) - _load)
                _mins.insert(pos + 1, _list[_load])
                _list_lens[pos] = _load
                del _list[_load:]
                self._rebuild = True
        else:
            _lists.append([value])
            _mins.append(value)
            _list_lens.append(1)
            self._rebuild = True

    def discard(self, value):
        """Remove `value` from sorted list if it is a member."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_right(value)
            if idx and _lists[pos][idx - 1] == value:
                self._delete(pos, idx - 1)

    def remove(self, value):
        """Remove `value` from sorted list; `value` must be a member."""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """Remove and return value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        value = self._lists[pos][idx]
        self._delete(pos, idx)
        return value

    def bisect_left(self, value):
        """Return the first index to insert `value` in the sorted list."""
        pos, idx = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """Return the last index to insert `value` in the sorted list."""
        pos, idx = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """Return number of occurrences of `value` in the sorted list."""
        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __contains__(self, value):
        """Return true if `value` is an element of the sorted list."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_left(value)
            return idx < len(_lists[pos]) and _lists[pos][idx] == value
        return False

    def __iter__(self):
        """Return an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return 'SortedList({0})'.format(list(self))

from collections import deque,defaultdict
g = defaultdict()
def bfs(g, start):
    queue, enqueued = deque([(None, start)]), set([start])
    while queue:
        parent, n = queue.popleft()
        yield parent, n
        # Can use a variable fin, and break if n==fin
        new = set(g[n]) - enqueued
        enqueued |= new
        queue.extend([(n, child) for child in new])
# list(bfs(dict,initial pt)) gives ==> [(None,start),(start,x1),(x1,x2),(x1,x3),(x2,finish)]

class dsu:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1 for i in range(n)]
        self.num_sets = n
    def find(self, a):
        acopy = a
        while a != self.parent[a]:
            a = self.parent[a]
        while acopy != a:
            self.parent[acopy], acopy = a, self.parent[acopy]
        return a
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a != b:
            if self.size[a] < self.size[b]:
                a, b = b, a
            self.num_sets -= 1
            self.parent[b] = a
            self.size[a] += self.size[b]

# Initialize with u = dsu(No. of ele)[No.+1 for index out of range]
# Use while acopy != a loop to find tree-like properties

# Custom HashMap and Set for Anti-hash-table test
class CustomHashMap:
    def __init__(self, type = dict, arr = []):
        self.RANDOM = random.randrange(2**62)
        self.dict = type([self.wrapper(i) for i in arr])
    def wrapper(self,num):
        return num ^ self.RANDOM
    def __setitem__(self, key, value):
        self.dict[self.wrapper(key)] = value
    def __getitem__(self, key):
        return self.dict[self.wrapper(key)]
    def __contains__(self, key):
        return self.wrapper(key) in self.dict
    def __iter__(self):
        return iter(self.wrapper(i) for i in self.dict)
    def items(self):
        return [(self.wrapper(i),j) for i,j in self.dict.items()]
    def __repr__(self):
        return repr({self.wrapper(i):j for i,j in self.dict.items()})
#Use akin: a = CustomHashMap(Counter,a)  : {a is a LIST})
#          a.items() is a number of tuples like (2,3); len(a.items()) to get len(a)

from random import randint
# Random number from 1 to 10^9
RANDOM = randint(1, 10 ** 9)
class h(int):
    def __init__(self, x):
        int.__init__(x)

    def __hash__(self):
        return super(h, self).__hash__() ^ RANDOM
# h(x) gives a changed value of x which wont hash-collide

def pfactor(n):
    ans=defaultdict(int)
    s = Sieve(ceil(n**0.5))
    # print(s)
    for i in s:
        x = divmod(n,i)
        # print("X==",x)
        while(x[1]==0):
            ans[i]+=1
            n = x[0]
            x = divmod(n,i)
        if(n==1):
            break
    if(n!=1):
        ans[n]+=1
    return(ans)
# Returns a defaultdict of prime factorization

# Calculate nCr%p
def ncr(n, r, p):
    num = den = 1
    for i in range(r):
        num = (num * (n - i)) % p
        den = (den * (i + 1)) % p
    return (num * pow(den,p - 2, p)) % p

def factor(n):
  lower,upper=[],[]
  i=1
  while i*i<=n:
    if n%i==0:
      lower.append(i)
      if i!=n//i:
        upper.append(n//i)
    i+=1
  return lower+upper[::-1]

import random
from sys import stdin,stdout
input=lambda :stdin.readline()[:-1]
from collections import defaultdict, Counter, deque, OrderedDict
import itertools;from itertools import permutations as perms, combinations as combs,combinations_with_replacement
from bisect import bisect_left, bisect_right
from heapq import heapify, heappush, heappop, nlargest, nsmallest
import math
from functools import reduce
from math import inf,floor,ceil,comb,lcm,gcd,log2
from operator import itemgetter

def solve():
    a = list(map(int,list(str(input()))))
    n = len(a)
    # print("A==",a)
    ans = [-1 for i in range(n)]
    c = []
    f= 0
    for i in range(n):
        if(i==0):
            for j in range(min(10,n)):
                c.append([a[f],f])
                f+=1
        else:
            if(f<n):
                c.append([a[f],f])
                f+=1
        t =  0; v=  -1
        for j in range(len(c)):
            if(c[j][1]<i):
                if(c[j][0]>v):
                    t= j
                    v = c[j][0]
            else:
                if(c[j][0]-c[j][1]+i>v):
                    t = j
                    v = c[j][0]-c[j][1]+i
        x = c.pop(t)
        for j in range(len(c)):
            if(c[j][1]<x[1]):
                c[j][1]+=1
        ans[i] = v

    # print("ANS==",ans)
    print(*ans,sep="")
for _ in range(int(input())):
    solve()

Answer: 2


#include<bits/stdc++.h>

using namespace std;

int main(){

int t;

cin>>t;

while(t--){

string s;

cin>>s;

int n = s.size();

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

{

if(s[i]=='8' || s[i]=='9') continue;

int best=s[i]-'0';

int x=i;

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

{

if(j<n && s[j]-'0'-(j-i)>best){

best=s[j]-'0'-(j-i);

x=j;

}

}

s[x]=best+'0';

while(x!=i){

swap(s[x],s[x-1]);

x--;

}

}

cout<<s<<endl;

}

return 0;

}

#include<bits/stdc++.h>

using namespace std;

int main(){

int t;

cin>>t;

while(t--){

string s;

cin>>s;

int n = s.size();

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

{

if(s[i]=='8' || s[i]=='9') continue;

int best=s[i]-'0';

int x=i;

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

{

if(j<n && s[j]-'0'-(j-i)>best){

best=s[j]-'0'-(j-i);

x=j;

}

}

s[x]=best+'0';

while(x!=i){

swap(s[x],s[x-1]);

x--;

}

}

cout<<s<<endl;

}

return 0;

}

Answer: 2


#include<bits/stdc++.h>
#define ll long long int
#define INF (ll)1e18
#define mod 998244353
using namespace std;
ll pow_mod(ll a,ll b){
    ll res=1;
    while(b>0){
        if(b%2)
        res=(res*a)%mod;
        b/=2;
        a=(a*a)%mod;
    }
    return res;
}
int main(){
    ll t;
    cin>>t;
    while(t--){
        string s;
        cin>>s;
        int n = s.size();
        for(int i = 0 ; i < n ; i++){
            // if((s[i]-'0') == 0) {
            //     continue;
            // }
            int maxi = s[i]-'0';
            int maxi_idx = i;
            int cnt = 0;
            bool chk = false;
            for(int j = i+1 ; j < min(i+9,n) ; j++){
                cnt++;
                if(maxi < ((s[j]-'0')-cnt)){
                    chk = true;
                    maxi = (s[j]-'0')-cnt;
                    maxi_idx = j;
                    //cout<<maxi<<"  "<<maxi_idx<<endl;
                }
            }
            if(chk){
                //cout<<maxi<<"  "<<maxi_idx<<"  "<<cnt<<endl;
                char val = '0'+maxi;
                //cout<<val<<endl;
                for(int j = maxi_idx ; j >= i ; j--){
                    if(j-1 >= 0) s[j] = s[j-1];
                }
                s[i] = val;
            }
            //cout<<s<<endl;
        }
        cout<<s<<endl;
    }
    return 0;
}

#include<bits/stdc++.h>
#define ll long long int
#define INF (ll)1e18
#define mod 998244353
using namespace std;
ll pow_mod(ll a,ll b){
    ll res=1;
    while(b>0){
        if(b%2)
        res=(res*a)%mod;
        b/=2;
        a=(a*a)%mod;
    }
    return res;
}
int main(){
    ll t;
    cin>>t;
    while(t--){
        string s;
        cin>>s;
        int n = s.size();
        for(int i = 0 ; i < n ; i++){
            if((s[i]-'0') == 0) {
                continue;
            }
            int maxi = s[i]-'0';
            int maxi_idx = i;
            int cnt = 0;
            bool chk = false;
            for(int j = i+1 ; j < min(i+9,n) ; j++){
                cnt++;
                if(maxi < ((s[j]-'0')-cnt)){
                    chk = true;
                    maxi = (s[j]-'0')-cnt;
                    maxi_idx = j;
                }
            }
            if(chk){
                //cout<<maxi<<"  "<<maxi_idx<<"  "<<cnt<<endl;
                char val = '0'+maxi;
                //cout<<val<<endl;
                for(int j = maxi_idx ; j >= i ; j--){
                    if(j-1 >= 0) s[j] = s[j-1];
                }
                s[i] = val;
            }
        }
        cout<<s<<endl;
    }
    return 0;
}

Answer: 1


#include <bits/stdc++.h>

using namespace std;

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

#define ll long long

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

const ll MAX = 1e18;

const int N = 2e5 + 100;

const ll mod = 1e9 + 7;

ll n, m, k;

string s;

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

void solve() {

cin >> s;

n = s.size();

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

ll ok = -1;

char z = s[i];

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

if (z < (s[j] - (j - i))) {

ok = j;

z = (s[j] - (j - i));

}

}

if (ok > -1) {

s[ok] = z;

}

for (int j = ok; j > i; j--) swap(s[j], s[j - 1]);

}

cout << s << '\n';

}

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

int main() {

ios::sync_with_stdio(NULL);

cin.tie(0);

cout.tie(0);

#ifndef ONLINE_JUDGE

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

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

#endif

int t = 1;

cin >> t;

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

solve();

}

return 0;

}

#include <bits/stdc++.h>

using namespace std;

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

#define ll long long

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

const ll MAX = 1e18;

const int N = 2e5 + 100;

const ll mod = 1e9 + 7;

ll n, m, k;

string s;

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

void solve() {

cin >> s;

n = s.size();

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

ll ok = -1;

char z = s[i];

for (int j = i + 1; j < min(n, i + 10ll); ++j) {

if (z < (s[j] - (j - i))) {

ok = j;

z = (s[j] - (j - i));

}

}

if (ok > -1) {

s[ok] = z;

for (int j = ok; j > i; j--) swap(s[j], s[j - 1]);

}

}

cout << s << '\n';

}

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

int main() {

ios::sync_with_stdio(NULL);

cin.tie(0);

cout.tie(0);

#ifndef ONLINE_JUDGE

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

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

#endif

int t = 1;

cin >> t;

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

solve();

}

return 0;

}

Answer: 2


#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// # define int long long
#define f(x, a, b) for (ll x = a; x < b; x++)
#define fm(x, a, b) for (int x = a; x > b; x--)
#define ll long long
#define pb push_back

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

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

int help(vector<vector<int>>& dp,string& a,string& b,string& c,int i,int j,int n,int m, int o){
    if (i==n){
        int ans=0;
        f(k,j,m){
            if (c[n+k]!=b[k]){ans+=1;}
        }
        return ans;
    }
    if (j==m){
        int ans=0;
        f(k,i,n){
            if (c[m+k]!=a[k]){ans+=1;}
        }
        return ans;
    }
    if (a[i]==c[i+j]){
        if (b[j]==c[i+j]){
            int x=help(dp,a,b,c,i+1,j,n,m,o);
            int y=help(dp,a,b,c,i,j+1,n,m,o);
            dp[i][j]=min(x,y);
        }
        else{
            int x=help(dp,a,b,c,i+1,j,n,m,o);
            int y=help(dp,a,b,c,i,j+1,n,m,o)+1;
            dp[i][j]=min(x,y);
        }
    }
    else if (b[j]==c[i+j]){
            int x=help(dp,a,b,c,i+1,j,n,m,o)+1;
            int y=help(dp,a,b,c,i,j+1,n,m,o);
            dp[i][j]=min(x,y);
    }
    else{
        int x=help(dp,a,b,c,i+1,j,n,m,o)+1;
        int y=help(dp,a,b,c,i,j+1,n,m,o)+1;
        dp[i][j]=min(x,y);
    }
    return dp[i][j];
}

int main()
{
  int t;
  t = 1;
  cin >> t;
  while (t--)
  {
   	string a,b,c; cin>>a>>b>>c;
   	int n=a.size(),m=b.size(),o=c.size();
   	vector<vector<int>> dp(n,vector<int>(m,-1));
   	int ans=help(dp,a,b,c,0,0,n,m,o);
   	cout<<ans<<endl;
  }
  return 0;
}

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// # define int long long
#define f(x, a, b) for (ll x = a; x < b; x++)
#define fm(x, a, b) for (int x = a; x > b; x--)
#define ll long long
#define pb push_back

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

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

int help(vector<vector<int>>& dp,string& a,string& b,string& c,int i,int j,int n,int m, int o){
    if (i==n){
        int ans=0;
        f(k,j,m){
            if (c[n+k]!=b[k]){ans+=1;}
        }
        return ans;
    }
    if (j==m){
        int ans=0;
        f(k,i,n){
            if (c[m+k]!=a[k]){ans+=1;}
        }
        return ans;
    }
    if (dp[i][j]!=-1){return dp[i][j];}
    if (a[i]==c[i+j]){
        if (b[j]==c[i+j]){
            int x=help(dp,a,b,c,i+1,j,n,m,o);
            int y=help(dp,a,b,c,i,j+1,n,m,o);
            dp[i][j]=min(x,y);
        }
        else{
            int x=help(dp,a,b,c,i+1,j,n,m,o);
            int y=help(dp,a,b,c,i,j+1,n,m,o)+1;
            dp[i][j]=min(x,y);
        }
    }
    else if (b[j]==c[i+j]){
            int x=help(dp,a,b,c,i+1,j,n,m,o)+1;
            int y=help(dp,a,b,c,i,j+1,n,m,o);
            dp[i][j]=min(x,y);
    }
    else{
        int x=help(dp,a,b,c,i+1,j,n,m,o)+1;
        int y=help(dp,a,b,c,i,j+1,n,m,o)+1;
        dp[i][j]=min(x,y);
    }
    return dp[i][j];
}

int main()
{
  int t;
  t = 1;
  cin >> t;
  while (t--)
  {
   	string a,b,c; cin>>a>>b>>c;
   	int n=a.size(),m=b.size(),o=c.size();
   	vector<vector<int>> dp(n,vector<int>(m,-1));
   	int ans=help(dp,a,b,c,0,0,n,m,o);
   	cout<<ans<<endl;
  }
  return 0;
}

Answer: 2


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

#define ll long long
#define all(x) (x).begin(), (x).end()
#define f(i, n) for (int i = 0; i < n; i++)
#define trace(x) cerr << #x << ": " << x << '\n'
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin >> t;
    while (t--)
    {
        string s;
        cin >> s;
        int n = s.size();
        for (int i = 0; i < n; i++)
        {
            char ch = s[i];
            int j = i - 1;
            while (j >= 0 and s[j] - '0' < (s[j + 1] - '0') - 1)
            {
                s[j + 1] = s[j + 1] - 1;
                swap(s[j + 1], s[j]);
                j--;
            }
        }
            cout << s << '\n';
    }
}

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

#define ll long long
#define all(x) (x).begin(), (x).end()
#define f(i, n) for (int i = 0; i < n; i++)
#define trace(x) cerr << #x << ": " << x << '\n'
string a, b, c;
const int N = 3e3 + 5;
int dp[N][N];
int na, nb, nc;
int fun(int i, int j)
{
    if (i == na and j == nb)
        return 0;
    if (i == na)
    {
        int count = 0;
        for (int k = j; k < nb; k++)
        {
            if (b[k] != c[i + k])
                count++;
        }
        return count;
    }
    if (j == nb)
    {
        int count = 0;
        for (int k = i; k < na; k++)
        {
            if (a[k] != c[j + k])
                count++;
        }
        return count;
    }
    if (dp[i][j] != -1)
        return dp[i][j];
    int ans;
    if (a[i] == c[j + i])
        ans = fun(i + 1, j);
    else
        ans = 1 + fun(i + 1, j);
    if (b[j] == c[i + j])
        ans = min(ans, fun(i, j + 1));
    else
        ans = min(ans, 1 + fun(i, j + 1));
    return dp[i][j] = ans;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin >> t;
    while (t--)
    {
        cin >> a >> b >> c;
        na = a.size();
        nb = b.size();
        nc = c.size();
        f(i, nc + 10)
        {
            f(j, nc + 10)
            {
                dp[i][j] = -1;
            }
        }
        cout << fun(0, 0) << '\n';
    }
}

Answer: 2


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

int minChange(int i, int j, string a, string b, string c) {
    if(i >= a.length() && j >= b.length()) return 0;
    else if(i >= a.length()) return (b[j] != c[i+j]) + minChange(i, j+1, a, b, c);
    else if(j >= b.length()) return (a[i] != c[i+j]) + minChange(i+1, j, a, b, c);
    else return min((a[i] != c[i+j])+minChange(i+1, j, a, b, c), (b[j] != c[i+j]) + minChange(i, j+1, a, b, c));
}

int main()
{
    int t;
    cin>>t;
    while(t--) {
        string a, b, c;
        cin>>a>>b>>c;
        cout<<minChange(0, 0, a, b, c)<<endl;
    }
    return 0;
}

Answer: 1


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define fi first
#define se second
const int MOD = 1e9+7;
const int maxn = 1e3 + 10;

void solve(){
    string a,b,c;
    cin >> a >> b >> c;
    int na = a.length();
    int nb = b.length();
    vector<vector<int>> dp(maxn, vector<int>(maxn, 1e15));
    dp[0][0] = 0;
    for(int i = 0; i <= na; i++){
        for(int j = 0; j <= nb; j++){
            if(i + j == 0) continue;
            if(i - 1 >= 0){
                dp[i][j] = min(dp[i][j], dp[i-1][j] + (c[i + j - 1] != a[i-1]));
            }
            if(j - 1 >= 0){
                dp[i][j] = min(dp[i][j], dp[i][j-1] + (c[i + j - 1] != b[j-1]));
            }
        }
    }

    cout << dp[na][nb] << endl;
}

int32_t main(){

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

    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define fi first
#define se second
const int MOD = 1e9+7;

void solve(){
    string a,b,c;
    cin >> a >> b >> c;
    int na = a.length();
    int nb = b.length();
    vector<vector<int>> dp(na + 1, vector<int>(nb + 1, 1e15));
    dp[0][0] = 0;
    for(int i = 0; i <= na; i++){
        for(int j = 0; j <= nb; j++){
            if(i + j == 0) continue;
            if(i - 1 >= 0){
                dp[i][j] = min(dp[i][j], dp[i-1][j] + (c[i + j - 1] != a[i-1]));
            }
            if(j - 1 >= 0){
                dp[i][j] = min(dp[i][j], dp[i][j-1] + (c[i + j - 1] != b[j-1]));
            }
        }
    }

    cout << dp[na][nb] << endl;
}

int32_t main(){

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

    return 0;
}

Answer: 2


/**
*    created: 2024-12-23 07:51:30
**/
#include<bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;

#ifndef ONLINE_JUDGE
#include "../debug.cpp"
#else
#define debug(...)
#define debugArr(...)
#endif

#define int long long
#define all(v) (v).begin(),(v).end()
#define allr(v) (v).rbegin(),(v).rend()
#define show(x) cout << x << endl
#define sz(x) (int)(x.size())
#define yesno(x) cout << ((x) ? "YES\n" : "NO\n")
#define rep(i, a, b) for(int i = a; i < b; ++i)
#define rrep(i, a, b) for(int i = a; i >= b; --i)

// order_of_key (k) : Number of items strictly smaller than k.
// find_by_order(k) : K-th element in a set (counting from zero).
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update> ordered_pset;
typedef long double lld;
using ull = unsigned long long;
const int N = 200200, INF = 8e18, MOD = 1000000007; //   1000000009, 1000000023, 1000000007, 998244353

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

void dxt(int test_case);
void pre_pro();
signed main(){
    ios_base::sync_with_stdio(false); cin.tie(NULL);
    pre_pro();
    int T = 1;
    cin >> T;
    for (int i = 1; i <= T; i++) {
        dxt(i);
    }
    return 0;
}

void pre_pro(){
}
void dxt(int test_case){
    string a,b,c;
    cin >> a >> b >> c;
    int n = sz(a);
    int m = sz(b);
    int k = sz(c);

    int dp[n + 1][m + 1][k + 1];
    memset(dp, 0, sizeof dp);

    rep(i, 0, n + 1){
        rep(j, 0, m + 1){
            rep(l, 0, k + 1){
                if(i == 0 && j == 0 && l == 0) continue;
                dp[i][j][l] = INF;
                if(i > 0) setmin(dp[i][j][l], dp[i - 1][j][l] + (a[i - 1] != c[i + j - 1]));
                if(j > 0) setmin(dp[i][j][l], dp[i][j - 1][l] + (b[j - 1] != c[i + j - 1]));
                if(l > 0) setmin(dp[i][j][l], dp[i][j][l - 1] + (c[i + j - 1] != c[i + j - 1]));
            }
        }
    }
    show(dp[n][m][k]);
}

/**
*    created: 2024-12-23 07:51:30
**/
#include<bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;

#ifndef ONLINE_JUDGE
#include "../debug.cpp"
#else
#define debug(...)
#define debugArr(...)
#endif

#define int long long
#define all(v) (v).begin(),(v).end()
#define allr(v) (v).rbegin(),(v).rend()
#define show(x) cout << x << endl
#define sz(x) (int)(x.size())
#define yesno(x) cout << ((x) ? "YES\n" : "NO\n")
#define rep(i, a, b) for(int i = a; i < b; ++i)
#define rrep(i, a, b) for(int i = a; i >= b; --i)

// order_of_key (k) : Number of items strictly smaller than k.
// find_by_order(k) : K-th element in a set (counting from zero).
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update> ordered_pset;
typedef long double lld;
using ull = unsigned long long;
const int N = 200200, INF = 8e18, MOD = 1000000007; //   1000000009, 1000000023, 1000000007, 998244353

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

void dxt(int test_case);
void pre_pro();
signed main(){
    ios_base::sync_with_stdio(false); cin.tie(NULL);
    pre_pro();
    int T = 1;
    cin >> T;
    for (int i = 1; i <= T; i++) {
        dxt(i);
    }
    return 0;
}

void pre_pro(){
}
void dxt(int test_case){
    string a,b,c;
    cin >> a >> b >> c;
    int n = sz(a);
    int m = sz(b);
    int k = sz(c);

    int dp[n + 1][m + 1];
    memset(dp, 0, sizeof dp);
    rep(i, 0, n + 1){
        rep(j, 0, m + 1){
            if(i == 0 && j == 0) continue;
            if(i == 0){
                dp[i][j] = dp[i][j - 1] + (b[j - 1] != c[i + j - 1]);
            }else if(j == 0){
                dp[i][j] = dp[i - 1][j] + (a[i - 1] != c[i + j - 1]);
            }else{
                dp[i][j] = min(dp[i - 1][j] + (a[i - 1] != c[i + j - 1]), dp[i][j - 1] + (b[j - 1] != c[i + j - 1]));
            }
        }
    }
    show(dp[n][m]);
}

Answer: 2


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int mod=1e9+7;

void solve(){
    string a,b,c;
    cin>>a>>b>>c;
    int n=a.size();
    int m=b.size();
    int l=c.size();
    vector<vector<int>>dp(n+1,vector<int>(m+1,1e9));
    dp[0][0]=0;
    for(int i=1;i<=n;i++){
        if(c[i-1]==a[i-1]){
            dp[i][0]=dp[i-1][0];
        }
        else{
            dp[i][0]=dp[i-1][0]+1;
        }
    }
    for(int i=1;i<=m;i++){
        if(c[i-1]==b[i-1]){
            dp[0][i]=dp[0][i-1];
        }
        else{
            dp[0][i]=dp[0][i-1]+1;
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            dp[i][j] = min(dp[i - 1][j] + (a[i - 1] != c[i + j - 1]),
                                dp[i][j - 1] + (b[j - 1] != c[i + j - 1]));
        }
    }
    cout<<dp[n][m]<<endl;
}
int32_t main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t=1;
    cin>>t;
    while(t--)solve();
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
int mod=1e9+7;

void solve(){
    string a,b,c;
    cin>>a>>b>>c;
    int n=a.size();
    int m=b.size();
    int l=c.size();
    vector<vector<int>>dp(n+1,vector<int>(m+1,1e9));
    dp[0][0]=0;
    for(int i=1;i<=n;i++){
        if(c[i-1]==a[i-1]){
            dp[i][0]=dp[i-1][0];
        }
        else{
            dp[i][0]=dp[i-1][0]+1;
        }
    }
    for(int i=1;i<=m;i++){
        if(c[i-1]==b[i-1]){
            dp[0][i]=dp[0][i-1];
        }
        else{
            dp[0][i]=dp[0][i-1]+1;
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(c[i+j-1]==a[i-1]){
                dp[i][j]=min(dp[i][j],dp[i-1][j]);
            }
            if(c[i+j-1]==b[j-1]){
                dp[i][j]=min(dp[i][j],dp[i][j-1]);
            }
            else{
                dp[i][j]=min(dp[i][j],min(dp[i-1][j]+1,dp[i][j-1]+1));
            }
        }
    }
    cout<<dp[n][m]<<endl;
}
int32_t main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t=1;
    cin>>t;
    while(t--)solve();
    return 0;
}

Answer: 1


//                                               <-------GAUTAM KUMAR SHAH------->
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
const long long mod=1e9+7;
#define loop(i,n)      for(int i=0;i<n;i++)
#define loopr(i,n)      for(int i=n;i>0;i--)
#define cin(arr,n)     for(int i=0;i<n;i++) cin>>arr[i];
#define loopv(i,k,n)   for(int i=k;i<n;i++)
#define vi vector<long long int>
#define mi map<long long int,long long int>
ll mod_expo(ll a, ll b) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} // (a^b)%mod
ll mminv(ll a) {return mod_expo(a, mod-2);}
ll mod_add(ll a, ll b) {a = a % mod; b = b % mod; return (((a + b) % mod) + mod) % mod;}
ll mod_mul(ll a, ll b) {a = a % mod; b = b % mod; return (((a * b) % mod) + mod) % mod;}
ll mod_sub(ll a, ll b) {a = a % mod; b = b % mod; return (((a - b) % mod) + mod) % mod;}
ll mod_div(ll a, ll b) {a = a % mod; b = b % mod; return (mod_mul(a, mminv(b)) + mod) % mod;}  //only for prime m
ll nCr(ll n,ll r) {if (r==0 || n==0) return 1; ll fac[n+1];fac[0]=1; for(int i = 1; i<n+1 ; i++)
fac[i]=(fac[i-1]*i)%mod;return(fac[n]*mminv(fac[r])%mod*mminv(fac[n-r])%mod)%mod;}

int solve(string &a,string &b,string &c,int i,int j,vector<vector<int>> &dp){
    int a1=a.size();
    int b1=b.size();
    int c1=c.size();

    int k=i+j;
    if(k==a1+b1){
        return 0;
    }
    if(dp[i][j]!=-1){
        return dp[i][j];
    }
    int pick1=INT_MAX,npick1=INT_MAX,pick2=INT_MAX,npick2=INT_MAX;
    if(a[i]==c[k] && i<a1){
        pick1=(solve(a,b,c,i+1,j,dp));
    }
    if(b[j]==c[k] && j<b1){
        pick2=(solve(a,b,c,i,j+1,dp));
    }
    if(i<a1)
    npick1=(1+solve(a,b,c,i+1,j,dp));
    if(j<b1)
    npick2=(1+solve(a,b,c,i,j+1,dp));
    return dp[i][j]=min(min(pick1,pick2),min(npick1,npick2));

}

int main(){
 ios_base::sync_with_stdio(false);
 cin.tie(NULL);
   int t;
   cin>>t;
   while(t--)
   {

        string a,b,c;
        cin>>a>>b>>c;
        int n1=a.size();
        int n2=b.size();
        vector<vector<int>> dp(n1+5,vector<int>(n2+5,-1));
        int ans=solve(a,b,c,0,0,dp);
        cout<<ans<<endl;

   }
   return 0;
}

//                                               <-------GAUTAM KUMAR SHAH------->
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
const long long mod=1e9+7;
#define loop(i,n)      for(int i=0;i<n;i++)
#define loopr(i,n)      for(int i=n;i>0;i--)
#define cin(arr,n)     for(int i=0;i<n;i++) cin>>arr[i];
#define loopv(i,k,n)   for(int i=k;i<n;i++)
#define vi vector<long long int>
#define mi map<long long int,long long int>
ll mod_expo(ll a, ll b) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} // (a^b)%mod
ll mminv(ll a) {return mod_expo(a, mod-2);}
ll mod_add(ll a, ll b) {a = a % mod; b = b % mod; return (((a + b) % mod) + mod) % mod;}
ll mod_mul(ll a, ll b) {a = a % mod; b = b % mod; return (((a * b) % mod) + mod) % mod;}
ll mod_sub(ll a, ll b) {a = a % mod; b = b % mod; return (((a - b) % mod) + mod) % mod;}
ll mod_div(ll a, ll b) {a = a % mod; b = b % mod; return (mod_mul(a, mminv(b)) + mod) % mod;}  //only for prime m
ll nCr(ll n,ll r) {if (r==0 || n==0) return 1; ll fac[n+1];fac[0]=1; for(int i = 1; i<n+1 ; i++)
fac[i]=(fac[i-1]*i)%mod;return(fac[n]*mminv(fac[r])%mod*mminv(fac[n-r])%mod)%mod;}

int solve(string &a,string &b,string &c,int i,int j){
    int a1=a.size();
    int b1=b.size();
    int c1=c.size();

    int k=i+j;
    if(k==a1+b1){
        return 0;
    }
    int pick1=INT_MAX,npick1=INT_MAX,pick2=INT_MAX,npick2=INT_MAX;
    if(a[i]==c[k] && i<a1){
        pick1=(solve(a,b,c,i+1,j));
    }
    if(b[j]==c[k] && j<b1){
        pick2=(solve(a,b,c,i,j+1));
    }
    if(i<a1)
    npick1=(1+solve(a,b,c,i+1,j));
    if(j<b1)
    npick2=(1+solve(a,b,c,i,j+1));
    return min(min(pick1,pick2),min(npick1,npick2));

}

int main(){
 ios_base::sync_with_stdio(false);
 cin.tie(NULL);
   int t;
   cin>>t;
   while(t--)
   {
        string a,b,c;
        cin>>a>>b>>c;
        int ans=solve(a,b,c,0,0);
        cout<<ans<<endl;

   }
   return 0;
}

Answer: 1


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

#define ll long long
#define FORI(i, n) for(ll i = 0; i < n; i++)
#define FOR(i, n) for(ll i = 1; i <= n; i++)
typedef vector < ll > vl;
typedef set < ll > setl;
#define ff first
#define ss second
#define all(v) v.begin(), v.end()
#define pll pair<ll, ll>
#define db double
#define nll cout << "\n"
#define nl "\n"
#define sync ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

const ll mod =  1000007;
const int MAX = 1e3 + 5;
const int imax = 2147483647;
ll n, m, k, res;
string a, b, c;
void solve(){
    cin >> a >> b >> c;
    n = a.size();
    m = b.size();
    a = '0' + a;
    b = '0' + b;
    c = '0' + c;
    vector < vl > dp(n + 5, vl (m + 5, INT_MAX));
    dp[0][0] = 0;
    FORI(i, n + 1){
        FORI(j, m + 1){
            if(!i && !j)break;
            if(!i){
                dp[i][j] = dp[i][j - 1] + 1;
            }
            else if(!j)dp[i][j] = dp[i - 1][j] + 1;
            else dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);
            if(i && c[i + j] == a[i]){
                dp[i][j] = min(dp[i][j], dp[i - 1][j]);
            }
            if(j && c[i + j] == b[j]){
                dp[i][j] = min(dp[i][j], dp[i][j - 1]);
            }
        }
    }
    cout << dp[n][m];
}
signed main(){
    // freopen("input.txt","r",stdin);
    // freopen("output.txt","w",stdout);
    sync;
    ll t = 1;
    cin >> t;
    FOR(i, t){
        // cout << "Case #" << i << ": ";
        solve();
        nll;
    }
}

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

#define ll long long
#define FORI(i, n) for(ll i = 0; i < n; i++)
#define FOR(i, n) for(ll i = 1; i <= n; i++)
typedef vector < ll > vl;
typedef set < ll > setl;
#define ff first
#define ss second
#define all(v) v.begin(), v.end()
#define pll pair<ll, ll>
#define db double
#define nll cout << "\n"
#define nl "\n"
#define sync ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

const ll mod =  1000007;
const int MAX = 1e3 + 5;
const int imax = 2147483647;
ll n, m, k, res;
string a, b, c;
void solve(){
    cin >> a >> b >> c;
    n = a.size();
    m = b.size();
    a = '0' + a;
    b = '0' + b;
    c = '0' + c;
    vector < vl > dp(n + 5, vl (m + 5, INT_MAX));
    dp[0][0] = 0;
    FORI(i, n + 1){
        FORI(j, m + 1){
            if(!i && !j)continue;
            if(!i){
                dp[i][j] = dp[i][j - 1] + 1;
            }
            else if(!j)dp[i][j] = dp[i - 1][j] + 1;
            else dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);
            if(i && c[i + j] == a[i]){
                dp[i][j] = min(dp[i][j], dp[i - 1][j]);
            }
            if(j && c[i + j] == b[j]){
                dp[i][j] = min(dp[i][j], dp[i][j - 1]);
            }
        }
    }
    cout << dp[n][m];
}
signed main(){
    // freopen("input.txt","r",stdin);
    // freopen("output.txt","w",stdout);
    sync;
    ll t = 1;
    cin >> t;
    FOR(i, t){
        // cout << "Case #" << i << ": ";
        solve();
        nll;
    }
}

Answer: 2


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

typedef long long ll;

int dp(string a, string b, string c, int ia, int ib, vector<vector<int>> arr)
{
    if (ia == a.size() && ib == b.size())
    {
        return 0;
    }

    int left = INT_MAX, right = INT_MAX;

    if (ia < a.size())
    {
        if (arr[ia + 1][ib] != -1)
        {
            left = arr[ia + 1][ib] + (a[ia] != c[ia + ib]);
        }
        else
        {
            left = dp(a, b, c, ia + 1, ib, arr) + (a[ia] != c[ia + ib]);
        }
    }
    if (ib < b.size())
    {
        if (arr[ia][ib + 1] != -1)
        {
            right = arr[ia][ib + 1] + (b[ib] != c[ia + ib]);
        }
        else
        {
            right = dp(a, b, c, ia, ib + 1, arr) + (b[ib] != c[ia + ib]);
        }
    }

    arr[ia][ib] = min(left, right);
    return arr[ia][ib];
}

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

    int t;
    cin >> t;
    while (t--)
    {
        string a, b, c;
        cin >> a >> b >> c;

        vector<vector<int>> arr(a.size() + 1, vector<int>(b.size() + 1, -1));

        cout << dp(a, b, c, 0, 0, arr) << endl;
    }

    return 0;
}

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

typedef long long ll;

int dp(string &a, string &b, string &c, int ia, int ib, vector<vector<int>> &arr)
{
    if (ia == a.size() && ib == b.size())
    {
        return 0;
    }

    if (arr[ia][ib] != -1)
    {
        return arr[ia][ib];
    }

    int left = INT_MAX, right = INT_MAX;

    if (ia < a.size())
    {
        if (arr[ia + 1][ib] != -1)
        {
            left = arr[ia + 1][ib] + (a[ia] != c[ia + ib]);
        }
        else
        {
            left = dp(a, b, c, ia + 1, ib, arr) + (a[ia] != c[ia + ib]);
        }
    }
    if (ib < b.size())
    {
        if (arr[ia][ib + 1] != -1)
        {
            right = arr[ia][ib + 1] + (b[ib] != c[ia + ib]);
        }
        else
        {
            right = dp(a, b, c, ia, ib + 1, arr) + (b[ib] != c[ia + ib]);
        }
    }

    arr[ia][ib] = min(left, right);
    return arr[ia][ib];
}

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

    int t;
    cin >> t;
    while (t--)
    {
        string a, b, c;
        cin >> a >> b >> c;

        vector<vector<int>> arr(a.size() + 1, vector<int>(b.size() + 1, -1));

        cout << dp(a, b, c, 0, 0, arr) << endl;
    }

    return 0;
}

Answer: 2


#include <bits/stdc++.h>
using namespace std;
#define  ull unsigned long long
#define int long long

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

	ull t;cin >> t;

    while (t--) {

        string a, b, c; cin >>a >> b >> c;
        int l1 = a.length(),l2=b.length(),l3=c.length();
        vector<int> prev(l3,0),curr(l3);
        for (int i = 0;i < l1;i++) {
            for (int j = 0;j < l3;j++) {
                if (j != 0){
                    if (a[i] == c[j]) curr[j] = 1 + prev[j - 1];
                    else curr[j] = max(curr[j - 1], prev[j]);
                }
                else {
                    if (a[i] == c[j]) curr[j] = 1 ;
                    else curr[j] = prev[j];
                }

            }
            prev = curr;
        }
        int a1 = curr[l3 - 1];string n;
        int count = 0;vector<int>r;
        for (int j = 0;j < l3;j++) {
            if (curr[j] <=count) {

                n += string(1,c[j]);
            }
            else count = curr[j];
        }
        l3 = n.size();
        vector<int> prev1(l3, 0), curr1(l3);
        for (int i = 0;i < l2;i++) {
            for (int j = 0;j < l3;j++) {
                if (j != 0) {
                    if (b[i] == n[j]) curr1[j] = 1 + prev1[j - 1];
                    else curr1[j] = max(curr1[j - 1], prev1[j]);
                }
                else {
                    if (b[i] == n[j]) curr1[j] = 1;
                    else curr1[j] = prev1[j];
                }

            }
            prev1 = curr1;
        }
        int a2 = curr[l3 - 1];
        cout << c.size() - a1 - a2<<endl;
    }
    return 0;
}

Answer: 2


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

#define ll long long int

ll power(ll a, ll b) { if (b == 0) { return 1; } ll res = power(a, b/2); if (b%2) { return res*res*a; } else { return res*res; } }

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

ll cnt = 0;

ll func(string &a, string &b, string &c, vector<vector<ll> > &dp, ll indexa, ll indexb, ll indexc, ll &n1, ll &n2, ll &n3) {
    cnt++;

    ll r1 = 1e9;
    ll r2 = 1e9;

    if (indexc == n3) {
        return 0;
    }

    // if (indexa == n1) {
    //     if (b[indexb] == c[indexc] && indexb<n2) {
    //         return dp[indexa][indexb] = func(a,b,c,dp,indexa,indexb+1, indexc+1);
    //     }
    //     else if (b[indexb] != c[indexc] && indexb<n2) {
    //         return dp[indexa][indexb] = 1+func(a,b,c,dp,indexa,indexb+1, indexc+1);
    //     }
    //     else {
    //         return 0;
    //     }
    // }

    // if (indexb == n2) {
    //     if (a[indexa] == c[indexc] && indexa<n1) {
    //         return dp[indexa][indexb] = func(a,b,c,dp,indexa+1,indexb, indexc+1);
    //     }
    //     else if (a[indexa] != c[indexc] && indexa<n1) {
    //         return dp[indexa][indexb] = 1+func(a,b,c,dp,indexa+1,indexb, indexc+1);
    //     }
    //     else {
    //         return 0;
    //     }
    // }

    if (dp[indexa][indexb] != -1) {
        return dp[indexa][indexb];
    }

    if (indexa < n1 && a[indexa] == c[indexc]) {
        r1 = func(a,b,c,dp,indexa+1,indexb,indexc+1,n1,n2,n3);
    }
    if (indexa < n1 && a[indexa] != c[indexc]) {
        r1 = min(r1, 1 + func(a,b,c,dp,indexa+1,indexb,indexc+1,n1,n2,n3));
    }
    if (indexb < n2 && b[indexb] == c[indexc]) {
        r1 = min(r1, func(a,b,c,dp,indexa,indexb+1,indexc+1,n1,n2,n3));
    }
    if (indexb < n2 && b[indexb] != c[indexc]) {
        r1 = min(r1, 1 + func(a,b,c,dp,indexa,indexb+1,indexc+1,n1,n2,n3));
    }
    return dp[indexa][indexb] = min(r1,r2);
}

int main() {
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

    ll t;
    cin >> t;

    while(t--) {
        string a,b,c;
        cin >> a >> b >> c;
        ll n1 = a.length();
        ll n2 = b.length();
        ll n3 = c.length();
        vector<vector<ll> > dp(n1+1, vector<ll> (n2+1, -1));

        ll ans = func(a,b,c,dp,0LL,0LL,0LL, n1, n2, n3);
        cout << ans << endl;
    }
    // cout << cnt << endl;
    // cerr << endl << "Execution Took: " << 1000 * clock() / CLOCKS_PER_SEC << " ms." << endl;
}

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

#define ll long long int

ll power(ll a, ll b) { if (b == 0) { return 1; } ll res = power(a, b/2); if (b%2) { return res*res*a; } else { return res*res; } }

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

ll cnt = 0;

ll func(string a, string b, string c, vector<vector<ll> > &dp, ll indexa, ll indexb, ll indexc, ll n1, ll n2 , ll n3) {
    cnt++;

    ll r1 = 1e9;
    ll r2 = 1e9;

    if (indexc == n3) {
        return 0;
    }
    if (dp[indexa][indexb] != -1) {
        return dp[indexa][indexb];
    }
    if (indexa == n1) {
        if (b[indexb] == c[indexc] && indexb<n2) {
            return dp[indexa][indexb] = func(a,b,c,dp,indexa,indexb+1, indexc+1, n1, n2,n3);
        }
        else if (b[indexb] != c[indexc] && indexb<n2) {
            return dp[indexa][indexb] = 1+func(a,b,c,dp,indexa,indexb+1, indexc+1, n1, n2,n3);
        }
        else {
            return 0;
        }
    }

    if (indexb == n2) {
        if (a[indexa] == c[indexc] && indexa<n1) {
            return dp[indexa][indexb] = func(a,b,c,dp,indexa+1,indexb, indexc+1, n1, n2,n3);
        }
        else if (a[indexa] != c[indexc] && indexa<n1) {
            return dp[indexa][indexb] = 1+func(a,b,c,dp,indexa+1,indexb, indexc+1, n1, n2,n3);
        }
        else {
            return 0;
        }
    }

    if (a[indexa] != c[indexc] && b[indexb] != c[indexc]) {
        r1 = 1 + func(a,b,c,dp,indexa+1, indexb, indexc+1, n1, n2,n3);
        r2 = 1 + func(a,b,c,dp,indexa,indexb+1, indexc+1, n1, n2,n3);
    }
    else {
        if (a[indexa] == c[indexc]) {
        r1 = func(a,b,c,dp,indexa+1, indexb, indexc+1, n1, n2,n3);
        }
        else {
            r1 = 1 + func(a,b,c,dp,indexa+1, indexb,indexc+1, n1, n2,n3);
        }

        if (b[indexb] == c[indexc]) {
        r2 = func(a,b,c,dp,indexa,indexb+1, indexc+1, n1, n2,n3);
        }
        else {
            r2 = 1+func(a,b,c,dp,indexa, indexb+1, indexc+1, n1, n2,n3);
        }
    }
    return dp[indexa][indexb] = min(r1,r2);
}

int main() {
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif

    ll t;
    cin >> t;

    while(t--) {
        string a,b,c;
        cin >> a >> b >> c;
        vector<vector<ll> > dp(1001, vector<ll> (1001, -1));
        ll n1 = a.length();
        ll n2 = b.length();
        ll n3 = c.length();
        ll ans = func(a,b,c,dp,0LL,0LL,0LL, n1 , n2 , n3);
        cout << ans << endl;
    }
    //cout << cnt << endl;
}

Answer: 1


// LonggVuz

#include<bits/stdc++.h>

using namespace std;

// ☞ Kuroba Kaito ☜

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

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

#define out(x) return cout << x, void()

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

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

#define el '\n'

#define int int64_t

const int mod = 1e9 + 7;

const int oo = 1e16 + 8;

const int mxn = 1e6 + 9;

int dp[2005][2005];

void LonggVuz(){

    string a, b, c; cin >> a >> b >> c;

    int n = len(a), m = len(b);

    a = " " + a; b = " " + b; c = " " + c;

    fo(i, n) dp[i][0] = dp[i - 1][0] + (a[i] != c[i]);

    fo(i, m) dp[0][i] = dp[0][i - 1] + (b[i] != c[i]);

    fo(i, n){

        fo(j, m){

            if(a[i] == b[j]){

                if(c[i + j] == a[i]){

                    dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]);

                }else dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1;

            }else{

                if(a[i] == c[i + j]){

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

                }else if(b[j] == c[i + j]){

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

                }else dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1;

            }

        }

    }

    cout << dp[n][m];

    fo(i, n) fo(j, m) dp[i][j] = oo;

}

signed main(){

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

    int tc = 1; cin >> tc;

    while(tc--){

        LonggVuz();

        if(tc) cout << el;

    }

    cerr << "Execution Time: " << 0.001 * clock() << "s\n";

}

// LonggVuz

#include<bits/stdc++.h>

using namespace std;

// ☞ Kuroba Kaito ☜

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

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

#define out(x) return cout << x, void()

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

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

#define el '\n'

#define int int64_t

const int mod = 1e9 + 7;

const int oo = 1e16 + 8;

const int mxn = 1e6 + 9;

int dp[2005][2005];

void LonggVuz(){

    string a, b, c; cin >> a >> b >> c;

    int n = len(a), m = len(b);

    a = " " + a; b = " " + b; c = " " + c;

    fo(i, n) dp[i][0] = dp[i - 1][0] + (a[i] != c[i]);

    fo(i, m) dp[0][i] = dp[0][i - 1] + (b[i] != c[i]);

    fo(i, n){

        fo(j, m){

            if(a[i] == b[j]){

                if(c[i + j] == a[i]){

                    dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]);

                }else dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;

            }else{

                if(a[i] == c[i + j]){

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

                }else if(b[j] == c[i + j]){

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

                }else dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1;

            }

        }

    }

    cout << dp[n][m];

    fo(i, n) fo(j, m) dp[i][j] = oo;

}

signed main(){

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

    int tc = 1; cin >> tc;

    while(tc--){

        LonggVuz();

        if(tc) cout << el;

    }

    cerr << "Execution Time: " << 0.001 * clock() << "s\n";

}

Answer: 1


#include <bits/stdc++.h>
#define int long long
#define sz(a) (int)a.size()
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()

using namespace std;

signed main() {
    ios_base::sync_with_stdio(false); cin.tie(nullptr);
    int t; cin >>t;
    while(t--){
        string a; string b; string c; cin >> a >> b >> c;
        vector<vector<int>> dp(sz(a)+1,vector<int>(sz(b)+1,1e9));
        dp[0][0]=0;
        for (int k = 0; k < sz(c); k++)
        {
            for (int i = 0; i <= min(k,sz(a)-1)+1; i++)
            {
                int j=(k+1)-i;
                if(i>0){
                    dp[i][j]=dp[i-1][j];
                    if(c[k]!=a[i-1]) dp[i][j]++;
                }
                if(j>0){
                    if(c[k]!=b[j-1]) dp[i][j]=min(dp[i][j-1]+1,dp[i][j]);
                    else dp[i][j]=min(dp[i][j-1],dp[i][j]);
                }
            }
        }
        cout << dp[sz(a)][sz(b)] << "\n";
    }
    return 0;
}

#include <bits/stdc++.h>
#define int long long
#define sz(a) (int)a.size()
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()

using namespace std;

signed main() {
    ios_base::sync_with_stdio(false); cin.tie(nullptr);
    int t; cin >>t;
    while(t--){
        string a; string b; string c; cin >> a >> b >> c;
        vector<vector<int>> dp(sz(a)+1,vector<int>(sz(b)+1,1e9));
        dp[0][0]=0;
        for (int k = 0; k < sz(c); k++)
        {
            for (int i = 0; i <= min(k,sz(a)-1)+1; i++)
            {
                int j=(k+1)-i;
                if(j>sz(b)) continue;
                if(i>0){
                    dp[i][j]=dp[i-1][j];
                    if(c[k]!=a[i-1]) dp[i][j]++;
                }
                if(j>0){
                    if(c[k]!=b[j-1]) dp[i][j]=min(dp[i][j-1]+1,dp[i][j]);
                    else dp[i][j]=min(dp[i][j-1],dp[i][j]);
                }
            }
        }
        cout << dp[sz(a)][sz(b)] << "\n";
    }
    return 0;
}

Answer: 2


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define endl "\n"
#define float long double
#define int long long int
#define ll long long
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define mod 1000000007
#define PI 3.141592653589793238462643383279
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define pb push_back
void solve(){
    string a,b,c;
    cin>>a>>b>>c;
    int n=a.size(),m=b.size(),sz=c.size();
    vector<vector<int>> dp(sz+1,vector<int> (n+1,1e9));
    dp[0][0]=0;
    for(int i=1;i<=sz;i++){
        for(int j=0;j<=n;j++){
            if(i-j<=m && i-j>0)dp[i][j]=min(dp[i-1][j]+!(b[i-j-1]==c[i-1]),dp[i][j]);
            if(j>0)dp[i][j]=min(dp[i-1][j-1]+!(a[j-1]==c[i-1]),dp[i][j]);
        }
    }
    cout<<dp[sz][n]<<endl;
}
int32_t main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define endl "\n"
#define float long double
#define int long long int
#define ll long long
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define mod 1000000007
#define PI 3.141592653589793238462643383279
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define pb push_back
void solve(){
    string a,b,c;
    cin>>a>>b>>c;
    int n=a.size(),m=b.size(),sz=c.size();
    vector<vector<int>> dp(sz+1,vector<int> (n+1,1e9));
    dp[0][0]=0;
    for(int i=1;i<=sz;i++){
        for(int j=0;j<=n;j++){
            if(i-j<=m)dp[i][j]=min(dp[i-1][j]+!(b[i-j-1]==c[i-1]),dp[i][j]);
            dp[i][j]=min(dp[i-1][j-1]+!(a[j-1]==c[i-1]),dp[i][j]);
        }
    }
    cout<<dp[sz][n]<<endl;
}
int32_t main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}

Answer: 1


//                                               <-------GAUTAM KUMAR SHAH------->
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
const long long mod=1e9+7;
#define loop(i,n)      for(int i=0;i<n;i++)
#define loopr(i,n)      for(int i=n;i>0;i--)
#define cin(arr,n)     for(int i=0;i<n;i++) cin>>arr[i];
#define loopv(i,k,n)   for(int i=k;i<n;i++)
#define vi vector<long long int>
#define mi map<long long int,long long int>
ll mod_expo(ll a, ll b) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} // (a^b)%mod
ll mminv(ll a) {return mod_expo(a, mod-2);}
ll mod_add(ll a, ll b) {a = a % mod; b = b % mod; return (((a + b) % mod) + mod) % mod;}
ll mod_mul(ll a, ll b) {a = a % mod; b = b % mod; return (((a * b) % mod) + mod) % mod;}
ll mod_sub(ll a, ll b) {a = a % mod; b = b % mod; return (((a - b) % mod) + mod) % mod;}
ll mod_div(ll a, ll b) {a = a % mod; b = b % mod; return (mod_mul(a, mminv(b)) + mod) % mod;}  //only for prime m
ll nCr(ll n,ll r) {if (r==0 || n==0) return 1; ll fac[n+1];fac[0]=1; for(int i = 1; i<n+1 ; i++)
fac[i]=(fac[i-1]*i)%mod;return(fac[n]*mminv(fac[r])%mod*mminv(fac[n-r])%mod)%mod;}

int solve(string &a,string &b,string &c,int i,int j){
    int a1=a.size();
    int b1=b.size();
    int c1=c.size();
    int k=i+j;
    if(k==a1+b1){
        return 0;
    }
    int pick1=INT_MAX,npick1=INT_MAX,pick2=INT_MAX,npick2=INT_MAX;
    if(a[i]==c[k]){
        pick1=(solve(a,b,c,i+1,j));
    }
    if(b[j]==c[k]){
        pick2=(solve(a,b,c,i,j+1));
    }
    npick1=(1+solve(a,b,c,i+1,j));
    npick2=(1+solve(a,b,c,i,j+1));
    return min(min(pick1,pick2),min(npick1,npick2));

}

int main(){
 ios_base::sync_with_stdio(false);
 cin.tie(NULL);
   int t;
   cin>>t;
   while(t--)
   {
        string a,b,c;
        cin>>a>>b>>c;
        int ans=solve(a,b,c,0,0);
        cout<<ans<<endl;

   }
   return 0;
}

Answer: 1


#include <cmath>
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <bitset>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define ll long long
#define int long long
#define pqi priority_queue<long long>
#define pi pair<long long, long long>
#define mi map<long long, long long>
#define vi vector<long long>
#define vvi vector<vector<long long>>

using namespace std;

int gcd(int a, int b){
    //a>b
    if(b==0) return a;
    return gcd(b,a%b);
}
istream &operator>>(istream &is, vector<int> &vec)
{
//    vec.clear();
    int num;
    while (is >> num)
    {
        vec.push_back(num);
        char ch = is.peek();
        if (ch == '\n')
        {
            is.ignore();
            break;
        }
    }
    return is;
}

void print(vector <int> v){
    for(auto it:v) cout << it <<' ';
    cout <<endl;
}
vector<int> prefixSum(vector<int> v ){
    vector<int> ans;
    int sum=0;
    for (int i =0; i < v.size();i++){
        sum+=v[i];
        ans.push_back(sum);
    }
    return ans;
}
void print(const vector<std::vector<int>> arr) {
    for (const std::vector<int>& row : arr) {
        for (int num : row) {

            std::cout << num << " ";
        }
        std::cout << std::endl;
    }
}
void print (const map<int, vi>& sum) {
    for (const auto& pair : sum) {
        int key = pair.first;
        const vi& values = pair.second;

        cout << "Key: " << key << " -> Values: [";
        for (size_t i = 0; i < values.size(); ++i) {
            cout << values[i];
            if (i < values.size() - 1) {
                cout << ", ";
            }
        }
        cout << "]" << endl;
    }
}
void print( vector<set<int>>& cycles) {
    for (const auto& cycle : cycles) {
        cout << "{ ";
        for (auto it = cycle.begin(); it != cycle.end(); ++it) {
            cout << *it;
            if (next(it) != cycle.end()) {
                cout << ", ";
            }
        }
        cout << " }" << endl;
    }
}
const int mod = 1e9 + 7;
const int N= 2e5 + 5;
int64_t fact[N];
int64_t pw(int64_t a, int64_t b) {
    int64_t r = 1;
    while(b > 0) {
        if(b & 1) r = (r * a) % mod;
        b /= 2;
        a = (a * a) % mod;
    }
    return r;
}
int64_t C(int64_t n, int64_t k) {
    if(n < k) return 0LL;
    return (fact[n] * pw((fact[n - k] * fact[k]) % mod, mod - 2)) % mod;
}

int modInverse(int a, int m) {
    int result = 1;
    int exp = m - 2;
    while (exp > 0) {
        if (exp % 2 == 1) {
            result = (result * a) % m;
        }
        a = (a * a) % m;
        exp /= 2;
    }
    return result;
}
vector<int> getDivisors(int n) {
    std::vector<int> divisors;

    // Loop from 1 to sqrt(n) to find divisors
    for (int i = 1; i <= std::sqrt(n); ++i) {
        if (n % i == 0) {
            divisors.push_back(i);
            // If i is not equal to n / i, add the corresponding divisor
            if (i != n / i) {
                divisors.push_back(n / i);
            }
        }
    }

    sort(divisors.begin(), divisors.end());
    return divisors;

}

int check(vi a, int d){
    int n = a.size();
    int m = 0, r = n-1, l = 0;
    int spare = 0 ;
    // cout << "d="<<d <<endl;

    while(l < r){
        if( a[l] > d){
            spare += (a[l] - d);
        }else if( a[l] < d){
            spare -= (d-a[l]);
            m += (d-a[l]);
            while( spare < 0){
                int k = min(a[r], -1* spare);
                spare += k;
                a[r] -= k;
                if (a[r] == 0) r--;
            }
        }
        l++;
    }
    // cout << "spare "<< spare << endl;
    return m + spare;
}

int f (int i, int j, string a, string b, string c, vector <vector <int>> &dp){
    int k = i + j;
    if(k == c.size()){
        return 0;
    }

    if (dp[i][j] != -1) return dp[i][j];

    int ans = INT_MAX;

    if(i < a.size()){

        int t = f ( i+1 , j , a ,b ,c , dp);
        //match
        if(a[i] == c[k]){
            ans = min (ans, t);
        }
        //changed
        ans = min ( ans, t + 1);

    }
    if( j < b.size()){
        int t = f ( i , j+1 , a ,b ,c , dp);
        //match
        if(b[j] == c[k]){
            ans = min (ans, t);
        }
        //changed
        ans = min ( ans, t + 1);
    }

    return dp[i][j] = ans;

}

void solve() {
    string a, b, c;
    cin >> a >> b >> c;

    // dp[i][j] represents minimum operations needed when we've used
    // i characters from string a and j characters from string b
    vector<vector<int>> dp(a.size() + 1, vector<int>(b.size() + 1, INT_MAX));

    // Base case - when we haven't used any characters
    dp[0][0] = 0;

    // Fill dp table
    for(int i = 0; i <= a.size(); i++) {
        for(int j = 0; j <= b.size(); j++) {
            // Skip invalid states
            if(dp[i][j] == INT_MAX) continue;

            int k = i + j;  // position in string c
            if(k == c.size()) continue;  // we've formed the complete string

            // Try taking character from string a
            if(i < a.size()) {
                int cost = (a[i] == c[k]) ? 0 : 1;
                dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + cost);
            }

            // Try taking character from string b
            if(j < b.size()) {
                int cost = (b[j] == c[k]) ? 0 : 1;
                dp[i][j + 1] = min(dp[i][j + 1], dp[i][j] + cost);
            }
        }
    }

    // Find answer when we've used all characters needed to form string c
    int result = INT_MAX;
    for(int i = 0; i <= a.size(); i++) {
        for(int j = 0; j <= b.size(); j++) {
            if(i + j == c.size()) {
                result = min(result, dp[i][j]);
            }
        }
    }

    cout << (result == INT_MAX ? -1 : result) << endl;
}

int32_t main()
{

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

#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int T = 1;

//    fact[0] = 1;
//    for(int64_t i = 1; i < N; ++i) fact[i] = (fact[i - 1] * i) % mod;
//
   cin >> T;

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

    return 0;
}

#include <cmath>
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <bitset>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define ll long long
#define int long long
#define pqi priority_queue<long long>
#define pi pair<long long, long long>
#define mi map<long long, long long>
#define vi vector<long long>
#define vvi vector<vector<long long>>

using namespace std;

int gcd(int a, int b){
    //a>b
    if(b==0) return a;
    return gcd(b,a%b);
}
istream &operator>>(istream &is, vector<int> &vec)
{
//    vec.clear();
    int num;
    while (is >> num)
    {
        vec.push_back(num);
        char ch = is.peek();
        if (ch == '\n')
        {
            is.ignore();
            break;
        }
    }
    return is;
}

void print(vector <int> v){
    for(auto it:v) cout << it <<' ';
    cout <<endl;
}
vector<int> prefixSum(vector<int> v ){
    vector<int> ans;
    int sum=0;
    for (int i =0; i < v.size();i++){
        sum+=v[i];
        ans.push_back(sum);
    }
    return ans;
}
void print(const vector<std::vector<int>> arr) {
    for (const std::vector<int>& row : arr) {
        for (int num : row) {

            std::cout << num << " ";
        }
        std::cout << std::endl;
    }
}
void print (const map<int, vi>& sum) {
    for (const auto& pair : sum) {
        int key = pair.first;
        const vi& values = pair.second;

        cout << "Key: " << key << " -> Values: [";
        for (size_t i = 0; i < values.size(); ++i) {
            cout << values[i];
            if (i < values.size() - 1) {
                cout << ", ";
            }
        }
        cout << "]" << endl;
    }
}
void print( vector<set<int>>& cycles) {
    for (const auto& cycle : cycles) {
        cout << "{ ";
        for (auto it = cycle.begin(); it != cycle.end(); ++it) {
            cout << *it;
            if (next(it) != cycle.end()) {
                cout << ", ";
            }
        }
        cout << " }" << endl;
    }
}
const int mod = 1e9 + 7;
const int N= 2e5 + 5;
int64_t fact[N];
int64_t pw(int64_t a, int64_t b) {
    int64_t r = 1;
    while(b > 0) {
        if(b & 1) r = (r * a) % mod;
        b /= 2;
        a = (a * a) % mod;
    }
    return r;
}
int64_t C(int64_t n, int64_t k) {
    if(n < k) return 0LL;
    return (fact[n] * pw((fact[n - k] * fact[k]) % mod, mod - 2)) % mod;
}

int modInverse(int a, int m) {
    int result = 1;
    int exp = m - 2;
    while (exp > 0) {
        if (exp % 2 == 1) {
            result = (result * a) % m;
        }
        a = (a * a) % m;
        exp /= 2;
    }
    return result;
}
vector<int> getDivisors(int n) {
    std::vector<int> divisors;

    // Loop from 1 to sqrt(n) to find divisors
    for (int i = 1; i <= std::sqrt(n); ++i) {
        if (n % i == 0) {
            divisors.push_back(i);
            // If i is not equal to n / i, add the corresponding divisor
            if (i != n / i) {
                divisors.push_back(n / i);
            }
        }
    }

    sort(divisors.begin(), divisors.end());
    return divisors;

}

int check(vi a, int d){
    int n = a.size();
    int m = 0, r = n-1, l = 0;
    int spare = 0 ;
    // cout << "d="<<d <<endl;

    while(l < r){
        if( a[l] > d){
            spare += (a[l] - d);
        }else if( a[l] < d){
            spare -= (d-a[l]);
            m += (d-a[l]);
            while( spare < 0){
                int k = min(a[r], -1* spare);
                spare += k;
                a[r] -= k;
                if (a[r] == 0) r--;
            }
        }
        l++;
    }
    // cout << "spare "<< spare << endl;
    return m + spare;
}

int f (int i, int j, string a, string b, string c, vector <vector <int>> &dp){
    int k = i + j;
    if(k == c.size()){
        return 0;
    }

    if (dp[i][j] != -1) return dp[i][j];

    int ans = INT_MAX;

    if(i < a.size()){

        int t = f ( i+1 , j , a ,b ,c , dp);
        //match
        if(a[i] == c[k]){
            ans = min (ans, t);
        }
        //changed
        ans = min ( ans, t + 1);

    }
    if( j < b.size()){
        int t = f ( i , j+1 , a ,b ,c , dp);
        //match
        if(b[j] == c[k]){
            ans = min (ans, t);
        }
        //changed
        ans = min ( ans, t + 1);
    }

    return dp[i][j] = ans;

}

void solve()
{
    string a , b, c;
    cin >> a >> b >>c;
    vector <vector <int>> dp (a.size() + 1, vector <int> (b.size() + 1, -1));
    cout << f(0,0,a,b,c, dp)<<endl;
}

int32_t main()
{

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

#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int T = 1;

//    fact[0] = 1;
//    for(int64_t i = 1; i < N; ++i) fact[i] = (fact[i - 1] * i) % mod;
//
   cin >> T;

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

    return 0;
}

Answer: 1


import math
def solve():
    a = input()
    b = input()
    c = input()

    n1,n2,n3 = len(a),len(b),len(c)

    dp = {}
    def util(i,j,k):
        if k >= n3:
            return 0

        if (i,j,k) in dp:
            return dp[(i,j,k)]

        res = 1+min(util(i+1,j,k+1),util(i,j+1,k+1))
        if i<n1 and a[i] == c[k]:
            res = min(res,util(i+1,j,k+1))
        if j<n2 and b[j] == c[k]:
            res = min(res,util(i,j+1,k+1))

        dp[(i,j,k)] = res
        return res

    print(util(0,0,0))

if __name__ == '__main__':
    t = int(input())
    while t > 0:
        solve()
        t -= 1

def solve():
    # Read input strings
    s1 = input()
    s2 = input()
    s3 = input()

    n = len(s1)
    m = len(s2)

    # If lengths don't match the requirements, it's impossible
    if len(s3) != n + m:
        print(-1)
        return

    # Create DP table
    dp = [[float('inf')] * (m + 1) for _ in range(n + 1)]
    dp[0][0] = 0  # Base case: empty strings need 0 changes

    # Fill dp table
    for i in range(n + 1):
        for j in range(m + 1):
            if i + j == 0:
                continue

            # Current position in s3 we're trying to match
            k = i + j - 1

            # Try taking from s1
            if i > 0:
                cost = 0 if s1[i-1] == s3[k] else 1
                dp[i][j] = min(dp[i][j], dp[i-1][j] + cost)

            # Try taking from s2
            if j > 0:
                cost = 0 if s2[j-1] == s3[k] else 1
                dp[i][j] = min(dp[i][j], dp[i][j-1] + cost)

    # Answer is in dp[n][m]
    ans = dp[n][m]
    print(ans if ans != float('inf') else -1)

if __name__ == '__main__':
    t = int(input())
    while t > 0:
        solve()
        t -= 1

Answer: 2


#include <bits/stdc++.h>
#define ll long long int
#define MOD 1000000007
using namespace std;
int solve(int i,int j,string& s,string &n,string& m,vector<vector<int>>&dp){
    if(i==n.size() && j==m.size())return 0;
    if(dp[i][j]!=-1)return dp[i][j];
    int ans=INT_MAX;
    if(i<n.size())ans=min(ans,solve(i+1,j,s,n,m,dp)+(n[i]!=s[i+j]));
    if(j<m.size())ans=min(ans,solve(i,j+1,s,n,m,dp)+(m[j]!=s[i+j]));
    return dp[i][j]=ans;
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t;
    cin >> t;
    while (t--) {
 long long a,b,c=0,k,d=0,cnt=0,sum=0,ans=0,e=1;
 string s,m,n;
 cin>>n>>m>>s;
 vector<vector<int>>dp(n.size()+1,vector<int>(m.size()+1,-1));
 cout<< solve(0,0,s,n,m,dp)<<endl;

    }
    return 0;
}

#include <bits/stdc++.h>

using namespace std;

int dp[100001][100001];

int solve(int i, int j, const string& a, const string& b, const string& res) {
    if (i == a.size() && j == b.size()) {
        return 0;
    }
    if (dp[i][j] != -1) {
        return dp[i][j];
    }
    int ans = INT_MAX;
    if (i < a.size()) {
        ans = min(ans, solve(i + 1, j, a, b, res) + (a[i] != res[i + j]));
    }
    if (j < b.size()) {
        ans = min(ans, solve(i, j + 1, a, b, res) + (b[j] != res[i + j]));
    }
    dp[i][j] = ans;
    return dp[i][j];
}

int main() {
    int tests;
    cin >> tests;
    while (tests--) {
        string a, b, res;
        cin >> a >> b >> res;
        fill(&dp[0][0], &dp[0][0] + sizeof(dp) / sizeof(int), -1);
        cout << solve(0, 0, a, b, res) << endl;
    }
}

Answer: 1


#include<bits/stdc++.h>

using namespace std;

#define vi vector<int>
#define pii pair<int, int>
#define ll long long
#define pb push_back
#define el "\n"
#define all(a) a.begin(), a.end()
#define viin(n, vctr) {vctr.resize(n); for(auto &i : vctr) cin >> i;}
#define vllin(n, vctr) {vctr.resize(n); for(auto &i : vctr) cin >> i;}
#define YES cout << "YES\n"
#define NO cout << "NO\n"
int mod = 1e9 + 7;

// Remove the loop if there is no testcase
void solve(){

	string a, b, c; cin >> a >> b >> c;
	vector<vi> dp(2005, vi(2005, 0));
	int sa = a.size(), sb = b.size();
	for(int i = 1; i <= sb; i++)
		dp[0][i] = dp[0][i - 1] + (c[i - 1] != b[i - 1]);
	for(int i = 1; i <= sa; i++)
		dp[i][0] = dp[i - 1][0] + (c[i - 1] != a[i - 1]);
	for(int i = 1; i <= sa; i++)
		for(int j = 1; j <= sb; j++){
			dp[i][j] = min(dp[i - 1][j] + (c[i + j - 1] != a[i - 1]), dp[i][j - 1] + (c[i + j - 1] != b[j - 1]));
		}

	cout << dp[sa][sb] << el;

}

int main(){
	#ifdef LOCAL
		// accept testcase inputs from file: input
		freopen("input.txt", "r", stdin);
		// output stdout to file: output
		freopen("output.txt", "w", stdout);
		auto begin = chrono::high_resolution_clock::now();
	#else
		// Make cin and cout as fast as stdio
		ios::sync_with_stdio(0);
		cin.tie(0);
	#endif

	int tt; cin >> tt; while(tt--)
	solve();

	#ifdef LOCAL
		auto end = chrono::high_resolution_clock::now();
		auto elapsed = chrono::duration_cast<chrono::milliseconds> (end - begin);
		cout << el << "Time elapsed: " << (double)elapsed.count() << "ms";
	#endif
	return 0;
}

#include<bits/stdc++.h>

using namespace std;

#define vi vector<int>
#define pii pair<int, int>
#define ll long long
#define pb push_back
#define el "\n"
#define all(a) a.begin(), a.end()
#define viin(n, vctr) {vctr.resize(n); for(auto &i : vctr) cin >> i;}
#define vllin(n, vctr) {vctr.resize(n); for(auto &i : vctr) cin >> i;}
#define YES cout << "YES\n"
#define NO cout << "NO\n"
int mod = 1e9 + 7;

// Remove the loop if there is no testcase
void solve(){

	string a, b, c; cin >> a >> b >> c;
	// vector<vi> dp(2005, vi(2005, 0));
	int dp[2005][2005];
	memset(dp, 0, sizeof dp);
	int sa = a.size(), sb = b.size();
	for(int i = 1; i <= sb; i++)
		dp[0][i] = dp[0][i - 1] + (c[i - 1] != b[i - 1]);
	for(int i = 1; i <= sa; i++)
		dp[i][0] = dp[i - 1][0] + (c[i - 1] != a[i - 1]);
	for(int i = 1; i <= sa; i++)
		for(int j = 1; j <= sb; j++){
			dp[i][j] = min(dp[i - 1][j] + (c[i + j - 1] != a[i - 1]), dp[i][j - 1] + (c[i + j - 1] != b[j - 1]));
		}

	cout << dp[sa][sb] << el;

}

int main(){
	#ifdef LOCAL
		// accept testcase inputs from file: input
		freopen("input.txt", "r", stdin);
		// output stdout to file: output
		freopen("output.txt", "w", stdout);
		auto begin = chrono::high_resolution_clock::now();
	#else
		// Make cin and cout as fast as stdio
		ios::sync_with_stdio(0);
		cin.tie(0);
	#endif

	int tt; cin >> tt; while(tt--)
	solve();

	#ifdef LOCAL
		auto end = chrono::high_resolution_clock::now();
		auto elapsed = chrono::duration_cast<chrono::milliseconds> (end - begin);
		cout << el << "Time elapsed: " << (double)elapsed.count() << "ms";
	#endif
	return 0;
}

Answer: 2