import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class B
{
        String line;
        StringTokenizer inputParser;
        BufferedReader is;
        FileInputStream fstream;
        DataInputStream in;
        String FInput="";

        void openInput(String file)
        {

                if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
                else
                {
                        try{

                        fstream = new FileInputStream(file);
                        in = new DataInputStream(fstream);
                        is = new BufferedReader(new InputStreamReader(in));
                        }catch(Exception e)
                        {
                                System.err.println(e);
                        }
                }

        }

        void readNextLine()
    	{
    		try {
    			line = is.readLine();
    			inputParser = new StringTokenizer(line, " ,\t");
    			//System.err.println("Input: " + line);
    		} catch (IOException e) {
    			System.err.println("Unexpected IO ERROR: " + e);
    		}
    		catch (NullPointerException e)
    		{
    			line=null;

    		}

    	}

        long NextLong()
        {
                String n = inputParser.nextToken();

                long val = Long.parseLong(n);

                 return val;
        }

        int NextInt()
        {
                String n = inputParser.nextToken();
                int val = Integer.parseInt(n);

                //System.out.println("I read this number: " + val);
                return val;
        }

        String NextString()
        {
                String n = inputParser.nextToken();
                return n;
        }

        void closeInput()
        {
                try {
                        is.close();
                } catch (IOException e) {
                        System.err.println("Unexpected IO ERROR: " + e);
                }

        }

        public static void main(String [] argv)
        {
                //String filePath="circles.in";
                String filePath=null;
                if(argv.length>0)filePath=argv[0];
                new B(filePath);

        }

        public B(String inputFile)
        {
        	openInput(inputFile);
    		StringBuilder sb = new StringBuilder();
    		readNextLine();
    		long W=NextLong(), m=NextLong(), K=NextLong();

        	long D=0, H=W;
        	long M=H/2;
        	while(D+1<H)
        	{
        		if(poss(m,m+M-1,W,K))D=M;
        		else H=M-1;
        		M=(D+H)/2;
        	}
        	M+=5;
        	while(!poss(m,m+M-1,W,K))M--;
        	sb.append(M);
        	System.out.println(sb);
    		closeInput();

        }

        private boolean poss(long from, long to, long w, long k) {
        	long need=0;
			if(get(from)<get(to))
			{
				long miss=getNum(get(from));
				need+=(miss-from)*get(from);
				from=miss;
			}
			while(get(from)<get(to))
			{
				long miss=getNum(get(from));
				need+=(miss-from)*get(from);
				from=miss;
			}
			need+=(to-from+1)*get(from);
			if(BigInteger.valueOf(need).multiply(BigInteger.valueOf(k)).compareTo(BigInteger.valueOf(w))<=0)return true;
			return false;
		}

		private long getNum(int x) {
			String ret="1";
			for(int i=0; i<x; i++)ret+="0";
			return new Long(ret);
		}

		int get(long x)
        {
        	return (""+x).length();
        }
}

#include <bits/stdc++.h>
using namespace std;
int numdigits(long long m) {
  int ret = 0;
  while (m) {
    m /= 10;
    ret++;
  }
  return ret;
}
long long extract(int x) {
  long long last = 10, first = 10;
  x -= 2;
  while (x--) {
    first *= 10;
  }
  last *= first;
  return (last - first);
}
long long T[23];
int main() {
  long long w, m, ans = 0, k;
  cin >> w >> m >> k;
  int digits = numdigits(m);
  int copy = digits;
  long long base = 10;
  copy--;
  while (copy--) base *= 10;
  T[digits] = base - m;
  for (int i = digits + 1; i <= 23; i++) T[i] = extract(i);
  for (int i = digits; i <= 23 && w > 0; i++) {
    if (w / (i * k) == 0) {
      break;
    }
    long long x = (w / (i * k)) >= T[i] ? T[i] : (w / (i * k));
    ans += x;
    w -= x * i * k;
  }
  cout << ans;
  return 0;
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;

public class A34Reconnaissance2
{
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		String line [] = br.readLine().split(" ");
		ArrayList<Integer> arr = new ArrayList<Integer>();
		for(int i=0;i<line.length;i++)
		{
			arr.add(Integer.parseInt(line[i]));
		}
		PriorityQueue<pair> pq = new PriorityQueue<pair>();
		for(int i=0;i<line.length-1;i++)
		{		pq.add(new pair(Math.abs(arr.get(i)-arr.get(i+1)),i+1,i+2));

		}pq.add(new pair(Math.abs((arr.get(0)-arr.get(line.length-1))),1,line.length));
		pair x1 = pq.remove();

		System.out.println(x1.i+" "+x1.ii);
	}
	static class pair implements Comparable<pair>
	{
		int x;
		int ii;
		int i;
		public pair (int x , int i,int ii)
		{
			this.x =x;
			this.i =i;
			this.ii = ii;
		}
		@Override
		public int compareTo(pair o) {

			return this.x-o.x;
		}
	}

}

n = int(input())
a = list(map(int, input().split()))
x = a[0]
for i in range(n-1):
	a[i] = abs(a[i] - a[i+1])
a[-1] = abs(x - a[-1])
m = min(a)
ind = a.index(m)
p, q = ind+1, ind+2
if q > n:
	q = 1
print(p,q)


#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const int mod = 1000000007;
const int maxn = 2000100;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int n, m;
  cin >> n >> m;
  vector<int> a(n + 5);
  vector<int> left(n + 5, 0), right(n + 5, 0);
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (int i = 1; i <= n; i++) {
    if (a[i] <= a[i - 1]) {
      right[i] = right[i - 1] + 1;
    } else
      right[i] = 1;
  }
  for (int i = n; i > 0; i--) {
    if (a[i] <= a[i + 1]) {
      left[i] = left[i + 1] + 1;
    } else
      left[i] = 1;
  }
  while (m--) {
    int l, r;
    cin >> l >> r;
    if (left[l] + right[r] > r - l + 1) {
      cout << "Yes"
           << "\n";
    } else
      cout << "No"
           << "\n";
  }
  return 0;
}

No
Yes
Yes
No
No
No
No
No
No
Yes
No
Yes
Yes
No
No
No
Yes
No
Yes
Yes

n,q = map(int,input().split())
arr = [int(x) for x in input().split()]
inc = [-1] * n
dec = [-1] * n
inc[n-1] = n-1
for i in range(n-2, -1, -1):
    if(arr[i]<=arr[i+1]):
        inc[i] = inc[i+1]
    else:
        inc[i] = i
dec[n-1] = n-1
for i in range(n-2, -1, -1):
    if(arr[i]>=arr[i+1]):
        dec[i] = dec[i+1]
    else:
        dec[i] = i
for i in range(q):
    l,r = map(int,input().split())
    if(dec[inc[l-1]]>=r-1):
        print("Yes")
    else:
        print("No")


//package Round_129;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

import static java.lang.Math.*;

public class e implements Runnable {

    String input = "";
    String output = "";
    BufferedReader bf;
    FastScanner in;
    PrintWriter out;

    public void solve() throws Exception {
        /*int n = in.nextInt();
        char a[] = in.next().toCharArray();
        char b[] = in.next().toCharArray();
        double s[] = new double[26];
        double sum = 0;
        for (int i = 0; i<n; i++){
            s[a[i] - 'A'] += (i + 1);
            sum += s[b[i] - 'A'] * (n - i);
        }

        Arrays.fill(s, 0.0);

        for (int i = n-1; i>=0; i--){
            sum += s[b[i] - 'A'] * (i+1);
            s[a[i] - 'A'] += (n - i);
        }

        double total = 0;
        for (int i = 1; i<=n; i++)
            total += i*i;

        out.println (sum / total);
         */
                int n = in.nextInt();
		String a = in.next();
		String b = in.next();
		double sum = 0.;
		double[] s = new double[26];
		for (int i = 0; i < n; ++i) {
			s[a.charAt(i) - 'A'] += (i + 1);
			sum += s[b.charAt(i) - 'A'] * (n - i);
		}
		Arrays.fill(s, 0.);
		for (int i = n - 1; i >= 0; --i) {
			sum += s[b.charAt(i) - 'A'] * (i + 1);
			s[a.charAt(i) - 'A'] += (n - i);
		}

		double total = 0.;
		for (long i = 1; i <= n; ++i) {
			total += i * i;
		}
		out.println(sum / total);
    }

    @Override
    public void run() {
        try {
            if (input.equals("")) {
                bf = new BufferedReader(new InputStreamReader(System.in));
            } else {
                bf = new BufferedReader(new FileReader(input));
            }

            in = new FastScanner(bf);

            if (output.equals("")) {
                out = new PrintWriter(System.out);
            } else {
                out = new PrintWriter(new File(output));
            }

            solve();

            out.flush();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    public static void main(String[] args) {
        new Thread(null, new e(), "1", 1 << 23).start();
    }

    class FastScanner {

        BufferedReader bf;
        StringTokenizer st;

        public FastScanner(BufferedReader bf) {
            this.bf = bf;
        }

        public String next() throws Exception {

            while (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(bf.readLine());
            }

            return st.nextToken();
        }

        public int nextInt() throws Exception {
            return Integer.parseInt(next());
        }

        public long nextLong() throws Exception {
            return Long.parseLong(next());
        }

        public double nextDouble() throws Exception {
            return Double.parseDouble(next());
        }
    }
}


import sys
input=sys.stdin.readline
import copy
from math import *
n=int(input())
a=[int(x) for x in input().split()]
d=[0 for i in range(70)]
for i in range(n):
    d[int(log(a[i]&(-a[i]),2))]+=1
print(n-max(d))
r=d.index(max(d))
for i in range(n):
    if int(log(a[i]&(-a[i]),2))!=r:
        print(a[i],end=" ")

#include <bits/stdc++.h>
using ll = long long;
using namespace std;
const int N = 2e5 + 10, E = 65;
int n, cnt[E];
ll a[N];
int main() {
  scanf("%d", &n);
  for (auto i = 0, _end = n - 1; i <= _end; ++i) {
    scanf("%lld", a + i);
    cnt[__builtin_ctzll(a[i])]++;
  }
  int ans = max_element(cnt, cnt + E) - cnt;
  printf("%d\n", n - cnt[ans]);
  for (auto i = 0, _end = n - 1; i <= _end; ++i)
    if (__builtin_ctzll(a[i]) != ans) printf("%lld ", a[i]);
  puts("");
}


#include <bits/stdc++.h>
using namespace std;
bool comp(const pair<long long, long long>& a,
          const pair<long long, long long>& b) {
  return a.first + a.second > b.first + b.second;
}
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long T = 1;
  while (T--) {
    long long n, r;
    cin >> n >> r;
    vector<pair<long long, long long>> v(n), vp, vn;
    for (auto it : v) {
      long long l, r;
      cin >> l >> r;
      if (r >= 0)
        vp.push_back({l, r});
      else
        vn.push_back({l, r});
    }
    sort(vp.begin(), vp.end());
    sort(vn.begin(), vn.end(), comp);
    bool ok = true;
    for (auto p : vp) {
      if (r >= p.first)
        r += p.second;
      else
        ok = false;
    }
    for (auto p : vn) {
      if (r >= p.first)
        r += p.second;
      else
        ok = false;
    }
    if (r < 0) ok = false;
    if (ok)
      cout << "YES\n";
    else
      cout << "NO\n";
  }
  return 0;
}

n,r = map(int,(input().split()))

plus=[]
minn=[]

for i in range (0,n):

    temp = list(map(int,input().split()))

    if temp[1] <=0:
        temp.append(temp[0]+temp[1])
        minn.append(temp)
    else:
        plus.append(temp)

plus.sort()
minn.sort(reverse=True,key = lambda x: x[2])
flag = True
for i in plus:

