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

import geometry.Point;
import geometry.Vector;

public class CF_166_B_POLYGONS {

	static final double EPS = 10e-10;

	static double angle(Point a, Point o, Point b) {
		Vector oa = new Vector(o, a), ob = new Vector(o, b);
		return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2()));
	}

	static boolean ccw(Point p, Point q, Point r) {
		return new Vector(p, q).cross(new Vector(p, r)) > 0;
	}

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

		int n = sc.nextInt();

		Point[] p = new Point[n + 1];

		for (int i = 0; i < n; i++)
			p[i] = new Point(sc.nextDouble(), sc.nextDouble());

		p[n] = p[0];

		int m = sc.nextInt();

		while (m-- > 0)
			if (!inPolygon(p, new Point(sc.nextDouble(), sc.nextDouble()))) {
				System.out.println("NO");
				return;
			}

		System.out.println("YES");

	}

	static boolean inPolygon(Point[] p, Point target) {
		int low = 1;
		int high = p.length - 1;

		boolean ccw = crossPrdouct(p[0], p[1], p[p.length - 1]) == 1;

		if(!ccw)
		{
			int temp = low ;
			low = high;
			high = temp;

		}

		while (Math.abs(low - high) > 1) {
				int mid = (low + high) /2;

				if (crossPrdouct(p[0], p[mid], target) > 0)
					low = mid;
				else
					high = mid;

			}

		return crossPrdouct(p[low], p[high],target ) >0;

	}

	static double crossPrdouct(Point p, Point q, Point r)
	{
		Vector pq = new Vector(p, q);
		Vector pr = new Vector(p, r);
		double cross = pq.cross(pr);

		if(Math.abs(cross) > EPS)
			return cross > 0 ? 1 : -1;

		return 0;

	}

	static class Vector {

		double x, y;

		Vector(double a, double b) {
			x = a;
			y = b;
		}

		Vector(Point a, Point b) {
			this(b.x - a.x, b.y - a.y);
		}

		Vector scale(double s) {
			return new Vector(x * s, y * s);
		} // s is a non-negative value

		double dot(Vector v) {
			return (x * v.x + y * v.y);
		}

		double cross(Vector v) {
			return x * v.y - y * v.x;
		}

		double norm2() {
			return x * x + y * y;
		}

		Vector reverse() {
			return new Vector(-x, -y);
		}

		Vector normalize() {
			double d = Math.sqrt(norm2());
			return scale(1 / d);
		}
	}

	static class Point implements Comparable<Point> {

		static final double EPS = 1e-9;

		double x, y;

		Point(double a, double b) {
			x = a;
			y = b;
		}

		public int compareTo(Point p) {
			if (Math.abs(y - p.y) > EPS)
				return y > p.y ? 1 : -1;

			return 0;
		}

		public double dist(Point p) {
			return Math.sqrt(sq(x - p.x) + sq(y - p.y));
		}

		boolean between(Point p, Point q)
		{
			return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x)
					&& y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y);
		}

		static double sq(double x) {
			return x * x;
		}

	}

	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 {
			return br.ready();
		}

	}

}

You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.

The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.

Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).

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

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Andy Phan
 */
public class b {

