E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.util.Arrays;

import java.io.IOException;

import java.util.TreeSet;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.Collections;

import java.io.InputStream;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 *

 * @author Indrajit Sinha

 */

public class Main {

	public static void main(String[] args) {

		InputStream inputStream = System.in;

		OutputStream outputStream = System.out;

		InputReader in = new InputReader(inputStream);

		PrintWriter out = new PrintWriter(outputStream);

		EMessengerSimulator solver = new EMessengerSimulator();

		solver.solve(1, in, out);

		out.close();

	}

	static class EMessengerSimulator {

		int n;

		PrintWriter out;

		InputReader in;

		final Comparator<Query> com = new Comparator<Query>() {

			public int compare(Query x, Query y) {

				int xx = Integer.compare(x.r, y.r);

				if (xx == 0)

					return Integer.compare(x.l, y.l);

				return xx;

			}

		};

		public void solve(int testNumber, InputReader in, PrintWriter out) {

			int t, i, j, tt, k;

			this.out = out;

			this.in = in;

			n = in.nextInt();

			int m = in.nextInt();

			int a[] = new int[m];

			int[] mn, mx;

			mn = new int[n];

			mx = new int[n];

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

				mn[i] = i;

				mx[i] = i;

			}

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

				a[i] = in.nextInt() - 1;

				mn[a[i]] = 0;

			}

			ArrayList<Integer> ar[] = new ArrayList[n];

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

				ar[i] = new ArrayList<>();

			}

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

				ar[a[i]].add(i);

			}

			TreeSet<Integer> ts = new TreeSet<>();

			SegmenTree sg = new SegmenTree();

			sg.build(n);

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

				if (ts.contains(a[i]))

					continue;

				mx[a[i]] = Math.max(mx[a[i]], a[i] + sg.query(a[i] + 1, n));

				ts.add(a[i]);

				sg.updateTreeNode(a[i], 1);

			}

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

				if (ar[i].size() == 0) {

					mx[i] = Math.max(mx[i], i + sg.query(i + 1, n));

				}

			}

			ArrayList<Query> queries = new ArrayList<>();

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

				if (i == 98) {

					int ou = 0;

				}

				for (j = 1; j < ar[i].size(); j++) {

					int l = ar[i].get(j - 1) + 1;

					int r = ar[i].get(j) - 1;

					if (l <= r) {

						queries.add(new Query(l, r, i));

					}

					if (j == ar[i].size() - 1) {

						l = ar[i].get(j) + 1;

						r = m - 1;

						if (l <= r)

							queries.add(new Query(l, r, i));

					}

				}

				if (ar[i].size() == 1) {

					int l = ar[i].get(0) + 1;

					int r = m - 1;

					if (l <= r)

						queries.add(new Query(l, r, i));

				}

			}

			Collections.sort(queries, com);

			int bit[] = new int[m + 1];

			int last_visit[] = new int[n + 5];

			Arrays.fill(last_visit, -1);

			int query_counter = 0, q = queries.size();

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

				if (last_visit[a[i]] != -1)

					update(last_visit[a[i]] + 1, -1, bit, m);

				last_visit[a[i]] = i;

				update(i + 1, 1, bit, m);

				while (query_counter < q && queries.get(query_counter).r == i) {

					int an = query(queries.get(query_counter).r + 1, bit, m) - query(queries.get(query_counter).l, bit, m);

					int idx = queries.get(query_counter).idx;

					mx[idx] = Math.max(mx[idx], an);

					query_counter++;

				}

			}

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

				pn((mn[i] + 1) + " " + (mx[i] + 1));

			}

		}

		void update(int idx, int val, int bit[], int n) {

			for (; idx <= n; idx += idx & -idx)

				bit[idx] += val;

		}

		int query(int idx, int bit[], int n) {

			int sum = 0;

			for (; idx > 0; idx -= idx & -idx)

				sum += bit[idx];

			return sum;

		}

		void pn(String zx) {

			out.println(zx);

		}

		class Query {

			int l;

			int r;

			int idx;

			Query(int a, int b, int c) {

				l = a;

				r = b;

				idx = c;

			}

		}

		class SegmenTree {

			int n;

			int[] tree;

			void build(int x) {

				n = x;

				tree = new int[2 * n + 1];

			}

			void updateTreeNode(int p, int value) {

				tree[p + n] = value;

				p = p + n;

				for (int i = p; i > 1; i >>= 1)

					tree[i >> 1] = tree[i] + tree[i ^ 1];

			}

			int query(int l, int r) {

				int res = 0;

				for (l += n, r += n; l < r;

				     l >>= 1, r >>= 1) {

					if ((l & 1) > 0)

						res += tree[l++];

					if ((r & 1) > 0)

						res += tree[--r];

				}

				return res;

			}

		}

	}

	static class InputReader {

		private InputStream stream;

		private byte[] buf = new byte[1024];

		private int curChar;

		private int numChars;

		public InputReader(InputStream stream) {

			this.stream = stream;

		}

		public int read() {

			if (numChars == -1) {

				throw new UnknownError();

			}

			if (curChar >= numChars) {

				curChar = 0;

				try {

					numChars = stream.read(buf);

				} catch (IOException e) {

					throw new UnknownError();

				}

				if (numChars <= 0) {

					return -1;

				}

			}

			return buf[curChar++];

		}

		public int nextInt() {

			return Integer.parseInt(next());

		}

		public String next() {

			int c = read();

			while (isSpaceChar(c)) {

				c = read();

			}

			StringBuffer res = new StringBuffer();

			do {

				res.appendCodePoint(c);

				c = read();

			} while (!isSpaceChar(c));

			return res.toString();

		}

		private boolean isSpaceChar(int c) {

			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;

		}

	}

}


D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.

import java.io.*;

import java.util.*;

public class D{

	static long gcd(long a, long b) {

		if (a == 0) return b;

		return gcd(b%a, a);

	}

	static long bf(long a, long m) {

		long cnt = 0;

		long gcd = gcd(a,m);

		for (int i = 0; i < m; i++) cnt += gcd(a+i,m)==gcd ? 1:0;

		return cnt;

	}

	static long pp(long a, long m) {

		long g = gcd(a,m);

		a/=g;

		m/=g;

		long ans = m;

		for (long i = 2; i *i<=m; i++) {

			if (m % i == 0) {

				while(m%i==0) m/=i;

				ans -= ans/i;

			}

		}

		if (m > 1) ans -= ans/m;

		return ans;

	}

	static List<Long> p;

	public static void main(String[] args) throws IOException {

		// br = new BufferedReader(new FileReader(".in"));

		// out = new PrintWriter(new FileWriter(".out"));

		//new Thread(null, new (), "peepee", 1<<28).start();

		boolean[] sieve = new boolean[(int)1e6+20];

		p = new ArrayList<Long>();

		for (int i = 2; i *i <= sieve.length; i++) {

			if (!sieve[i]) {

				for (int j = i*i; j < sieve.length; j+=i) sieve[j] = false;

			}

		}

		for (int i = 2; i < sieve.length; i++) if (!sieve[i]) p.add((long)i);

//		long a = (long)(Math.random()*1e3+1);

//		long b = a + (long)(Math.random()*1e2+12);

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

//			long ta = a*i;

//			long tb = b*i;

//			out.println(bf(ta,tb) + " " + pp(ta,tb));

//		}

		readInput();

		out.close();

	}