    if i[0] <= r:
        r+= i[1]
        #print(r)
    else:
        flag=False
        break
#print("GANTI")
if flag:
    for i in minn:
        if i[0] <= r:
            r +=i[1]
            #print(r)
        else:
            flag=False
            break

if flag and r>=0:
    print("YES")
else:
    print("NO")


#include <bits/stdc++.h>
using namespace std;
int main() {
  srand(time(NULL));
  ios::sync_with_stdio(false);
  string s;
  cin >> s;
  int n = s.size();
  for (int a = 1; a <= 5; a++) {
    for (int b = 1; b <= 20; b++) {
      int sz = a * b;
      if (sz < n) continue;
      int k = sz - n;
      int x = k / a, y = k % a;
      vector<vector<char>> v(a, vector<char>(b, '*'));
      int pos = 0;
      for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
          if (i < y) {
            if (j < x + 1) continue;
          } else {
            if (j < x) continue;
          }
          v[i][j] = s[pos++];
        }
      }
      cout << a << ' ' << b << endl;
      for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) cout << v[i][j];
        cout << endl;
      }
      return 0;
    }
  }
  return 0;
}

3 15
MyNameIsLifeIA*
mForeverByYourS
ideMyNameIsLife

3 18
uvkxATqVwsCaAJeBaB
GXZKiktZFHbzywaqN*
drGSNfgTIwOBFzKDv*

5 17
aoNtJAeHshvQrvwRg
ZHkrdxwyaaHOIsyE*
MxtRNkMifYfRoRba*
mpjmPoUVpNJvSvEy*
aQjEvGcRAJJSPORp*

5 18
yWptRMTHCgVSOpLWsh
usRuXELfcnMUbustg*
mNXUOGkdTwafvAcGy*
FUtIvCoaYIPZqcJGz*
GmccLiQPCPURmDsVi*

3 15
MyNameIsLifeIAm
ForeverByYourSi
deMyNameIsLife*

4 20
IVABxGWcbNtZOIzknsfc
jfPSfuTByIAEqOqvnVuW
yjQJfCzzLPIDjAHNQziK
ZhnjwLmjElNOMGjPvhC*

def print2d(a):
    for i in range(len(a)):
        print(''.join(list(map(str, a[i]))))

st = input()
for i in range(1, 5 + 1):
    vst = len(st) // i
    ost = len(st) % i
    if vst + min(ost, 1) > 20:
        continue
    a = [0] * i
    ind = 0
    f = 0

    for j in range(len(a)):
        a[j] = []

    for j in range(len(a)):
        for k in range(vst):
            a[j].append(st[ind])
            ind += 1

        if ost > 0:
            ost -= 1
            a[j].append(st[ind])
            ind += 1
            f = 1

        elif f != 0:
            a[j].append('*')

    if a[-1][-1] == '*' or a[-1][-1] == st[-1]:
        print(len(a), len(a[0]))
        print2d(a)
        exit()


#include <bits/stdc++.h>
using namespace std;
long long n, x, y;
string s;
vector<int> v;
int main(void) {
  ios_base::sync_with_stdio(false);
  cin >> n >> x >> y;
  cin >> s;
  for (int i = 0; i < n; i++) {
    int j = i;
    while (j < n and s[j] == s[i]) {
      j++;
    }
    v.emplace_back(s[i] - '0');
    i = j - 1;
  }
  if (v[0] == 1) v.erase(v.begin());
  if (v.size() and v.back() == 1) v.pop_back();
  if (v.size() == 0) {
    cout << 0 << endl;
    return 0;
  }
  long long zero = 0, one = 0;
  for (int x : v) {
    if (x == 1)
      one++;
    else
      zero++;
  }
  cout << min(one * x + y, zero * y) << endl;
  return 0;
}

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class C493 {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int a = scan.nextInt();
		long x = scan.nextLong();
		long y = scan.nextLong();
		long ans = 0;
		int[] arr =new int[a];
		String s = scan.next();

		Pattern pat = Pattern.compile("0+");
		Pattern pat1 = Pattern.compile("1+");
		Matcher matcher = pat.matcher(s);
		Matcher matcher1 = pat1.matcher(s);
		long count = 0;
		long count1 =0;
		while(matcher1.find())count1++;
		while (matcher.find()) count++;

		for(int i = 0;i<a;i++){
			arr[i] = s.charAt(i)-'0';
		}
		if(!s.contains("0")){
			System.out.println(0);
			return;
		}
		if(s.charAt(0)=='1'){
			count1--;
		}
		if(s.charAt(s.length()-1)=='1'){
		    count1--;
		}
		long cost = count1*x+y;
		long cost1 = count*y;
		System.out.println(Math.min(cost1, cost));
	}

}


#include <bits/stdc++.h>
using namespace std;
int min(int a, int b, int c) {
  if (a < b) {
    return a < c ? a : c;
  }
  return b < c ? b : c;
}
int main() {
  int l, r, a;
  cin >> l >> r >> a;
  int ans = 0;
  cout << min(2 * (l + a), 2 * (r + a), ((l + r + a) - ((l + r + a) % 2)));
  return 0;
}

l, r, a = map(int, input().split())
while a != 0:
    if l < r:
        l += 1
    else:
        r += 1
    a -= 1
print(min(l, r)*2)


foo = int(input())
gr = 0
lo = 0

for i in range(foo):
    bar = int((input().split(' '))[0])
    if bar < 0:
        lo += 1
    else:
        gr += 1
    if lo > 1 and gr > 1:
        print('No')
        break
else:
    print('Yes')