    public static void main(String[] args) {
        FS in = new FS(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n = in.nextInt();
        VecL[] a = new VecL[n];

        for(int i = 0; i < n; i++) a[i] = new VecL(in.nextInt(), in.nextInt());

        TreeMap<Long, SegL> upper = new TreeMap<>();
        TreeMap<Long, SegL> lower = new TreeMap<>();

        for(int i = 0; i < n; i++) {
            SegL seg = new SegL(a[i], a[(i+1)%n]);
            if(a[i].x < a[(i+1)%n].x || (a[i].x == a[(i+1)%n].x && a[i].y > a[(i+1)%n].y)) upper.put(a[i].x, seg);
            else lower.put(a[i].x, seg);
        }

        int m = in.nextInt();
        for(int i = 0; i < m; i++) {
            VecL vec = new VecL(in.nextInt(), in.nextInt());
            Map.Entry<Long, SegL> upperE = upper.floorEntry(vec.x);
            Map.Entry<Long, SegL> lowerE = lower.ceilingEntry(vec.x);
            if(upperE == null || upperE.getValue().side(vec) != -1) {
                System.out.println("NO");
                return;
            }
            if(lowerE == null || lowerE.getValue().side(vec) != -1) {
                System.out.println("NO");
                return;
            }
        }

        System.out.println("YES");

        out.close();
    }

    static class SegL {

        VecL from, to, dir;

        public SegL(VecL from, VecL to) {
            this.from = from;
            this.to = to;
            dir = to.sub(from);
        }

        //check if the segment contains the point
        public boolean contains(VecL p) {
            VecL d = p.sub(from);
            if (d.cross(dir) != 0) {
                return false;
            }
            long dot = d.dot(dir);
            return dot >= 0 && dot <= dir.mag2();
        }

        //(assuming I go left to right)
        //returns:
        //	1 if point is above me
        //	0 if point is on me
        //	-1 if point is below me
        public long side(VecL o) {
            long cross = dir.cross(o.sub(from));
            return cross == 0 ? 0 : cross / Math.abs(cross);
        }

        //returns true if this segl intersects the other, including at endpoints
        //note: returns false if the two segments lie on the same line
        public boolean intersects(SegL o) {
            return side(o.from) != side(o.to) && o.side(from) != o.side(to);
        }

        public String toString() {
            return from + " -> " + to;
        }

        //#
        static long gcd(long a, long b) {
            a = Math.abs(a);
            b = Math.abs(b);
            return b == 0 ? a : gcd(b, a % b);
        }
        //$

        //returns the lattice point of intersection or null if it is nonlattice or does not exist
        public VecL latticeIntersect(SegL o) {
            if (!intersects(o)) {
                return null;
            }
            long dirGCD = gcd(dir.x, dir.y), oDirGCD = gcd(o.dir.x, o.dir.y);
            VecL va= new VecL(dir.x / dirGCD, dir.y / dirGCD), vb = new VecL(o.dir.x / oDirGCD, o.dir.y / oDirGCD);
            if (va.x < 0 && va.y < 0) {
                va.x *= -1;
                va.y *= -1;
            }
            if (vb.x < 0 && vb.y < 0) {
                vb.x *= -1;
                vb.y *= -1;
            }
            if (va.equals(vb)) {
                return null;
            }
            long bottomScalar = va.x / gcd(va.x, va.y);
            long topScalar = va.y / gcd(va.x, va.y);
            long t2Scalar = -bottomScalar * vb.y + topScalar * vb.x;
            long t2Ans = bottomScalar * (o.from.y - from.y) - topScalar * (o.from.x - from.x);
            if (t2Ans % t2Scalar != 0) {
                return null;
            }
            long t2 = t2Ans / t2Scalar;
            return new VecL(t2 * vb.x + o.from.x, t2 * vb.y + o.from.y);
        }
    }

    static class VecL implements Comparable<VecL> {

        long x, y;

        public VecL(long x, long y) {
            this.x = x;
            this.y = y;
        }

        public VecL add(VecL o) {
            return new VecL(x + o.x, y + o.y);
        }

        public VecL sub(VecL o) {
            return new VecL(x - o.x, y - o.y);
        }

        public VecL scale(long s) {
            return new VecL(x * s, y * s);
        }

        public long dot(VecL o) {
            return x * o.x + y * o.y;
        }

        public long cross(VecL o) {
            return x * o.y - y * o.x;
        }

        public long mag2() {
            return dot(this);
        }

        public VecL rot90() {
            return new VecL(-y, x);
        }

        public VecL rot270() {
            return new VecL(y, -x);
        }

        public String toString() {
            return "(" + x + ", " + y + ")";
        }

        public int hashCode() {
            return Long.hashCode(x << 13 ^ (y * 57));
        }

        public boolean equals(Object oo) {
            VecL o = (VecL) oo;
            return x == o.x && y == o.y;
        }

        public int compareTo(VecL o) {
            if (x != o.x) {
                return Long.compare(x, o.x);
            }
            return Long.compare(y, o.y);
        }

        //origin->q1, axes-> quadrant in ccw direction
        public int quadrant() {
            if (x == 0 || y == 0) {
                if (y == 0) {
                    if (x >= 0) {
                        return 1;
                    } else {
                        return 3;
                    }
                } else if (y >= 0) {
                    return 2;
                } else {
                    return 4;
                }
            }
            if (x > 0) {
                if (y > 0) {
                    return 1;
                } else {
                    return 4;
                }
            } else if (y > 0) {
                return 2;
            } else {
                return 3;
            }
        }

        public int radialCompare(VecL o) {
            if (quadrant() == o.quadrant()) {
                return -Long.signum(cross(o));
            }
            return Integer.compare(quadrant(), o.quadrant());
        }
    }

    static class FS {

        BufferedReader in;
        StringTokenizer token;

        public FS(InputStream str) {
            in = new BufferedReader(new InputStreamReader(str));
        }

        public String next() {
            if (token == null || !token.hasMoreElements()) {
                try {
                    token = new StringTokenizer(in.readLine());
                } catch (IOException ex) {
                }
                return next();
            }
            return token.nextToken();
        }

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


import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class CF123_D1_D{
	public static void main(String[] args)throws Throwable {
		MyScanner sc=new MyScanner();
		PrintWriter pw=new PrintWriter(System.out);

		char [] s=sc.next().toCharArray();
		SA=new SuffixAutomaton(s);
		int n=SA.idx+1;
		acceptState=new boolean [n];
		int cur=SA.idx;
		while(true){
			acceptState[cur]=true;
			if(cur==0)
				break;
			cur=SA.link[cur];
		}
		cnt=new long [n];
		Arrays.fill(cnt, -1);
		long ans=0;
		for(int i=0;i<=SA.idx;i++){
			long x=dfs(i);
			int cnt=SA.len[i]-SA.len[SA.link[i]];
			ans+=x*(x+1)*cnt/2;
		}
		pw.println(ans);
		pw.flush();
		pw.close();
	}
	static SuffixAutomaton SA;
	static boolean [] acceptState;
	static long [] cnt;

	static long dfs(int u){
		if(cnt[u]!=-1)
			return cnt[u];
		long ans=acceptState[u]? 1 : 0;
		for(Entry<Character, Integer> e : SA.nxt[u].entrySet()){
			int v=e.getValue();
			ans+=dfs(v);
		}
		return cnt[u]=ans;
	}

	static class SuffixAutomaton {
		int [] link,len;
		TreeMap<Character, Integer> [] nxt;
		int lst, idx;

		SuffixAutomaton(char [] s){
			int n=s.length;
			link=new int [n<<1];
			len=new int [n<<1];
			nxt=new TreeMap [n<<1];
			nxt[0]=new TreeMap<Character, Integer>();
			for(char c : s)
				addLeter(c);
		}

		void addLeter(char c){
			int cur = ++idx;
			int p=lst;
			while(!nxt[p].containsKey(c)){
				nxt[p].put(c, cur);
				p=link[p];
			}
			int q=nxt[p].get(c);

			// a node containing an edge with character c stopped me and it is not the root
			if(q!=cur){
				if(len[q]==len[p]+1)
					link[cur]=q;
				else{
					int clone=++idx;
					len[clone]=len[p]+1;
					link[clone]=link[q];
					nxt[clone]=new TreeMap<Character, Integer>(nxt[q]);
					link[cur]=link[q]=clone;
					while(nxt[p].get(c)==q){
						nxt[p].put(c, clone);
						p=link[p];
					}
				}
			}
			len[cur]=len[lst]+1;
			nxt[cur]=new TreeMap<Character, Integer>();
			lst=cur;
		}

	}

	static class MyScanner {
		BufferedReader br;
		StringTokenizer st;
		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {while (st == null || !st.hasMoreElements()) {
			try {st = new StringTokenizer(br.readLine());}
			catch (IOException e) {e.printStackTrace();}}
		return st.nextToken();}
		int nextInt() {return Integer.parseInt(next());}
		long nextLong() {return Long.parseLong(next());}
		double nextDouble() {return Double.parseDouble(next());}
		String nextLine(){String str = "";
		try {str = br.readLine();}
		catch (IOException e) {e.printStackTrace();}
		return str;}
	}
}

You are given a string s. Each pair of numbers l and r that fulfill the condition 1 ≤ l ≤ r ≤ |s|, correspond to a substring of the string s, starting in the position l and ending in the position r (inclusive).Let's define the function of two strings F(x, y) like this. We'll find a list of such pairs of numbers for which the corresponding substrings of string x are equal to string y. Let's sort this list of pairs according to the pair's first number's increasing. The value of function F(x, y) equals the number of non-empty continuous sequences in the list.For example: F(babbabbababbab, babb) = 6. The list of pairs is as follows:(1, 4), (4, 7), (9, 12)Its continuous sequences are:   (1, 4)  (4, 7)  (9, 12)  (1, 4), (4, 7)  (4, 7), (9, 12)  (1, 4), (4, 7), (9, 12) Your task is to calculate for the given string s the sum F(s, x) for all x, that x belongs to the set of all substrings of a string s.

The only line contains the given string s, consisting only of small Latin letters (1 ≤ |s| ≤ 105).

Print the single number — the sought sum. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

NoteIn the first sample the function values at x equal to "a", "aa", "aaa" and "aaaa" equal 10, 6, 3 and 1 correspondingly.In the second sample for any satisfying x the function value is 1.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Deque;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Rustam Musin (t.me/musin_acm)
 */
public class Main {
  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    OutputWriter out = new OutputWriter(outputStream);
    DStroka solver = new DStroka();
    solver.solve(1, in, out);
    out.close();
  }

  static class DStroka {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      String s = in.next();
      long answer = new DStroka.Solve(s).solve();
      out.print(answer);
    }

    static long sum(long n) {
      return n * (n + 1) / 2;
    }

    static class Solve {
      int n;
      char[] s;
      int[] order;
      int[] type;
      int[] lcp;

      Solve(String s) {
        s += "$";
        this.s = s.toCharArray();
        n = s.length();
      }

      long solve() {
        initSuffixArray();
        initLCP();
        DS ds = new DS();
        for (int i = 1; i < n; i++) ds.update(i);
        return ds.finish();
      }

      void updateTypes(int len) {
        int[] type2 = new int[n];
        type2[order[0]] = 0;
        for (int i = 1, j = 0; i < n; i++) {
          int left1 = type[order[i]];
          int left2 = type[order[i - 1]];
          int right1 = type[(order[i] + len) % n];
          int right2 = type[(order[i - 1] + len) % n];
          if (left1 != left2 || right1 != right2) j++;
          type2[order[i]] = j;
        }
        System.arraycopy(type2, 0, type, 0, n);
      }

      void countSort(int typeCount, int len) {
        int[] count = new int[typeCount];
        for (int t : type) count[t]++;
        for (int i = 0, j = 0; i < typeCount; i++) {
          int x = count[i];
          count[i] = j;
          j += x;
        }
        int[] order2 = new int[n];
        for (int x : order) order2[count[type[x]]++] = x;
        System.arraycopy(order2, 0, order, 0, n);
        updateTypes(len);
      }

      void initSuffixArray() {
        order = new int[n];
        type = new int[n];
        for (int i = 0; i < n; i++) order[i] = i;
        for (int i = 0; i < n; i++) type[i] = s[i];
        countSort(1 << 8, 0);
        for (int len = 1, typeCount; (typeCount = type[order[n - 1]] + 1) < n; len <<= 1) {
          for (int i = 0; i < n; i++) order[i] = (order[i] - len + n) % n;
          countSort(typeCount, len);
        }
      }

      void initLCP() {
        lcp = new int[n];
        for (int i = 0, k = 0; i < n - 1; i++) {
          int pi = type[i];
          int j = order[pi - 1];
          while (s[i + k] == s[j + k]) k++;
          lcp[pi] = k;
          if (k > 0) k--;
        }
      }

      class DS {
        Deque<IntIntPair> q;
        long total = 0;

        DS() {
          q = new ArrayDeque<>();
          q.add(IntIntPair.makePair(-1, 0));
        }

        void drop(int at) {
          while (q.peekLast().first > at) {
            IntIntPair cur = q.pollLast();
            if (q.peekLast().first == cur.first) {
              q.addLast(IntIntPair.makePair(cur.first, cur.second + q.pollLast().second));
              continue;
            }
            int left = Math.max(q.peekLast().first, at) + 1;
            int right = cur.first;
            int len = right - left + 1;
            total += len * sum(cur.second);
            q.addLast(IntIntPair.makePair(left - 1, cur.second));
          }
        }

        void update(int i) {
          drop(lcp[i] - 1);
          int lastIndex = n - 2 - order[i];
          q.addLast(IntIntPair.makePair(lastIndex, 1));
        }

        long finish() {
          drop(-1);
          return total;
        }

      }

    }

  }

  static class IntIntPair implements Comparable<IntIntPair> {
    public final int first;
    public final int second;

    public static IntIntPair makePair(int first, int second) {
      return new IntIntPair(first, second);
    }

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

    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      IntIntPair pair = (IntIntPair) o;

      return first == pair.first && second == pair.second;
    }

    public int hashCode() {
      int result = first;
      result = 31 * result + second;
      return result;
    }

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

    public int compareTo(IntIntPair o) {
      int value = Integer.compare(first, o.first);
      if (value != 0) {
        return value;
      }
      return Integer.compare(second, o.second);
    }

  }