	static void readInput() throws IOException{

		read();

		int t= RI();

		while(t-->0) {

			read();

			long a = RL();

			long m = RL();

			out.println(pp(a,m));

		}

	}

	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

	static StringTokenizer st;

	static void read() throws IOException{st = new StringTokenizer(br.readLine());}

	static int RI() throws IOException{return Integer.parseInt(st.nextToken());}

	static long RL() throws IOException{return Long.parseLong(st.nextToken());}

	static double RD() throws IOException{return Double.parseDouble(st.nextToken());}

}


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

import java.util.*;

public class Solution

{

    public static void main(String[] args){

        Scanner sc=new Scanner(System.in);

        long h=sc.nextLong();

        int n=sc.nextInt();

        long[] ar=new long[n];

        long base=h;

        int an=0;

        int pr=0;

        boolean ok=false;

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

            ar[i]=sc.nextLong();

            base+=ar[i];

            an++;

            if(base<=0 && ok==false){ok=true;pr=an;}

        }

        if(base>=h){

            if(ok)System.out.println(pr);

            else System.out.println("-1");

        }

        else{

           long b=h;

           long max=0;

           long ans=0;long extra=0;

           long min=0;

            ok=true;

           long overall=0;

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

               ans++;

               b+=ar[i];

               min+=ar[i];

               overall+=ar[i];

               if(Math.abs(min)>max && min<0){

                   max=Math.abs(min);

                   extra=i+1;

               }

               if(b<=0 && ok){ok=false;break;}

           }

           if(!ok)System.out.println(ans);

           else{

               long rem=b-max;

               overall=Math.abs(overall);

               if(rem<=0){

                    while(true){

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

                    if(b<=0)break;

                    b+=ar[i];

                    ans++;

                    if(b<=0)break;

                }

                if(b<=0)break;

              }

               }

               else{

                  long div=rem/overall;

                  rem-=div*overall;

                  div=div*(long)n;

                  ans+=div;

                  rem+=max;

                   while(true){

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

                    if(rem<=0)break;

                    rem+=ar[i];

                    ans++;

                    if(rem<=0)break;

                }

                if(rem<=0)break;

              }

               }

               System.out.println(ans);

           }

        }

    }

}


B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string:   Pick an integer kk, (1≤k≤n1≤k≤n).  For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length 22)  weqr (after reversing the second substring of length 22)  werq (after reversing the last substring of length 22)  Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds:   aa is a prefix of bb, but a≠ba≠b;  in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows :   for k=1k=1 : abab  for k=2k=2 : baba  for k=3k=3 : abab  for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.*;

public class StringModification {

    static class Pair {

        int f;

        int s; //

        Pair() {

        }

        Pair(int f, int s) {

            this.f = f;

            this.s = s;

        }

    }

    static class Fast {

        BufferedReader br;

        StringTokenizer st;

        public Fast() {

            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());

        }

        int[] readArray(int n) {

            int a[] = new int[n];

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

                a[i] = nextInt();

            return a;

        }

        long[] readArray1(int n) {

            long a[] = new long[n];

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

                a[i] = nextLong();

            return a;

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine().trim();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    /*  static long noOfDivisor(long a)

      {

          long count=0;

          long t=a;

          for(long i=1;i<=(int)Math.sqrt(a);i++)

          {

              if(a%i==0)

                  count+=2;

          }

          if(a==((long)Math.sqrt(a)*(long)Math.sqrt(a)))

          {

              count--;

          }

              return count;

      }*/

    static boolean isPrime(long a) {

        for (long i = 2; i <= (long) Math.sqrt(a); i++) {

            if (a % i == 0)

                return false;

        }

        return true;

    }

    static void primeFact(int n) {

        int temp = n;

        HashMap<Integer, Integer> h = new HashMap<>();

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

            if (temp % i == 0) {

                int c = 0;

                while (temp % i == 0) {

                    c++;

                    temp /= i;

                }

                h.put(i, c);

            }

        }

        if (temp != 1)

            h.put(temp, 1);

    }

    static void reverseArray(int a[]) {

        int n = a.length;

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

            a[i] = a[i] ^ a[n - i - 1];

            a[n - i - 1] = a[i] ^ a[n - i - 1];

            a[i] = a[i] ^ a[n - i - 1];

        }

    }

    static void sort(int[] a) {

        ArrayList<Integer> l = new ArrayList<>();

        for (int i : a) l.add(i);

        Collections.sort(l);

        for (int i = 0; i < a.length; i++) a[i] = l.get(i);

    }

    static void sort(long[] a) {

        ArrayList<Long> l = new ArrayList<>();

        for (long i : a) l.add(i);

        Collections.sort(l);

        for (int i = 0; i < a.length; i++) a[i] = l.get(i);

    }

    static int min(int a, int b) {

        return a < b ? a : b;

    }

    static int max(int a, int b) {

        return a < b ? a : b;

    }

    static long maxSum(int arr[], int n, int k) {

        long res = 0;

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

            res += arr[i];

        long curr_sum = res;

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

            curr_sum += arr[i] - arr[i - k];

            res = Math.max(res, curr_sum);

        }

        return res;

    }

    static boolean check(int n,int k,char s[],StringBuffer max[])

    {

        StringBuffer sa=new StringBuffer();

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

            sa.append(s[i]);

        if(((n-k)&1)==0)

        {

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

                sa.append(s[i]);

        }

        else //ans==3

        {

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

                sa.append(s[i]);

        }

        if(sa.compareTo(max[0])<0) {

            max[0] = sa;

            return true;

        }

return false;

    }

    public static void main(String args[]) throws IOException {

        Fast sc = new Fast();

        PrintWriter out = new PrintWriter(System.out);

        int t1 = sc.nextInt();

        while (t1-- > 0) {

            int n = sc.nextInt();

            String s1 = sc.next();

            char s[] = s1.toCharArray();

            StringBuffer max[]=new StringBuffer[1];

            max[0]=new StringBuffer(s1);

            int ans1=1;

            for (int k = 2; k <= n; k++)

            {

                    if(check(n,k,s,max))

                    {

                        ans1=k;

                    }

            }

            out.println(max[0]);

              out.println(ans1);

        }

        out.close();

    }

}

      /*  public static void main(String args[]) throws IOException {

            Fast sc = new Fast();

            PrintWriter out = new PrintWriter(System.out);

            int t1 = sc.nextInt();

            while (t1-- > 0) {

                int n=sc.nextInt();

               String s1=sc.next();

               char s[]=s1.toCharArray();

               TreeMap<Integer, TreeSet<Integer>> tm=new TreeMap<>();

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

               {

                   char ch=s[i];

                   if(tm.get(ch-97)==null)

                   {

                       TreeSet<Integer> ts1=new TreeSet<>();

                       ts1.add(i);

                       tm.put(ch-97,ts1);

                   }

                   else

                   {

                       TreeSet ts1=tm.get(ch-97);

                       ts1.add(i); tm.put(ch-97,ts1);

                   }

               }

               TreeSet<Integer> ts1=null;

               for(Map.Entry<Integer,TreeSet<Integer>> en:tm.entrySet())

               {

                   ts1=en.getValue();

                   break;

               }

               if(ts1.size()==1)

               {

                   int ans=ts1.first()+1;

                   String sa="";

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

                       sa+=s[i];

                   if(((n-ans)&1)==0)

                   {

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

                           sa+=s[i];

                   }

                   else //ans==3

                   {

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

                           sa+=s[i];

                   }

                   out.println(sa);

                   out.println(ans);

               }

            else

               {

              //     out.println(-1);

                   int ans=-1;

                   int comp=Integer.MAX_VALUE;

                   for(int ne:ts1)

                   {

                       if(ne!=0)

                       {

                         if(comp>s[ne-1])

                         {

                             comp=s[ne-1];

                             ans=ne+1;

                         }

                       }

                   }

                   String sa="";

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

                       sa+=s[i];

                   if(((n-ans)&1)==0)

                   {

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

                           sa+=s[i];

                   }

                   else //ans==3

                   {

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

                           sa+=s[i];

                   }

                   if(sa.equals(s1))

                   {

                       out.println(sa);out.println(1);

                   }

                   else

                   {

                       out.println(sa);out.println(ans);

                   }

               }

            }

            out.close();

        }

    }

*/