4
1 1
9 9
2 10
3 11
```

Note that these inputs are randomly generated and may not necessarily produce the expected

yes no yes yes yes yes yes yes yes yes yes yes yes yes no yes yes yes yes no yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes no yes yes yes yes yes yes yes yes yes

import java.io.*;
import java.util.*;

public class Main{

    public static void main (String[] args) {
        int a,b,c,d=0,e=0;
        Scanner sc = new Scanner(System.in);
        a = sc.nextInt();
        while(a-->0){
            b = sc.nextInt();
        c = sc.nextInt();
        if(b<0){
            d++;
        }else{
            e++;
        }
        }
        if(d<=1 || e<=1){
            System.out.println("yes");
        }else{
            System.out.println("no");
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {

	void howUdoin() {

		int n = inpi();
        int k = inpi();
        int p = inpi();
        int[] a = new int[n];
        int[] b = new int[k];
        for (int i = 0; i < n; i++){
        	a[i] = inpi();
        }
        for (int j = 0; j < k; j++) {
        	b[j] = inpi();
        }
        Arrays.sort(a);
        Arrays.sort(b);
        long ans = Long.MAX_VALUE;
        for (int i = 0; i+n <= k ; i++) {
            long temp = 0;
            for (int j = 0; j < n; j++) {
                temp = Math.max(temp, Math.abs(a[j] - b[j + i]) + Math.abs(b[j + i] - p));
            }
           ans = Math.min(ans,temp);
        }
        System.out.println(ans);

	}

	InputStream obj;
	PrintWriter out;
	String check = "";

	public static void main(String[] args) throws IOException {
		new Main().main1();
	}

	void main1() throws IOException {
		out = new PrintWriter(System.out);
		obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes());
		howUdoin();
		out.flush();
		out.close();
	}
	byte inbuffer[] = new byte[1024];
	int lenbuffer = 0, ptrbuffer = 0;

	int readByte() {
		if (lenbuffer == -1) {
			throw new InputMismatchException();
		}
		if (ptrbuffer >= lenbuffer) {
			ptrbuffer = 0;
			try {
				lenbuffer = obj.read(inbuffer);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
		}
		if (lenbuffer <= 0) {
			return -1;
		}
		return inbuffer[ptrbuffer++];
	}

	boolean isSpaceChar(int c) {
		return (!(c >= 33 && c <= 126));
	}

	int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b));
		return b;
	}

	String inps() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	String inpsl() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (b!='\n') {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	int inpi() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	long inpl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	float inpf() {
		return Float.parseFloat(inps());
	}

	double inpd() {
		return Double.parseDouble(inps());
	}

	char inpc() {
		return (char) skip();
	}

	int[] inpia(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = inpi();
		}
		return a;
	}

	long[] inpla(int n) {
		long a[] = new long[n];
		for (int i = 0; i < n; i++) {
			a[i] = inpl();
		}
		return a;
	}

	String[] inpsa(int n) {
		String a[] = new String[n];
		for (int i = 0; i < n; i++) {
			a[i] = inps();
		}
		return a;
	}

}

#include <bits/stdc++.h>
using namespace std;
long long n, k, p;
int a[3000];
int b[3000];
int ch(long long mid) {
  long long lastky = 0;
  for (int i = 0; i < n; i++) {
    int ok = 0;
    while (lastky < k) {
      long long minx = abs(a[i] - b[lastky]) + abs(b[lastky] - p);
      minx = abs(a[i] - b[lastky]) + abs(b[lastky] - p);
      lastky++;
      if (minx <= mid) {
        ok = 1;
        break;
      }
    }
    if (!ok) return 0;
  }
  return 1;
}
int main() {
  cin >> n >> k >> p;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  for (int i = 0; i < k; i++) {
    cin >> b[i];
  }
  b[k] = 1e10;
  sort(a, a + n);
  sort(b, b + k);
  long long st = 0, En = 1e10;
  long long ans = 1e10;
  while (st <= En) {
    long long mid = (st + En) / 2;
    if (ch(mid)) {
      En = mid - 1;
      ans = mid;
    } else {
      st = mid + 1;
    }
  }
  cout << ans;
}


for _ in range(int(input())):
  x,y,p,q=map(int,input().split())
  l,r,res=0,10**18,-1
  while l<=r:
    mid=(l+r)//2
    a,b=p*mid-x,q*mid-y
    if a<=b and a>-1 and b>-1:res=b;r=mid-1
    else :l=mid+1
  print(res)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

public class Main {

    static StreamTokenizer st;
    static int a, b, p, q;
    static double r;
    static long sol;

    public static void main(String[] args) throws IOException {
        st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        int n = ri();
        sol = -1;
        while (n-- > 0) {
            a = ri();
            b = ri();
            p = ri();
            q = ri();
            sol = -1;
            search(1, (long) 2e9);
            if (sol < 0) {
                System.out.println(-1);
            } else {
                long x = sol * p - a;
                System.out.println(x + (sol * q) - b - x);
            }
        }
    }

    static void search(long lo, long hi) {
        if (lo > hi) {
            return;
        }
        long mid = (lo + hi) >> 1;
        long x = p * mid;
        long y = q * mid;
        if (x >= a && (x - a + b) <= y) {
            sol = mid;
            if (hi == mid) {
                return;
            }
            hi = mid;
        } else {
            if (lo == mid) {
                return;
            }
            lo = mid;
        }
        search(lo, hi);
    }

    static int ri() throws IOException {
        st.nextToken();
        return (int) st.nval;
    }
}


def binary_search_first_true(predicate, from_inclusive, to_inclusive):
    lo = from_inclusive - 1
    hi = to_inclusive + 1
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if not predicate(mid):
            lo = mid
        else:
            hi = mid
    return hi

def tri(n):
	return n*(n+1)//2

def f(n, m, t):
	return n-tri(t-m-1)-t

def solve(n, m):
	if m >= n:
		return n
	ans = binary_search_first_true(lambda x: f(n, m, x) <= 0, m+1, n)
	return ans

def main(sc):
	n, m = sc.next_ints(2)
	ans = solve(n, m)
	print(ans)

class Scanner:
	def __init__(self):
		self.idx = 0
		self.tokens = []

	def next(self):
		while self.idx == len(self.tokens) or not len(self.tokens[self.idx]):
			if self.idx == len(self.tokens):
				self.idx = 0
				self.tokens = input().split()
			else:
				self.idx += 1
		self.idx += 1
		return self.tokens[self.idx-1]

	def next_string(self):
		return self.next()

	def next_strings(self, n):
		return [self.next_string() for i in range(0, n)]

	def next_int(self):
		return int(self.next())

	def next_ints(self, n):
		return [self.next_int() for i in range(0, n)]

scanner = Scanner()
main(scanner)

import java.util.Scanner;

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

		long n = scan.nextLong();
		long m = scan.nextLong();

		if (m >= n) {
			System.out.print(n);
			System.exit(0);
		}

		long ans = m;

		long s = 2 * (n - m);

		double kdouble = (Math.sqrt(1 + s * 4)) / 2;

		long k = (long) kdouble;
		for (long l = k - 1000; l < k + 1000; l++) {
			if (l <= 0) {
				continue;
			}
			long side = l * l + l;
			if (side >= s) {
				System.out.print(l + ans);
				System.exit(0);
			}
		}
	}
}


#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 10;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  string s, s1;
  cin >> s >> s1;
  reverse(s.begin(), s.end());
  reverse(s1.begin(), s1.end());
  s1.resize(N + 5, '0');
  s.resize(N + 5, '0');
  for (long long i = N - 1; i > 0; --i) {
    while (s[i] == '1' && s[i - 1] == '1') {
      s[i] = '0';
      s[i - 1] = '0';
      s[i + 1] = '1';
      i += 2;
    }
  }
  for (long long i = N - 1; i > 0; --i) {
    while (s1[i] == '1' && s1[i - 1] == '1') {
      s1[i] = '0';
      s1[i - 1] = '0';
      s1[i + 1] = '1';
      i += 2;
    }
  }
  reverse(s1.begin(), s1.end());
  reverse(s.begin(), s.end());
  if (s == s1)
    cout << "=";
  else if (s > s1)
    cout << ">";
  else
    cout << "<";
}

import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.math.BigDecimal;

public class Main {

  public static class MyScanner {
      BufferedReader reader;
      StringTokenizer tokenizer;

      public MyScanner() {
          reader = new BufferedReader(new InputStreamReader(System.in));
          tokenizer = new StringTokenizer("");
      }

      public String next() {
          while (!tokenizer.hasMoreTokens()) {
            try {
              tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          return tokenizer.nextToken();
      }

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

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

      public double nextDouble() {
        return Double.parseDouble(next());
      }
  }

  PrintWriter out;
  MyScanner sc;

  public Main()
  {
    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    sc = new MyScanner();
  }

  public void fin() {
    out.flush();
  }

  /* ========== MAIN ========== */

  int N_MAX=100000;

  public void init() {
  }

  BigInteger[] reduce(final String S) {
    BigInteger[] s = new BigInteger[N_MAX];
    Arrays.fill(s, BigInteger.ZERO);

    for (int i=0; i<S.length(); ++i) {
      if (S.charAt(S.length()-1-i) == '1') {
        s[i] = BigInteger.ONE;
      }
    }

    for (int i=s.length-1; i>=2; --i) {
      if (s[i].compareTo(BigInteger.ZERO)>0) {
        s[i-1] = s[i-1].add(s[i]);
        s[i-2] = s[i-2].add(s[i]);
        s[i] = null;
      }
    }

    return new BigInteger[]{s[0], s[1]};
  }

  BigDecimal translate(final BigInteger[] s) {
    final BigDecimal q  = new BigDecimal((Math.sqrt(5) + 1.0)/2.0);
    final BigDecimal b1 = new BigDecimal(s[1]);
    final BigDecimal b0 = new BigDecimal(s[0]);
    return q.multiply(b1).add(b0);
  }

  String compare(final BigInteger[] s1, final BigInteger[] s2) {
    if (Arrays.equals(s1, s2)) {
      return "=";
    }

    final BigDecimal d1 = translate(s1);
    final BigDecimal d2 = translate(s2);

    final int comp = d1.compareTo(d2);
    if (comp < 0) {
      return "<";
    } else if (comp > 0) {
      return ">";
    } else {
      throw new AssertionError("Never");
    }
  }

  public void solve() {
    final String S1 = sc.next();
    final String S2 = sc.next();

    final BigInteger[] s1 = reduce(S1);
    final BigInteger[] s2 = reduce(S2);

    out.println(compare(s1, s2));
  }

  public static void main(String[] args) {
     Main m = new Main();
     m.init();
     m.solve();
     m.fin();
  }
}


O-|O-OOO
O-|O-OOO
O-|O-OOO
O-|O-OOO
O-|O-OOO
O-|O-OOO
O-|O-OOO
O-|O-OOO
O-|O-OOO

O-|O-OOO
O-|OO-OO
O-|OOO-O
O-|OOOO-
-O|-OOOO
-O|O-OOO
-O|OO-OO
-O|OOO-O
-O|OOOO-

import java.util.*;
public class SoroBan {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		int num=scn.nextInt();
		String str="";
		int num2=1;
		while(num2!=0) {
			int rem=num%10;
			if(rem-5>=0)
			{	str=str+"-O|";
			int i=1;
				for(;i<=(rem-5);i++) {
					str=str+"O";
				}
				str=str+"-";
				for(int j=1;j+i-1<=4;j++)
					str=str+"O";
			}
			else {
				str=str+"O-|";
				for(int i=1;i<=(rem);i++) {
					str=str+"O";
				}
				str=str+"-";
				for(int j=1;j<=4-rem;j++)
					str=str+"O";
			}
			System.out.println(str);
			str="";
			num=num/10;
			num2=num;
		}
	}

}


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class SMSC {
	static int n;

	public static void main(String[] args){
		FastScanner sc = new FastScanner();
		n = sc.nextInt();
		long time = 0;
		long size = 0;
		long largestSize = 0;
		int[] remain = new int[n+1];
		int[] jobsArrive = new int[n+1];
		int[] jobsLength = new int[n+1];
		for(int i=0;i<n;i++){
			jobsArrive[i] = sc.nextInt();
			jobsLength[i] = sc.nextInt();
		}
		jobsArrive[n] = Integer.MAX_VALUE;

		time = jobsArrive[0];
		remain[0] = jobsLength[0];
		size = jobsLength[0];
		largestSize = size;
		int lastTask = 0;
		int curTask = 0;
		while(curTask != n){
			largestSize = Math.max(size, largestSize);
			long consumption = Math.min(remain[curTask], jobsArrive[lastTask+1]-time);
			size -= consumption;
			time += consumption;
			remain[curTask] -= consumption;
			if(remain[curTask] == 0){
				curTask++;
			}

			if(curTask != n && (curTask > lastTask || jobsArrive[lastTask+1] == time)){
				//get new job
				lastTask++;
				remain[lastTask] = jobsLength[lastTask];
				size += jobsLength[lastTask];
				time = jobsArrive[lastTask];
			}
		}
		System.out.println(time + " " + largestSize);
	}

	public static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(String s) {
			try {
				br = new BufferedReader(new FileReader(s));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		public FastScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String nextToken() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(nextToken());
		}

		long nextLong() {
			return Long.parseLong(nextToken());
		}

		double nextDouble() {
			return Double.parseDouble(nextToken());
		}
	}
}

import re
import itertools
from collections import Counter, deque

class Task:
    tasks = []
    answer = ""

    def getData(self):
        numberOfTasks = int(input())
        for i in range(0, numberOfTasks):
            self.tasks += [[int(x) for x in input().split(' ')]]
        #inFile = open('input.txt', 'r')
        #inFile.readline().rstrip()
        #self.childs = inFile.readline().rstrip()

    def solve(self):
        queueSize, maxQueueSize = 0, 0
        time, timeOfLastMessage = 1, 1
        currentTask = 0
        while currentTask < len(self.tasks) or queueSize > 0:
            maxQueueSize = max(maxQueueSize, queueSize)
            if currentTask < len(self.tasks):
                timeDelta = self.tasks[currentTask][0] - time
                queueSize -= min(queueSize, timeDelta)
                time += timeDelta
            else:
                timeOfLastMessage = time + queueSize
                break

            if currentTask < len(self.tasks) and \
                    self.tasks[currentTask][0] == time:
                queueSize += self.tasks[currentTask][1]
                currentTask += 1
        self.answer = str(timeOfLastMessage) + " " + str(maxQueueSize)

    def printAnswer(self):
        print(self.answer)
        #outFile = open('output.txt', 'w')
        #outFile.write(self.answer)

task = Task()
task.getData()
task.solve()
task.printAnswer()


#include <bits/stdc++.h>
const long long inf = 1e9;
const long double eps = 1e-6;
const long long N = 1e6;
const long long M = 1e6;
using namespace std;
void ret(string s) {
  cout << s;
  exit(0);
}
string s;
int a[100][100], b, ans = 0;
int mx, mn, len = 0, pos, n, k, h;
bool u[1000];
int main() {
  cin >> n >> k;
  pos = k - 1;
  for (int i = 0; i < k; i++) {
    cin >> h;
    a[i][0] = h;
    u[h] = true;
  }
  for (int i = 1; i <= n * k; i++)
    if (!u[i]) {
      pos++;
      if (pos == k) {
        pos = 0;
        len++;
      }
      a[pos][len] = i;
    }
  for (int i = 0; i < k; i++) {
    for (int j = 0; j < n; j++) cout << a[i][j] << " ";
    cout << "\n";
  }
  return 0;
}

ar = []
for i in input().split():
    ar.append(int(i))
ar2 = []
for i in input().split():
    ar2.append(int(i))
temp = list(set(range(1, ar[0]*ar[1]+1))-set(ar2))
for i in range(len(ar2)):
    res = []
    res.append(ar2[i])
    while (len(res) != ar[0]):
        res.append(temp[0])
        temp.pop(0)
    print(*res)


x1, x2, a, b = map(int, input().split())
if a <= 0 <= b:
    if x1 < x2:
        if x2 - x1 <= b:
            print("FIRST")
            print(x2)
        else:
            print("DRAW")
    else:
        if x1 - x2 <= -a:
            print("FIRST")
            print(x2)
        else:
            print("DRAW")
else:
    reverse = False
    if a < 0:
        x1, x2, a, b = -x1, -x2, -b, -a
        reverse = True
    if x1 > x2:
        print("DRAW")
    else:
        if (x2 - x1) % (a + b) == 0:
            print("SECOND")
        elif a <= (x2 - x1) % (a + b) <= b:
            print("FIRST")
            print((x1 + (x2 - x1) % (a + b))
                  if not reverse else -(x1 + (x2 - x1) % (a + b)))
        else:
            print("DRAW")

0 2 10 4
```

Note that the inputs are random and not necessarily representative of all possible inputs that conform to the input data format.

#include <bits/stdc++.h>
using namespace std;
long long x1, x2, a, b;
int main() {
  cin >> x1 >> x2 >> a >> b;
  long long dx = x1 - x2;
  if (a <= 0 && 0 <= b) {
    if (-b <= dx && dx <= -a) {
      puts("FIRST");
      cout << x1 - dx << endl;
    } else
      puts("DRAW");
    return 0;
  }
  if (dx * a > 0) {
    puts("DRAW");
    return 0;
  }
  long long len = abs(a) + abs(b);
  dx %= len;
  if (dx == 0) {
    puts("SECOND");
    return 0;
  }
  if (-b <= dx && dx <= -a) {
    puts("FIRST");
    cout << x1 - dx << endl;
  } else
    puts("DRAW");
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  long long t;
  cin >> t;
  for (long long i = 0; i < t; i++) {
    long long r, g, b;
    cin >> r >> g >> b;
    long long mx = max(max(r, g), b);
    long long sum = r + g + b;
    if (mx > (sum + 1) / 2) {
      cout << "No" << endl;
    } else {
      cout << "Yes" << endl;
    }
  }
  return 0;
}

YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES

n = int(input())
for i in range(n):
    l = [int(k) for k in input().split()]
    l.sort()
    if l[2] <= l[1]+l[0]+1 :
    	print("YES")
    else :
    	print("NO")