  static class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private InputReader.SpaceCharFilter filter;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (numChars == -1) {
        throw new InputMismatchException();
      }
      if (curChar >= numChars) {
        curChar = 0;
        try {
          numChars = stream.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (numChars <= 0) {
          return -1;
        }
      }
      return buf[curChar++];
    }

    public String readString() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      StringBuilder res = new StringBuilder();
      do {
        if (Character.isValidCodePoint(c)) {
          res.appendCodePoint(c);
        }
        c = read();
      } while (!isSpaceChar(c));
      return res.toString();
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next() {
      return readString();
    }

    public interface SpaceCharFilter {
      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
      this.writer = new PrintWriter(writer);
    }

    public void close() {
      writer.close();
    }

    public void print(long i) {
      writer.print(i);
    }

  }
}

[{'input': 'aaaa\r\n', 'output': ['20\r\n']}, {'input': 'abcdef\r\n', 'output': ['21\r\n']}, {'input': 'abacabadabacaba\r\n', 'output': ['188\r\n']}, {'input': 'tkth\r\n', 'output': ['11\r\n']}, {'input': 'eqkrqe\r\n', 'output': ['23\r\n']}, {'input': 'cwuiax\r\n', 'output': ['21\r\n']}, {'input': 'hhhhqhqh\r\n', 'output': ['59\r\n']}, {'input': 'gmxfmcgp\r\n', 'output': ['38\r\n']}, {'input': 'eleellleeee\r\n', 'output': ['104\r\n']}, {'input': 'usussubuubbbbs\r\n', 'output': ['138\r\n']}, {'input': 'lhmpaugvnqzrfxke\r\n', 'output': ['136\r\n']}, {'input': 'xkkkkkkkkkkkkkkkkxkkkk\r\n', 'output': ['1098\r\n']}, {'input': 'pprppppriiriiiirprppprriir\r\n', 'output': ['512\r\n']}, {'input': 'jsoxkutcvyshsinfmtrpujedcbmyqlojzco\r\n', 'output': ['646\r\n']}, {'input': 'emcegmekgnlefkeguqkfffnduqhfhhhndlfhlfdqdncefnn\r\n', 'output': ['1227\r\n']}, {'input': 'ffffdjfddffdjdfffddjfffffffjfffjdjfffjfjfdjjfjdjjdjjjdffd\r\n', 'output': ['2564\r\n']}, {'input': 'cxvhmeyouudwuglhbwndzwmjjsgrnuwnzwaycfspyyrdckjcidfsabvdxzjkvm\r\n', 'output': ['2023\r\n']}, {'input': 'cahdktuxuukmbuqcqactqhqdcxpkqcuumckttdpmpqxxkacpappxuqkxbuahqdphhddhquthqaapm\r\n', 'output': ['3258\r\n']}, {'input': 'hhwhhwhhhwhwwhhwwwhwhhhwhwwwhhwhwhhhhhhwhwhwwwhhwwwhhwhhhhwhwwhwhwwwwhhwwhwhwwwhhhwwhwhwhhwwwhwhhhwwwhwhw\r\n', 'output': ['10856\r\n']}, {'input': 'cnrkvxbljhitbvoysdpghhhnymktvburpvxybnvugkzudmnmpuhevzyjpbtraaepszhhssmcozkgbjayztrvqwdfmjlhtvarkkdsbnjrabqexpfjozmjzfbmdsihovoxmmtjgtfyaisllysnekdxozhdwu\r\n', 'output': ['12399\r\n']}, {'input': 'qasiyhdivaiyyhdqiqsvqhtqsetxqvaeqatxesxehisyqiivhvayaxvsxhsydiesaxydysqhedxqhsqivvidqtsitiiveexiehsqdteahyxtsyqetahviyhqvytexethsqssxiytqhxxxdihxietsyxqhtitheyeateeyhythxhhqaad\r\n', 'output': ['17103\r\n']}, {'input': 'ggwgwwgwwkggwgwwkgwwwggwwwggkgkgwkwgkkgkwwgwkkggwggkwgwgkgwwkwkkkkwggwwkwkkkgwkwwwwwgwkwkkwkggwwgggkkwwkgkgkwgkgkwggkwgggwwkgkwgkwkkgwkkkkggwwwgkggkwwgkwkgwgggkggkkkwwwwwkkgkwggwgkwwwwggwwgkkggwkkwkkgkwggggggkkwkkgkkkwkwwkwggwkkwggggwg\r\n', 'output': ['41166\r\n']}, {'input': 'tmoqyzoikohtgkybnwjizgjypzycmtstmsizrqrmczmqmpewxiwlqzcaufxkchqyjegktxihlksisbgogpyxkltioovelwaqcbebgcyygxsshsirkwvtsvhpqtbomueaszkrlixueyeiccvfiuoogomjlhjkacnxtimkprmjttpmeaminvmcqagrpjighsvaosojymcjoyopsvkrphzbnckcvvckicmjwpvawjuzkofnuvcahwhzjpfngwyobiufivsjnekjcloobvzawrvosnkvalmr\r\n', 'output': ['42165\r\n']}, {'input': 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\r\n', 'output': ['2214420\r\n']}, {'input': 'zzzzooozzzoozozoozzzzzzozooozoozoozzozzozoooozzzzzzoooozzozooozoozzzozozoooooozzzozozooooozozozozzooozozzooozzzzozozoozoozzzozooozzzzoozzzzozzzzoooozozozozozzoooozzzooozzoooooooozozzozozooozzzooooozozooozozzozozoozzozzzzooozzoozozozzozozoozozzzoozozoooozzooozozooooozzzzzoozoozzzozzzoozzoozozzooozzzzzzoozzozzoozzzoozozzooozoozzzozooozozzoozoozozzzzzoozoozzzooooozooooooozooooozzoozoozzzooooozoozozozozzzoozzzzzoozzzzzzooooooozzzzozzozzo\r\n', 'output': ['190205\r\n']}]


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

public class D {
	static char[] s;
	static int n, cor[];
	static int[][][][] memo;
	static int mod = (int) 1e9 + 7;

	static int dp(int i, int j, int ci, int cj) {
		if (i >= j)
			return 1;
		if (memo[i][j][ci][cj] != -1)
			return memo[i][j][ci][cj];
		long res = 0;
		if(j != cor[i] || cj != 2)
			res = (res + 1l*dp(i+1, cor[i]-1, ci, 2)*dp(cor[i]+1, j, 2, cj)%mod) % mod;
		if(j != cor[i] || cj != 1)
			res = (res + 1l*dp(i+1, cor[i]-1, ci, 1)*dp(cor[i]+1, j, 1, cj)%mod) % mod;
		if(ci == 0){
			res = (res + 1l*dp(i+1, cor[i]-1, 1, 0)*dp(cor[i]+1, j, 0, cj)%mod) % mod;
			res = (res + 1l*dp(i+1, cor[i]-1, 2, 0)*dp(cor[i]+1, j, 0, cj)%mod) % mod;
		}
		else{
			res = (res + 1l*dp(i+1, cor[i]-1, ci==1?2:1, 0)*dp(cor[i]+1, j, 0, cj)%mod) % mod;
		}
//		System.out.println(i + " " + j + " " + ci + " " + cj + " " + res);
		return memo[i][j][ci][cj] = (int) res;
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		Scanner sc = new Scanner();
		PrintWriter out = new PrintWriter(System.out);
		s = sc.next().toCharArray();
		n = s.length;
		memo = new int[n + 1][n + 1][3][3];
		for (int[][][] i : memo)
			for (int[][] j : i)
				for (int[] k : j)
					Arrays.fill(k, -1);
		cor = new int[n];
		Stack<Integer> st = new Stack<>();
		for (int i = 0; i < s.length; i++) {
			if (s[i] == '(')
				st.add(i);
			else {
				int tmp = st.pop();
				cor[i] = tmp;
				cor[tmp] = i;
			}
		}
//		System.out.println(Arrays.toString(cor));
		out.println(dp(0, n-1, 0, 0));
		out.flush();
		out.close();
	}

	static class Scanner {
		BufferedReader bf;
		StringTokenizer st;

		public Scanner() {
			bf = new BufferedReader(new InputStreamReader(System.in));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(bf.readLine());
			return st.nextToken();
		}

		public int nextInt() throws NumberFormatException, IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws NumberFormatException, IOException {
			return Double.parseDouble(next());
		}

		public long nextLong() throws NumberFormatException, IOException {
			return Long.parseLong(next());
		}
	}
}

Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not.In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one.   You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled:   Each bracket is either not colored any color, or is colored red, or is colored blue.  For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored.  No two neighboring colored brackets have the same color. Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109 + 7).

The first line contains the single string s (2 ≤ |s| ≤ 700) which represents a correct bracket sequence.

Print the only number — the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109 + 7).