D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.

//package com.example.practice.codeforces;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
//D. Happy New Year
public class Solution {
    public static void main (String [] args) throws IOException {
        // Use BufferedReader rather than RandomAccessFile; it's much faster
        final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        // input file name goes above
        //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("inflate.out")));

        StringTokenizer st = new StringTokenizer(input.readLine());
        int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());
        int[][] ns = new int[n][2];
        for(int i=0;i<n;++i){
            st = new StringTokenizer(input.readLine());
            ns[i][0] = Integer.parseInt(st.nextToken());
            ns[i][1] = Integer.parseInt(st.nextToken());
        }
        System.out.println(calc(n, m, k, ns));
        //out.close();       // close the output file
    }

    private static int calc(final int n, final int m, final int k, int[][] ns) {
        HashMap<Integer, Node> map = new HashMap<>();
        int p = 0, pre = 0, finished = 0;
        for (int[] kk : ns){
            if (!map.containsKey(kk[0])){
                map.put(kk[0], new Node(kk[0]));
            }
            map.get(kk[0]).st.add(p);
            if (!map.containsKey(kk[1]+1)){
                map.put(kk[1]+1, new Node(kk[1]+1));
            }
            map.get(kk[1]+1).en.add(p++);
        }
        Node[] nds = new Node[map.size()];
        p = 0;
        for (Node nd : map.values()){
            nds[p++] = nd;
        }
        Arrays.sort(nds);
        final int ks = 1<<k;
        int[][] dp = new int[nds.length][ks];
        int[] mask = new int[n], bitCount = new int[ks];
        for (int i=1;i<ks;++i){
            if((i&1) == 1)bitCount[i]=bitCount[i-1]+1;
            else bitCount[i]=bitCount[i>>1];
        }
        for (int i=0;i<dp.length-1;++i){
            pre -= finished;
            int d = 1, added = 0;
            for (int a : nds[i].st){
                while((d&pre) != 0) {
                    d = d << 1;
                }
                mask[a] = d;
                added += d;
                pre += d;
            }
            finished = 0;
            for (int a : nds[i+1].en){
                finished += mask[a];
            }
            for (int j=0;j<ks;++j) {
                if ((j & pre) == j) {
                    int t = 0;
                    if ((bitCount[j] & 1) == 1) {
                        t += nds[i + 1].start - nds[i].start;
                    }
                    if (i > 0) {
                        t += dp[i - 1][j - (j & added)];
                    }
                    dp[i][j - (j & finished)] = Math.max(dp[i][j - (j & finished)], t);
                }
            }
        }
        return dp[dp.length-2][0];
    }

    static class Node implements Comparable<Node>{
        int start;
        ArrayList<Integer> st;
        ArrayList<Integer> en;
        public Node(int a){
            start = a;
            st = new ArrayList<>(4);
            en = new ArrayList<>(4);
        }
        @Override
        public int compareTo(Node nd){
            return this.start - nd.start;
        }
    }
}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

import java.util.*;

public class Main

{

	public static void main(String[] args) {

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

		while(t--!=0){

		    int a=sc.nextInt();

		    int b=sc.nextInt();

		    int ans=0;

		    boolean p=true;

		    if(a==b){

		        p=false;

		        System.out.println(0);

		    }

		    else if(a>b){

		        int d=a-b;

		        ans++;

		        if(d%2!=0){

		            ans+=1;

		        }

		    }

		    else{

		        int d=b-a;

		        ans++;

		        if(d%2!=1){

		            ans++;

		        }

		    }

		    if(p==true){

		        System.out.println(ans);

		    }

		}

	}

}


E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class teambuilding {

    static class Node implements Comparable<Node>{
        int ind;
        int v;
        Node(int ind, int v){
            this.ind = ind;
            this.v = v;
        }
        public int compareTo(Node s){
            if(v != s.v) return s.v - v;
            return ind - s.ind;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken()), p = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());
        Node[] ar = new Node[n];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) ar[i] = new Node(i, Integer.parseInt(st.nextToken()));
        long[][] vs = new long[n][p];
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < p; j++) {
                vs[i][j] = Long.parseLong(st.nextToken());
            }
        }
        Arrays.sort(ar);
        long[][] dp = new long[(1 << p)][n];
        for (int i = 0; i < (1 << p); i++) for (int j = 0; j < n; j++) dp[i][j] = -1;
        dp[0][0] = ar[0].v;
        for (int i = 0; i < p; i++) dp[(1 << i)][0] = vs[ar[0].ind][i];
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < (1 << p); j++) {
                if(dp[j][i - 1] == -1) continue;
                int onecount = Integer.bitCount(j);
//                System.out.println(j + " " + onecount);
                if(k - (i - onecount + 1) >= 0){
                    dp[j][i] = Math.max(dp[j][i - 1] + ar[i].v, dp[j][i]);
                } else {
                    dp[j][i] = Math.max(dp[j][i], dp[j][i - 1]);
                }
                for (int l = 0; l < p; l++) {
                    //i is the current one to choose, j is the bitmask, l is the position
                    if((j >> l) % 2 == 1) continue;
                    dp[(j | (1 << l))][i] = Math.max(dp[j][i - 1] + vs[ar[i].ind][l], dp[(j | (1 << l))][i]);
                }
            }
        }
        System.out.println(dp[(1 << p) - 1][n - 1]);
    }
}


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

import java.util.*;

import java.io.*;

import java.math.BigInteger;

public class CODE {

    public static class pair implements Comparable<pair> {

        int x;

        int y;

        public pair(int par1, int par2) {

            x = par1;

            y = par2;

        }

        @Override

        public int compareTo(pair p) {

            return x - p.x;

        }

        @Override

        public String toString() {

            return +x + " " + y;

        }

    }

    static long mod = (long) (1e9 + 7);

    public static long facn(long n, long x) {

        long ans = 1;

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

            ans *= n;

            ans %= mod;

            n--;

        }

        long k = 1;

        long t = x;

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

            k *= x;

            k %= mod;

            x--;

        }

