jiahuimbzuai/CoQuIR huggingface dataset:
//  [rust]
fn read_stdin() -> String {
    use std::io::Read;
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input).unwrap();
    input
}

fn scan<'a, I: Iterator<Item = &'a str>, T: std::str::FromStr>(tokens: &mut I) -> T {
    tokens.next().unwrap().parse().ok().unwrap()
}

fn rep<T, F: FnMut() -> T>(n: usize, mut f: F) -> Vec<T> {
    (0..n).map(|_| f()).collect()
}

fn main() {
    let input = read_stdin();
    let tokens = &mut input.split_whitespace();
    let n: usize = scan(tokens);
    let p: Vec<i32> = rep(n, || scan(tokens));
    let q: Vec<i32> = rep(n, || scan(tokens));
    let ord_p = order(p);
    let ord_q = order(q);
    println!("{}", (ord_p - ord_q).abs());
}

fn order(p: Vec<i32>) -> i32 {
    let mut x = p.clone();
    x.sort();
    let mut count = 0;
    for i in p {
        for j in 0..x.len() {
            if x[j] == i {
                x.remove(j);
                if j > 0 {
                    count += j * factorial(x.len());
                }
                break;
            }
        }
    }
    count as i32
}

fn factorial(n: usize) -> usize {
    if n == 0 {
        1
    } else {
        n * factorial(n - 1)
    }
}
//  [rust]
use std::io::{self, BufRead};

fn find_index(ps: &Vec<usize>, n: usize) -> usize {
  let mut digits: Vec<usize> = (1..(n+1)).collect();
  let mut total: usize = 0;
  for i in 0..n {
    if let Some(j) = digits.iter().position(|&x| x == ps[i]) {
      let x =  j * (1..(n-i)).product::<usize>();
      total += x;
      digits.remove(j);
    }
  }
  total
}

fn main() {
  let stdin = io::stdin();
  let mut lines = stdin.lock().lines();
  let line = lines.next().unwrap().unwrap();
  let n: usize = line.parse().unwrap();
  let line = lines.next().unwrap().unwrap();
  let ps: Vec<usize> = line.split(' ').map(|x| x.parse().unwrap()).collect();
  let line = lines.next().unwrap().unwrap();
  let qs: Vec<usize> = line.split(' ').map(|x| x.parse().unwrap()).collect();
  let x = find_index(&ps, n);
  let y = find_index(&qs, n);
  let ans = if x < y { y - x } else { x - y };
  println!("{}", ans);
}
//  [rust]
use whiteread::parse_line;

fn func(left: Vec<isize>, right: Vec<isize>, cand: &mut Vec<Vec<isize>>) {
    if right.is_empty() {
        cand.push(left);
        return;
    }
    for i in 0..right.len() {
        let mut lc: Vec<isize> = left.iter().copied().collect();
        let mut rc: Vec<isize> = right.iter().copied().collect();
        lc.push(rc.remove(i));
        func(lc, rc, cand);
    }
}

fn main() {
    let _n: usize = parse_line().unwrap();
    let p: Vec<isize> = parse_line().unwrap();
    let q: Vec<isize> = parse_line().unwrap();
    let mut candidate: Vec<Vec<isize>> = Vec::new();
    let mut first: Vec<isize> = p.iter().copied().collect();
    first.sort();

    func(Vec::new(), first, &mut candidate);
    let pp = candidate.iter().position(|x| x.eq(&p)).unwrap();
    let qp = candidate.iter().position(|x| x.eq(&q)).unwrap();
    println!("{}", pp.max(qp) - pp.min(qp));
}
//  [rust]
use proconio::input;

#[allow(unused_mut)]
fn main() {
    input! {
        n: usize,
        p: [usize;n],
        q: [usize;n],
    };
    let mut perm = Vec::new();
    permutation(n, &mut vec![], &mut perm);
    let a = perm.iter().position(|v| v == &p).unwrap() as isize;
    let b = perm.iter().position(|v| v == &q).unwrap() as isize;
    let res = (a - b).abs();
    println!("{}", res);
}

fn permutation(max: usize, v: &mut Vec<usize>, all: &mut Vec<Vec<usize>>) {
    for i in 1..=max {
        if !v.contains(&i) {
            v.push(i);
            permutation(max, v, all);
            v.pop();
        }
    }
    if v.len() == max {
        let v = v.clone();
        all.push(v);
    }
}
//  [typescript]
function Main(input: string) {
  const lines: string[] = input.split('\n');

  const n = parseInt(lines[0]);
  const p = lines[1].split(' ').map(x => parseInt(x));
  const q = lines[2].split(' ').map(x => parseInt(x));

  const d = Math.abs(order(p) - order(q));

  console.log(d);
}

function order(p: number[]): number {
  const n = p.length;
  let result = 0;
  const set = new Set();
  for (let i = 0; i < n; i++) {
    const m = interval(1, p[i] - 1).filter(x => !set.has(x)).length;
    result += m * factorial(n - (i + 1));
    set.add(p[i]);
  }
  return result;
}

function interval(start: number, end: number): number[] {
  if (start > end) {
    return []
  } else {
    let tmp = [];
    for (let i = start; i <= end; i++) {
      tmp.push(i);
    }
    return tmp
  }
}