NoteLet's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below.     The two ways of coloring shown below are incorrect.

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

public class D
{
    private static int [] pair;
    private static final int MOD = 1000000000 + 7;
    private static long [][][][] memo;
    public static void main(String[] strings) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        char [] str = reader.readLine().toCharArray();
        int n = str.length;
        int [] last = new int[n/2+1];
        Arrays.fill(last, -1);

        pair = new int[n];
        int sum = 0;
        for(int i = 0 ; i < n ; i++)
        {
            sum += str[i] == '(' ? 1 : -1;
            if(str[i] == ')')
            {
                pair[last[sum+1]] = i;
                pair[i] = last[sum+1];
            }
            else
                last[sum] = i;
        }

        memo = new long[n][n][3][3];
        for(long [][][] fill1 : memo)
            for(long [][] fill2 : fill1)
                for(long [] fill3 : fill2)
                    Arrays.fill(fill3, -1);

        long res = rec(0, n-1, 2, 2);
        System.out.println(res);
    }

    private static long rec(int left, int right, int pLeft, int pRight)
    {
        if(left > right)
            return 1;

        if(memo[left][right][pLeft][pRight] != -1)
            return memo[left][right][pLeft][pRight];

        int mid = pair[left];
        long res = 0;

        res += (pLeft*(rec(left+1, mid-1, 1, 2) * rec(mid+1, right, 2, pRight))%MOD)%MOD;
        res %= MOD;
        res += ((right == mid ? pRight : 2)*(rec(left+1, mid-1, 2, 1) * rec(mid+1, right, 1, pRight))%MOD)%MOD;
        res %= MOD;

        return memo[left][right][pLeft][pRight] = res;
    }
}