#include <bits/stdc++.h>
using namespace std;
int N, Z, X[200000];
bool check(int C) {
  int offset = N - C;
  for (int i = 0; i < C; i++)
    if (X[offset + i] - X[i] < Z) return false;
  return true;
}
int main() {
  cin >> N >> Z;
  for (int i = 0; i < N; i++) cin >> X[i];
  sort(X, X + N);
  int ng = N / 2 + 1, ok = 0;
  while (ng - ok > 1) {
    int mid = (ng + ok) / 2;
    (check(mid) ? ok : ng) = mid;
  }
  cout << ok << endl;
  return 0;
}

n,z=(int(i) for i in input().split())
k=0
x=sorted([int(i) for i in input().split()])
i,j=0,n//2
while i<n//2 and j<n:
    if x[j]-x[i]>=z:
        i+=1
        k+=1
    j+=1
print(k)


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 2;
long long a[N], dp[N], dpp[N];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t, i, x, n, ans = 0;
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> a[i];
    dp[i] = 1;
    dpp[i] = 1;
  }
  for (i = 2; i <= n; i++) {
    if (a[i] == a[i - 1]) {
      dp[i] += dp[i - 1];
    }
  }
  for (i = n - 1; i > 0; i--) {
    if (a[i] == a[i + 1]) {
      dpp[i] += dpp[i + 1];
    }
  }
  for (i = 1; i < n; i++) {
    if (a[i] != a[i + 1]) {
      ans = max(ans, (min(dp[i], dpp[i + 1])) * 2);
    }
  }
  cout << ans << "\n";
  return 0;
}

n = int(input())
a = [int(s) for s in input().split()]
i = 0
j = 0
cur1 = 0
cur = 0
res = 0
b = a[0]
prev = 0
while j < n and a[j] == b:
    j+=1
    cur1 += 1
    cur += 1

while i < n and j < n:
    if b == 1:
        b = 2
    else:
        b = 1
    prev = cur
    cur = 0
    while j < n and a[j] == b:
        j += 1
        cur1 += 1
        cur += 1

    if 2*min(prev, cur) > res:
        res = 2*min(prev, cur)
    while i < n and a[i] == 3 - b:
        i += 1
        cur1 -= 1
print(res)


/*
 * Programmer  : HackOlympus
 * Date        : 29 Jun 2021
 * Purpose     : Wrong Subtraction
 */

import java.util.* ;
import java.lang.* ;

public class wrong_subtraction
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in) ;
        int n,k ;
        n = scan.nextInt() ;
        k = scan.nextInt() ;

        while (k-- > 0)
        {
            if (n % 10 != 0)
            {
                n-- ;
            }
            else
            {
                n = n/10 ;
            }
        }
        System.out.println(n) ;

    }

}

a, b = input().split(' ')
a=int(a)
for i in range(int(b)):
    if (a%10 != 0):
        a -= 1
    else:
        a /= 10
print(int(a))


import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n,k,t=LI()
  if t<=k:
    return t

  if n<t:
    if n+k<t:
      return 0
    else:
      return n+k-t

  return k

# main()
print(main())

#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int n, k, t;
  cin >> n >> k >> t;
  if (t <= k) {
    cout << t;
  } else {
    if (t <= n) {
      cout << k;
    } else if (t > n && t <= n + k) {
      cout << k - (t % n);
    } else {
      cout << "0";
    }
  }
}


import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.*;
import java.util.Map.Entry;

public class Main
{

    public static void main(String[] args) throws Exception
    {
        /*
        FileWriter writer = new FileWriter("input.txt");
        for(int i=1;i<=10000000;++i)
        {
            long a = Mother_Class.getRandomInteger(1, 100000000);
            long b = Mother_Class.getRandomInteger(1, 100000000);
            writer.write(a+" "+b+"\n");
        }
        writer.close();*/

        //long start = System.currentTimeMillis();
        Reader r = new Reader();
        Print p = new Print();
        int n = r.rint();

        if(n%7==0)
        {
            int v = (n/7)*2;
            p.println(v+" "+v);
        }
        else
        {
            int weeks = n/7;
            int days = n%7;
            int min = weeks*2;
            min += days==6 ? 1:0;
            int max = weeks*2;
            max += days>=1 ? 1 : 0;
            max += days>=2 ? 1: 0;
            p.println(min+" "+max);
        }
        //long end = System.currentTimeMillis();
        //p.println("Execution Time: "+(end-start)+"ms");
        p.close();
    }

}

class Pair
{
    public int first;
    public int second;

    public Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }

    @Override
    public String toString()
    {
        return "{"+first+", "+second+"}";
    }

}

class CustomCompare implements Comparator<Pair>
{

    @Override
    public int compare(Pair o1, Pair o2)
    {
        return o2.first - o1.first;
    }

}

class Triplet
{
    public int first;
    public int second;
    public int third;

    public Triplet(int first, int second, int third)
    {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    @Override
    public String toString()
    {
        return "{"+first+", "+second+", "+third+"}";
    }
}

class Reader
{
    final private int BUFFER_SIZE = 1 << 16;
    private DataInputStream din;
    private byte[] buffer;
    private int bufferPointer, bytesRead;

    public Reader()
    {
        din = new DataInputStream(System.in);
        buffer = new byte[BUFFER_SIZE];
        bufferPointer = bytesRead = 0;
    }

    public Reader(String file_name) throws IOException
    {
        din = new DataInputStream(new FileInputStream(file_name));
        buffer = new byte[BUFFER_SIZE];
        bufferPointer = bytesRead = 0;
    }

    public String rstren() throws IOException
    {
        byte[] buf = new byte[500000]; // line length
        int cnt = 0, c;
        while ((c = read()) != -1)
        {
            if (c=='\n' || c==13)
            {
                if (cnt != 0)
                {
                    break;
                }
                else
                {
                    continue;
                }
            }
            buf[cnt++] = (byte)c;
        }
        return new String(buf, 0, cnt);
    }

    public int rint() throws IOException
    {
        int ret = 0;
        byte c = read();
        while ((c <= 47 || c>=58) && c!=45)
        {
            c = read();
        }
        boolean neg = (c == '-');
        if (neg) { c = read(); }
        do
        {
            ret = ret * 10 + c - '0';
        }
        while ((c = read()) >= '0' && c <= '9');

        if (neg) { return -ret; }
        return ret;
    }

    public long rlong() throws IOException
    {
        long ret = 0;
        byte c = read();
        while ((c <= 47 || c>=58) && c!=45) { c = read(); }
        boolean neg = (c == '-');
        if (neg) { c = read(); }
        do
        {
            ret = ret * 10 + c - '0';
        }
        while ((c = read()) >= '0' && c <= '9');
        if (neg) { return -ret; }
        return ret;
    }

    public double rdouble() throws IOException
    {
        double ret = 0, div = 1;
        byte c = read();
        while ((c <= 47 || c>=58) && c!=45) { c = read(); }
        boolean neg = (c == '-');
        if (neg) { c = read(); }
        do
        {
            ret = ret * 10 + c - '0';
        }
        while ((c = read()) >= '0' && c <= '9');

        if (c == '.')
        {
            while ((c = read()) >= '0' && c <= '9')
            {
                ret += (c - '0') / (div *= 10);
            }
        }
        if (neg) { return -ret; }
        return ret;
    }

    private void fillBuffer() throws IOException
    {
        bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
        if (bytesRead == -1) { buffer[0] = -1; }
    }

    private byte read() throws IOException
    {
        if (bufferPointer == bytesRead) { fillBuffer(); }
        return buffer[bufferPointer++];
    }

    public void close() throws IOException
    {
        if (din == null) { return; }
        din.close();
    }
}

class Print
{
    private final BufferedWriter bw;
    public Print()
    {
        this.bw=new BufferedWriter(new OutputStreamWriter(System.out));
    }
    public void print(Object object)throws IOException
    {
        bw.append(""+object);
    }
    public void println(Object object)throws IOException
    {
        print(object);
        bw.append("\n");
    }
    public void close()throws IOException
    {
        bw.close();
    }
}


import math

def numberOfMultiples(n, z):
    return n // z

if __name__ == "__main__":
    n, p = map(int, input().split())
    f = [0] * n
    g = [0] * n
    for i in range(n):
        l, r = map(int, input().split())
        #print((r - l + 1) - len([i for i in range(l, r + 1) if i % p == 0]))
        f[i] = (r - l + 1) - (numberOfMultiples(r, p) - numberOfMultiples(l - 1, p))
        g[i] = (r - l + 1)

    def compute_frac_gain(index):
        return 1 - ((f[index - 1] * f[index]) / (g[index - 1] * g[index]))

    frac_gains = 0
    for i in range(1, n):
        frac_gain = compute_frac_gain(i)
        frac_gains += frac_gain
    frac_gain = 1 - ((f[-1] * f[0]) / (g[-1] * g[0]))
    frac_gains += frac_gain
    print(frac_gains * 2000)

#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 10;
const long long MOD = 1e9 + 7;
int N, M, K, Q;
pair<long long, long long> A[MAX];
double prob[MAX];
int main() {
  int i, j;
  long long P;
  scanf("%d%lld", &N, &P);
  for (i = 0; i < N; ++i) {
    scanf("%lld %lld", &A[i].first, &A[i].second);
  }
  for (i = 0; i < N; ++i) {
    long long y = A[i].second / P;
    long long x = (A[i].first + P - 1) / P;
    prob[i] = (double)(y - x + 1) / (double)(A[i].second - A[i].first + 1);
    prob[i] = 1.0 - prob[i];
  }
  double exp = 0.0;
  for (i = 0; i < N; ++i) {
    double tmp = prob[i] * prob[(i + 1) % N];
    exp += 2000.0 * (1.0 - tmp);
  }
  printf("%.6lf", exp);
}


#include <bits/stdc++.h>
using namespace std;
int N, y, K;
long long P;
int A[2 * 100005];
int pref[2 * 100005], suf[2 * 100005];
int main() {
  cin >> N >> K >> P;
  for (int i = 0; i < N; ++i) {
    cin >> A[i];
  }
  pref[0] = A[0];
  suf[N] = A[N];
  for (int i = 1; i < N; ++i) pref[i] = (A[i] | pref[i - 1]);
  for (int i = N - 1; i >= 0; --i) suf[i] = (A[i] | suf[i + 1]);
  long long ormax = -1;
  for (int i = 0; i < N; ++i) {
    long long x = A[i];
    for (int j = 0; j < K; ++j) x = P * x;
    long long orr;
    if (i == 0)
      orr = x | suf[i + 1];
    else
      orr = x | pref[i - 1] | suf[i + 1];
    ormax = max(orr, ormax);
  }
  cout << ormax;
  return 0;
}

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String line1 = in.nextLine();
        String line2 = in.nextLine();
        String[] nkx = line1.split(" ");
        int n = Integer.parseInt(nkx[0]);
        int k = Integer.parseInt(nkx[1]);
        int x = Integer.parseInt(nkx[2]);
        String[] ai = line2.split(" ");
        long[] arr = new long[n];
        long max = -1;
        int index = 0;
        for (String s : ai)
        {
            long a = Long.parseLong(s);
            arr[index] = a;
            index++;
        }

        long[] leftarr = new long[n];
        leftarr[0] = 0;
        for (int i = 1; i < n; i++)
        {
            leftarr[i] = leftarr[i - 1] | arr[i - 1];
        }

        long[] rightarr = new long[n];
        rightarr[n - 1] = 0;
        for (int i = n - 2; i >= 0; i--)
        {
            rightarr[i] = rightarr[i + 1] | arr[i + 1];
        }
        long result = -1;
        for (int i = 0; i < n; i++)
        {
            long temp = arr[i];
            for(int j = 1; j <= k ; j++)
            {
                temp*=x;
            }
            long t = leftarr[i]|rightarr[i]|temp;
            if(t > result)
            {
                result = t;
            }
        }

        System.out.println(result);
    }
}


n,x=int(input()),list(map(int, input().split(" ")))
tmp=sorted(x,reverse=True)
for i in x:
    print(tmp.index(i)+1)