//      BigInteger b = BigInteger.valueOf((k)).modInverse(BigInteger.valueOf((mod)));

        long b = modPow(k, mod - 2, mod);

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

    }

    public static long modInverse(long a, long m) {

        a = a % m;

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

            if ((a * x) % m == 1)

                return x;

        return 1;

    }

    static long modPow(long a, long e, long mod) { // O(log e)

        a %= mod;

        long res = 1;

        while (e > 0) {

            if ((e & 1) == 1)

                res = (res * a) % mod;

            a = (a * a) % mod;

            e >>= 1;

        }

        return res % mod;

    }

    public static void bb(Serializable s) {

        System.out.println(55);

    }

    public static int dfs(int u) {

        vis[u] = true;

        rank[u] = rnk;

        int ans = 1;

        for (int v : adj[u])

            if (!vis[v])

                ans += dfs(v);

        return ans;

    }

    public static void dfsD(int u) {

        dist[u] = dst;

        for (int v : adj[u])

            if (dist[v] == -1)

                dfsD(v);

    }

    static ArrayList<Integer>[] adj, adj2;

    static int n, m, k, rnk, dst;

    static boolean[] vis;

    static int[] dist, rank;

    public static String rev(String str) {

        StringBuilder sb = new StringBuilder();

        for (int i = str.length() - 1; i >= 0; i--)

            sb.append(str.charAt(i));

        // System.out.println(sb);

        return sb.toString();

    }

    static PriorityQueue<pair> pq;

    static int p;

    static int[][] Matrix;

    static long[][] memo;

    static pair[] Arr;

//  public static long dp(int idx, int mask) {

//      int k=idx-Integer.bitCount(mask);

//      if (k==0&&Integer.bitCount(mask)==p)

//          return 0;

//      long ans = 0;

//      if (memo[mask][idx] != -1)

//          return memo[mask][idx];

//      if (kk > 0)

//          ans = Math.max(ans, Arr[k+p-kk - pp].y + dp(kk - 1, pp, mask));

//      if (pp > 0)

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

//              if ((mask & (1 << i)) == 0)

//                  ans = Math.max(Matrix[Arr[k+p-kk - pp].x][i] + dp(kk, pp - 1, mask | 1 << i), ans);

//

//      return memo[mask][pp][kk] = ans;

//  }

    public static void main(String[] args) throws IOException {

        try {

            System.setIn(new FileInputStream("input.txt"));

            System.setOut(new PrintStream(new FileOutputStream("output.txt")));

        } catch (Exception e) {

            System.err.println("Error");

        }

        Scanner sc = new Scanner(System.in);

        PrintWriter pw = new PrintWriter(System.out);

        int n = sc.nextInt();

        Long[]Arr = new Long[n];

        for (int i = 0; i < n; i++)Arr[i] = sc.nextLong();

        for (int i = 0; i < n; i++)Arr[i] -= sc.nextLong();

        Arrays.sort(Arr);

        long sum = 0;

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

            int lo = 0;

            int hi = n - 1;

            int mid = n;

            int ans = n;

            while (hi >= lo) {

                mid = (lo + hi) / 2;

                if (Arr[i] + Arr[mid] > 0) {

                    ans = mid;

                    hi = mid - 1;

                } else {

                    lo = mid + 1;

                }

            }

            sum += n - ans;

        }

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

            if (Arr[i] > 0)sum--;

        }

        pw.println(sum / 2);

        pw.close();

    }

    /*Scanner sc = new Scanner(System.in);

            PrintWriter pw = new PrintWriter(System.out);

            int t=sc.nextInt();

            while(t-->0) {

                int n=sc.nextInt();

                int[]Arr=new int [n];

                for(int i=0;i<n;i++)Arr[i]=sc.nextInt();

                for(int i=0;i<n;i++)Arr[i]-=sc.nextInt();

                Arrays.sort(Arr);

                int sum=0;

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

                {

                    int lo=0;

                    int hi=n-1;

                    int mid=n+1;

                    int ans=n+1;

                    while(hi>=lo) {

                        mid=(lo+hi)/2;

                    }

                }

                }

            pw.close();*/

    public static class trie {

        trie[] arr;

        int isLeaf;

        int freq;

        public trie() {

            super();

            this.arr = new trie[26];

            this.isLeaf = 0;

            this.freq = 0;

        }

        public void add(String str) {

            add(str, 0);

        }

        private void add(String str, int idx) {

            if (idx == str.length()) {

                isLeaf++;

                return;

            }

            int x = str.charAt(idx) - 'a';

            if (arr[x] == null)

                arr[x] = new trie();

            arr[x].freq++;

            arr[x].add(str, idx + 1);

        }

        public int numOfPref(String str) {

            return numOfPref(str, 0);

        }

        private int numOfPref(String str, int idx) {

            if (idx == str.length())

                return freq;

            int x = str.charAt(idx) - 'a';

            if (arr[x] == null)

                return 0;

            return arr[x].numOfPref(str, idx + 1);

        }

        public int numofStr(String str) {

            return numOfStr(str, 0);

        }

        private int numOfStr(String str, int idx) {

            if (idx == str.length())

                return isLeaf;

            int x = str.charAt(idx) - 'a';

            if (arr[x] == null)

                return 0;

            return arr[x].numOfStr(str, idx + 1);

        }

        public boolean contains(String str) {

            return numofStr(str) != 0;

        }

        public boolean containsPref(String str) {

            return numOfPref(str) != 0;

        }

    }

    public static class Scanner {

        StringTokenizer st;

        BufferedReader br;

        public Scanner(InputStream s) {

            br = new BufferedReader(new InputStreamReader(s));

        }

        public String next() throws IOException {

            while (st == null || !st.hasMoreTokens())

                st = new StringTokenizer(br.readLine());

            return st.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public String nextLine() throws IOException {

            return br.readLine();

        }

        public double nextDouble() throws IOException {

            String x = next();

            StringBuilder sb = new StringBuilder("0");

            double res = 0, f = 1;

            boolean dec = false, neg = false;

            int start = 0;

            if (x.charAt(0) == '-') {

                neg = true;

                start++;

            }

            for (int i = start; i < x.length(); i++)

                if (x.charAt(i) == '.') {

                    res = Long.parseLong(sb.toString());

                    sb = new StringBuilder("0");

                    dec = true;

                } else {

                    sb.append(x.charAt(i));

                    if (dec)

                        f *= 10;

                }

            res += Long.parseLong(sb.toString()) / f;

            return res * (neg ? -1 : 1);

        }

        public boolean ready() throws IOException, IOException {

            return br.ready();

        }

    }

}


A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.

import java.util.*;
import  static java.lang.System.out;

public class Main {
    static Scanner sc;

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

//        int t = sc.nextInt();
//        for(int __ = 0; __ < t; __++){
            var n = sc.nextLong();
            var m = sc.nextLong();
            if(m % n != 0) out.println(-1);
            else{
                m /= n;
                int c = 0;
                while((m & 1) == 0) {
                    m >>= 1;
                    c++;
                }
                while( m % 3 == 0) {
                    m /= 3;
                    c++;
                }
                if(m != 1) out.println(-1);
               else out.println(c);
            }

        //}

        sc.close();
    }

    public static int[] intar(int n){
        var f = new int[n];
        for(int i = 0; i < n; i++) f [i] = sc.nextInt();
        return f;
    }

    public static void outintar(int[] a, String d){
        out.print(a[0]);
        for(int i = 1; i < a.length; i++)
        {
            out.print(" ");
            out.print(a[i]);
        }
        out.println();
    }
}


C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1
abac
OutputCopyaba
InputCopy19 5 1821
aupontrougevkoffice
OutputCopyau
NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a".

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;