//package round83;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class C3 {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		long y = nl()-2001;
		int m = ni();

		int[][] lt = new int[m][2];
		for(int i = 0;i < m;i++){
			lt[i][0] = ni() - 1;
			lt[i][1] = ni() - 1;
		}

		int[] a = new int[n];
		int used = 0;
		outer:
		for(int i = 0;i < n;i++){
			inner:
			for(int j = 0;j < n;j++){
				if(used<<31-j>=0){
					a[i] = j;
					for(int k = 0;k < m;k++){
						if(lt[k][0] <= i && lt[k][1] <= i && a[lt[k][0]] > a[lt[k][1]])continue inner;
					}

					int L = n-i-1;
					long[] dp = new long[1<<L]; // position
					dp[0] = 1;
					int[] left = new int[n];
					int lp = 0;
					for(int k = 0;k < n;k++){
						if(used<<31-k>=0)left[lp++] = k;
					}

					for(int k = 1;k < 1<<L;k++){
						int h = Integer.bitCount(k)-1;
						iinner:
						for(int l = 0;l < L;l++){
							if(k<<31-l<0){
								for(int f = 0;f < m;f++){
									if(lt[f][0] <= i && lt[f][1] == i+1+l && a[lt[f][0]] > left[h])continue iinner;
									if(lt[f][0] == i+l+1 && lt[f][1] <= i && left[h] > a[lt[f][1]])continue iinner;
									if(lt[f][0] == i+l+1 && lt[f][1] > i && k<<31-(lt[f][1]-(i+1))<0)continue iinner;
								}
								dp[k] += dp[k^1<<l];
							}
						}
					}

					long v = dp[(1<<L)-1];
					if(y < v){
						used |= 1<<j;
						continue outer;
					}else{
						y -= v;
					}
				}
			}
			out.println("The times have changed");
			return;
		}
		for(int i = 0;i < n;i++){
			if(i > 0)out.print(' ');
			out.print(a[i]+1);
		}
		out.println();
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception
	{
		new C3().run();
	}

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}

In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far.The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall.Traditionally GUC has n professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from 1 to n, with 1 being the most senior professor and n being the most junior professor.The ceremonial hall has n seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, m pairs of seats are in "senior-junior" relation, and the tradition requires that for all m pairs of seats (ai, bi) the professor seated in "senior" position ai should be more senior than the professor seated in "junior" position bi.GUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that:   The seating of the professors changes every year.  Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall.  Each consecutive year lexicographically next arrangement of the professors is used. The arrangement of the professors is the list of n integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc.Given n, the number of professors, y, the current year and m pairs of restrictions, output the arrangement of the professors for this year.

The first line contains three integers n, y and m (1 ≤ n ≤ 16, 2001 ≤ y ≤ 1018, 0 ≤ m ≤ 100) — the number of professors, the year for which the arrangement should be computed, and the number of pairs of seats for which the seniority relation should be kept, respectively. The next m lines contain one pair of integers each, "ai bi", indicating that professor on the ai-th seat is more senior than professor on the bi-th seat (1 ≤ ai, bi ≤ n, ai ≠ bi). Some pair may be listed more than once. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin stream (you may also use the %I64d specificator).

Print the order in which the professors should be seated in the requested year. If by this year the GUC would have ran out of arrangements, or the given "senior-junior" relation are contradictory, print "The times have changed" (without quotes).

NoteIn the first example the lexicographically first order of seating is 1 2 3.In the third example the GUC will run out of arrangements after the year 3630800.In the fourth example there are no valid arrangements for the seating.The lexicographical comparison of arrangements is performed by the < operator in modern programming languages. The arrangement a is lexicographically less that the arrangement b, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.

1 2 3
1 2 3 7 4 6 5
The times have changed
The times have changed

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.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
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);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        long[][] dp;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            long y = in.nextLong() - 2000;
            int m = in.nextInt();

            final String noSolution = "The times have changed";

            boolean[][] graph = new boolean[n][n];
            for (int i = 0; i < m; ++i) {
                int x = in.nextInt() - 1, t = in.nextInt() - 1;
                graph[x][t] = true;
            }

            boolean[][] accesible = new boolean[n][n];
            for (int i = 0; i < n; ++i) {
                dfs(graph, accesible[i], i);
            }

            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (i != j && accesible[i][j] && accesible[j][i]) {
                        out.println(noSolution);
                        return;
                    }
                }
            }

            int[] g = new int[n];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (accesible[i][j])
                        g[i] |= 1 << j;
                }
            }

            dp = new long[n + 1][1 << n];
            int[] pos = new int[n];
            Arrays.fill(pos, -1);

            if (count(pos, g) < y) {
                out.println(noSolution);
                return;
            }

            int[] fans = new int[n];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (pos[j] != -1) continue;

                    pos[j] = i;
                    long x = count(pos, g);
                    if (x < y) {
                        y -= x;
                    } else {
                        fans[i] = j;
                        break;
                    }
                    pos[j] = -1;
                }
            }

            for (int i = 0; i < n; ++i)
                out.print((fans[i] + 1) + " ");
            out.println();
        }

        private void dfs(boolean[][] graph, boolean[] accesible, int node) {
            accesible[node] = true;
            for (int i = 0; i < graph.length; ++i) {
                if (graph[node][i] && !accesible[i]) {
                    dfs(graph, accesible, i);
                }
            }
        }

        private long count(int[] pos, int[] g) {
            int n = pos.length;
            int used = 0;
            for (int i = 0; i < n; ++i) {
                if (pos[i] != -1)
                    used |= 1 << pos[i];
            }
            for (long[] p : dp) {
                Arrays.fill(p, 0);
            }
            dp[0][0] = 1;
            for (int i = 0; i < n; ++i) {
                for (int conf = 0; conf < 1 << n; ++conf) {
                    if (dp[i][conf] == 0) continue;
                    for (int j = 0; j < n; ++j) {
                        if ((conf & g[j]) != 0) continue;
                        if ((pos[i] == -1 && (used & (1 << j)) == 0) ||
                                pos[i] == j) {
                            dp[i + 1][conf | (1 << j)] += dp[i][conf];
                        }
                    }
                }
            }
            return dp[n][(1 << n) - 1];
        }

    }

    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 long nextLong() {
            return Long.parseLong(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;
        }

    }
}


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

public class A {

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

		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt(), m = sc.nextInt(), a = sc.nextInt() - 1, b = sc.nextInt() - 1;

		if(a % m == 0 && b % m == m - 1)
			out.println(1);
		else if(a / m == b / m || a % m == 0 && b == n - 1)
			out.println(1);
		else if(a / m + 1 == b / m || a % m == b % m + 1 || a % m == 0 || b % m == m - 1)
			out.println(2);
		else
			out.println(3);
		out.flush();
		out.close();
	}

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

	}
}

Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.

The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.

Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.

NoteThe images below illustrate statement tests.The first test:In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.The second test:In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.

import java.util.Scanner;