#include <bits/stdc++.h>
using namespace std;
int a[2001] = {0}, b[2001];
int main() {
  int n;
  cin >> n;
  for (int i = 1, j; i <= n; i++) {
    cin >> j;
    a[j]++;
    b[i] = j;
  }
  int ranking = 1, temp;
  for (int i = 2000; i >= 1; i--) {
    if (a[i] != 0) {
      temp = a[i];
      a[i] = ranking;
      ranking += temp;
    }
  }
  for (int i = 1; i <= n; i++) {
    if (i == n) {
      cout << a[b[i]];
      break;
    }
    cout << a[b[i]] << " ";
  }
  return 0;
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class D {

    static int n=1000000;

    static void solve(int[] x) {
        boolean[]
                bx=new boolean[n],
                by=new boolean[n];
        for (int i=0; i<x.length; i++) {
            bx[x[i]]=true;
        }

        int free_cnt=0, pending_cnt=0, cnt=0;
        int[] free=new int[n];

        for (int i=0; i<n>>1; i++) {
            if(bx[i]||bx[n-1-i]) {
                if(bx[i]&&bx[n-1-i]) {
                    if(free_cnt>0) {
                        by[free[free_cnt-1]]=by[n-1-free[free_cnt-1]]=true;
                        cnt+=2;
                        free_cnt--;
                    } else {
                        pending_cnt++;
                    }
                } else {
                    if(bx[i]) {
                        by[n-1-i]=true;
                        cnt++;
                    } else {
                        by[i]=true;
                        cnt++;
                    }
                }
            } else {
                if(pending_cnt>0) {
                    by[i]=by[n-1-i]=true;
                    cnt+=2;
                    pending_cnt--;
                } else {
                    free[free_cnt++]=i;
                }
            }
        }

        sb.setLength(0);
        sb.append(cnt+"\n");
        for (int i=0; i<n; i++) {
            if(by[i]) {
                sb.append((i+1)+" ");
            }
        }
        sb.setLength(sb.length()-1);

        System.out.println(sb.toString());
    }

    static StringBuilder sb=new StringBuilder();
    static void parse(String l, int[] here) {
        sb.setLength(0);
        int len=l.length(), j=0;
        for (int i=0; i<len; i++) {
            char c=l.charAt(i);
            if(c==' ') {
                here[j++]=Integer.parseInt(sb.toString())-1;
                sb.setLength(0);
            } else {
                sb.append(c);
            }
        }
        if(sb.length()>0) {
            here[j++]=Integer.parseInt(sb.toString())-1;
        }
    }

    static void run_stream(InputStream ins) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());
        int[] x=new int[n];
        parse(br.readLine(), x);
        solve(x);
    }

    public static void main(String[] args) throws IOException {
        run_stream(System.in);
//        int[] in=new int[] {1, 2, 3, 100, 500000, 500001, 999901, 999997, 999999};
//        int[] out=new int[] {4, 5, 99, 499999, 500002, 999902, 999996, 999998, 1000000};
//
//        int sum1=0, sum2=0;
//        for (int i=0; i<in.length; i++) {
//            sum1+=in[i]-1;
//        }
//        for (int i=0; i<out.length; i++) {
//            sum2+=n-out[i];
//        }
//
//        System.out.println(sum1+" "+sum2);
    }

}


import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.TreeSet;

import java.math.BigInteger;

public class Main {

	public static boolean debug = false;

	public static void main(String[] args) {
		Reader in = null;
		Writer out = null;

		if(debug) {
			in = new Reader(args[0]);
			out = new Writer(args[1]);
		} else {
			in = new Reader();
			out = new Writer();
		}

		int n = in.nextInt();
		int k = in.nextInt();
		int[] nums = new int[n+1];
		if(fillNums(nums, n, k)) {
			for(int i=1; i<=n; i++)
				out.print(nums[i]+" ");
		} else out.print(-1);
		/*
		Vector<Integer> nums = new Vector<Integer>();
		boolean[] used = new boolean[n+1];
		for(int i=1; i<=k; i++) {
			if(((1<<i)&((1<<i)-1))==0) {
				if((1<<i)>n) {
					nums.clear();
					break;
				}
				nums.add(1<<i);
				used[nums.lastElement()] = true;
			} else {
				used[i] = true;
				nums.add(i);
			}
		}
		int tempC = 0;
		int tempNum = 1;
		while(k<n) {
			//out.println(nums);
			while(used[tempNum+tempC]) tempC++;
			nums.add(tempNum+tempC);
			if(nums.lastElement()>n) {
				nums.clear();
				break;
			}
			tempNum++;
			k++;
		}

		if(nums.size()==0) out.print(-1);
		else
			for(Integer num: nums)
				out.print(num+" ");*/
		out.close();
	}

	static boolean fillNums(int[] nums, int n, int k) {
		if(n==k) return false;
		nums[1] = 1;
		for(int i=2; i<=k+1; i++)
			nums[i] = i;
		for(int i=k+2; i<=n; i+=2) {
			//System.out.println(i+" "+Arrays.toString(nums));
			if(i<n) {
				nums[i] = i+1;
				nums[i+1] = i;
			} else {
				/*for(int j=k+2; j<n; j++) {
					System.out.println(i+" "+j+" "+nums[j]);
					if(gcd(i, j)==1 && gcd(i, nums[j])==1) {
						nums[i] = nums[j];
						nums[j] = i;
						return true;
					}
				}*/
				nums[i] = 1;
				nums[1] = i;
				return true;//false;
			}
		}
		return true;
	}

	static int gcd(int a, int b) {
		if(b==0) return a;
		return gcd(b, a%b);
	}
}

class Writer {

	private BufferedWriter output;

	public Writer() {
		output = new BufferedWriter(new OutputStreamWriter(System.out));
	}

	public Writer(String s) {
		try {
			output = new BufferedWriter(new FileWriter(s));
		} catch(Exception ex) { ex.printStackTrace(); System.exit(0);}
	}

	public void println() {
		try {
			output.append("\n");
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}

	public void print(Object o) {
		try {
			output.append(o.toString());
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}

	public void println(Object o) {
		try {
			output.append(o.toString()+"\n");
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}

	public void printf(String format, Object... args) {
		try {
			output.append(String.format(format, args));
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}

	public void printfln(String format, Object... args) {
		try {
			output.append(String.format(format, args)+"\n");
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}

	public void flush() {
		try {
			output.flush();
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}

	public void close() {
		try {
			output.close();
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}
}

class Reader {
	private BufferedReader input;
	private StringTokenizer line = new StringTokenizer("");

	public Reader() {
		input = new BufferedReader(new InputStreamReader(System.in));
	}

	public Reader(String s) {
		try {
			input = new BufferedReader(new FileReader(s));
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}

	public void fill() {
		try {
			if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine());
		} catch(IOException io) { io.printStackTrace(); System.exit(0);}
	}

	public double nextDouble() {
		fill();
		return Double.parseDouble(line.nextToken());
	}

	public String nextWord() {
		fill();
		return line.nextToken();
	}

	public int nextInt() {
		fill();
		return Integer.parseInt(line.nextToken());
	}

	public long nextLong() {
		fill();
		return Long.parseLong(line.nextToken());
	}

	public double readDouble() {
		double d = 0;
		try {
			d = Double.parseDouble(input.readLine());
		} catch(IOException io) {io.printStackTrace(); System.exit(0);}
		return d;
	}

	public int readInt() {
		int i = 0;
		try {
			i = Integer.parseInt(input.readLine());
		} catch(IOException io) {io.printStackTrace(); System.exit(0);}
		return i;
	}

	public int[] readInts(int n) {
		int[] a = new int[n];
		for(int i=0; i<n; i++)
			a[i] = nextInt();
		return a;
	}

	public void fillInts(int[] a) {
		for(int i=0; i<a.length; i++)
			a[i] = nextInt();
	}

	public long readLong() {
		long l = 0;
		try {
			l = Long.parseLong(input.readLine());
		} catch(IOException io) {io.printStackTrace(); System.exit(0);}
		return l;
	}

	public String readLine() {
		String s = "";
		try {
			s = input.readLine();
		} catch(IOException io) {io.printStackTrace(); System.exit(0);}
		return s;
	}
}

#include <bits/stdc++.h>
using namespace std;
template <typename T>
void SOUT(T what) {
  cout << what << endl;
}
int main() {
  int n, k;
  scanf("%d %d", &n, &k);
  if (k >= n) {
    cout << "-1\n";
    return 0;
  }
  int i = n;
  vector<int> out;
  for (; i >= 1; i--) {
    if (k > 0) {
      out.push_back(i);
      k--;
    } else
      break;
  }
  for (; i >= 2; i -= 2) {
    out.push_back(i - 1);
    out.push_back(i);
  }
  if (i == 1) out.push_back(1);
  reverse((out).begin(), (out).end());
  for (int i = 0; i < (out.size()); ++i) cout << out[i] << " ";
  cout << endl;
}


def f(x, p):
    q = []
    while x:
        q.append(x)
        x = p[x]
    return q
from collections import defaultdict
n, k = map(int, input().split())
t = list(map(int, input().split()))
p = [0] * (n + 1)
for i, j in enumerate(t, 1):
    p[j] = i
p = [f(i, p) for i, j in enumerate(t, 1) if j == 0]
s = defaultdict(int)
for i in p:
    if k in i: t = {i.index(k) + 1}
    else: s[len(i)] += 1
s = [list(range(i, k * i + 1, i)) for i, k in s.items()]
for q in s:
    t |= {x + y for x in q for y in t}
print('\n'.join(map(str, sorted(list(t)))))

#include <bits/stdc++.h>
using namespace std;
int f[1024], w[1024], front[1024], cntw, n, x;
bool g[1024];
int getfa(int x) {
  if (!f[x]) return x;
  f[x] = getfa(f[x]);
  return f[x];
}
int main() {
  cin >> n >> x;
  for (int i = 1; i <= n; ++i) {
    int y;
    scanf("%d", &y);
    front[i] = y;
    if (!y) continue;
    f[i] = getfa(y);
  }
  int fa(getfa(x)), cntx(1);
  int y(front[x]);
  while (y) {
    ++cntx;
    y = front[y];
  }
  for (int i = 1; i <= n; ++i) {
    if (i == fa || f[i]) continue;
    ++cntw;
    for (int j = 1; j <= n; ++j)
      if (getfa(j) == getfa(i)) ++w[cntw];
  }
  g[0] = true;
  for (int i = 1; i <= cntw; ++i)
    for (int j = n; j >= w[i]; --j) g[j] |= g[j - w[i]];
  for (int i = 0; i <= n; ++i)
    if (g[i]) printf("%d\n", i + cntx);
  return 0;
}


n = int(input())
segments = []
minl = 10**9
maxr = 1

for i in range(n):
    a, b = map(int, input().split())
    segments.append((a, b))
    if a<minl:
        minl = a
    if b>maxr:
        maxr = b

if (minl, maxr) in segments:
    print(segments.index((minl, maxr))+1)
else:
    print(-1)

#include <bits/stdc++.h>
using namespace std;
int n, l[100005], r[100005];
int main() {
  scanf("%d", &n);
  int x = 1 << 30, y = -1 << 30;
  for (int i = 0; i < n; i++) {
    scanf("%d %d", &l[i], &r[i]);
    x = min(x, l[i]);
    y = max(y, r[i]);
  }
  int ind = -1;
  for (int i = 0; i < n; i++) {
    if (l[i] <= x && y <= r[i]) ind = i + 1;
  }
  printf("%d\n", ind);
  return 0;
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;

public class VKRound3A {
    static BufferedReader br = new BufferedReader(new InputStreamReader(
            System.in));
    static StringTokenizer st = new StringTokenizer("");
    static int nextInt() throws Exception {
        return Integer.parseInt(next());
    }
    static String next() throws Exception {
        while (true) {
            if (st.hasMoreTokens()) {
                return st.nextToken();
            }
            String s = br.readLine();
            if (s == null) {
                return null;
            }
            st = new StringTokenizer(s);
        }
    }
    static int n, m;
    static int state [];
    static ArrayList<Integer> graph1 [];
    static ArrayList<Integer> graph2 [];
    static boolean vis1 [], vis2 [];
    public static void dfs_source(int idx){
        vis1[idx] = true;
        for(Integer nxt : graph1[idx]){
            if(!vis1[nxt] && state[nxt] != 1)
                dfs_source(nxt);
        }
    }

    public static void dfs_dest(int idx){
        vis2[idx] = true;
        if(state[idx] == 1)
            return;
        for(Integer nxt : graph2[idx]){
            if(!vis2[nxt])
                dfs_dest(nxt);
        }
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args)throws Exception {
        n = nextInt();
        m = nextInt();
        state = new int [n + 1];
        vis1 = new boolean [n + 1];
        vis2 = new boolean [n + 1];
        graph1 = new ArrayList [n + 1];
        graph2 = new ArrayList [n + 1];
        for(int i = 0 ; i < n + 1 ; ++i)
            graph1[i] = new ArrayList<Integer>();
        for(int i = 0 ; i < n + 1 ; ++i)
            graph2[i] = new ArrayList<Integer>();
        for(int i = 1 ; i < n + 1 ; ++i)
            state[i] = nextInt();
        for(int i = 0 ; i < m ; ++i){
            int a = nextInt();
            int b = nextInt();
            graph1[a].add(b);
            graph2[b].add(a);
        }
        for(int i = 1 ; i < n + 1 ; ++i){
            if(state[i] == 1 && !vis1[i])
                dfs_source(i);
        }
        for(int i = 1 ; i < n + 1 ; ++i){
            if(state[i] == 2 && !vis2[i])
                dfs_dest(i);
        }
        for(int i = 1 ; i < n + 1 ; ++i){
            if(vis1[i] && vis2[i])
                System.out.println(1);
            else
                System.out.println(0);
        }
    }
}

#include <bits/stdc++.h>
using namespace std;
const long long int M = 5e5 + 5, LG = 17, inf = 1e18;
int n, m;
long long int f[M];
vector<long long int> g[M], h[M];
long long int c2[M];
long long int c1[M];
void dfs1(long long int x) {
  if (c1[x] == 1) return;
  c1[x] = 1;
  for (long long int y : g[x]) {
    dfs1(y);
  }
}
void dfs2(long long int x) {
  if (c2[x] == 1) return;
  c2[x] = 1;
  if (f[x] == 1) return;
  for (long long int y : h[x]) {
    dfs2(y);
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> f[i];
  for (int i = 0; i < m; i++) {
    long long int a, b;
    cin >> a >> b;
    a--;
    b--;
    g[a].push_back(b);
    h[b].push_back(a);
  }
  for (int i = 0; i < n; i++) {
    if (f[i] == 1) dfs1(i);
  }
  for (int i = 0; i < n; i++) {
    if (f[i] == 2) dfs2(i);
  }
  for (int i = 0; i < n; i++) {
    cout << (c1[i] && c2[i]) << '\n';
  }
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  vector<vector<int> > a(m + n + 1), b(m + n + 1);
  int c;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      scanf("%d", &c);
      a[i + j].push_back(c);
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      scanf("%d", &c);
      b[i + j].push_back(c);
    }
  }
  bool isgood = true;
  for (int i = 0; i < m + n + 1; i++) {
    sort(a[i].begin(), a[i].end());
    sort(b[i].begin(), b[i].end());
    if (a[i] != b[i]) {
      isgood = false;
      break;
    }
  }
  if (isgood) {
    printf("YES\n");
  } else {
    printf("NO\n");
  }
  return 0;
}

import java.util.*;
import java.io.*;

public class Nastya_Is_Transporting_Matrix {

	static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FastReader t = new FastReader();
		PrintWriter o = new PrintWriter(System.out);
		int m = t.nextInt();
		int n = t.nextInt();
		int[][] a = new int[m][n];
		int[][] b = new int[m][n];
		ArrayList<Integer>[] l1 = new ArrayList[m + n - 1];
		ArrayList<Integer>[] l2 = new ArrayList[m + n - 1];
		boolean flag = true;

		for (int i = 0; i < m + n - 1; ++i) {
			l1[i] = new ArrayList<>();
			l2[i] = new ArrayList<>();
		}

		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				a[i][j] = t.nextInt();
				l1[i + j].add(a[i][j]);
			}
		}

		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				b[i][j] = t.nextInt();
				l2[i + j].add(b[i][j]);
			}
		}

		for (int i = 0; i < m + n - 1; ++i) {
			Collections.sort(l1[i]);
			Collections.sort(l2[i]);

			for (int j = 0; j < l1[i].size(); ++j)
				if (l1[i].get(j).intValue() != l2[i].get(j).intValue()) {
					flag = false;
					break;
				}
		}

		if (flag)
			o.println("YES");
		else
			o.println("NO");

		o.flush();
		o.close();
	}
}


import java.util.*;
import java.io.*;

public class Solution{
    public static class pair{
        int x;
        int y;
    }
    public static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
        public String next() {
			while (!st.hasMoreElements())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
		public int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) {
				a[i]=nextInt();
			}
			return a;
		}public double nextDouble() {
			return Double.parseDouble(next());
		}
    }