public class C1310C_2 {
    public static void main(String[] args) {
        var scanner = new BufferedScanner();
        var writer = new PrintWriter(new BufferedOutputStream(System.out));

        var n = scanner.nextInt();
        var m = scanner.nextInt();
        var k = scanner.nextLong();
        var s = scanner.next().toCharArray();
//        var n = 1000;
//        var m = 800;
//        var k = (long) 1e18;
//        var sb = new StringBuilder();
//        for (int i = 0; i < n; i++) {
//            sb.append((char) (Math.random() * 3 + 'a'));
//        }
//        var s = sb.toString().toCharArray();
        var t = System.nanoTime();
        writer.println(solve(n, m, k, s));
//        System.out.println((System.nanoTime() - t) / 1e9);

        scanner.close();
        writer.flush();
        writer.close();
    }

    static final long K_MAX = (long) 1e18;

    private static String solve(int n, int m, long k, char[] s) {
        var lcp = lcp(n, s);
        var subs = subs(n, s, lcp);
        var low = 0;
        var high = subs.size() - 1;
        var found = -1;
        while (low <= high && found < 0) {
            var mid = (low + high) >>> 1;
            var gte = countGte(n, s, m, subs.get(mid), lcp);
            var countFrom = gte[1] + 1;
            var countTo = gte[1] + gte[0];
//            System.out.println(subs.get(mid) + " " + Arrays.toString(gte));
            if (countFrom <= k && k <= countTo) {
                found = mid;
            } else if (countTo < k) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }

        }
        return new String(s, subs.get(found).from, subs.get(found).len);
    }

    static int compare(int from1, int len1, int from2, int len2, int[][] lcp, char[] s) {
        var common = lcp[from1][from2];
        if (common >= len1 || common >= len2) {
            return Integer.compare(len1, len2); // 谁长谁大
        } else {
            return Character.compare(s[from1 + common], s[from2 + common]);
        }
    }

    private static long[] countGte(int n, char[] s, int m, Sub minS, int[][] lcp) {
        int minSLen = minS.len;
        var dp0 = new long[m + 1][n + 1];
        var dp1 = new long[m + 1][n + 1];
        dp0[0][0] = 0; // 长度为0划分为0个部分，其中至少一个等于minS的划分数为0。
        dp1[0][0] = 1; // 长度为0划分为0个部分，其中所有都大于minS的划分数为1。
        for (int parts = 1; parts <= m; parts++) {
            var change = new HashMap<Integer, List<Integer>>();
            var dp0Acc = new long[]{0, 0}; // [0]:small sum; [1]:large count
            var dp1Acc = new long[]{0, 0}; // [0]:small sum; [1]:large count
            for (int len = parts; len <= n; len++) {
                int start = len - 1;
                // 前面开始的子串，到这一步可能有几个变化：一直是minS前缀（长度可能是0）的，变大于、等于、小于minS了。
                // 先把当前这个加进去
                if (compare(start, len - start, minS.from, minS.len, lcp, s) > 0) {
                    // 第1位就大于minS的，无论怎么延长都会一直大于minS，所以后面的len+x(x>=0)都会用到
                    add(dp0Acc, dp0[parts - 1][start]);
                    add(dp1Acc, dp1[parts - 1][start]);
                } else {
                    var common = min(lcp[start][minS.from], minS.len);
                    var changePos = common == minSLen ? start + common - 1
                                                      : start + common;
                    change.compute(changePos, (k, v) -> {
                        if (v == null) {
                            v = new ArrayList<>();
                        }
                        v.add(start);
                        return v;
                    });
                }
                var equalStarts = new ArrayList<Integer>();
                for (Integer startToChange : change.getOrDefault(start, List.of())) {
                    int compare = compare(startToChange, len - startToChange, minS.from, minS.len, lcp, s);
                    if (compare == 0) {
                        add(dp0Acc, dp0[parts - 1][startToChange], dp1[parts - 1][startToChange]);
                        equalStarts.add(startToChange);
                    } else if (compare > 0) {
                        add(dp0Acc, dp0[parts - 1][startToChange]);
                        add(dp1Acc, dp1[parts - 1][startToChange]);
                    }
                }
                dp0[parts][len] = translate(dp0Acc);
                dp1[parts][len] = translate(dp1Acc);
                for (Integer equalStart : equalStarts) {
                    // 相等只在当前len有用
                    minus(dp0Acc, dp0[parts - 1][equalStart], dp1[parts - 1][equalStart]);
                    // len+1就可能变大或者变小
                    change.compute(start + 1, (k, v) -> {
                        if (v == null) {
                            v = new ArrayList<>();
                        }
                        v.add(equalStart);
                        return v;
                    });
                }
            }
        }
        return new long[]{dp0[m][n], dp1[m][n]};
    }

    private static int min(int... a) {
        var ans = Integer.MAX_VALUE;
        for (int x : a) {
            ans = Math.min(ans, x);
        }
        return ans;
    }

    private static long translate(long[] acc) {
        return acc[0] > K_MAX || acc[1] > 0 ? K_MAX + 1 : acc[0];
    }

    private static void minus(long[] acc, long... a) {
        for (long x : a) {
            if (x > K_MAX) {
                acc[1]--;
            } else {
                acc[0] -= x;
            }
        }
    }

    static void add(long[] sum, long... a) {
        for (long x : a) {
            if (x > K_MAX) {
                sum[1]++;
            } else {
                sum[0] += x;
            }
        }
    }

    private static List<Sub> subs(int n, char[] s, int[][] lcp) {
        var t = System.nanoTime();
        var tmp = new ArrayList<Sub>();
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                tmp.add(new Sub(i, j, s, lcp));
            }
        }
//        System.out.println("sub collect: " + (System.nanoTime() - t) / 1e9);
        t = System.nanoTime();
        var ans = tmp.stream().distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
//        System.out.println("sub distinct and sort: " + (System.nanoTime() - t) / 1e9);
        return ans;
    }

    static class Sub implements Comparable<Sub> {
        final int from;
        final int to;
        final int len;
        final char[] s;
        final int[][] lcp;
        int hash;

        Sub(int from, int to, char[] s, int[][] lcp) {
            this.from = from;
            this.to = to;
            this.s = s;
            this.lcp = lcp;
            len = to - from + 1;
        }

        @Override
        public int compareTo(Sub o) {
            return compare(from, len, o.from, o.len, lcp, s);
        }

        @Override
        public String toString() {
            return "Sub{" +
                    "from=" + from +
                    ", to=" + to +
                    ", len=" + len +
                    ", s=" + Arrays.toString(s) +
                    ", sub=" + new String(s, from, len) +
                    '}';
        }

        @Override
        public int hashCode() {
            int h = hash;
            if (h == 0 && len > 0) {
                for (int i = from; i <= to; i++) {
                    h = 31 * h + (s[i] & 0xff);
                }
                hash = h;
            }
            return h;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            } else if (this == obj) {
                return true;
            } else if (getClass() != obj.getClass()) {
                return false;
            }
            Sub o = (Sub) obj;
            if (len == o.len) {
                for (int i = 0; i < len; i++) {
                    if (s[from + i] != s[o.from + i]) {
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        }
    }

    private static int[][] lcp(int n, char[] s) {
        var ans = new int[n + 1][n + 1];
        for (int i = n - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                if (s[i] == s[j]) {
                    ans[i][j] = ans[i + 1][j + 1] + 1;
                } else {
                    ans[i][j] = 0;
                }
            }
        }
        return ans;
    }

    public static class BufferedScanner {
        BufferedReader br;
        StringTokenizer st;

        public BufferedScanner(Reader reader) {
            br = new BufferedReader(reader);
        }

        public BufferedScanner() {
            this(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;
        }

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    static long gcd(long a, long b) {
        if (a < b) {
            return gcd(b, a);
        }
        while (b > 0) {
            long tmp = b;
            b = a % b;
            a = tmp;
        }
        return a;
    }

    static long inverse(long a, long m) {
        long[] ans = extgcd(a, m);
        return ans[0] == 1 ? (ans[1] + m) % m : -1;
    }

    private static long[] extgcd(long a, long m) {
        if (m == 0) {
            return new long[]{a, 1, 0};
        } else {
            long[] ans = extgcd(m, a % m);
            long tmp = ans[1];
            ans[1] = ans[2];
            ans[2] = tmp;
            ans[2] -= ans[1] * (a / m);
            return ans;
        }
    }

    private static List<Integer> primes(double upperBound) {
        var limit = (int) Math.sqrt(upperBound);
        var isComposite = new boolean[limit + 1];
        var primes = new ArrayList<Integer>();
        for (int i = 2; i <= limit; i++) {
            if (isComposite[i]) {
                continue;
            }
            primes.add(i);
            int j = i + i;
            while (j <= limit) {
                isComposite[j] = true;
                j += i;
            }
        }
        return primes;
    }

}


B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png   When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4];  Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]);  Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4];  Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3