public class frames {
public static void main(String args[]){
	Scanner s = new Scanner(System.in);
	int n = s.nextInt(),m=s.nextInt(),a=s.nextInt(),b=s.nextInt();
	if(a<=m&&b<=m){
		System.out.println(1);
	}
	else if(m==1||a==b){
		System.out.println(1);
	}
	else if(b-a<m&&(b/m-1==a/m)&&b%m==0){

	System.out.println(1);
	}
	else if(b-a<m&&(b/m==a/m)&&a%m!=0){

		System.out.println(1);
	}
	else if(a%m==1&&n==b){
		System.out.println(1);
	}
	else if (a%m==1&&b%m==0){
		System.out.println(1);
	}
	else if (a%m!=1&&b%m==0){
		System.out.println(2);
	}
	else if (a%m==1&&b%m!=0){
		System.out.println(2);
	}
	else if (a%m!=1&&b==n||(a%m==0&&(b%m==m-1))){

		System.out.println(2);
	}
	else if (a%m-b%m==1){
		System.out.println(2);
	}
	else if(a%m==0&&b%m!=0&&a/m==b/m){

		System.out.println(2);
	}
	else if(a%m!=0&&b%m!=0&&a/m==b/m-1){
		System.out.println(2);

	}

	else
		System.out.println(3);

}
}


import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;

/* Name of the class has to be "Main" only if the class is public*/
public class CF602C
{
    static class FastReader {

        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

    static class Node {

        long pp;
        long a, b;

        Node(long x, long y) {
            a = x;
            b = y;
            pp = a * b;
        }
    }
    static class Comp implements Comparator<Node> {

        public int compare(Node o1, Node o2) {
            if (o1.pp > o2.pp) {
                return 1;
            } else {
                return -1;
            }
        }
    }
    public static void main(String[] args) {
        FastReader sc=new FastReader();
        PrintWriter out=new PrintWriter(System.out);
        //your code starts here
        int n=sc.nextInt();
        LinkedList<Integer> adj[]=new LinkedList[n];
        int m=sc.nextInt();
        for(int i=0;i<n;i++) adj[i]=new LinkedList();
        for(int i=0;i<m;i++)
        {
            int a=sc.nextInt()-1;
            int b=sc.nextInt()-1;
            // adding edges of undirected graph
            adj[a].add(b);
            adj[b].add(a);
        }
        if(m==0 || m==(n*(n-1)/2)) {
            out.println(-1); out.close(); return;
        }
        int[] dist=new int[n]; Arrays.fill(dist, Integer.MAX_VALUE);
        dist[0]=0;
        boolean visited[]=new boolean[n];
        Queue<Integer> pq=new LinkedList();
        pq.add(0); visited[0]=true;
        while(!pq.isEmpty())
        {
            int s=pq.poll();
            visited[s]=true;
            for(int node : adj[s])
            {
                if(visited[node]) continue;
                visited[node]=true;
                dist[node]=dist[s]+1;
                pq.add(node);
            }
        }
        //for(int i:dist) out.print(i+" ");
         if(dist[n-1]==Integer.MAX_VALUE) out.println(-1);
         else out.println(dist[n-1]);
        out.close();
    }
}

In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

NoteIn the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;

/* Name of the class has to be "Main" only if the class is public*/
public class CF602C
{
    static class FastReader {

        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

    static class Node {

        long pp;
        long a, b;

        Node(long x, long y) {
            a = x;
            b = y;
            pp = a * b;
        }
    }
    static class Comp implements Comparator<Node> {