    public static void main(String[] args) throws IOException{
        FastScanner fs=new FastScanner();
// 		int t=fs.nextInt();
		PrintWriter out=new PrintWriter(System.out);
        // while(t-->0){
            int n=fs.nextInt();
            int k=fs.nextInt();
            int[] arr=fs.readArray(n);
            String s=fs.next();
            int i=0;
            long sum=0;
            while(i<n){
                char ch=s.charAt(i);
                int g=i;
                while(i<n&&s.charAt(i)==ch){
                    i++;
                }
                ArrayList<Integer> l=new ArrayList<>();
                for(int j=g;j<i;j++){
                    l.add(arr[j]);
                }
                Collections.sort(l,Collections.reverseOrder());
                for(int j=0;j<Math.min(l.size(),k);j++){
                    sum+=l.get(j);
                }
            }
            System.out.println(sum);
        // }
        out.close();
    }
    public static long calc(long n,long b){
        if(b==1){
            return Long.MAX_VALUE;
        }
        long val=(long)Math.ceil(n/b);
        long p=2;
        long ans=val;
        while(val!=0){
            val=(long)Math.ceil((long)n/(long)Math.pow(b,p));
            p++;
            ans+=val;
        }
        return ans;
    }
    public static long quala(long b){
        long val=(long)Math.ceil(Math.pow(1+(8*b),0.5));
        if(val%2==0){
            long va=(long)(2+val)/(long)2;
            return va;
        }else{
            long va=(long)(1+val)/(long)2;
            return va;
        }
    }
    public static String find(int a,int b){
        if(a==3){
            if(b==1){
                return "abb";
            }else if(b==2){
                return "bab";
            }else{
                return "bba";
            }
        }
        int v=((a-1)*(a-2))/2;
        if(b<=v){
            String s=find(a-1,b);
            StringBuffer sb=new StringBuffer(s);
            int diff=a-s.length();
            while(diff-->0){
                sb.insert(0,"a");
            }
            return sb.toString();
        }else{
            int diff=b-v;
            StringBuffer sb=new StringBuffer();
            sb.append("b");
            for(int i=0;i<a-diff-1;i++){
                sb.append("a");
            }
            sb.append("b");
            for(int i=0;i<diff-1;i++){
                sb.append("a");
            }
            return sb.toString();
        }
        // return new String("a"+s);
    }
    public static long z(long val){
        long p=1;
        while(val!=0){
            long rem=val%10;
            p*=rem;
            val=val/10;
        }
        return p;
    }
    public static int[] soe(int n){
        int[] arr=new int[n];
        arr[0]=0;
        for(int i=1;i<n;i++){
            if(arr[i]==0){
                for(int j=(2*(i+1))-1;j<n;j=j+i+1){
                    arr[j]=1;
                }
            }
        }
        return arr;
    }
    public static int[][] floydWarshall(int graph[][],int V){
        int dist[][] = new int[V][V];
        int i, j, k;
        for (i = 0; i < V; i++){
            for (j = 0; j < V; j++){
                dist[i][j] = graph[i][j];
            }
        }
        for (k = 0; k < V; k++) {
            for (i = 0; i < V; i++){
                for (j = 0; j < V; j++){
                    if (dist[i][k] + dist[k][j] < dist[i][j]){
                        dist[i][j] = dist[i][k] + dist[k][j];
                    }
                }
            }
        }
        return dist;
    }
    public static class Comp implements Comparator<pair>{
        public int compare(pair a,pair b){
            if(a.x!=b.x){
                return b.x-a.x;
            }else{
                return a.y-b.y;
            }
        }
    }
    public static long gcd(long a,long b){
        if (b == 0)
        return a;
        return gcd(b, a % b);
    }
    public static int lcm(int a,int b){
        int x=Math.max(a,b);
        int y=Math.min(a,b);
        long ans=x;
        while(ans%y!=0){
            ans+=x;
        }
        if(ans>Integer.MAX_VALUE){
            return -1;
        }
        return (int)ans;
    }
    public static long fact(int n){
        long ans=1;
        for(int i=1;i<=n;i++){
            ans*=i;
        }
        return ans;
    }
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  vector<long long> tmp;
  int n, k;
  cin >> n >> k;
  long long mas[n], ans = 0;
  for (int i = 0; i < (int)(n); ++i) cin >> mas[i];
  vector<pair<long long, long long> > ext;
  string s;
  cin >> s;
  for (int i = 0; i < (int)(s.length()); ++i) {
    ext.push_back(make_pair(mas[i], s[i]));
  }
  for (long long i = 0; i < s.length(); i++) {
    long long start = i, loop = k;
    while (s[i] == s[i + 1] && i < s.length() - 1) i++;
    for (long long j = start; j <= i; j++) {
      tmp.push_back(ext[j].first);
    }
    sort(tmp.begin(), tmp.end());
    for (long long i = tmp.size() - 1; i >= 0; i--) {
      ans += tmp[i];
      loop--;
      if (loop <= 0) break;
    }
    tmp.clear();
  }
  cout << ans;
  return 0;
}