function factorial(n: number): number {
  let tmp = 1;
  for (let i = 2; i <= n; i++) {
    tmp *= i;
  }
  return tmp;
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
{
  const main = (
    input: string
  ): void | string | number | string[] | number[] => {
    const r = _reader(input)
    const [N] = r.nn()
    const P = r.s().replace(/ /g, '')
    const Q = r.s().replace(/ /g, '')

    // console.log(P)
    // console.log(Q)

    const a: number[][] = []

    generatePermutation(a, [], range(1, N), N)

    let start = 0
    let end = 0

    // console.log(a.map(v => v.map(String).join('')))

    a.map(v => v.map(String).join('')).forEach((v, i) => {
      if (v === P) {
        start = i
      }
      if (v === Q) {
        end = i
      }
    })

    return Math.abs(start - end)
  }

  const generatePermutation = function(perm, pre, post, n) {
    var elem, i, rest, len

    if (n > 0)
      for (i = 0, len = post.length; i < len; ++i) {
        rest = post.slice(0)
        elem = rest.splice(i, 1)
        generatePermutation(perm, pre.concat(elem), rest, n - 1)
      }
    else perm.push(pre)
  }

  const range = (a: number, b: number) => {
    const nums: number[] = []

    for (let i = a; i <= b; i++) nums.push(i)
    return nums
  }

  const _range = (n: number) => Array.from(Array(n).keys())
  const _reader = (str: string, i = 0) => {
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')
    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map(v => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  const _getInput = () => require('fs').readFileSync('/dev/stdin', 'utf8')
  const _res = main(_getInput())

  if (typeof _res === 'number' || typeof _res === 'string') console.log(_res)
  if (typeof _res === 'object') console.log(_res.join(' '))
}
//  [typescript]
export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const n: number = parseInt(tmp[0].split(" ")[0]);
    const p: number[] = tmp[1].split(" ").map(int => parseInt(int));
    const q: number[] = tmp[2].split(" ").map(int => parseInt(int));
    const allList: number[] = [];
    for (let i = 1; i <= n; i++) {
      allList.push(i);
    }
    const pList: number[][] = Main.add(allList);
    let a = 0;
    let b = 0;
    for (let i = 0, len = pList.length; i < len; i++) {
      const l = pList[i];
      let pBoo = true;
      let qBoo = true;
      for (let j = 0; j < n; j++) {
        pBoo &= p[j] == l[j];
        qBoo &= q[j] == l[j];
      }
      if (pBoo) {
        a = i;
      }
      if (qBoo) {
        b = i;
      }
    }
    return `${Math.abs(a - b)}`;
  }

  static add(remainList: number[]): number[][] {
    let list = [];
    for (let i = 0, len = remainList.length; i < len; i++) {
      const a = remainList[i];
      const r = remainList.slice(0, i).concat(remainList.slice(i + 1, remainList.length));
      if (r.length == 0) {
        list.push([a]);
        continue;
      }
      const ll = Main.add(r);
      for (let j = 0, lenj = ll.length; j < lenj; j++) {
        ll[j].unshift(a);
      }
      list = list.concat(ll);
    }
    return list;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
const main = (input: string) => {
  const lines = input.trim().split("\n")
  const N = parseInt(lines[0])
  const [p, q] = lines.slice(1).map(line => line.split(" ").map(str => parseInt(str)))
  let [pOrder, qOrder] = [0, 0]
  const sequence = []
  for (let i = 1; i <= N; i++) {
    sequence.push(i)
  }

  const getPermutation = ({result, pre, post, n}: {
    result: number[][], pre: number[], post: number[], n: number
  }) => {
    if (n > 0) {
      post.forEach((_, i) => {
        const rest = [...post];
        const elem = rest.splice(i, 1);
        getPermutation({ result, pre: [...pre, ...elem], post: rest, n: n - 1});
      });
    } else {
      result.push(pre);
    }
    return result;
  }

  const permutation = getPermutation({ result: [], pre: [], post: sequence, n: N })

  for (let i = 0; i < permutation.length; i++) {
    if(JSON.stringify(permutation[i]) === JSON.stringify(p)) {
      pOrder = i + 1
    }
    if(JSON.stringify(permutation[i]) === JSON.stringify(q)) {
      qOrder = i + 1 
    }
  }

  console.log(Math.abs(pOrder - qOrder));
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const ceil=(a)=>{return Math.ceil(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))};const gcd=(x,y)=>{while(y){[x,y]=[y,x%y]}return x};const sum=(arr)=>{return arr.reduce((a,b)=>a+b);};const isPrime=(n:number):boolean=>{if(n<2)return false;const suq=Math.sqrt(n);for(let i=2;i<=suq;i++){if(n%i==0){return false;}}return true;};
const permutation = ({ result = [], pre = [], post, n = post.length }) => {
  if (n > 0) {
    post.forEach((_, i) => {
      const rest = [...post];
      const elem = rest.splice(i, 1);
      permutation({ result, pre: [...pre, ...elem], post: rest, n: n - 1});
    });
  } else {
    result.push(pre);
  }
  return result;
};
const main=()=>{
  let n=tn(),[a,b]=[tnn(n),tnn(n)]
  let x=[...a]
  let c=permutation({post: x.sort()})
  let aa=a.join('')
  let bb=b.join('')
  let aaa,bbb
  for(let i=0;i<c.length;i++){
    if(c[i].join('')==aa)aaa=i
    if(c[i].join('')==bb)bbb=i
  }
  to(abs(aaa-bbb))
}
main()
//  [python]
# -*- coding: utf-8 -*-

import sys
import os
import math


N = int(input())
s_list = []
for i in range(N):
    s_list.append(input().strip())

alphabets = 'abcdefghijklmnopqrstuvwxyz'

for c in alphabets:
    min_count = float('inf')
    for s in s_list:
        count = s.count(c)

        if count < min_count:
            min_count = count
    print(c * min_count, end='')
print()
//  [python]
# -*- coding:utf-8 -*-
n = int(input())
S = []
ans = []
for factor in range(n):
    S.append(input())
for tmp in "abcdefghijklmnopqrstuvwxyz":
    l = []
    for tmp2 in range(n):
        l.append(S[tmp2].count(tmp))
    factor = min(l)
    for tmp3 in range(factor):
        ans.append(tmp)
s = ''.join(ans)
print(s)
//  [python]
alpha=list('abcdefghijklmnopqrstuvwxyz')
a=[]
ans=''
n=int(input())
for i in range(n):
    a.append(str(input()))

for s in alpha:
    count=50
    for i in a:
        if i.count(s)<count:
            count=i.count(s)
    ans += s*count

print(ans)
//  [python]
import copy
N=int(input())

s=[0]*N

for i in range (N) :
    s[i]=sorted(list(input()))

t=copy.deepcopy(s)
flag=0
ans=[]
i=0
while(len(s[0])>i) :
    for j in range (1,N) :
        if(s[0][i] in s[j]):
            s[j].remove(s[0][i])
        else:
            s=copy.deepcopy(t)
            flag=1
            break
    if(flag==0):
        ans.append(s[0][i])
        s[0].remove(s[0][i])
        i=-1
    t=copy.deepcopy(s)
    flag=0
    i+=1

sorted(ans)
print("".join(ans))
//  [python]
from collections import Counter
n = int(input())
x = []
for i in range(n):
    s = input()
    t = Counter(s)
    x.append(t)
ans = ""
for i in "abcdefghijklmnopqrstuvwxyz":
    tmp = []
    for j in x:
        tmp.append(j[i])
    ans += i*min(tmp)
print(ans)
//  [python]
n = int(input())

cnt = [[0] * n for _ in range(26)]
for i in range(n):
    s = input()
    for c in s:
        cnt[ord(c) - ord('a')][i] += 1

for i in range(26):
    for _ in range(min(cnt[i])):
        print(chr(ord('a')+i), end='')
//  [java]
import java.io.*;
import java.util.*;

public class Main {
    public static PrintWriter out;
    public static FastScanner in;

    private void solve(){
        int[] count = new int[26];
        Arrays.fill(count,Integer.MAX_VALUE);

        int n = in.nextInt();
        for(int i=0;i<n;i++){
            String s = in.nextLine();
            int[] nC = new int[26];
            Arrays.fill(nC,0);
            for(int j=0;j<s.length();j++){
                nC[s.charAt(j)-'a']++;
            }

            for(int j=0;j<26;j++){
                count[j] = Math.min(count[j],nC[j]);
            }
        }

        for(int i=0;i<26;i++){
            char c = (char)('a'+i);
            while(count[i] > 0){
                out.print(c);
                count[i]--;
            }
        }
        out.print("");
    }

    private void runIO() {
        in = new FastScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        solve();
        out.close();
    }
    private static class FastScanner {
        BufferedReader bufferedReader;
        StringTokenizer stringTokenizer;

        private FastScanner() {
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        }

        private String next() {
            if (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
                try {
                    stringTokenizer = new StringTokenizer(bufferedReader.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return stringTokenizer.nextToken();
        }

        private int nextInt() {
            return Integer.parseInt(next());
        }

        private long nextLong() {
            return Long.parseLong(next());
        }

        private String nextLine() {
            String ret = "";
            try {
                ret = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ret;
        }
    }

    public static void main(String[] args) {
        new Main().runIO();
    }
}
//  [java]
import java.io.*;
import java.util.*;

public class Main {

	public static void main(String[] args) throws IOException{
		Scanner scan = new Scanner(System.in);
		int n = Integer.parseInt(scan.nextLine());
		String[] str = new String[n];
		String az = "abcdefghijklmnopqrstuvwxyz";
		String ans = "";
		boolean judge = true;
		for(int i = 0; i < str.length; i++){
			str[i] = scan.nextLine();
		}
		for(int i = 0; i < az.length();){
			judge = true;
			for(int j = 0; j < n ; j++){
				if(!str[j].matches(".*" + az.substring(i, i + 1) + ".*")){
					judge = false;
					break;
				}else{
					str[j] = str[j].replaceFirst(az.substring(i, i + 1), "");
				}
			}
			if(judge == true){
				ans += az.substring(i, i + 1);
			}else{
				i++;
			}
		}
		System.out.println(ans);
	}
}
//  [java]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = Integer.parseInt(sc.next());

        List<String> list = new ArrayList<>();

        IntStream.range(0, n).forEach(i -> list.add(sc.next()));

        int[] alpha = new int[26];
        Arrays.fill(alpha, 50);

        list.forEach(s -> {
            IntStream.rangeClosed('a', 'z').forEach(i ->
                alpha[i - 'a'] = (int) Math.min(alpha[i - 'a'], s.chars().filter(j -> j == i).count())
            );
        });

        for (char i = 'a'; i <= 'z'; i++) {
            for (int j = 0; j < alpha[i - 'a']; j++) {
                System.out.print(i);
            }
        }
    }
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
//debug
#ifdef grief
#define debug(...) do{\
	fprintf(stderr , "%s - %d : (%s) = " , __PRETTY_FUNCTION__ , __LINE__ , #__VA_ARGS__ );\
	_DO(__VA_ARGS__);\
}while(0)
template<typename I> void _DO(I&&x){
	cerr<<x<<endl;
}
template<typename I,typename...T> void _DO(I&&x,T&&...tail){
	cerr<<x<<" , ";
	_DO(tail...);
}
#else
#define debug(...)
#endif
//type
typedef long long ll;
typedef pair<int,int> pii;
typedef long long ll;
typedef pair<ll,ll> pll;
typedef priority_queue<pll,vector<pll>,greater<pll> > heap;
//macro
#define SZ(x) ((ll)(x).size())
#define ALL(x) (x).begin(),(x).end()
#define F first
#define S second
#define mkp make_pair
#define pb push_back
const ll INF=1e9;
const ll MAX=1e6+5;
const ll MOD=1e9+7;
//}}}
int mi[300];
int cnt[300];
int main(){
	ios_base::sync_with_stdio(0); cin.tie(0);
	for(int i='a';i<='z';i++)
		mi[i]=INF;
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		string s;
		cin>>s;
		for(char c:s)
			cnt[c]++;
		for(int i='a';i<='z';i++){
			mi[i]=min(mi[i],cnt[i]);
			cnt[i]=0;
		}
	}
	for(char i='a';i<='z';i++){
		for(int j=0;j<mi[i];j++){
			cout<<i;
		}
	}
	cout<< '\n';
	return 0;
}
//  [cpp]
#include <cstdio>
#include <math.h>
#include <algorithm>
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <set>
#include <map>

using namespace std;

#define EPS 1e-14
#define FOR(i,a,b) for (int i=(a);i<(b);i++)
#define REP(i,n) FOR(i, 0, n)
#define PI 2*acos(0.0)
#define ALL(a) (a).begin(),(a).end()
#define DEBUG(x) cout<<#x <<": "<< x << "\n"
#define DEBUG_ARR(a) REP(i, size(a)){ cout << #a << "[" << i << "]: " << a[i] << "\n"; }
const int VX[] = { 0, 1, 0, -1 };
const int VY[] = { 1, 0, -1, 0 };
const long MOD = 1000000007;

typedef long long ll;

int main() {
	//	--- I/O 高速化 ---
	cin.tie(0);
	ios::sync_with_stdio(false);
	// --- ここまで ---

	int n, arr[26] = { 0 }, _arr[26] = { 0 };
	cin >> n;
	string str;

	cin >> str;
	REP(i, str.length()) {
		arr[str[i] - 'a']++;
	}

	REP(i, n - 1) {
		cin >> str;
		REP(j, 26) _arr[j] = 0;

		REP(j, str.length()) {
			_arr[str[j] - 'a']++;
		}
		REP(j, 26) {
			if (_arr[j] < arr[j]) {
				arr[j] = _arr[j];
			}
		}
	}

	REP(i, 26) {
		REP(j, arr[i]) {
			cout << (char)('a' + i);
		}
	}
	cout << endl;

	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(n);++i)
#define ALL(A) A.begin(), A.end()
#define INF (1<<20)
using namespace std;

typedef long long ll;
typedef pair<int, int> P;

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	int n; cin >> n;
	vector<string> S(n);
	rep (i, n){
		cin >> S[i];
	} // end rep

	int cnt[50][26];
	memset(cnt, 0, sizeof(cnt));
	rep (i, n){
		int m = (int)S[i].length();
		rep (j, m){
			++cnt[i][(int)(S[i][j] - 'a')];
		} // end rep
	} // end rep

	int minSum[26];
	rep (i, 26) minSum[i] = INF;
	rep (j, 26){
		rep (i, n){
			minSum[j] = min(minSum[j], cnt[i][j]);
		} // end rep
	} // end rep

	string res = "";
	rep (i, 26){
		rep (j, (int)minSum[i]){
			res += (char)('a' + i);
		} // end rep
	} // end rep
	cout << res << endl;
	
	return 0;
}
//  [cpp]
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int n;
string *S;

int dp[51][51];
string dp2[51][51];

string func(string x, string y)
{
	for (int i = 0; i < 51; ++i) {
		for (int j = 0; j < 51; ++j) {
			dp[i][j] = 0;
			dp2[i][j] = "";
		}
	}

	for (unsigned int i = 0; i < x.length(); i++) {
		for (unsigned int j = 0; j < y.length(); j++) {
			if (x[i] == y[j]) {
				dp[i + 1][j + 1] = dp[i][j] + 1;
				dp2[i + 1][j + 1] = dp2[i][j] + x[i];
			} else {
				dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]);
				if (dp[i][j + 1] > dp[i + 1][j]) {
					dp2[i + 1][j + 1] = dp2[i][j + 1];
				} else {
					dp2[i + 1][j + 1] = dp2[i + 1][j];
				}
			}
		}
	}
	return dp2[x.length()][y.length()];
}

int main(void)
{

	cin >> n;
	S = new string[n];
	for (int i = 0; i < n; ++i) {
		cin >> S[i];
		sort(S[i].begin(), S[i].end());
	}
	
	for (int j = 0; j < n - 1; ++j) {
		for (int i = 1; i < n; ++i) {
			S[i] = func(S[j], S[i]);
		}
	}

	cout << S[n-1] << endl;

	return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;


#define f(i,a,b) for(int i=(int)(a);i<=(int)(b);i++)
#define char_f(i,a) for(int i=(int)(a);(char)s[i]!='\0';i++)
#define rf(i,a,b) for(int i=(int)(a);i>=(int)(b);i--)
#define llf(i,a,b) for(long long int i=(long long int)(a);i<=(long long int)(b);i++)
#define llrf(i,a,b) for(long long int i=(long long int)(a);i>=(long long int)(b);i--)



#define ll long long
#define fi first
#define se second
#define pb push_back
#define pop pop_back
#define mem(ara) memset((ara),0,sizeof(ara))
#define memn(ara) memset((ara),-1,sizeof(ara))
#define b begin()
#define e end()
#define em emplace
#define eb emplace_back





#define si set<int>
#define sd set<double>
#define sll set<long long int>
#define ss set<string>
#define sc set<char>

#define pii pair<int,int>
#define pli pair<long long int,int>
#define pil pair<int,long long int>
#define pll pair<long long int,long long int>
#define pci pair<char,int>
#define pic pair<int,char>
#define pcl pair<char,long long int>
#define plc pair<long long int,char>

#define pss pair<string,string>
#define pcc pair<char,char>

#define pis pair<int,string>
#define psi pair<string,int>
#define pls pair<long long int,string>
#define psl pair<string,long long int>
#define pdd pair<double,double>
#define pcs pair<char,string>
#define psc pair<string,char>



#define vi  vector<int>
#define vll vector<long long int>
#define vd vector<double>
#define vs vector<string>
#define vc vector<char>
#define vii vector<pii>



#define mod 1000000007
#define mx (1<<30)-1
#define llmx (1ll<<62)
#define n_size 100005
#define g_size 10000005
double PI=acos(-1);



///unsigned int uMAX=4294967295;
///unsigned ll int ullMAX=18446744073709551615;





int arr[g_size],arr1[g_size];



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

	int n,m,T,res;

	int maxi=-mx,mini=mx,count=0;

	int i,j,k;

	bool flag;

	string s1,s2;

	char s[100000];

	int ara[n_size],ara2[n_size];

    f(i,0,27){
        arr1[i]=mx;
    }

	cin>>n;
	f(i,0,n-1)
	{
	    cin>>s;
	    mem(arr);
	    f(j,0,strlen(s)-1)
	    {
	        arr[s[j]-'a']++;
	    }

	    f(i,0,27){
            arr1[i]=min(arr1[i],arr[i]);
	    }

	}

	f(i,0,27)
	{
	   if(arr1[i]>=0 && arr1[i]<=50) {
        k=arr1[i];
        f(j,1,k)
	    {
	        char c=i+'a';
	        cout<<c;
	    }
	}
	}
	cout<<endl;


}
//  [c]
#include<stdio.h>
int main(){
  char s[51];
  int a[26],b[26];
  int n,i,j;
  scanf("%d",&n);
  for(i=0;i<26;i++)a[i]=100;
  for(i=0;i<n;i++){
    for(j=0;j<26;j++)b[j]=0;
    scanf("%s",s);for(j=0;s[j];j++)b[s[j]-'a']++;
    for(j=0;j<26;j++)a[j]=a[j]<b[j]?a[j]:b[j];
  }
  for(i=0;i<26;i++)for(j=0;j<a[i];j++)printf("%c",'a'+i);printf("\n");
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int i, n;
	char S[51][51];
	scanf("%d", &n);
	for (i = 1; i <= n; i++) scanf("%s", S[i]);
	
	int j, min[26], count[26] = {};
	for (j = 0; j < 26; j++) min[j] = 100;
	for (i = 1; i <= n; i++) {
		for (j = 0; j < 26; j++) count[j] = 0;
		for (j = 0; S[i][j] != 0; j++) count[S[i][j] - 'a']++;
		for (j = 0; j < 26; j++) if (count[j] < min[j]) min[j] = count[j];
	}
	
	for (j = 0; j < 26; j++) {
		for (i = 0; i < min[j]; i++) printf("%c", 'a' + j);
	}
	fflush(stdout);
	return 0;
}
//  [c]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    int map[26] = {0};

    int n;
    scanf("%d", &n);
    char **str_list = malloc(n * sizeof(char *));

    for (int i = 0; i < n; i++)
    {
        str_list[i] = malloc(51 * sizeof(char));
        scanf("%s", str_list[i]);
    }

    for (int i = 0; i < 26; i++)
    {
        char letter = 'a' + i;
        int min = 50;
        for (int j = 0; j < n; j++)
        {
            int letter_count = 0;
            for (int k = 0; k < strlen(str_list[j]); k++)
            {
                if (str_list[j][k] == letter) letter_count++;
            }
            if (letter_count < min) min = letter_count;
        }
        map[i] = min;
    }

    for (int i = 0; i < 26; i++)
    {
        char letter = 'a' + i;
        for (int j = 0; j < map[i]; j++)
        {
            printf("%c", letter);
        }
    }

    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#define min(x, y) ((x)>(y) ? (y) : (x))

int main(){
  int n;  scanf("%d", &n);
  int table[55][30] = {0};

  for(int i=1; i<=n; i++){
    char s[55];  scanf("%s", s);
    int len = strlen(s);
    for(int j=0; j<len; j++)
      table[i][(int)s[j]-(int)'a']++;
  }

  int ans[30] = {0};
  for(int i=0; i<=(int)'z'-(int)'a'; i++){
    int mini = 555;
    for(int j=1; j<=n; j++)
      mini = min(mini, table[j][i]);
    ans[i] = mini;
  }
  
  for(int i=0; i<=(int)'z'-(int)'a'; i++)
    for(int j=0; j<ans[i]; j++)
      printf("%c", (char)(i+(int)'a'));
  puts("");

  return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
int min(int x, int y){return x<y?x:y;}
int main(void){
	int n,i,j,num[50][26]={0};
	char s[51];
	scanf("%d",&n);
	for(i=0;i<n;i++){
		scanf("%s",s);
		for(j=0;j<strlen(s);j++){
			num[i][s[j]-97]++;
		}
	}
	int x;
	char cha = 'a';
	for(i=0;i<26;i++){
		x=50;
		for(j=0;j<n;j++){
			x = min(x,num[j][i]);
		}
		for(j=0;j<x;j++){
			printf("%c",cha);
		}
		cha++;
	}
	printf("\n");
	
	return 0;
}
//  [c]
#include<stdio.h>
#include<string.h>
int main(){
  int i,j,n,len;
  scanf("%d",&n);
  char s[n+1][51],alpha[n+1][27];
  for(i=0;i<n;i++){
    scanf("%*c%s",s[i]);
    for(j=0;j<27;j++)
      alpha[i][j]=0;
  }
  for(i=0;i<n;i++){
    len=strlen(s[i]);
    for(j=0;j<len;j++){
      alpha[i][s[i][j]-'a']++;
    }
  }
  for(i=0;i<26;i++){
    alpha[n][i]=alpha[0][i];
    for(j=1;j<n;j++){
      if(alpha[n][i]>alpha[j][i])
        alpha[n][i]=alpha[j][i];
    }
  }
  for(i=0;i<26;i++){
    while(alpha[n][i]>0){
      printf("%c",'a'+i);
      alpha[n][i]--;
    }
  }
  puts("");
  return 0;
}
//  [javascript]
function Main(input) {
  input = input.trim()
  input = input.split("\n");
  var N = input[0];
  input.shift();
  var arr = new Array(26).fill(0);
  var mem = new Array(26).fill(0);
      var A = input[0].split("");
  for(var i=0;i<input[0].length;i++){
    arr[A[i].charCodeAt(0)-97]++;
  }
  for(i=1;i<N;i++){
    var str = input[i].split("");
    for(var j=0;j<str.length;j++){
     mem[str[j].charCodeAt(0)-97]++;
    }
    for(var k=0;k<26;k++){
    if(arr[k]>mem[k]){
    arr[k]=mem[k]
    }
    }
    mem.fill(0);
  }
  for(var p=0;p<26;p++){
    for(var e=0;e<arr[p];e++){
     process.stdout.write(String.fromCharCode(p+97));
    }
  }
  console.log();
}Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function frequency(s) {
    var freq = new Array(26).fill(0);
    for (var i = 0; i < s.length; i++) {
        var index = s[i].charCodeAt() - "a".charCodeAt();
        freq[index]++;
    }
    return freq;
}

function freqMatch(freq1, freq2) {
    for (var i = 0; i < 26; i++) {
        freq1[i] = Math.min(freq1[i], freq2[i]);
    }
    return freq1;
}

function Main(input) {
    input = input.split("\n");
    var n = parseInt(input[0], 10);
    var strings = input.slice(1, n+1);
    var freq1 = frequency(strings[0]);
    for (var i = 1; i < strings.length; i++) {
        var freq2 = frequency(strings[i]);
        freq1 = freqMatch(freq1, freq2);
    }
    res = "";
    for (var i = 0; i < 26; i++) {
        for (var j = 0; j < freq1[i]; j++) {
            res += String.fromCharCode(i+"a".charCodeAt());
        }
    }
    console.log(res);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
	input = input.split("\n");
  var len = parseInt(input[0]);
  var engList = "abcdefghijklmnopqrstuvwxyz".split("");
  var lastList = {};
  for(var i = 0; i < engList.length; i++){
    lastList[engList[i]] = 50;
  }
  var inputList = [];
  for(var i = 1; i <= len; i++){
    var tmp = input[i].split("");
    var tmpList = {};
    for(var j = 0; j < tmp.length; j++){
      if(tmpList[tmp[j]] == null){
         tmpList[tmp[j]] = 1;
         }else{
          tmpList[tmp[j]]++; 
         }
    }
    inputList.push(tmpList);
  }
  for(var i = 0; i < inputList.length ; i++){
    var tmp = inputList[i];
    for(var j = 0; j < engList.length; j++){
      if(tmp[engList[j]] == null){
         lastList[engList[j]] = 0;
         }else{
           lastList[engList[j]] = Math.min(lastList[engList[j]],tmp[engList[j]]);
         }
    }
  }
  var output = "";
  for(var i = 0; i < engList.length; i++){
    var tmp = lastList[engList[i]];
    for(var j = 0; j < tmp; j++){
      output += engList[i];
    }
  }
  console.log(output);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main( input ){

    input = input.split( '\n' )
    
    var n = Number( input[0] )
    var str = []
    
    for( var i=1; i<n+1; i++ ){
        str.push( [].slice.call( input[i] ).sort() )
    }
    
    var output = ''
    var base = str.shift()
    
    function arr( base, str ){
        if( str.length === 0 ) return base
        
        var s = str.shift()
        
        var out = []
        for( var i=0; i<base.length; i++ ){
            for( var j=0; j<s.length; j++ ){
                if( base[i] === s[j] ){
                    out.push( base[i] )
                    s.splice( j, 1 )
                    break
                }
            }
        }
        
        return arr( out, str )
    }
    
    var result = arr( base, str )
    
    if( result.length === 0 ) console.log()
    else console.log( result.join( '' ) )
    
}

Main( require( 'fs' ).readFileSync( '/dev/stdin', 'utf8' ) )
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let n = nextInt()
    let alpha = "abcdefghijklmnopqrstuvwxyz"
    let arr = new Array(26).fill(-1)
    while(hasNext()){
        let str = next()
        let cnt = new Array(26).fill(0)
        for(let el of str){
            let idx = alpha.indexOf(el)
            cnt[idx]++
        }
        for(let i = 0; i<arr.length; i++){
            if(cnt[i] == 0) arr[i] = 0
            else if (arr[i] == -1 && cnt[i] !== 0) arr[i] = cnt[i]
            else if (arr[i] !== 0 && cnt[i] !== 0) arr[i] = Math.min(arr[i], cnt[i])
        }
    }
    let ans = []
    for(let i = 0; i<arr.length; i++){
        if(arr[i] == 0) continue
        while(arr[i]>0){
            ans.push(alpha[i])
            arr[i]--
        }
    }
    ans.sort()
    console.log(ans.join(""))
}
Main()
//  [javascript]
function Main(input) {
  input = input.split("\n");
  var n = parseInt(input[0]);
  s = new Array(n);
  for(i=0;i<n;i++){
    s[i]=input[i+1];
  }
  alf = new Array(26).fill(0);
  for(i=0;i<alf.length;i++){
    alfsub = new Array(n).fill(0);
    alf[i]=alfsub;
  }
  alf2= new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
  for(i=0;i<n;i++){
    for(j=0;j<alf2.length;j++){
      regexp = new RegExp(alf2[j],'g');
      if(s[i].match(regexp)!=null){
      alf[j][i]=s[i].match(regexp).length;
      }
    }
  }
  var ans ="";
  for(i=0;i<alf.length;i++){
    for(j=0;j<Math.min.apply(null,alf[i]);j++){
      ans+=alf2[i];
    }
  }

  console.log('%s', ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func main() {
	sc.Split(bufio.ScanWords)
	n := getInt()
	m := [26]int{}
	for j := 0; j < 26; j++ {
		m[j] = 100
	}
	for i := 0; i < n; i++ {
		s := getString()
		x := [26]int{}
		for _, v := range s {
			x[int(v-'a')]++
		}
		for j := 0; j < 26; j++ {
			m[j] = min(m[j], x[j])
		}
	}

	for i := 0; i < 26; i++ {
		for j := 0; j < m[i]; j++ {
			fmt.Print(string(i + 'a'))
		}
	}
	out()
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(r, &n)
	ss := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(r, &ss[i])
	}

	alphabetCounts := make([]int, 26)
	for i := 0; i < len(alphabetCounts); i++ {
		alphabetCounts[i] = 50
	}
	for _, s := range ss {
		tmpCounts := make([]int, 26)
		for j := 0; j < len(s); j++ {
			tmpCounts[s[j]-'a']++
		}

		for j := 0; j < 26; j++ {
			alphabetCounts[j] = min(alphabetCounts[j], tmpCounts[j])
		}
	}

	// 出力
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	for i := 0; i < len(alphabetCounts); i++ {
		for j := 0; j < alphabetCounts[i]; j++ {
			fmt.Fprint(w, string('a'+byte(i)))
		}
	}
	fmt.Fprintln(w, "")
}

// Union-Find
type unionFind struct {
	d []int
}

func newUnionFind(n int) *unionFind {
	uf := new(unionFind)
	uf.d = make([]int, n)
	for i := 0; i < n; i++ {
		uf.d[i] = -1
	}
	return uf
}

func (uf *unionFind) find(x int) int {
	if uf.d[x] < 0 {
		return x
	}
	uf.d[x] = uf.find(uf.d[x])
	return uf.d[x]
}

func (uf *unionFind) unite(x, y int) bool {
	rootX := uf.find(x)
	rootY := uf.find(y)
	if rootX == rootY {
		return false
	}

	if uf.d[rootX] < uf.d[rootY] {
		uf.d[rootX] += uf.d[rootY]
		uf.d[rootY] = rootX
	} else {
		uf.d[rootY] += uf.d[rootX]
		uf.d[rootX] = rootY
	}

	return true
}

func (uf *unionFind) same(x, y int) bool {
	return uf.find(x) == uf.find(y)
}

func (uf *unionFind) size(x int) int {
	return -uf.d[uf.find(x)]
}

// mod combination
func modpow(a, n, mod int) int {
	res := 1
	for n > 0 {
		if n%2 != 0 {
			res = res * a % mod
		}
		a = a * a % mod
		n = n / 2
	}
	return res
}

func modcomb(n, a, mod int) int {
	x := 1
	y := 1
	for i := 0; i < a; i++ {
		x = x * (n - i)
		x %= mod
		y = y * (i + 1)
		y %= mod
	}
	return x * modpow(y, mod-2, mod) % mod
}

func modfactorial(n, mod int) int {
	result := 1
	for i := 1; i <= n; i++ {
		result = (result * i) % mod
	}
	return result
}

// Utility

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func primeFactor(x int) map[int]int {
	res := make(map[int]int)
	for i := 2; i*i <= x; i++ {
		for x%i == 0 {
			res[i]++
			x = x / i
		}
	}
	if x != 1 {
		res[x] = 1
	}
	return res
}

func divisor(x int) []int {
	res := make([]int, 0)
	for i := 1; i*i <= x; i++ {
		if x%i == 0 {
			res = append(res, i)
			if i != x/i {
				res = append(res, x/i)
			}
		}
	}
	return res
}

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

func lcm(x, y int) int {
	return x / gcd(x, y) * y
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var n int
	con.Scan(&n)
	m := make([]int, 26)
	for i := 0; i < 26; i++ {
		m[i] = 100
	}
	for i := 0; i < n; i++ {
		var s string
		con.Scan(&s)
		d := make([]int, 26)
		for _, c := range s {
			d[c-'a']++
		}
		for j := 0; j < 26; j++ {
			if d[j] < m[j] {
				m[j] = d[j]
			}
		}
	}
	for i := 0; i < 26; i++ {
		for j := 0; j < m[i]; j++ {
			con.Printf("%c", 'a'+i)
		}
	}
	con.Println()
	return nil
}
//  [go]
package main

import (
	"fmt"
	"strings"
)

func main() {
	// Code for C - Dubious Document
	var N int
	fmt.Scanf("%d", &N)

	var S string
	count := make([][]int, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%s", &S)
		count[i] = make([]int, 26)
		for j := 0; j < 26; j++ {
			count[i][j] = strings.Count(S, string('a'+j))
		}
	}

	var min int
	for j := 0; j < 26; j++ {
		min = 100
		for i := 0; i < N; i++ {
			if min > count[i][j] {
				min = count[i][j]
			}
		}
		fmt.Printf("%s", strings.Repeat(string('a'+j), min))
	}
	fmt.Printf("\n")
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	N := ReadInt()
	m := make([]map[byte]int, N)
	for i := 0; i < N; i++ {
		m[i] = make(map[byte]int)
		s := ReadString()
		for _, c := range []byte(s) {
			m[i][c]++
		}
	}
	v := ""
	for c := byte('a'); c <= 'z'; c++ {
		min := 1 << 62
		for i := 0; i < N; i++ {
			if min > m[i][c] {
				min = m[i][c]
			}
		}
		v += strings.Repeat(string(c), min)
	}
	fmt.Println(v)
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}
//  [ruby]
n = gets.to_i
st = readlines.map{|s| s.chomp }
l = ("a".."z")
ans = ""
l.each do |c|
  a = st.map{|s| s.count(c)}
  ans += c * a.min
end

puts ans
//  [ruby]
STRS = readlines.drop(1).map(&:chomp)
ans = ""
('a'..'z').each do |c|
  ans += c * STRS.map{|s| s.count(c)}.min
end
puts ans
//  [ruby]
a_to_z = ("a".."z").to_a
alphabets = {}
a_to_z.each do |char|
  alphabets[char] = 0
end

n = gets.to_i
words = n.times.map { gets.chomp }
alphabets.each do |key, value|
  count = []
  words.each do |word|
    count <<  word.count(key)
  end # of words.each
  alphabets[key] += count.min
end # of alphabets.map!
# p alphabets

answer = ""
alphabets.each do |key, value|
  unless value == 0
    answer += key * value
  end
end
puts answer
//  [ruby]
N = gets.to_i
S = readlines.map { _1.chomp.chars.sort }
S.map! { _1.group_by(&:itself) }

ans = []
S[0].each do |k,v|
  cnt = v.size
  S.each do |s|
    if s[k]
      cnt = [cnt, s[k].size].min
    else
      cnt = 0
      break
    end
  end
  ans.push(*v[0,cnt])
end
puts ans.join
//  [ruby]
n = gets.to_i
map = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
ans = Array.new(26,0)
s = []
n.times do |i|
  s[i] = gets.chomp
end
s[0].length.times do |i|
  ans[map.index(s[0][i])] += 1
end
1.upto(n-1) do |i|
  tmp = Array.new(26,0)
  s[i].length.times do |j|
    tmp[map.index(s[i][j])] += 1
  end
  26.times do |k|
    ans[k] = tmp[k] if ans[k] > tmp[k]
  end
end
string = ""
26.times do |i|
  ans[i].times do
    string = string + map[i]
  end
end
puts string
//  [ruby]
n = gets.to_i
atoz = ("a".."z")
ans = atoz.each_with_object(Hash.new) { |c, h| h[c.to_sym] = 50 }

n.times do
  s = gets.chomp
  ans.each do |k, v|
    count = s.count(k.to_s)
    ans[k] = count if count <= v
  end
end

puts ans.select { |_, v| v > 0 }.map { |k, v| [k.to_s * v] }.join
//  [rust]
#![allow(unused, non_snake_case, dead_code, non_upper_case_globals)]
use std::cmp::*;
use std::collections::*;
use std::mem::*;

fn main() {
    let (r, w, e) = (std::io::stdin(), std::io::stdout(), std::io::stderr());
    let mut io = IO::new(r.lock(), w.lock(), e.lock());
    assert_eq!(!0usize, std::usize::MAX); //🙊
    assert!(0 == 0); //😇
    let mut c = vec![INF; 26];

    let n = io.read::<usize>();
    for _ in 0..n {
        let s = io.chars();
        let mut cs = vec![0; 26];
        for &c in &s {
            let cti = (c as u8 - b'a') as usize;
            cs[cti] += 1;
        }
        for i in 0..26 {
            c[i] = min(c[i], cs[i]);
        }
    }

    for i in 0..26 {
        if c[i] > 0 {
            for j in 0..c[i] {
                io.write((b'a' + i as u8) as char);
            }
        }
    }
    io.writeln("");
}

static MX: usize = 1010101;
static MOD: i64 = 1000000007;
static INF: i64 = std::i64::MAX >> 1;
// IO
use std::io::*;
struct IO<R: Read, W: Write, E: Write> {
    Read: R,
    Write: BufWriter<W>,
    Error: BufWriter<E>,
}
impl<R: Read, W: Write, E: Write> IO<R, W, E> {
    fn new(r: R, w: W, e: E) -> IO<R, W, E> {
        IO {
            Read: r,
            Write: BufWriter::new(w),
            Error: BufWriter::new(e),
        }
    }
    fn read<T>(&mut self) -> T
    where
        T: std::str::FromStr,
    {
        let next: String = self
            .Read
            .by_ref()
            .bytes()
            .map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect();
        next.parse().ok().unwrap()
    }
    fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
    fn chari(&mut self) -> Vec<i64> {
        self.chars()
            .iter()
            .map(|&c| (c as u8 - b'0') as i64)
            .collect::<Vec<i64>>()
    }
    fn readn<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read::<T>()).collect::<Vec<_>>()
    }
    fn readmat<T: std::str::FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<T>> {
        (0..n).map(|_| self.readn(m)).collect()
    }
    fn write<S: ToString>(&mut self, val: S) {
        self.Write.write(val.to_string().as_bytes());
    }
    fn writeln<S: ToString>(&mut self, val: S) {
        self.Write.write(val.to_string().as_bytes());
        self.Write.write(b"\n");
    }
    fn debug<S: std::fmt::Debug>(&mut self, val: S) {
        writeln!(self.Error, "(debug) {:?}", &val);
    }
    fn debug2<S: std::fmt::Debug, T: std::fmt::Debug>(&mut self, val1: S, val2: T) {
        writeln!(self.Error, "(debug2) {:?} -> {:?}", val1, val2);
    }
    fn debug3<S: std::fmt::Debug, T: std::fmt::Debug, U: std::fmt::Debug>(
        &mut self,
        val1: S,
        val2: T,
        val3: U,
    ) {
        writeln!(
            self.Error,
            "(debug3) {:?} -> {:?} -> {:?}",
            val1, val2, val3
        );
    }
}
//  [rust]
//入力マクロここから
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
macro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }
macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
//入力マクロここまで

use std::cmp::*;
use std::collections::BTreeMap;

fn main() {
    input! {
        n: usize,
        s: [chars;n],
    }

    let mut cnt = vec![0; 26];

    for i in 0..n {
        let mut dic = BTreeMap::new();
        for e in s[i].iter() {
            *dic.entry(e).or_insert(0) += 1_u64;
        }
        for j in 0..26 {
            let t = *dic.get(&(('a' as u8 + j as u8) as char)).unwrap_or(&0);
            cnt[j] = if i == 0 { t } else { min(cnt[j], t) }
        }
    }

    for i in 0..26 {
        for _ in 0..cnt[i] {
            print!("{}", ('a' as u8 + i as u8) as char);
        }
    }

    println!();
}