//some updates in import stuff

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

/*

    Always check before submitting list

    -> int to long conversion needed

    -> while loop mein break case shi ho

    -> extra kuch output na ho rha free fund mein

*/

//update this bad boi too

public class Main{

    static int mod = (int) (Math.pow(10, 9)+7);

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

	static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };

	static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };

	static final double eps = 1e-10;

	static Set<Integer> primeNumbers = new HashSet<>();

    public static void main(String[] args) throws IOException{

        MyScanner sc = new MyScanner();

        //changes in this line of code

        out = new PrintWriter(new BufferedOutputStream(System.out));

        // out = new PrintWriter(new BufferedWriter(new FileWriter("output.out")));

        //Write Code Below

        int n = sc.nextInt();

        int m = sc.nextInt();

        Graph g = new Graph(n+1);

        Graph tg = new Graph(n+1);

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

            int from = sc.nextInt();

            int to = sc.nextInt();

            g.addEdge(from, to);

            tg.addEdge(to, from);

        }

        int k = sc.nextInt();

        int[] path = new int[k];

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

            path[i] = sc.nextInt();

        }

        //now solve using BFS and transposed graph baby!!! (sexy, think out of the box type of think)

        int[] dist = tg.giveDist(path[k-1]);

        Pair ans = g.minMaxPair(path[k-1],k,path, dist);

        out.println(ans.a + " " + ans.b);

        out.close();

    }

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

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

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

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

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

 //Updation Required

    //Fenwick Tree (customisable)

    //Segment Tree (customisable)

    //-----CURRENTLY PRESENT-------//

    //Graph

    //DSU

    //powerMODe

    //power

    //Segment Tree (work on this one)

    //Prime Sieve

    //Count Divisors

    //Next Permutation

    //Get NCR

    //isVowel

    //Sort (int)

    //Sort (long)

    //Binomial Coefficient

    //Pair

    //Triplet

    //lcm (int & long)

    //gcd (int & long)

    //gcd (for binomial coefficient)

    //swap (int & char)

    //reverse

    //SOME LATEST UPDATIONS!!!

    //mod_mul

    //mod_div

    //Fast input and output

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

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

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

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

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

    //finding combinations in O(1) (basically the most basic logic you can think of)

    //not that complicated as i though it of

    //GRAPH (basic structure)

    public static class Graph{

        public int V;

        public ArrayList<ArrayList<Integer>> edges;

        //2 -> [0,1,2] (current)

        Graph(int V){

            this.V  = V;

            edges = new ArrayList<>(V+1);

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

                edges.add(new ArrayList<>());

            }

        }

        public void addEdge(int from , int to){

            edges.get(from).add(to);

        }

        public int[] giveDist(int fpoint){

            int[] visited = new int[V];

            int[] dist = new int[V];

            ArrayDeque<Integer> que = new ArrayDeque<>(); //transpose graph thingie is pretty cool (quality question baby)

            que.add(fpoint);

            dist[fpoint] = 0;

            while(!que.isEmpty()){

                int curr = que.poll();

                visited[curr] = 1;

                for(int edge : edges.get(curr)){

                    if(visited[edge] != 1){

                        que.add(edge);

                        visited[edge] = 1;

                        dist[edge] = dist[curr] + 1;

                    }

                }

            }

            // out.println(Arrays.toString(dist));

            return dist;

        }

        public Pair minMaxPair(int fpoint, int k, int[] path, int[] dist){

            int min = 0;

            int max = 0;

            //this function might not be working perfectly, let's think about it now

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

                int curr = path[i];

                int next = path[i+1];

                //now let's add in set

                Set<Integer> set = new HashSet<>();

                for(int edge : edges.get(curr)){

                    if(dist[edge] == dist[curr]-1) set.add(edge);

                }

                // out.println(set);

                //this bad boi is pretty accurate for sure (now figure out something else)

                if(set.contains(next) && set.size() > 1){

                    max++;

                }else if(!set.contains(next)){

                    max++;

                    min++;

                }

            }

            return new Pair(min, max);

        }

    }

    //DSU (path and rank optimised)

    public static class DisjointUnionSets {

        int[] rank, parent;

        int n;

        public DisjointUnionSets(int n)

        {

            rank = new int[n];

            parent = new int[n];

            Arrays.fill(rank, 1);

            Arrays.fill(parent,-1);

            this.n = n;

        }

        public int find(int curr){

            if(parent[curr] == -1)

                return curr;

            //path compression optimisation

            return parent[curr] = find(parent[curr]);

        }

        public void union(int a, int b){

            int s1 = find(a);

            int s2 = find(b);

            if(s1 != s2){

                if(rank[s1] < rank[s2]){

                    parent[s1] = s2;

                    rank[s2] += rank[s1];

                }else{

                    parent[s2] = s1;

                    rank[s1] += rank[s2];

                }

            }

        }

    }

    //with mod

    public static long powerMOD(long x, long y)

    {

        long res = 1L;

        while (y > 0)

        {

            // If y is odd, multiply x with result

            if ((y & 1) != 0){

                x %= mod;

                res %= mod;

                res = (res * x)%mod;

            }

            // y must be even now

            y = y >> 1; // y = y/2

            x%= mod;

            x = (x * x)%mod;  // Change x to x^2

        }

        return res%mod;

    }

    //without mod

    public static long power(long x, long y)

    {

        long res = 1L;

        while (y > 0)

        {

            // If y is odd, multiply x with result

            if ((y & 1) != 0){

                res = (res * x);

            }

            // y must be even now

            y = y >> 1; // y = y/

            x = (x * x);

        }

        return res;

    }

    public static class segmentTree{

        public long[] arr;

        public long[] tree;

        public long[] lazy;

        segmentTree(long[] array){

            int n = array.length;

            arr = new long[n];

            for(int i= 0; i < n; i++) arr[i] = array[i];

            tree = new long[4*n + 1];

            lazy = new long[4*n + 1];

        }

        public  void build(int[]arr, int s, int e, int[] tree, int index){

            if(s == e){

                tree[index] = arr[s];

                return;

            }

            //otherwise divide in two parts and fill both sides simply

            int mid = (s+e)/2;

            build(arr, s, mid, tree, 2*index);

            build(arr, mid+1, e, tree, 2*index+1);

            //who will build the current position dude

            tree[index] = Math.min(tree[2*index], tree[2*index+1]);

        }

        public  int query(int sr, int er, int sc, int ec, int index, int[] tree){

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(sc != ec){

                    lazy[2*index+1] += lazy[index];

                    lazy[2*index] += lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap

            if(sr > ec || sc > er) return Integer.MAX_VALUE;

            //found the index baby

            if(sr <= sc && ec <= er) return tree[index];

            //finding the index on both sides hehehehhe

            int mid = (sc + ec)/2;

            int left = query(sr, er, sc, mid, 2*index, tree);

            int right = query(sr, er, mid+1, ec, 2*index + 1, tree);

            return Integer.min(left, right);

        }

        //now we will do point update implementation

        //it should be simple then we expected for sure

        public  void update(int index, int indexr, int increment, int[] tree, int s, int e){

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(s != e){

                    lazy[2*index+1] = lazy[index];

                    lazy[2*index] = lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap

            if(indexr < s || indexr > e) return;

            //found the required index

            if(s == e){

                tree[index] += increment;

                return;

            }

            //search for the index on both sides

            int mid = (s+e)/2;

            update(2*index, indexr, increment, tree, s, mid);

            update(2*index+1, indexr, increment, tree, mid+1, e);

            //now update the current range simply

            tree[index] = Math.min(tree[2*index+1], tree[2*index]);

        }

        public  void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){

            //if not at all in the same range

            if(e < sr || er < s) return;

            //complete then also move forward

            if(s == e){

                tree[index] += increment;

                return;

            }

            //otherwise move in both subparts

            int mid = (s+e)/2;

            rangeUpdate(tree, 2*index, s, mid, sr, er, increment);

            rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment);

            //update current range too na

            //i always forget this step for some reasons hehehe, idiot

            tree[index] = Math.min(tree[2*index], tree[2*index + 1]);

        }

        public  void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){

            //update lazy values

            //resolve lazy value before going down

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(s != e){

                    lazy[2*index+1] += lazy[index];

                    lazy[2*index] += lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap case

            if(sr > e || s > er) return;

            //complete overlap

            if(sr <= s && er >= e){

                tree[index] += increment;

                if(s != e){

                    lazy[2*index+1] += increment;

                    lazy[2*index] += increment;

                }

                return;

            }

            //otherwise go on both left and right side and do your shit

            int mid = (s + e)/2;

            rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment);

            rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment);

            tree[index] = Math.min(tree[2*index+1], tree[2*index]);

            return;

        }

    }

    //prime sieve

    public static void primeSieve(int n){

        BitSet bitset = new BitSet(n+1);

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

            if (i == 0 || i == 1) {

                bitset.set((int) i);

                continue;

            }

            if(bitset.get((int) i)) continue;

            primeNumbers.add((int)i);

            for(long j = i; j <= n ; j+= i)

                bitset.set((int)j);

        }

    }

    //number of divisors

    // public static int countDivisors(long number){

    //     if(number == 1) return 1;

    //     List<Integer> primeFactors = new ArrayList<>();

    //     int index = 0;

    //     long curr = primeNumbers.get(index);

    //     while(curr * curr <= number){

    //         while(number % curr == 0){

    //             number = number/curr;

    //             primeFactors.add((int) curr);

    //         }

    //         index++;

    //         curr = primeNumbers.get(index);

    //     }

    //     if(number != 1) primeFactors.add((int) number);

    //     int current = primeFactors.get(0);

    //     int totalDivisors = 1;

    //     int currentCount = 2;

    //     for (int i = 1; i < primeFactors.size(); i++) {

    //         if (primeFactors.get(i) == current) {

    //             currentCount++;

    //         } else {

    //             totalDivisors *= currentCount;

    //             currentCount = 2;

    //             current = primeFactors.get(i);

    //         }

    //     }

    //     totalDivisors *= currentCount;

    //     return totalDivisors;

    // }

    //now adding next permutation function to java hehe

    public static boolean next_permutation(int[] p) {

        for (int a = p.length - 2; a >= 0; --a)

          if (p[a] < p[a + 1])

            for (int b = p.length - 1;; --b)

              if (p[b] > p[a]) {

                int t = p[a];

                p[a] = p[b];

                p[b] = t;

                for (++a, b = p.length - 1; a < b; ++a, --b) {

                  t = p[a];

                  p[a] = p[b];

                  p[b] = t;

                }

                return true;

              }

        return false;

    }

    //is vowel function

    public static boolean isVowel(char c)

    {

        return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' ||     c=='u' || c=='U');

    }

    //to sort the array with better method

	public static void sort(int[] a) {

		ArrayList<Integer> l=new ArrayList<>();

		for (int i:a) l.add(i);

		Collections.sort(l);

		for (int i=0; i<a.length; i++) a[i]=l.get(i);

	}

    //sort long

    public static void sort(long[] a) {

		ArrayList<Long> l=new ArrayList<>();

		for (long i:a) l.add(i);

		Collections.sort(l);

		for (int i=0; i<a.length; i++) a[i]=l.get(i);

	}

    //for calculating binomialCoeff

    public static int binomialCoeff(int n, int k)

    {

        int C[] = new int[k + 1];

        // nC0 is 1

        C[0] = 1;

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

            // Compute next row of pascal

            // triangle using the previous row

            for (int j = Math.min(i, k); j > 0; j--)

                C[j] = C[j] + C[j - 1];

        }

        return C[k];

    }

    //Pair with int int

    public static class Pair{

        public int a;

        public int b;

        Pair(int a , int b){

            this.a = a;

            this.b = b;

        }

        @Override

        public String toString(){

            return a + " -> " + b;

        }

    }

    //Triplet with int int int

    public static class Triplet{

        public int a;

        public int b;

        public int c;

        Triplet(int a , int b, int c){

            this.a = a;

            this.b = b;

            this.c = c;

        }

        @Override

        public String toString(){

            return a + " -> " + b;

        }

    }

    //Shortcut function

    public static long lcm(long a , long b){

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

    }

    //let's make one for calculating lcm basically

    public static int lcm(int a , int b){

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

    }

    //int version for gcd

    public static int gcd(int a, int b){

        if(b == 0)

            return a;

        return gcd(b , a%b);

    }

    //long version for gcd

    public static long gcd(long a, long b){

        if(b == 0)

            return a;

        return gcd(b , a%b);

    }

     //for ncr calculator(ignore this code)

     public static long __gcd(long n1, long n2)

     {

         long gcd = 1;

         for (int i = 1; i <= n1 && i <= n2; ++i) {

             // Checks if i is factor of both integers

             if (n1 % i == 0 && n2 % i == 0) {

                 gcd = i;

             }

         }

         return gcd;

     }

    //swapping two elements in an array

    public static void swap(int[] arr, int left , int right){

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

    }

    //for char array

    public static void swap(char[] arr, int left , int right){

        char temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

    }

    //reversing an array

    public static void reverse(int[] arr){

        int left = 0;

        int right = arr.length-1;

        while(left <= right){

            swap(arr, left,right);

            left++;

            right--;

        }

    }

    public static long expo(long a, long b, long mod) {

        long res = 1;

        while (b > 0) {

            if ((b & 1) == 1L) res = (res * a) % mod;  //think about this one for a second

            a = (a * a) % mod;

            b = b >> 1;

        }

        return res;

    }

    //SOME EXTRA DOPE FUNCTIONS

    public static long mminvprime(long a, long b) {

        return expo(a, b - 2, b);

    }

    public static long mod_add(long a, long b, long m) {

        a = a % m;

        b = b % m;

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

    }

    public static long mod_sub(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a - b) % m) + m) % m;

    }

    public static long mod_mul(long a, long b, long m) {

        a = a % m;

        b = b % m;

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

    }

    public static long mod_div(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (mod_mul(a, mminvprime(b, m), m) + m) % m;

    }

    //O(n) every single time remember that

    public static long nCr(long N, long K , long mod){

        long upper = 1L;

        long lower = 1L;

        long lowerr = 1L;

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

            upper = mod_mul(upper, i, mod);

        }

        for(long i = 1; i <= K; i++){

            lower = mod_mul(lower, i, mod);

        }

        for(long i = 1; i <= (N - K); i++){

            lowerr = mod_mul(lowerr, i, mod);

        }

        // out.println(upper + " " + lower + " " + lowerr);

        long answer = mod_mul(lower, lowerr, mod);

        answer = mod_div(upper, answer, mod);

        return answer;

    }

    // ll *fact = new ll[2 * n + 1];

	// ll *ifact = new ll[2 * n + 1];

	// fact[0] = 1;

	// ifact[0] = 1;

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

	// {

	// 	fact[i] = mod_mul(fact[i - 1], i, MOD1);

	// 	ifact[i] = mminvprime(fact[i], MOD1);

	// }

    //ifact is basically inverse factorial in here!!!!!(imp)

    public static long combination(long n, long r, long m, long[] fact, long[] ifact) {

        long val1 = fact[(int)n];

        long val2 = ifact[(int)(n - r)];

        long val3 = ifact[(int)r];

        return (((val1 * val2) % m) * val3) % m;

    }

    //-----------PrintWriter for faster output---------------------------------

    public static PrintWriter out;

    //-----------MyScanner class for faster input----------

    public static class MyScanner {

      BufferedReader br;

      StringTokenizer st;

        public MyScanner() {

            br = new BufferedReader(new InputStreamReader(System.in));

        }

        // public MyScanner() throws FileNotFoundException {

        //     br = new BufferedReader(new FileReader("input.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;

        }

    }

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

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author lucasr
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		MyScanner in = new MyScanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		ACowAndHaybales solver = new ACowAndHaybales();
		int testCount = Integer.parseInt(in.next());
		for (int i = 1; i <= testCount; i++)
			solver.solve(i, in, out);
		out.close();
	}

	static class ACowAndHaybales {
		public static MyScanner sc;
		public static PrintWriter out;

		public void solve(int testNumber, MyScanner sc, PrintWriter out) {
			ACowAndHaybales.sc = sc;
			ACowAndHaybales.out = out;
			int n = sc.nextInt();
			int d = sc.nextInt();
			int[] piles = sc.nextIntArray(n);
			while (d > 0) {
				boolean found = false;
				for (int j = 1; j < n; j++) {
					if (piles[j] > 0 && j <= d) {
						piles[j]--;
						piles[0]++;
						d -= j;
						found = true;
						break;
					}
				}
				if (!found) break;
			}
			out.println(piles[0]);
		}

	}

	static class MyScanner {
		private BufferedReader br;
		private StringTokenizer tokenizer;

		public MyScanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

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

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

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

	}
}