prime = []
def SieveOfEratosthenes():
    n = 6000
    global prime
    prime = [True for q in range(n + 1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
SieveOfEratosthenes()
I = input
n=int(I())
a=list(map(int,I().split()))
p=0
i=n*2+1
while True:
    if prime[i]==True:
        p=i
        break
    i+=1
ans=['2 '+str(n)+' 1','1 '+str(n)+' '+str(p)]
for i in range(n-1):
    ans.append('2 '+str(i+1)+' '+str(p-i))
print(n+1)
for i in ans:
    print(i)


import java.util.*;
import java.io.*;
import java.math.BigInteger;

public class F {
	FastScanner in;
	PrintWriter out;
	boolean systemIO = true;

	public int dfs(int v, int father) {
		int d = 0;
		if (to[v].length == 1) {
			return 0;
		}
		int n = 0;
		for (int i : to[v]) {
			if (i != father) {
				int x = dfs(i, v) + 1;
				if (x <= 0) {
					continue;
				}
				if (x + d > k) {
					ans++;
					d = Math.min(d, x);
				} else {
					d = Math.max(d, x);
					n++;
				}
			}
		}
		if (n == 0) {
			return -1;
		}
		return d;
	}

	public class Info {
		int v;
		int father;
		int d;
		int n;
		int i;

		public Info(int v, int father, int d, int n, int i) {
			this.v = v;
			this.father = father;
			this.d = d;
			this.n = n;
			this.i = i;
		}

	}

	int[][] to;
	int ans = 0;
	int k;

	public void solve() {
		int n = in.nextInt();
		k = in.nextInt();
		to = new int[n][];
		int[] x = new int[n - 1];
		int[] y = new int[n - 1];
		int[] sz = new int[n];
		for (int i = 0; i < to.length - 1; i++) {
			x[i] = in.nextInt() - 1;
			y[i] = in.nextInt() - 1;
			sz[x[i]]++;
			sz[y[i]]++;
		}
		for (int i = 0; i < to.length; i++) {
			to[i] = new int[sz[i]];
		}
		int[] free = new int[n];
		for (int i = 0; i < x.length; i++) {
			to[x[i]][free[x[i]]] = y[i];
			free[x[i]]++;
			to[y[i]][free[y[i]]] = x[i];
			free[y[i]]++;
		}
		int root = -1;
		for (int i = 0; i < to.length; i++) {
			if (to[i].length > 1) {
				root = i;
				break;
			}
		}
//		if (dfs(root, -1) >= 0) {
//			ans++;
//		}
//		int[] father = new int[n];
//		int v = root;
//		father[v] = -1;
		Stack<Info> stack = new Stack<>();
		int answer = 0;
		stack.add(new Info(root, -1, 0, 0, -1));
		w :
		while (!stack.isEmpty()) {
			Info inf = stack.pop();
//			System.out.println(answer + " " + inf.v + " " + inf.father + " " + inf.d + " " + inf.n + " " + inf.i + " " + ans + " " + stack.size());
			if (inf.i < 0) {
				if (to[inf.v].length == 1) {
					answer = 0;
					continue;
				}
				for (int i = 0; i < to[inf.v].length; i++) {
					if (to[inf.v][i] != inf.father) {
						stack.add(new Info(inf.v, inf.father, inf.d, inf.n, i));
						stack.add(new Info(to[inf.v][i], inf.v, 0, 0, -1));
						continue w;
					}
				}
			} else {
				int q = answer + 1;
				if (q > 0) {
					if (q + inf.d > k) {
						ans++;
						inf.d = Math.min(inf.d, q);
					} else {
						inf.d = Math.max(inf.d, q);
						inf.n++;
					}
				}
				for (int i = inf.i + 1; i < to[inf.v].length; i++) {
					if (to[inf.v][i] != inf.father) {
						stack.add(new Info(inf.v, inf.father, inf.d, inf.n, i));
						stack.add(new Info(to[inf.v][i], inf.v, 0, 0, -1));
						continue w;
					}
				}
				if (inf.n == 0) {
					answer = -1;
				} else {
					answer = inf.d;
				}
			}
		}
		if (answer >= 0) {
			ans++;
		}
		out.println(ans);
	}

	public void run() {
		try {
			if (systemIO) {
				in = new FastScanner(System.in);
				out = new PrintWriter(System.out);
			} else {
				in = new FastScanner(new File("input.txt"));
				out = new PrintWriter(new File("output.txt"));
			}
			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		FastScanner(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		FastScanner(InputStream f) {
			br = new BufferedReader(new InputStreamReader(f));
		}

		String nextLine() {
			try {
				return br.readLine();
			} catch (IOException e) {
				return null;
			}
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

		double nextDouble() {
			return Double.parseDouble(next());
		}

	}

	// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
	public static void main(String[] arg) {
		new F().run();
	}
}

#include <bits/stdc++.h>
#pragma GCC optimize("Ofast,unroll-loops")
using namespace std;
const int N = 1e6 + 2;
vector<int> adj[N];
int k, ans = 1;
int dfs(int u, int pai = -1) {
  bool leaf = true;
  vector<int> deps;
  for (int v : adj[u]) {
    if (v == pai) continue;
    int depth = dfs(v, u) + 1;
    deps.push_back(depth);
    leaf = false;
  }
  if (leaf) return 0;
  sort(deps.begin(), deps.end());
  while (int(deps.size()) > 1) {
    int a = deps[int(deps.size()) - 1], b = deps[int(deps.size()) - 2];
    if (a + b <= k) return a;
    ans++;
    deps.pop_back();
  }
  return deps[0];
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n >> k;
  for (int i = 0; i < n - 1; ++i) {
    int a, b;
    cin >> a >> b;
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  int root;
  for (int i = 1; i <= n; ++i) {
    if (int(adj[i].size()) != 1) root = i;
  }
  dfs(root);
  cout << ans << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int n, a[111];
bool u[111];
bool pr(int x) {
  int y = -1, z = -1;
  for (int i = x; i < n; ++i)
    if (!u[i]) {
      y = a[i];
      break;
    }
  for (int i = x; i >= 0; --i)
    if (!u[i]) {
      z = a[i];
      break;
    }
  if (y < 0 || z < 0)
    return 0;
  else
    return abs(y - z) > 1;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
    if (i > 0)
      if (abs(a[i] - a[i - 1]) > 1) return cout << "NO", 0;
  }
  for (int i = 0; i < n; ++i) {
    int mx = 0, mi;
    for (int j = 0; j < n; ++j)
      if (a[j] > mx && !u[j]) {
        mx = a[j];
        mi = j;
      }
    u[mi] = 1;
    if (pr(mi)) return cout << "NO", 0;
  }
  cout << "YES";
  return 0;
}

n = int(input())
l = [int(x) for x in input().split()]

while len(l) > 1:

    if len([i for i in range(len(l)-1) if abs(l[i] - l[i+1]) > 1 ])>0:
        print ('NO')
        exit(0)

    l.remove(max(l))

print('YES')


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author ChamathK
 */
public class Main {

  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    FastScanner in = new FastScanner(inputStream);
    FastPrinter out = new FastPrinter(outputStream);
    TaskA solver = new TaskA();
    solver.solve(1, in, out);
    out.close();
  }

  static class TaskA {

    public void solve(int testNumber, FastScanner in, FastPrinter out) {
      int n = in.nextInt();
//        int[] primes = MathUtils.genPrimes(40000);
//
//        while (n-->0){
//            int a = in.nextInt(), b = in.nextInt();
//            int pi = 0;
//            int good = 1;
//            while (primes[pi]<= Math.sqrt(Math.max(a,b)+1)){
//                if (a%primes[pi]==0 || b%primes[pi]==0){
//                    int x = 0, y =0;
//                    int p = primes[pi];
//                    while (a%p==0){
//                        x++; a/=p;
//                    }
//                    while (b%p==0){
//                        y++;
//                        b/=p;
//                    }
//
//                    if (2*x < y || 2*y<x || (x+y)%3!=0){
//                        good = 0;
//                        break;
//                    }
//
//
//                }
//
//                pi++;
//
//            }
//
//            if (a!=1 || b!=1){
//                good = 0;
//            }
//
//            if (good == 1) {
//                out.println("Yes");
//            } else {
//                out.println("No");
//            }
//
//        }
      while (n-- > 0) {
        long a = in.nextLong(), b = in.nextLong();

        long low = 0, high = 1000001;
        long xx = a * b;

        while (high - low > 1) {
          long mid = (high + low) / 2;

          if (mid * mid * mid >= xx) {
            high = mid;
          } else {
            low = mid;
          }

        }

        if (high * high * high == xx && a % high == 0 && b % high == 0) {
          out.println("Yes");
        } else {
          out.println("No");
        }

      }
    }

  }

  static class FastScanner extends BufferedReader {

    public FastScanner(InputStream is) {
      super(new InputStreamReader(is));
    }

    public int read() {
      try {
        int ret = super.read();
//            if (isEOF && ret < 0) {
//                throw new InputMismatchException();
//            }
//            isEOF = ret == -1;
        return ret;
      } catch (IOException e) {
        throw new InputMismatchException();
      }
    }

    public String next() {
      StringBuilder sb = new StringBuilder();
      int c = read();
      while (isWhiteSpace(c)) {
        c = read();
      }
      if (c < 0) {
        return null;
      }
      while (c >= 0 && !isWhiteSpace(c)) {
        sb.appendCodePoint(c);
        c = read();
      }
      return sb.toString();
    }

    static boolean isWhiteSpace(int c) {
      return c >= 0 && c <= 32;
    }

    public int nextInt() {
      int c = read();
      while (isWhiteSpace(c)) {
        c = read();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = read();
      }
      int ret = 0;
      while (c >= 0 && !isWhiteSpace(c)) {
        if (c < '0' || c > '9') {
          throw new NumberFormatException("digit expected " + (char) c
              + " found");
        }
        ret = ret * 10 + c - '0';
        c = read();
      }
      return ret * sgn;
    }

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

    public String readLine() {
      try {
        return super.readLine();
      } catch (IOException e) {
        return null;
      }
    }

  }

  static class FastPrinter extends PrintWriter {

    public FastPrinter(OutputStream out) {
      super(out);
    }

    public FastPrinter(Writer out) {
      super(out);
    }

  }
}

#include <bits/stdc++.h>
using namespace std;
long long r;
bool is_perfect_cube(long long n) {
  r = (long long)round(cbrt(n));
  if (r * r * r == n) return true;
  return false;
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    int a, b;
    scanf("%d %d", &a, &b);
    if (is_perfect_cube((long long)a * b)) {
      if (((long long)a + b) % r == 0)
        printf("Yes\n");
      else
        printf("No\n");
    } else
      printf("No\n");
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  long long a, b, c, d;
  cin >> a >> b >> c >> d;
  for (int i = 0; i <= 1e6; i++) {
    long long x = (i * c) + d - b;
    if (x < 0) continue;
    if (x % a == 0) {
      cout << x + b;
      return 0;
    }
  }
  cout << "-1";
}

import math
R=lambda:list(map(int,input().split()))
a,b=R()
c,d=R()
if abs(b-d)%math.gcd(a,c)!=0:
  print(-1)
  exit(0)
while b != d:
  if b<d: b+=a
  else: d+=c
print(b)


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Main {
	static Scanner in;
	static int n, xr = 0, yr = 0, xb = 0, yb = 0;
	static char s[], sr[], sb[];
	public static void main(String[] args) throws FileNotFoundException {
//		in = new Scanner(new File("input.txt"));
		in = new Scanner(System.in);
		n = in.nextInt();
		sr = new char[n];
		sb = new char[n];
		for(int i = 0;i < n;i++){
			if(i%2 == 0){
				sr[i] = 'r';
				sb[i] = 'b';
			}else{
				sr[i] = 'b';
				sb[i] = 'r';
			}
		}
		s = in.next().toCharArray();
		for(int i = 0;i < n;i++){
			if(s[i] == 'r' && sr[i] == 'b') xr++;
			else if(s[i] == 'b' && sr[i] == 'r') yr++;
			if(s[i] == 'r' && sb[i] == 'b') xb++;
			if(s[i] == 'b' && sb[i] == 'r') yb++;
		}
		System.out.println(Math.min(Math.max(xr, yr), Math.max(xb, yb)));
	}
}


#include <bits/stdc++.h>
using namespace std;
const int NMAX = 2e5 + 5;
int n, answer, root, curr;
int parent[NMAX];
int vis[NMAX];
vector<int> roots;
void dfs(int node) {
  if (vis[node] != 0) {
    if (vis[node] == curr) {
      parent[node] = node;
      roots.push_back(node);
    } else {
      return;
    }
  }
  vis[node] = curr;
  if (node != parent[node]) {
    dfs(parent[node]);
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> parent[i];
    if (parent[i] == i) {
      root = i;
      roots.push_back(i);
    }
  }
  if (roots.empty()) answer = 1;
  for (int i = 1; i <= n; ++i) {
    ++curr;
    dfs(i);
  }
  for (int &x : roots) {
    parent[x] = roots[0];
    ++answer;
  }
  --answer;
  cout << answer << '\n';
  for (int i = 1; i <= n; ++i) {
    cout << parent[i] << ' ';
  }
  return 0;
}

from collections import  defaultdict
from sys import stdin,setrecursionlimit
setrecursionlimit(10**6)
import threading
def f(a):
	n=len(a)
	a=list(map(lambda s:s-1,a))
	root=None
	for i in range(len(a)):
		if a[i]==i:
			root=i
	vis=[0]*(n)
	traitors=[]
	for i in range(0,n):
		cycle=-1
		cur=i
		move=set()

		while vis[cur]==0:
			vis[cur]=1
			move.add(cur)
			if a[cur] in move:
				cycle=cur
			cur=a[cur]
		if cycle!=-1:
			traitors.append(cycle)
	ans=len(traitors)-1
	if root==None:
		a[traitors[0]]=traitors[0]
		root=traitors[0]
		ans+=1
	for i in traitors:
		if i!=root:
			a[i]=root
	print(ans)
	a=list(map(lambda s:s+1,a))
	return a
n=input()
a=list(map(int,input().strip().split()))
print(*f(a))


#include <bits/stdc++.h>
using namespace std;
int main() {
  int arr[95]{};
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    int m;
    scanf("%d", &m);
    arr[m] = 1;
  }
  int c = 0;
  int ans = 0;
  int i;
  for (i = 1; i <= 90; i++) {
    c++;
    if (arr[i] != 0) {
      c = 0;
    }
    if (c == 15) {
      break;
    }
  }
  if (i == 91) i--;
  cout << i;
}

import java.util.Scanner;

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

        int n = sc.nextInt();
        int prev=0, cur=0, time=0;

        for(int i=0; i<n+1; i++) {
            if(i!=n) cur=sc.nextInt();
            else cur=90;
            if(cur-prev <= 15) {
                time+=cur-prev;
            }
            else {
                time+=15;
                break;
            }
            prev=cur;
        }

        System.out.println(time);
    }
}


import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;

public class Ideone
{
	public static void main (String[] args)
	{
		Scanner in= new Scanner(System.in);
		int x=in.nextInt();
		int y=in.nextInt();
		int tmp = x - 1;
		BigInteger sum = BigInteger.valueOf(0);

		for(int i=0;i<x;i++)
		{
		  int s=in.nextInt();
		  BigInteger tmpBI = BigInteger.valueOf(s);
		  for(int j=0;j<tmp;j++)
		  {
	            tmpBI = tmpBI.multiply(BigInteger.valueOf(y));
		  }
		  sum = sum.add(tmpBI);
		  tmp--;

		}

		x=in.nextInt();
		y=in.nextInt();
		tmp = x - 1;
		BigInteger sum2 = BigInteger.valueOf(0);

		for(int i=0;i<x;i++)
		{
		  int s=in.nextInt();
		  BigInteger tmpBI = BigInteger.valueOf(s);
		  for(int j=0;j<tmp;j++)
		  {
	            tmpBI = tmpBI.multiply(BigInteger.valueOf(y));
		  }
		  sum2 = sum2.add(tmpBI);
		  tmp--;
		}

		if (sum.compareTo(sum2) == 0)
			System.out.println("=");
		else if (sum.compareTo(sum2) < 0)
			System.out.println("<");
		else
			System.out.println(">");

	}
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, bn;
  cin >> n >> bn;
  long long int sum = 0;
  while (n--) {
    int a;
    cin >> a;
    sum = (long long int)bn * sum + a;
  }
  long long int sum1 = 0;
  int m, bm;
  cin >> m >> bm;
  while (m--) {
    int a;
    cin >> a;
    sum1 = (long long int)bm * sum1 + a;
  }
  if (sum > sum1)
    cout << '>';
  else if (sum < sum1)
    cout << '<';
  else
    cout << '=';
}


from sys import stdin
c = [[0]*1002 for _ in range(0,1002)]
MOD = int(1e9+7)

for i in range(0,1002):
    c[i][0] = c[i][i] = 1
    for j in range(0,i):
        c[i][j] = (c[i-1][j-1] + c[i-1][j])%MOD

r = map(int,stdin.read().split())

n = next(r)
ans = 1
sum = 0

for _ in range(0,n):
    x = next(r)
    ans = (ans * c[sum+x-1][sum])%MOD
    sum += x

print(ans)

#include <bits/stdc++.h>
const int Mod = (int)1e9 + 7;
const int MX = 2147483647;
const long long MXLL = 9223372036854775807;
const int Sz = 1110111;
using namespace std;
inline void Read_rap() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
long long a[Sz], n, f[Sz], ans = 1, len = 0;
long long binpow(long long a, long long b) {
  long long res = 1;
  while (b) {
    if (b & 1) {
      res *= a, res %= Mod;
      b--;
    }
    a *= a;
    a %= Mod;
    b >>= 1;
  }
  return res;
}
long long C(long long x, long long y) {
  long long res = f[x + y - 1];
  res *= binpow(f[x], Mod - 2);
  res %= Mod;
  res *= binpow(f[y - 1], Mod - 2);
  res %= Mod;
  return res;
}
int main() {
  Read_rap();
  f[0] = 1;
  for (int i = 1; i < Sz; i++) f[i] = (f[i - 1] * i) % Mod;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    ans *= C(len, a[i]);
    ans %= Mod;
    len += a[i];
  }
  cout << ans;
  return 0;
}


import java.util.Arrays;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Comparator;
import java.io.IOException;
import java.util.StringTokenizer;
import java.math.*;
import java.util.*;

public class B
{
    public static void main(String[]args)
    {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskX solver = new TaskX();
        solver.solve(1,in,out);
        out.close();
    }
}

class TaskX
{
    public void solve(int testNumber, InputReader in, PrintWriter out)
    {
        int n,m,k;
        n = in.nextInt();
        m = in.nextInt();
        k = in.nextInt();
        char mat[][] = new char[n][m];
        int sum[] = new int[m];

        for(int i=0;i<m;++i) sum[i] = 0;

        for(int i=0;i<n;++i)
        {
            String s = in.next();
            for(int j=0;j<m;++j)
            {
                mat[i][j] = s.charAt(j);
                if( mat[i][j] == 'U' ) if(i%2==0) sum[j]++;
                if( mat[i][j] == 'L' )
                {
                    int pos = j-i;
                    if( pos>=0 ) sum[pos]++;
                }
                if(mat[i][j] == 'R' )
                {
                    int pos = j+i;
                    if( pos<m ) sum[pos]++;
                }
                if( mat[i][j]=='D') if( i == 0 ) sum[j]++;
            }
        }

        for(int i=0;i<m;++i) out.printf("%d ",sum[i]);
            out.println();
    }
}

class InputReader
{
    public BufferedReader reader;
    public StringTokenizer tokenizer;
    public InputReader(InputStream stream){
        reader = new BufferedReader(new InputStreamReader(stream), 32768);
        tokenizer = null;
    }
    public String next(){
        while (tokenizer == null || !tokenizer.hasMoreTokens()){
            try{
                tokenizer = new StringTokenizer(reader.readLine());
            }
            catch (IOException e){
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }
    public int nextInt() {
        return Integer.parseInt(next());
    }
}


import java.io.*;
import java.util.*;

public class P388C
{
    public static StringTokenizer st;
    public static void nextLine(BufferedReader br) throws IOException
    {
        st = new StringTokenizer(br.readLine());
    }

    public static String next()
    {
        return st.nextToken();
    }

    public static int nextInt()
    {
        return Integer.parseInt(st.nextToken());
    }

    public static long nextLong()
    {
        return Long.parseLong(st.nextToken());
    }

    public static double nextDouble()
    {
        return Double.parseDouble(st.nextToken());
    }

    static int[] dp;

    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        nextLine(br);
        int n = nextInt();
        int[][] piles = new int[n][];
        int sum = 0;
        for (int i = 0; i < n; i++)
        {
            nextLine(br);
            int s = nextInt();
            piles[i] = new int[s];
            for (int j = 0; j < s; j++)
            {
                piles[i][j] = nextInt();
                sum += piles[i][j];
            }
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        int win = 0;
        for (int i = 0; i < n; i++)
        {
            if (piles[i].length % 2 == 0)
            {
                for (int j = 0; j < piles[i].length / 2; j++)
                {
                    win += piles[i][j];
                }
            }
            else
            {
                list.add(piles[i][piles[i].length / 2]);
                for (int j = 0; j < piles[i].length / 2; j++)
                {
                    win += piles[i][j];
                }
            }
        }
        Collections.sort(list, Collections.<Integer>reverseOrder());
        for (int i = 0; i < list.size(); i++)
        {
            if (i % 2 == 0)
            {
                win += list.get(i);
            }
        }
        System.out.println(win + " " + (sum - win));
    }
}

#include <bits/stdc++.h>
using namespace std;
vector<int> vec;
int main() {
  int n;
  cin >> n;
  int A = 0, B = 0;
  for (int i = 0; i < n; i++) {
    int s;
    cin >> s;
    for (int j = 0; j < s / 2; j++) {
      int x;
      cin >> x;
      A += x;
    }
    if (s % 2) {
      int x;
      cin >> x;
      vec.push_back(x);
    }
    for (int j = 0; j < s / 2; j++) {
      int x;
      cin >> x;
      B += x;
    }
  }
  sort(vec.begin(), vec.end());
  reverse(vec.begin(), vec.end());
  for (int i = 0; i < vec.size(); i++) {
    if (i % 2)
      B += vec[i];
    else
      A += vec[i];
  }
  cout << A << ' ' << B << endl;
}


import java.util.Scanner;

public class B270 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int[] A = new int[N];
        for (int n=0; n<N; n++) {
            A[n] = in.nextInt();
        }
        int pos = N-1;
        while (pos > 0 && A[pos-1] < A[pos]) pos--;
        System.out.println(pos);
    }

}

n = int(input())
arr = list(map(int,input().split()))
ans = n-1
for i in range(-1,-n,-1):
    if arr[i]>arr[i-1]:
        ans-=1
    else:
        break
print(ans)


n=int(input())
A=[0]*n
ans=[0]*n
for i in range(n):
	A[i]=list(map(int,input().split()))
	for j in range(n):
		if(j==i):continue
		ans[i]|=A[i][j]
for i in range(n):
	print(ans[i],' ',end='')

#include <bits/stdc++.h>
using namespace std;
int n;
void EXEC() {
  cin >> n;
  for (int i = 0; i < n; ++i) {
    int s = 0;
    int t;
    for (int j = 0; j < n; ++j) {
      cin >> t;
      if (t != -1) s |= t;
    }
    cout << s << ' ';
  }
  cout << endl;
}
int main() {
  EXEC();
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
void swap(int &x, int &y) {
  int t = x;
  x = y;
  y = t;
}
int main() {
  int n;
  cin >> n;
  int *p = new int[n];
  vector<int> k;
  for (int i = 0; i < n; i++) {
    cin >> p[i];
    k.push_back(p[i]);
  }
  sort(k.begin(), k.end());
  int count = 0;
  for (int i = 0; i < n; i++)
    if (p[i] != k[i]) count++;
  if (count < 3)
    cout << "YES";
  else
    cout << "NO";
  delete[] p;
  return 0;
}

YES YES NO NO NO YES NO YES YES YES YES YES YES YES YES YES YES NO NO YES NO NO YES NO YES YES NO YES YES YES YES NO YES NO YES YES NO NO NO NO YES NO NO YES NO YES YES YES NO YES YES NO

n = int(input())
a = list(map(int, input().split()))
b = sorted(a)
res = 0
for i in range(n):
    if a[i] != b[i]:
        res += 1
print('YES' if res <= 2 else 'NO')


#include <bits/stdc++.h>
int main() {
  int n, cnt = 0;
  scanf("%d", &n);
  int a[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  int maxx = a[0];
  int minn = a[0];
  for (int i = 0; i < n; i++) {
    if (a[i] > maxx) {
      maxx = a[i];
      cnt++;
    }
    if (a[i] < minn) {
      minn = a[i];
      cnt++;
    }
  }
  printf("%d\n", cnt);
  return 0;
}

n=int(input())
a=list(map(int,input().split()))
c=[]
d=0
c.append(a[0])
for i in range(1,n):
    y=a[i]-a[i-1]
    if y>0 and a[i]>max(c):
        c.append(a[i])
        d+=1
    elif y<0 and a[i]<min(c):
        c.append(a[i])
        d+=1
print(d)
#print(c)