        public int compare(Node o1, Node o2) {
            if (o1.pp > o2.pp) {
                return 1;
            } else {
                return -1;
            }
        }
    }
    public static void main(String[] args) {
        FastReader sc=new FastReader();
        PrintWriter out=new PrintWriter(System.out);
        //your code starts here
        int n=sc.nextInt();
        boolean adj[][]=new boolean[n][n];
        int m=sc.nextInt();
        for(int i=0;i<m;i++)
        {
            int a=sc.nextInt()-1;
            int b=sc.nextInt()-1;
            // adding edges of undirected graph
            adj[a][b]=true; adj[b][a]=true;
        }
        if(m==0 || m==(n*(n-1)/2)) {
            out.println(-1); out.close(); return;
        }
        int[] dist=new int[n]; Arrays.fill(dist, Integer.MAX_VALUE);
        dist[0]=0;
        Queue<Integer> q=new LinkedList();
        q.add(0);
        while(!q.isEmpty())
        {
            int s=q.poll();
            for(int i=0;i<n;i++)
            {
                if(!adj[0][n-1] && adj[s][i])
                {
                    if(dist[i]==Integer.MAX_VALUE) {
                    dist[i]=dist[s]+1;
                    q.add(i);
                    }
                }
                else if(!adj[s][i] && adj[0][n-1])
                {
                    if(dist[i]==Integer.MAX_VALUE)
                    {
                        dist[i]=dist[s]+1;
                        q.add(i);
                    }
                }
            }
        }
        //for(int i:dist) out.print(i+" ");
         if(dist[n-1]==Integer.MAX_VALUE) out.println(-1);
         else out.println(Math.max(1,dist[n-1]));
        out.close();
    }
}


from collections import defaultdict
n, t = int(input()), input().split()
p = defaultdict(int)
for i in t:
    p[i] += 1
if len(p) < 3: print(0)
else:
    q = list(p.items())
    a, b = q[0][1], q[1][1]
    x, y = 0, 1
    if a < b: x, y, a, b = y, x, b, a
    for i in range(2, len(q)):
        if q[i][1] > b:
            if q[i][1] > a: x, y, a, b = i, x, q[i][1], a
            else: y, b = i, q[i][1]
    k = n // 3
    if a > k:
        c, s = n - a - b, n - a
        if c > b: q[x], q[y], k = (q[x][0], (s >> 1)), (q[y][0], b - (s & 1)), (s >> 1)
        #(q[y][0], b - (s & 1)), (s >> 1)
        else: q[x], q[y], k = (q[x][0], c), (q[y][0], c), c
    q = [(int(x), y) for x, y in q]
    q.sort(reverse = True)
    p, n = [], 2 * k
    for i in q:
        p += [str(i[0]) + ' ']  * i[1]
    print(k)
    print('\n'.join(p[i] + p[k + i] + p[n + i] for i in range(k)))
    #mas facil estaba examen de Cappo

Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled:  Each boy plays for exactly one team (x + y = n).  The sizes of teams differ in no more than one (|x - y| ≤ 1).  The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.

The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills.

On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.

NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.

n = int(input())
a = list(map(int, input().split()))
all = []
for i in range(n):
    all.append([a[i], i + 1])

all.sort(key = lambda x: x[0])

team_1 = []
team_2 = []
for i in range(n):
    if i % 2 == 0:
        team_1.append(all[i][1])
    else:
        team_2.append(all[i][1])

print(len(team_1))
print(*team_1)
print(len(team_2))
print(*team_2)


n=int(input())
L=list(map(int,input().split()))
m=int(input())
M=list(map(int,input().split()))
N=[]
maxi=0
count=0
for i in range(0,m):
	for j in range(0,n):
		temp=L[i]//M[j]
		if(L[i]%M[j]==0):
			N.append(temp)
			if(temp>maxi):
				maxi=temp

for i in range(0,len(N)):
	if(N[i]==maxi):
		count+=1

print(count)

Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

import collections as cl

n, a = int(input()), map(int, input().split())
m, b = int(input()), list(map(int, input().split()))

ans = cl.Counter([xb // xa for xa in a for xb in b if xb % xa == 0])
print(ans[max(ans.keys())])


n, x, y = int(input()),int(input()),int(input())

a = y-n+1

if a**2 + n - 1 >= x:
    print(a)
    for i in range(n-1):
        print(1)
else:
    print(-1)

Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: a12 + a22 + ... + an2 ≥ x a1 + a2 + ... + an ≤ y

The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use cin, cout streams or the %I64d specificator.

Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.

n, x, y = map(int, input().split())
if y < n:
     print(-1)
else:
    q = y - n + 1
    if (q ** 2 + n - 1) >= x:
        print(q)
        for i in  range(n - 1):
            print(1)
    else:
        print(-1)


from math import sqrt

n, v1, v2 = [int(i) for i in input().split()]
x = [int(i) for i in input().split()]
x1, y1 = [int(i) for i in input().split()]

minim = x[1] / v1 + sqrt((x1-x[1])**2 + (y1)**2) / v2 #Время, если студен выйдет на первой остановке и побежит (если он быстрее автобуса)
res = 2
for i in range(2, n):
    t = x[i] / v1 + sqrt((x1-x[i])**2 + (y1)**2) / v2
    if t < minim:
        minim = t
        res = i + 1
    elif t == minim and sqrt((x1-x[res-1])**2 + (y1)**2) < sqrt((x1-x[i])**2 + (y1)**2):
        res = i+1
print(res)

And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

from math import sqrt

n, v1, v2 = [int(i) for i in input().split()]
x = [int(i) for i in input().split()]
x1, y1 = [int(i) for i in input().split()]

minim = x[1] / v1 + sqrt((x1-x[1])**2 + (y1)**2) / v2 #Время, если студен выйдет на первой остановке и побежит (если он быстрее автобуса)
res = 2
for i in range(2, n):
    t = x[i] / v1 + sqrt((x1-x[i])**2 + (y1)**2) / v2
    if t < minim:
        minim = t
        res = i + 1
    elif t == minim and sqrt((x1-x[res-1])**2 + (y1)**2) > sqrt((x1-x[i])**2 + (y1)**2):
        res = i+1
print(res)


import sys

answer = [0,0,0,0,0]
n = map(int,raw_input().split())[0]
p = map(int,raw_input().split())
balance = 0
prices = map(int,raw_input().split())[::-1]
#print prices
for i in xrange(n):
    balance += p[i]
    j = 0
    while(j<5):
        #print i, balance, j
        if (balance>=prices[j]):
            answer[j]+=1
            balance-=prices[j]
            j -= 1
        j+=1
        #print j
print " ".join(map(str,answer[::-1]))
print balance

Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

n = int(raw_input())
pts = [int(i) for i in raw_input().split()]
goods = [int(i) for i in raw_input().split()]

left = 0
gets = [0]*5
for p in pts:
    left += p
    for i in xrange(4, -1, -1):
        gets[i] += left/goods[i]
        left %= goods[i]
print gets[0], gets[1], gets[2], gets[3], gets[4]
print left


#!/usr/local/bin/python

n,limit = map(int,raw_input().split(" "))
ary = map(int,raw_input().split(" "))
comp = ["-" for i in xrange(n)]

num = 0
while True:
        if ary == comp:
                print num
                exit()
        t = 0
        for i in xrange(len(ary)):
                if ary[i] == "-":
                        continue
                if i == 0 or t == 0:
                        tmp = ary[i]
                        ary[i] += 1
                        t = 1
                elif tmp != ary[i]:
                        tmp = ary[i]
                        ary[i] += 1
                if ary[i] == limit:
                        ary[i] = "-"
        num += 1

In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.

The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.

# -*- coding: utf-8 -*-

N , K = [int(n) for n in raw_input().split(" ")]
r = []
num = raw_input().split(" ")
#N , K = 100 , 100
#num = [1 for i in xrange(100)]

for i in xrange(K):
    r.append(0)
for n in num:
    t = int(n)
    r[t - 1] += 1
cnt = 0
while True:
    i = 0
    while i < K - 1 and r[i] == 0:
        i += 1
    if i == K - 1:
        break
    for i in xrange(K - 2 , -1 , -1):
        #print i,
        if r[i] != 0:
            r[i] -= 1
            r[i + 1] += 1
    #print
    cnt += 1
print cnt


n = int(input())
st = list(input())
ans = 0
i = 0
while st and i < len(st):
    if st[i] == 'L':
        n -= i + 1
        st = st[i + 1:]
        i = -1
    elif st[i] == 'R':
        n -= 1
        for j in range(i + 1, len(st)):
            if st[j] == 'L':
                n -= j - i
                if (j - i) % 2 == 0:
                    n += 1
                st = st[j + 1:]
                i = -1
                break
            if st[j] == 'R':
                n -= j - i - 1
                st = st[j:]
                i = -1
                break
        n -= j - i
    i += 1
print(n)

Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

n = int(input())
s = input()
s = list(s)
v = 0
while(True):
    lExits = False
    rExits = False
    if ('L' in s):
        l = s.index('L')
        lExits = True
    if ('R' in s):
        r = s.index('R')
        rExits = True
    if (lExits == False and rExits == False):
        break
    if (lExits == True and rExits == False):
        for i in range(l+1):
            s[i] = 'F'
        break
    if (lExits == False and rExits == True):
        for i in range(r,n):
            s[i] = 'F'
        break
    if (lExits == True and rExits == True):
        if (l < r):
            for i in range(l+1):
                s[i] = 'F'
        else:
            for i in range(r,l+1):
                s[i] = 'F'
            if ((l - r) % 2 == 0):
                s[r] = '.'
c = 0
for i in s:
    if (i == '.'):
        c += 1
print(c)


import math

n = int(raw_input())
Ss = []
Ds = []
Ts = []
Dp = []
Tp = []

for i in range(n+1):
    Ss.append(tuple(int(i) for i in raw_input().split()))

Vs, Vp = [int(i) for i in raw_input().split()]
Ps = tuple(int(i) for i in raw_input().split())

t = 0
for i in range(n):
    d = 0
    for c in range(3):
        d += (Ss[i+1][c] - Ss[i][c])**2
    d = d**.5
    Ds.append(d)
    t += d/Vs
    Ts.append(t)

for i in range(n):
    d = 0
    t = 0
    for c in range(3):
        d += (Ss[i+1][c] - Ps[c])**2
    d = d**.5
    Dp.append(d)
    t = d/Vp
    Tp.append(t)

print "Ss", Ss
print "Ps", Ps
print "Ds", Ds
print "Ts", Ts
print "Dp", Dp
print "Tp", Tp
"""
if Tp[-1]  T
for i in range(n):
    if Tp[i] >
"""

Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

t = int(raw_input())
N = []
N.append(10000)
[N.append(int(i)) for i in raw_input().split()]
sol = 0
dpx, dpy = [0]*2000, [0]*2000

N.append(10000)
for i in range(1, t+1):
    if N[i] >= N[i - 1]:
        dpy[i] = dpy[i - 1] + 1
    else:
        dpy[i] = 1

for i in range(t, 0, -1):
    if N[i] >= N[i + 1]:
        dpx[i] = dpx[i + 1] + 1
    else:
        dpx[i] = 1

for i in range(1, t+1):
    if dpy[i] + dpx[i] - 1 > sol:
        sol = dpx[i] + dpy[i] - 1

print sol


import math
n = int(input())
front = dict()
back = dict()
for i in range(n):
    a, b = map(int,input().split())
    if a in front:
        front[a] += 1
    else:
        front[a] = 1

    if b in back:
        back[b] += 1
    else:
        back[b] = 1

ans = -1
m = dict()
for key, value in front.items():
    if value >= n/2:
        ans = 0
        break
    elif key in back and front[key] + back[key] >= n/2:
        m[key] = math.ceil(n/2) - front[key]

else:
    if len(m) > 0:
        ans = min(sorted(m.values()))
    else:
        for key, value in back.items():
            if value >= n/2:
                ans = math.ceil(n/2)
                break
        else:
            ans = -1
print(ans)

The Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces.

On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.

NoteIn the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.

import math
n = int(input())
front = dict()
back = dict()
for i in range(n):
    a, b = map(int,input().split())
    if a in front:
        front[a] += 1
    else:
        front[a] = 1

    if b != a:
       if b in back:
          back[b] += 1
       else:
          back[b] = 1

ans = -1
m = dict()
for key, value in front.items():
    if value >= n/2:
        ans = 0
        break
    elif key in back and front[key] + back[key] >= n/2:
        m[key] = math.ceil(n/2) - front[key]

else:
    if len(m) > 0:
        ans = min(sorted(m.values()))
    else:
        for key, value in back.items():
            if value >= n/2:
                ans = math.ceil(n/2)
                break
        else:
            ans = -1
print(ans)


n, b = map(int, input().split())
t = list(map(int, input().split()))
s, d = sum(t), max(t)
b -= d * n - s
if b < 0: print(-1)
d += b / n
for i in range(n): t[i] = str(d - t[i])
print('\n'.join(t))

A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously:   there were b milliliters poured in total. That is, the bottle need to be emptied;  after the process is over, the volumes of the drink in the mugs should be equal.

The first line contains a pair of integers n, b (2 ≤ n ≤ 100, 1 ≤ b ≤ 100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the current volume of drink in the i-th mug.

Print a single number "-1" (without the quotes), if there is no solution. Otherwise, print n float numbers c1, c2, ..., cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique. Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.

x=[int(i) for i in input().split()]
n=x[0]
y=[int(i) for i in input().split()]
if x[1]<max(y)*n-sum(y):
    print(-1)
    raise SystemExit

for i in range(n):
    s=x[1]/n-y[i]++sum(y)/n
    print('%.6f'% s)


The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

n = int(input())
d = [int(x) for x in input().split()]
a, b = [int(x) for x in input().split()]
print(d[a-1]+sum(d[a:b-1]))


c=[0]*1000001
n=int(input())
mi=ma=k=0
for i in range(n):
   a,b=input().split()
   b=int(b)
   if a=="+": k+=1; c[b]=1
   else:
      if c[b]: k-=1; c[b]=0
      else: mi-=1
   ma=max(ma,k)
   mi=min(mi,k)
print(ma-mi)

Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

d=set()
m=0
for _ in range(int(input())):
	x,i=input().split()
	if x=="-":
		if i in d:d.remove(i)
		else:m+=1
	else:
	  d.add(i)
	m=max(m,len(d))
print(m)


from sys import stdin

n = int(stdin.readline())
m = int(stdin.readline())
a = []

if n % 2:
  a.append(m % 1000)
  m /= 1000

while m:
  a.append(m % 100)
  m /= 100

print '-'.join(map(str, reversed(a)))

Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.

The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.

Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.

import sys

def digits(phone_number):
    if phone_number:
        phone_number = phone_number.rstrip('\r|\n')
        length = len(phone_number)

        # Not even.
        if length in [2, 3]:
            return phone_number
        elif length % 2:
            return phone_number[0:3] + "-" + digits(phone_number[3:])
        return phone_number[0:2] + "-" + digits(phone_number[2:])
    else:
        return phone_number

if __name__ == '__main__':
    data = []
    for line in sys.stdin:
        data.append(line)

    for l in data[1::2]:
        print(digits(l))


def main():
    n = input()
    pos = 1
    for i in range(1, n):
        pos = (pos + i) % n
        print pos,

if __name__ == '__main__':
    main()

A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

def main():
    n = input()
    pos = 0
    for i in range(1, n):
        pos = (pos + i) % n
        print pos + 1,

if __name__ == '__main__':
    main()


Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.  Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.

The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).

NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

n = int(input())

mod = 10**9 +7

def power_2_k(k):
    if k == 0:
        return 1
    if k % 2 == 0:
        lower = power_2_k(k // 2)
        return (lower * lower) % mod
    else:
        k -= 1
        lower = power_2_k(k // 2)
        return (((lower * lower) % mod) * 2) % mod

p = power_2_k(n)
print((p * (p + 1) // 2) % mod)


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

#http://codeforces.com/problemset/problem/722/A

time_format = int(raw_input())
time = raw_input().split(":")

hour = time[0]
minutes = time[1]

if (time_format == 12):
    if (int(hour) > 12):
        if (hour[1] == "0"):
            hour = "10"
        else:
            hour = "0" + hour[1]
    if (hour == "00"):
        hour = "01"
else:
    if (int(hour) > 23):
        hour = "0" + hour[1]

if (int(minutes) > 59):
    minutes = "0" + minutes[1]

print hour + ":" + minutes


a,b,n = map(int,input().split())
ans = "No solution"

if a == 0 and b == 0:
    ans =5
elif a == 0 and b!= 0:
    ans
elif a != 0 and b == 0:
    ans = 0
else:
    a = b / a
    if a < 0 :
        a = abs(a)
        b = 0
    for i in range(1001):
        if i ** n == a:
            ans = i

    if b == 0 :ans = - ans

print(ans)

A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient X — the coefficient of income growth during one year. This coefficient should satisfy the equation:A·Xn = B.Surely, the king is not going to do this job by himself, and demands you to find such number X.It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient X must be integers. The number X may be zero or negative.

The input contains three integers A, B, n (|A|, |B| ≤ 1000, 1 ≤ n ≤ 10).

Output the required integer coefficient X, or «No solution», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.

a,b,n = map(int,input().split())
ans = "No solution"

if a == 0 and b == 0:
    ans =5
elif a == 0 and b!= 0:
    ans
elif a != 0 and b == 0:
    ans = 0
elif b%a != 0:
    ans
else:
    a = b / a
    if a < 0 :
        a = abs(a)
        b = 0
    for i in range(1001):
        if i ** n == a:
            ans = i

    if b == 0 :ans = - ans

print(ans)