F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values:  his departure station ajaj;  his arrival station bjbj;  minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1

import java.io.*;

import java.util.*;

public class Sol{

	public static List<Integer> adj[];

	public static int query[][];

	public static int get[][] = new int[5000][5000];

	public static int edge[];

	public static int par[];

	public static int depth[];

	public static int n, m, D;

	public static void main(String[] args) throws IOException{

		FastIO sc = new FastIO(System.in);

		PrintWriter out = new PrintWriter(System.out);

		boolean poss = true;

		n = sc.nextInt();

		par = new int[n];

		depth = new int[n];

		edge = new int[n-1];

		adj = new ArrayList[n];

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

			adj[i] = new ArrayList<>();

		}

		int idx = 0;

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

			int a = sc.nextInt()-1;

			int b = sc.nextInt()-1;

			adj[a].add(b);

			adj[b].add(a);

			get[a][b] = idx;

			get[b][a] = idx;

			idx++;

			edge[i] = -1;

		}

		depth[0] = 0;

		par[0] = 0;

		DFS(0, 0);

		int m = sc.nextInt();

		query = new int[m][3];

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

			query[i][0] =sc.nextInt()-1;

			query[i][1] = sc.nextInt()-1;

			query[i][2] = sc.nextInt();

		}

		ColumnSort(query, 2);

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

			boolean change = false;

			int num = query[i][2];

			int curr1 = query[i][0];

			int curr2 = query[i][1];

			while(curr1!=curr2) {

				if(depth[curr1]>depth[curr2]) {

					idx = get[curr1][par[curr1]];

					if(edge[idx]==-1||edge[idx]==num) {

						edge[idx] = num;

						change = true;

					}

					curr1 = par[curr1];

				}else {

					idx = get[curr2][par[curr2]];

					if(edge[idx]==-1||edge[idx]==num) {

						edge[idx] = num;

						change = true;

					}

					curr2 = par[curr2];

				}

			}

			if(!change) poss = false;

		}

		if(!poss) {

			out.println(-1);

		}else {

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

				out.print(Math.max(edge[i], 1) + " ");

			}

			out.println();

		}

		out.close();

	}

	public static void DFS(int curr, int p) {

		for(int i: adj[curr]) {

			if(i==p) continue;

			par[i] = curr;

			depth[i] = depth[curr]+1;

			DFS(i, curr);

		}

	}

    public static void ColumnSort(int arr[][], int col) {

        Arrays.sort(arr, new Comparator<int[]>() {

            @Override

          public int compare(int[] entry1,

                             int[] entry2) {

            	Integer a = entry1[col];

            	Integer b = entry2[col];

            	return a.compareTo(b);

          }

        });

    }

	static class FastIO {

		// Is your Fast I/O being bad?

		InputStream dis;

		byte[] buffer = new byte[1 << 17];

		int pointer = 0;

		public FastIO(String fileName) throws IOException {

			dis = new FileInputStream(fileName);

		}

		public FastIO(InputStream is) throws IOException {

			dis = is;

		}

		int nextInt() throws IOException {

			int ret = 0;

			byte b;

			do {

				b = nextByte();

			} while (b <= ' ');

			boolean negative = false;

			if (b == '-') {

				negative = true;

				b = nextByte();

			}

			while (b >= '0' && b <= '9') {

				ret = 10 * ret + b - '0';

				b = nextByte();

			}

			return (negative) ? -ret : ret;

		}

		long nextLong() throws IOException {

			long ret = 0;

			byte b;

			do {

				b = nextByte();

			} while (b <= ' ');

			boolean negative = false;

			if (b == '-') {

				negative = true;

				b = nextByte();

			}

			while (b >= '0' && b <= '9') {

				ret = 10 * ret + b - '0';

				b = nextByte();

			}

			return (negative) ? -ret : ret;

		}

		byte nextByte() throws IOException {

			if (pointer == buffer.length) {

				dis.read(buffer, 0, buffer.length);

				pointer = 0;

			}

			return buffer[pointer++];

		}

		String next() throws IOException {

			StringBuffer ret = new StringBuffer();

			byte b;

			do {

				b = nextByte();

			} while (b <= ' ');

			while (b > ' ') {

				ret.appendCodePoint(b);

				b = nextByte();

			}

			return ret.toString();

		}

	}

}