import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Mixture {

    static long[] favorite = new long[3];
    static long[][] matrix = new long[3][3];

    static void add(int to, int from) {
        for (int j = 0; j <= 2; j++) {
            matrix[to][j] += matrix[from][j];
        }
    }

    static void subtract(int to, int from) {
        for (int j = 0; j <= 2; j++) {
            matrix[to][j] -= matrix[from][j];
        }
    }

    static void reduce(int a, int b) {
        while (favorite[a] != 0L && favorite[b] != 0L) {
            if (favorite[a] >= favorite[b]) {
                favorite[a] -= favorite[b];
                subtract(a, b);
            } else {
                favorite[b] -= favorite[a];
                subtract(b, a);
            }
        }
        if (favorite[a] != 0L) {
            favorite[b] += favorite[a];
            add(b, a);
            favorite[a] -= favorite[b];
            subtract(a, b);
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tokenizer = new StringTokenizer(in.readLine());
        for (int j = 0; j <= 2; j++) {
            favorite[j] = Long.parseLong(tokenizer.nextToken());
            matrix[j][j] = 1L;
        }
        reduce(0, 1);
        reduce(1, 2);
        /*for (int y = 0; y <= 2; y++) {
            for (int x = 0; x <= 2; x++) {
                System.out.print(matrix[y][x] + " ");
            }
            System.out.println();
        }*/
        int amt00 = 0;
        int amtPosInfty = 0;
        int amtNegInfty = 0;
        int amtMatch = 0;
        TreeMap<Rational, Integer> positive = new TreeMap<>();
        TreeMap<Rational, Integer> negative = new TreeMap<>();
        int j = 0;
        int n = Integer.parseInt(in.readLine());
        long[] xs = new long[n + 1];
        long[] ys = new long[n + 1];
        StringBuilder out = new StringBuilder();
        for (; n > 0; n--) {
            tokenizer = new StringTokenizer(in.readLine());
            if (tokenizer.nextToken().charAt(0) == 'A') {
                j++;
                for (int a = 0; a <= 2; a++) {
                    long k = Long.parseLong(tokenizer.nextToken());
                    xs[j] += matrix[0][a] * k;
                    ys[j] += matrix[1][a] * k;
                }
                if (xs[j] == 0L) {
                    if (ys[j] == 0L) {
                        amt00++;
                    } else if (ys[j] > 0L) {
                        amtPosInfty++;
                    } else {
                        amtNegInfty++;
                    }
                } else {
                    Rational q = new Rational(xs[j], ys[j]);
                    if (xs[j] > 0L) {
                        if (positive.compute(q, (__, prev) -> prev == null ? 1 : (prev + 1)) == 1 && negative.containsKey(q)) {
                            amtMatch++;
                        }
                    } else {
                        if (negative.compute(q, (__, prev) -> prev == null ? 1 : (prev + 1)) == 1 && positive.containsKey(q)) {
                            amtMatch++;
                        }
                    }
                }
            } else {
                int j2 = j;
                j = Integer.parseInt(tokenizer.nextToken());
                if (xs[j] == 0L) {
                    if (ys[j] == 0L) {
                        amt00--;
                    } else if (ys[j] > 0L) {
                        amtPosInfty--;
                    } else {
                        amtNegInfty--;
                    }
                } else {
                    Rational q = new Rational(xs[j], ys[j]);
                    if (xs[j] > 0L) {
                        if (positive.compute(q, (__, prev) -> prev == 1 ? null : (prev - 1)) == null && negative.containsKey(q)) {
                            amtMatch--;
                        }
                    } else {
                        if (negative.compute(q, (__, prev) -> prev == 1 ? null : (prev - 1)) == null && positive.containsKey(q)) {
                            amtMatch--;
                        }
                    }
                }
                j = j2;
            }
            if (amt00 > 0) {
                out.append(1);
            } else if (amtMatch > 0 || (amtPosInfty > 0 && amtNegInfty > 0)) {
                out.append(2);
            } else {
                boolean exists = false;
                if (positive.size() >= 2) {
                    Rational q = negative.ceilingKey(positive.firstKey());
                    if (q != null && q.compareTo(positive.lastKey()) <= 0) {
                        exists = true;
                    }
                }
                if (!exists && negative.size() >= 2) {
                    Rational q = positive.ceilingKey(negative.firstKey());
                    if (q != null && q.compareTo(negative.lastKey()) <= 0) {
                        exists = true;
                    }
                }
                if (!exists && amtPosInfty > 0 && !positive.isEmpty() && !negative.isEmpty()) {
                    Rational q = positive.firstKey();
                    Rational r = negative.lastKey();
                    Rational s = new Rational(-r.num, r.denom);
                    if (q.compareTo(s) < 0) {
                        exists = true;
                    }
                }
                if (!exists && amtNegInfty > 0 && !positive.isEmpty() && !negative.isEmpty()) {
                    Rational q = positive.lastKey();
                    Rational r = negative.firstKey();
                    Rational s = new Rational(-r.num, r.denom);
                    if (q.compareTo(s) > 0) {
                        exists = true;
                    }
                }
                if (exists) {
                    out.append(3);
                } else {
                    out.append(0);
                }
            }
            out.append('\n');
        }
        System.out.print(out);
    }

    static class Rational implements Comparable<Rational> {
        final long num;
        final long denom;

        Rational(long num, long denom) {
            if (denom > 0L) {
                this.num = num;
                this.denom = denom;
            } else {
                this.num = -num;
                this.denom = -denom;
            }
        }

        @Override
        public int compareTo(Rational other) {
            long d = (num * other.denom) - (other.num * denom);
            if (d > 0L) {
                return 1;
            } else if (d == 0L) {
                return 0;
            } else {
                return -1;
            }
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Mixture {

    static long[] favorite = new long[3];
    static long[][] matrix = new long[3][3];

    static void add(int to, int from) {
        for (int j = 0; j <= 2; j++) {
            matrix[to][j] += matrix[from][j];
        }
    }

    static void subtract(int to, int from) {
        for (int j = 0; j <= 2; j++) {
            matrix[to][j] -= matrix[from][j];
        }
    }

    static void reduce(int a, int b) {
        while (favorite[a] != 0L && favorite[b] != 0L) {
            if (favorite[a] >= favorite[b]) {
                favorite[a] -= favorite[b];
                subtract(a, b);
            } else {
                favorite[b] -= favorite[a];
                subtract(b, a);
            }
        }
        if (favorite[a] != 0L) {
            favorite[b] += favorite[a];
            add(b, a);
            favorite[a] -= favorite[b];
            subtract(a, b);
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tokenizer = new StringTokenizer(in.readLine());
        for (int j = 0; j <= 2; j++) {
            favorite[j] = Long.parseLong(tokenizer.nextToken());
            matrix[j][j] = 1L;
        }
        reduce(0, 1);
        reduce(1, 2);
        /*for (int y = 0; y <= 2; y++) {
            for (int x = 0; x <= 2; x++) {
                System.out.print(matrix[y][x] + " ");
            }
            System.out.println();
        }*/
        int amt00 = 0;
        int amtPosInfty = 0;
        int amtNegInfty = 0;
        int amtMatch = 0;
        TreeMap<Rational, Integer> positive = new TreeMap<>();
        TreeMap<Rational, Integer> negative = new TreeMap<>();
        int j = 0;
        int n = Integer.parseInt(in.readLine());
        long[] xs = new long[n + 1];
        long[] ys = new long[n + 1];
        StringBuilder out = new StringBuilder();
        for (; n > 0; n--) {
            tokenizer = new StringTokenizer(in.readLine());
            if (tokenizer.nextToken().charAt(0) == 'A') {
                j++;
                for (int a = 0; a <= 2; a++) {
                    long k = Long.parseLong(tokenizer.nextToken());
                    xs[j] += matrix[0][a] * k;
                    ys[j] += matrix[1][a] * k;
                }
                if (xs[j] == 0L) {
                    if (ys[j] == 0L) {
                        amt00++;
                    } else if (ys[j] > 0L) {
                        amtPosInfty++;
                    } else {
                        amtNegInfty++;
                    }
                } else {
                    Rational q = new Rational(xs[j], ys[j]);
                    if (xs[j] > 0L) {
                        if (positive.compute(q, (__, prev) -> prev == null ? 1 : (prev + 1)) == 1 && negative.containsKey(q)) {
                            amtMatch++;
                        }
                    } else {
                        if (negative.compute(q, (__, prev) -> prev == null ? 1 : (prev + 1)) == 1 && positive.containsKey(q)) {
                            amtMatch++;
                        }
                    }
                }
            } else {
                int j2 = j;
                j = Integer.parseInt(tokenizer.nextToken());
                if (xs[j] == 0L) {
                    if (ys[j] == 0L) {
                        amt00--;
                    } else if (ys[j] > 0L) {
                        amtPosInfty--;
                    } else {
                        amtNegInfty--;
                    }
                } else {
                    Rational q = new Rational(xs[j], ys[j]);
                    if (xs[j] > 0L) {
                        if (positive.compute(q, (__, prev) -> prev == 1 ? null : (prev - 1)) == null && negative.containsKey(q)) {
                            amtMatch--;
                        }
                    } else {
                        if (negative.compute(q, (__, prev) -> prev == 1 ? null : (prev - 1)) == null && positive.containsKey(q)) {
                            amtMatch--;
                        }
                    }
                }
                j = j2;
            }
            if (amt00 > 0) {
                out.append(1);
            } else if (amtMatch > 0 || (amtPosInfty > 0 && amtNegInfty > 0)) {
                out.append(2);
            } else {
                boolean exists = false;
                if (positive.size() >= 2) {
                    Rational q = negative.ceilingKey(positive.firstKey());
                    if (q != null && q.compareTo(positive.lastKey()) <= 0) {
                        exists = true;
                    }
                }
                if (!exists && negative.size() >= 2) {
                    Rational q = positive.ceilingKey(negative.firstKey());
                    if (q != null && q.compareTo(negative.lastKey()) <= 0) {
                        exists = true;
                    }
                }
                if (!exists && amtPosInfty > 0 && !positive.isEmpty() && !negative.isEmpty()) {
                    Rational q = positive.firstKey();
                    Rational r = negative.lastKey();
                    Rational s = new Rational(-r.num, r.denom);
                    if (q.compareTo(s) < 0) {
                        exists = true;
                    }
                }
                if (!exists && amtNegInfty > 0 && !positive.isEmpty() && !negative.isEmpty()) {
                    Rational q = positive.firstKey();
                    Rational r = negative.lastKey();
                    Rational s = new Rational(-r.num, r.denom);
                    if (q.compareTo(s) > 0) {
                        exists = true;
                    }
                }
                if (exists) {
                    out.append(3);
                } else {
                    out.append(0);
                }
            }
            out.append('\n');
        }
        System.out.print(out);
    }

    static class Rational implements Comparable<Rational> {
        final long num;
        final long denom;

        Rational(long num, long denom) {
            if (denom > 0L) {
                this.num = num;
                this.denom = denom;
            } else {
                this.num = -num;
                this.denom = -denom;
            }
        }

        @Override
        public int compareTo(Rational other) {
            long d = (num * other.denom) - (other.num * denom);
            if (d > 0L) {
                return 1;
            } else if (d == 0L) {
                return 0;
            } else {
                return -1;
            }
        }
    }
}


//package bubblecup13.f;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

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

	void solve()
	{
		int n = ni(), m = ni();
		List<Integer> cols = new ArrayList<>();
		for(int i = 0;i < m;i++){
			cols.add(i);
		}
		int[] minima = new int[n];
		Arrays.fill(minima, m-1);
		int[] valmin = new int[n];
		Arrays.fill(valmin, Integer.MAX_VALUE);
		SMAWK(cols, 0, n-1, 1, minima, valmin);

		int ans = 0;
		for(int i = 0;i < n;i++){
			if(valmin[i] < valmin[ans]){
				ans = i;
			}
		}
		out.println("! " + valmin[ans]);
		out.flush();
	}

	Map<Long, Integer> cache = new HashMap<>();

	int f(int i, int j)
	{
		long code = (long)i<<32|j;
		if(cache.containsKey(code))return cache.get(code);
		out.println("? " + (i+1) + " " + (j+1));
		out.flush();
		int ret = ni();
		cache.put(code, ret);
		return ret;
	}

	void SMAWK(List<Integer> js, int ib, int ie, int id, int[] minima, int[] valmin) {
		if (ib > ie) return;

		Deque<Integer> js2 = new ArrayDeque<>();
		for (int q = 0, i = ib; q < js.size(); ++q) {
			while (!js2.isEmpty() && f(i, js2.getLast()) >= f(i, js.get(q))) {
				js2.pollLast(); i -= id; }
			if ( js2.size() != (ie-ib)/id ) {
				js2.addLast(js.get(q)); i += id; }
		}

		SMAWK(new ArrayList<>(js2), ib+id, ie, id*2, minima, valmin);

		for (int i = ib, q = 0; i <= ie; i += id*2) {
			int jt = (i + id <= ie ? minima[i+id] : js.get(js.size()-1));
			int fm = Integer.MAX_VALUE, fq;
			for (; q < js.size(); ++q) {
				if ( fm > (fq = f(i, js.get(q))) ) {
					fm = fq;
					minima[i] = js.get(q);
					valmin[i] = fq;
				}
				if (js.get(q).equals(jt)) break;
			}
		}
	}

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

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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);
        TaskF solver = new TaskF();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskF {
        long[] cnt;
        int n;
        long[] a;
        long[] b;

        boolean check(long day) {
            for (int i = 0; i < n; ++i) b[i] = a[i];
            long r = day / (7 * n);
            for (int i = 0; i < n; ++i) {
                b[i] -= r * cnt[i];
                if (b[i] <= 0) return true;
            }
            int mod = (int) (day % (7 * n));
            int th = 0;
            int id = 0;
            for (int i = 0; i < mod; ++i) {
                if (th != 6) {
                    b[id]--;
                    if (b[id] <= 0) return true;
                }
                th = (th + 1) % 7;
                id = (id + 1) % n;
            }
            return false;
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            n = in.nextInt();
            cnt = new long[n];
            a = new long[n];
            b = new long[n];
            for (int i = 0; i < n; ++i) a[i] = in.nextInt();
            int th = 0;
            int id = 0;
            for (int i = 0; i < n * 7; ++i) {
                if (th != 6) cnt[id]++;
                th = (th + 1) % 7;
                id = (id + 1) % n;
            }

            long lo = 1;
            long hi = (long) 1e17;
            long best = -1;
            while (lo <= hi) {
                long mid = (lo + hi) / 2;
                if (check(mid)) {
                    best = mid;
                    hi = mid - 1;
                } else {
                    lo = mid + 1;
                }
            }
            check(best);
            for (int i = 0; i < n; ++i)
                if (b[i] <= 0) {
                    out.println(i + 1);
                    break;
                }
        }

    }

    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 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 int nextInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public static boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -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.Set;
import java.util.InputMismatchException;
import java.util.HashMap;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Comparator;
import java.io.InputStream;

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

    static class PiscesFast {
        public static int INF = (int) (1e9);
        public static int TIME = 0;
        int n;

        static int sgn(int x) {
            if (x == 0) return 0;
            return x < 0 ? -1 : 1;
        }

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            n = in.nextInt();
            PiscesFast.Node[] ns = new PiscesFast.Node[n];
            for (int i = 0; i < n; i++) ns[i] = new PiscesFast.Node(i);
            for (int i = 0; i < n - 1; i++) {
                int a = in.nextInt() - 1;
                int b = in.nextInt() - 1;
                int w = in.nextInt() * 2;
                ns[a].addEdge(ns[b], w);
                ns[b].addEdge(ns[a], w);
            }

            int k = in.nextInt();
            for (int i = 0; i < k; i++) {
                int d = in.nextInt() * 2;
                int f = in.nextInt();
                int l = in.nextInt() - 1;

                ns[l].addObservation(d, f);
            }

            ns[0].dfsSize(null);
            out.println(ns[0].dfs(null).getMax());
        }

        static class State {
            TreeSet<PiscesFast.State.Segment> small;
            TreeSet<PiscesFast.State.Point> bounds;

            void addSegment(PiscesFast.State.Point l, PiscesFast.State.Point r) {
                int speed = sgn(r.diff) - sgn(l.diff);
                if (speed > 0) {
                    int t = (r.pos() - l.pos() + speed - 1) / speed + TIME;
                    small.add(new PiscesFast.State.Segment(t, l));
                }
            }

            void removeSegment(PiscesFast.State.Point l, PiscesFast.State.Point r) {
                int speed = sgn(r.diff) - sgn(l.diff);
                if (speed > 0) {
                    int t = (r.pos() - l.pos() + speed - 1) / speed + TIME;
                    small.remove(new PiscesFast.State.Segment(t, l));
                }
            }

            public State() {
                bounds = new TreeSet<>();
                small = new TreeSet<>();
                bounds.add(new PiscesFast.State.Point(-INF, 0));
                bounds.add(new PiscesFast.State.Point(INF, 0));
                addSegment(bounds.first(), bounds.last());
            }

            void proceed(int time) {
                while (small.size() > 0 && small.first().a <= time) {
                    PiscesFast.State.Point a = small.first().p;
                    PiscesFast.State.Point b = bounds.higher(a);
                    int ctime = small.first().a;
                    removeSegment(a, b);

                    int pos = a.pos(ctime);
                    int cdiff = a.diff + b.diff;
                    if (b.pos(ctime) != pos && cdiff > 0) pos--;

                    PiscesFast.State.Point c = bounds.lower(a);
                    PiscesFast.State.Point d = bounds.higher(b);
                    removeSegment(c, a);
                    removeSegment(b, d);
                    bounds.remove(b);
                    bounds.remove(a);

                    PiscesFast.State.Point x = new PiscesFast.State.Point(pos, cdiff, ctime);
                    bounds.add(x);
                    addSegment(c, x);
                    addSegment(x, d);
                }
                TIME = time;
            }

            int get(int x) {
                int ans = 0;
                PiscesFast.State.Point p = bounds.ceiling(new PiscesFast.State.Point(x, 0));
                if (p.pos() == x && p.diff < 0) ans = Math.max(ans, -p.diff);
                p = bounds.ceiling(new PiscesFast.State.Point(x + 1, 0));
                if (p.pos() == x + 1 && p.diff > 0) ans = Math.max(ans, p.diff);
                return ans;
            }

            void add(int x, int t) {
                PiscesFast.State.Point toadd = new PiscesFast.State.Point(x, t);
                PiscesFast.State.Point g = bounds.ceiling(toadd);
                if (toadd.compareTo(g) < 0) {
                    PiscesFast.State.Point a = bounds.lower(g);
                    removeSegment(a, g);
                    bounds.add(toadd);
                    addSegment(a, toadd);
                    addSegment(toadd, g);
                } else {
                    PiscesFast.State.Point a = bounds.lower(g);
                    PiscesFast.State.Point b = bounds.higher(g);
                    removeSegment(a, g);
                    removeSegment(g, b);
                    toadd = new PiscesFast.State.Point(x, t + g.diff);
                    bounds.remove(g);
                    bounds.add(toadd);
                    addSegment(a, toadd);
                    addSegment(toadd, b);
                }
            }

            int getMax() {
                int res = 0;
                int c = 0;
                for (PiscesFast.State.Point p : bounds) {
                    c += p.diff;
                    res = Math.max(res, c);
                }
                return res;
            }

            static class Point implements Comparable<PiscesFast.State.Point> {
                public int x;
                public int diff;

                public Point(int x, int diff) {
                    this(x, diff, TIME);
                }

                public Point(int x, int diff, int time) {
                    this.diff = diff;
                    this.x = x + sgn(diff) * time;
                }

                public int pos() {
                    return pos(TIME);
                }

                public int pos(int time) {
                    return x - sgn(diff) * time;
                }

                public int compareTo(PiscesFast.State.Point other) {
                    return pos() - other.pos();
                }

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

                    PiscesFast.State.Point point = (PiscesFast.State.Point) o;

                    if (x != point.x) return false;
                    return diff == point.diff;
                }

                public int hashCode() {
                    int result = x;
                    result = 31 * result + diff;
                    return result;
                }

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

            }

            static class Segment implements Comparable<PiscesFast.State.Segment> {
                public int a;
                public PiscesFast.State.Point p;

                public Segment(int index, PiscesFast.State.Point p) {
                    this.a = index;
                    this.p = p;
                }

                public int compareTo(PiscesFast.State.Segment other) {
                    if (a != other.a) return a - other.a;
                    else return p.compareTo(other.p);
                }

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

                    PiscesFast.State.Segment segment = (PiscesFast.State.Segment) o;

                    if (a != segment.a) return false;
                    return p != null ? p.equals(segment.p) : segment.p == null;
                }

                public int hashCode() {
                    int result = a;
                    result = 31 * result + (p != null ? p.hashCode() : 0);
                    return result;
                }

            }

        }

        static class Node {
            List<PiscesFast.Node> children;
            List<Integer> weights;
            int index;
            int size;
            List<Integer> order;
            HashMap<Integer, Integer> observations;

            public Node(int index) {
                this.index = index;
                children = new ArrayList<>();
                weights = new ArrayList<>();
                observations = new HashMap<>();
                order = new ArrayList<>();
            }

            public void addEdge(PiscesFast.Node other, int weight) {
                children.add(other);
                weights.add(weight);
                order.add(order.size());
            }

            public void addObservation(int time, int fish) {
                observations.put(time, fish);
            }

            public void dfsSize(PiscesFast.Node parent) {
                this.size = 1;
                for (PiscesFast.Node x : children) {
                    if (x == parent) continue;
                    x.dfsSize(this);
                    this.size += x.size;
                }
                order.sort(Comparator.comparingInt(x -> -children.get(x).size));
            }

            public PiscesFast.State dfs(PiscesFast.Node parent) {
                PiscesFast.State cur = null;
                for (int i = 0; i < children.size(); i++) {
                    PiscesFast.Node c = children.get(order.get(i));
                    int len = weights.get(order.get(i));
                    if (c == parent) continue;
                    TIME -= len;
                    PiscesFast.State t = c.dfs(this);
                    t.proceed(TIME + len - 1);
                    if (cur == null) {
                        cur = t;
                    } else {
                        for (PiscesFast.State.Point p : t.bounds) {
                            if (p.pos() > -INF && p.pos() < INF) {
                                cur.add(p.pos(), p.diff);
                            }
                        }
                    }
                }
                if (cur == null) cur = new PiscesFast.State();

                Set<Integer> g = observations.keySet();
                for (int k : g) {
                    observations.put(k, Math.max(0, observations.get(k) - cur.get(k)));
                }
                cur.proceed(TIME + 1);
                for (Map.Entry<Integer, Integer> e : observations.entrySet()) {
                    int k = e.getKey(), v = e.getValue();
                    cur.add(k, v);
                    cur.add(k + 1, -v);
                }
                return cur;
            }

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1 << 16];
        private int curChar;
        private int numChars;

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

        public int read() {
            if (this.numChars == -1) {
                throw new InputMismatchException();
            } else {
                if (this.curChar >= this.numChars) {
                    this.curChar = 0;

                    try {
                        this.numChars = this.stream.read(this.buf);
                    } catch (IOException var2) {
                        throw new InputMismatchException();
                    }

                    if (this.numChars <= 0) {
                        return -1;
                    }
                }

                return this.buf[this.curChar++];
            }
        }

        public int nextInt() {
            int c;
            for (c = this.read(); isSpaceChar(c); c = this.read()) {
                ;
            }

            byte sgn = 1;
            if (c == 45) {
                sgn = -1;
                c = this.read();
            }

            int res = 0;

            while (c >= 48 && c <= 57) {
                res *= 10;
                res += c - 48;
                c = this.read();
                if (isSpaceChar(c)) {
                    return res * sgn;
                }
            }

            throw new InputMismatchException();
        }

        public static boolean isSpaceChar(int c) {
            return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
        }

    }

    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 println(int i) {
            writer.println(i);
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.Random;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            DLinearCongruentialGenerator solver = new DLinearCongruentialGenerator();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class DLinearCongruentialGenerator {
        public int log(int x, int y) {
            int ans = 0;
            while (y != 0 && y % x == 0) {
                ans++;
                y /= x;
            }
            return ans;
        }

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int limit = (int) 2e6;
            IntegerMultiWayStack primeFactors = Factorization.factorizeRangePrime(limit);
            int[] cnts = new int[limit + 1];
            int[] times = new int[limit + 1];
            int[] xs = new int[n];

            in.populate(xs);
            Randomized.shuffle(xs);
            Arrays.sort(xs);
            SequenceUtils.reverse(xs);
            boolean[] retain = new boolean[n];
            for (int i = 0; i < n; i++) {
                int x = xs[i];
                if (cnts[x] == 0) {
                    retain[i] = true;
                    cnts[x] = 1;
                    times[x] = 1;
                    continue;
                }

                for (IntegerIterator iterator = primeFactors.iterator(x - 1); iterator.hasNext(); ) {
                    int p = iterator.next();
                    int log = log(p, x - 1);
                    if (cnts[p] < log) {
                        cnts[p] = log;
                        times[p] = 0;
                    }
                    if (cnts[p] == log) {
                        times[p]++;
                    }
                }
            }

            Modular mod = new Modular(1e9 + 7);
            int prod = 1;
            for (int i = 1; i <= limit; i++) {
                for (int j = 0; j < cnts[i]; j++) {
                    prod = mod.mul(prod, i);
                }
            }

            for (int i = 0; i < n; i++) {
                int x = xs[i];
                boolean unique = false;
                if (retain[i]) {
                    if (cnts[x] == 1 && times[x] == 1) {
                        unique = true;
                    }
                } else {
                    for (IntegerIterator iterator = primeFactors.iterator(x - 1); iterator.hasNext(); ) {
                        int p = iterator.next();
                        int log = log(p, x - 1);
                        if (cnts[p] == log && times[p] == 1) {
                            unique = true;
                        }
                    }
                }
                if (!unique) {
                    prod = mod.plus(prod, 1);
                    break;
                }
            }

            out.println(prod);
        }

    }

    static class Modular {
        int m;

        public Modular(int m) {
            this.m = m;
        }

        public Modular(long m) {
            this.m = (int) m;
            if (this.m != m) {
                throw new IllegalArgumentException();
            }
        }

        public Modular(double m) {
            this.m = (int) m;
            if (this.m != m) {
                throw new IllegalArgumentException();
            }
        }

        public int valueOf(int x) {
            x %= m;
            if (x < 0) {
                x += m;
            }
            return x;
        }

        public int valueOf(long x) {
            x %= m;
            if (x < 0) {
                x += m;
            }
            return (int) x;
        }

        public int mul(int x, int y) {
            return valueOf((long) x * y);
        }

        public int plus(int x, int y) {
            return valueOf(x + y);
        }

        public String toString() {
            return "mod " + m;
        }

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static boolean isMultiplicationOverflow(long a, long b, long limit) {
            if (limit < 0) {
                limit = -limit;
            }
            if (a < 0) {
                a = -a;
            }
            if (b < 0) {
                b = -b;
            }
            if (a == 0 || b == 0) {
                return false;
            }
            //a * b > limit => a > limit / b
            return a > limit / b;
        }

    }

    static class RandomWrapper {
        private Random random;
        public static RandomWrapper INSTANCE = new RandomWrapper(new Random());

        public RandomWrapper() {
            this(new Random());
        }

        public RandomWrapper(Random random) {
            this.random = random;
        }

        public int nextInt(int l, int r) {
            return random.nextInt(r - l + 1) + l;
        }

    }

    static class Randomized {
        public static void shuffle(int[] data) {
            shuffle(data, 0, data.length - 1);
        }

        public static void shuffle(int[] data, int from, int to) {
            to--;
            for (int i = from; i <= to; i++) {
                int s = nextInt(i, to);
                int tmp = data[i];
                data[i] = data[s];
                data[s] = tmp;
            }
        }

        public static int nextInt(int l, int r) {
            return RandomWrapper.INSTANCE.nextInt(l, r);
        }

    }

    static class MinimumNumberWithMaximumFactors {
        private static int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};

        public static long[] maximumPrimeFactor(long n) {
            long[] ans = new long[2];
            ans[0] = 1;
            for (int i = 0; i < primes.length; i++) {
                if (DigitUtils.isMultiplicationOverflow(ans[0], primes[i], n)) {
                    break;
                }
                ans[0] *= primes[i];
                ans[1]++;
            }
            return ans;
        }

    }

    static class IntegerMultiWayStack {
        private int[] values;
        private int[] next;
        private int[] heads;
        private int alloc;
        private int stackNum;

        public IntegerIterator iterator(final int queue) {
            return new IntegerIterator() {
                int ele = heads[queue];

                public boolean hasNext() {
                    return ele != 0;
                }

                public int next() {
                    int ans = values[ele];
                    ele = next[ele];
                    return ans;
                }
            };
        }

        private void doubleCapacity() {
            int newSize = Math.max(next.length + 10, next.length * 2);
            next = Arrays.copyOf(next, newSize);
            values = Arrays.copyOf(values, newSize);
        }

        public void alloc() {
            alloc++;
            if (alloc >= next.length) {
                doubleCapacity();
            }
            next[alloc] = 0;
        }

        public boolean isEmpty(int qId) {
            return heads[qId] == 0;
        }

        public IntegerMultiWayStack(int qNum, int totalCapacity) {
            values = new int[totalCapacity + 1];
            next = new int[totalCapacity + 1];
            heads = new int[qNum];
            stackNum = qNum;
        }

        public void addLast(int qId, int x) {
            alloc();
            values[alloc] = x;
            next[alloc] = heads[qId];
            heads[qId] = alloc;
        }

        public String toString() {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < stackNum; i++) {
                if (isEmpty(i)) {
                    continue;
                }
                builder.append(i).append(": ");
                for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) {
                    builder.append(iterator.next()).append(",");
                }
                if (builder.charAt(builder.length() - 1) == ',') {
                    builder.setLength(builder.length() - 1);
                }
                builder.append('\n');
            }
            return builder.toString();
        }

    }

    static class Factorization {
        public static IntegerMultiWayStack factorizeRangePrime(int n) {
            int maxFactorCnt = (int) MinimumNumberWithMaximumFactors.maximumPrimeFactor(n)[1];
            IntegerMultiWayStack stack = new IntegerMultiWayStack(n + 1, n * maxFactorCnt);
            boolean[] isComp = new boolean[n + 1];
            for (int i = 2; i <= n; i++) {
                if (isComp[i]) {
                    continue;
                }
                for (int j = i; j <= n; j += i) {
                    isComp[j] = true;
                    stack.addLast(j, i);
                }
            }
            return stack;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(int c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(int c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static class SequenceUtils {
        public static void swap(int[] data, int i, int j) {
            int tmp = data[i];
            data[i] = data[j];
            data[j] = tmp;
        }

        public static void reverse(int[] data, int l, int r) {
            while (l < r) {
                swap(data, l, r);
                l++;
                r--;
            }
        }

        public static void reverse(int[] data) {
            reverse(data, 0, data.length - 1);
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        public void populate(int[] data) {
            for (int i = 0; i < data.length; i++) {
                data[i] = readInt();
            }
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static interface IntegerIterator {
        boolean hasNext();

        int next();

    }
}


/**
 * author: derrick20
 * created: 10/5/20 11:58 AM
 */
import java.io.*;
import java.util.*;

public class ICup implements Runnable {
    public static void main(String[] args) throws Exception {
        new Thread(null, new ICup(), ": )", 1 << 28).start();
    }

    public void run() {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        int T = sc.nextInt();
        long[] vals = sc.nextLongs(T);
        long[] sqrts = new long[60];
        sqrts[2] = 2;
        for (int i = 3; i < sqrts.length; i++) {
            sqrts[i] = (2 * sqrts[i - 1] - 1 + mod) % mod;
        }

        for (long v : vals) {
            if (v == 1) {
                out.println(1);
            } else if (v == 2 || v == 3) {
                out.println(2);
            } else {
                long sum = 0;
                long ct = 0;
                for (int bit = 2; bit < 60; bit++) {
                    if (((v >> bit) & 1) > 0) {
                        sum += sqrts[bit];
                        ct += 1;
                    }
                }
                long amt = sum - (ct - 1);
                long ans = (amt * amt) % mod;
                if ((v & 2) > 0) {
                    ans += amt;
                }
                ans %= mod;
                out.println(ans);
            }
        }
        out.close();
    }

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

    static class FastScanner {
        private int BS = 1 << 16;
        private char NC = (char) 0;
        private byte[] buf = new byte[BS];
        private int bId = 0, size = 0;
        private char c = NC;
        private double cnt = 1;
        private BufferedInputStream in;

        public FastScanner() {
            in = new BufferedInputStream(System.in, BS);
        }

        public FastScanner(String s) {
            try {
                in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
            } catch (Exception e) {
                in = new BufferedInputStream(System.in, BS);
            }
        }

        private char getChar() {
            while (bId == size) {
                try {
                    size = in.read(buf);
                } catch (Exception e) {
                    return NC;
                }
                if (size == -1) return NC;
                bId = 0;
            }
            return (char) buf[bId++];
        }

        public int nextInt() {
            return (int) nextLong();
        }

        public int[] nextInts(int N) {
            int[] res = new int[N];
            for (int i = 0; i < N; i++) {
                res[i] = (int) nextLong();
            }
            return res;
        }

        public long[] nextLongs(int N) {
            long[] res = new long[N];
            for (int i = 0; i < N; i++) {
                res[i] = nextLong();
            }
            return res;
        }

        public long nextLong() {
            cnt = 1;
            boolean neg = false;
            if (c == NC) c = getChar();
            for (; (c < '0' || c > '9'); c = getChar()) {
                if (c == '-') neg = true;
            }
            long res = 0;
            for (; c >= '0' && c <= '9'; c = getChar()) {
                res = (res << 3) + (res << 1) + c - '0';
                cnt *= 10;
            }
            return neg ? -res : res;
        }

        public double nextDouble() {
            double cur = nextLong();
            return c != '.' ? cur : cur + nextLong() / cnt;
        }

        public double[] nextDoubles(int N) {
            double[] res = new double[N];
            for (int i = 0; i < N; i++) {
                res[i] = nextDouble();
            }
            return res;
        }

        public String next() {
            StringBuilder res = new StringBuilder();
            while (c <= 32) c = getChar();
            while (c > 32) {
                res.append(c);
                c = getChar();
            }
            return res.toString();
        }

        public String nextLine() {
            StringBuilder res = new StringBuilder();
            while (c <= 32) c = getChar();
            while (c != '\n') {
                res.append(c);
                c = getChar();
            }
            return res.toString();
        }

        public boolean hasNext() {
            if (c > 32) return true;
            while (true) {
                c = getChar();
                if (c == NC) return false;
                else if (c > 32) return true;
            }
        }
    }
    static void ASSERT(boolean assertion, String message) {
        if (!assertion) throw new AssertionError(message);
    }
    static void ASSERT(boolean assertion) {
        if (!assertion) throw new AssertionError();
    }
}


/**
 * author: derrick20
 * created: 10/5/20 11:58 AM
 */
import java.io.*;
import java.util.*;

public class ICup implements Runnable {
    public static void main(String[] args) throws Exception {
        new Thread(null, new ICup(), ": )", 1 << 28).start();
    }

    public void run() {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        int T = sc.nextInt();
        long[] vals = sc.nextLongs(T);
        int[] sqrts = new int[60];
        sqrts[2] = 2;
        for (int i = 3; i < sqrts.length; i++) {
            sqrts[i] = 2 * sqrts[i - 1] - 1;
        }
        for (long v : vals) {
            if (v == 1) {
                out.println(1);
            } else if (v == 2 || v == 3) {
                out.println(2);
            } else {
                long sum = 0;
                long ct = 0;
                for (int bit = 2; bit < 60; bit++) {
                    if (((v >> bit) & 1) > 0) {
                        sum += sqrts[bit];
                        ct += 1;
                    }
                }
                long amt = sum - (ct - 1);
                long ans = (amt * amt) % mod;
                if ((v & 2) > 0) {
                    ans += amt;
                }
                ans %= mod;
                out.println(ans);
            }
        }
        out.close();
    }

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

    static class FastScanner {
        private int BS = 1 << 16;
        private char NC = (char) 0;
        private byte[] buf = new byte[BS];
        private int bId = 0, size = 0;
        private char c = NC;
        private double cnt = 1;
        private BufferedInputStream in;

        public FastScanner() {
            in = new BufferedInputStream(System.in, BS);
        }

        public FastScanner(String s) {
            try {
                in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
            } catch (Exception e) {
                in = new BufferedInputStream(System.in, BS);
            }
        }

        private char getChar() {
            while (bId == size) {
                try {
                    size = in.read(buf);
                } catch (Exception e) {
                    return NC;
                }
                if (size == -1) return NC;
                bId = 0;
            }
            return (char) buf[bId++];
        }

        public int nextInt() {
            return (int) nextLong();
        }

        public int[] nextInts(int N) {
            int[] res = new int[N];
            for (int i = 0; i < N; i++) {
                res[i] = (int) nextLong();
            }
            return res;
        }

        public long[] nextLongs(int N) {
            long[] res = new long[N];
            for (int i = 0; i < N; i++) {
                res[i] = nextLong();
            }
            return res;
        }

        public long nextLong() {
            cnt = 1;
            boolean neg = false;
            if (c == NC) c = getChar();
            for (; (c < '0' || c > '9'); c = getChar()) {
                if (c == '-') neg = true;
            }
            long res = 0;
            for (; c >= '0' && c <= '9'; c = getChar()) {
                res = (res << 3) + (res << 1) + c - '0';
                cnt *= 10;
            }
            return neg ? -res : res;
        }

        public double nextDouble() {
            double cur = nextLong();
            return c != '.' ? cur : cur + nextLong() / cnt;
        }

        public double[] nextDoubles(int N) {
            double[] res = new double[N];
            for (int i = 0; i < N; i++) {
                res[i] = nextDouble();
            }
            return res;
        }

        public String next() {
            StringBuilder res = new StringBuilder();
            while (c <= 32) c = getChar();
            while (c > 32) {
                res.append(c);
                c = getChar();
            }
            return res.toString();
        }

        public String nextLine() {
            StringBuilder res = new StringBuilder();
            while (c <= 32) c = getChar();
            while (c != '\n') {
                res.append(c);
                c = getChar();
            }
            return res.toString();
        }

        public boolean hasNext() {
            if (c > 32) return true;
            while (true) {
                c = getChar();
                if (c == NC) return false;
                else if (c > 32) return true;
            }
        }
    }
    static void ASSERT(boolean assertion, String message) {
        if (!assertion) throw new AssertionError(message);
    }
    static void ASSERT(boolean assertion) {
        if (!assertion) throw new AssertionError();
    }
}


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

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

	void solve()
	{
		int n = ni();
		int m = ni();
		int[] a = na(n);
		long[] as = new long[n];
		for(int i = 0;i < n;i++){
			as[i] = (long)a[i]<<32|i;
		}
		Arrays.sort(as);

		int s = (int)Math.sqrt(n);
		// time split
		int[][] minblock = new int[n/s+1][];
		int[] imos = new int[n/s+2];
		for(int i = 0;i <= n;i++){
			if(i % s == 0){
				minblock[i/s] = Arrays.copyOf(imos, n/s+2);
				for(int j = 1;j <= n/s;j++){
					minblock[i/s][j] += minblock[i/s][j-1];
				}
			}

			if(i == n)break;
			if(0 > (int)as[i]-m+1){
				int l = Math.max(0, (int)as[i]-m+1);
				int r = (int)as[i];
				if(l/s <= r/s){
					imos[l/s]++;
					imos[r/s]--;
				}
			}else{
				int l = Math.max(0, (int)as[i]-m+1);
				int r = (int)as[i];
				if(l/s+1 <= r/s){
					imos[l/s+1]++;
					imos[r/s]--;
				}
			}
		}

		int[][] mininblock = new int[n/s+1][];
		int[][] wheninblock = new int[n/s+1][];
		for(int i = 0;i < n/s+1;i++){
			mininblock[i] = new int[2*s+1];
			wheninblock[i] = new int[2*s+1];
		}

		int[] map = new int[n];
		int[] ps = new int[n/s+1];
		for(int i = 0;i < n;i++){
			int l = Math.max(0, (int)as[i]-m+1);
			int r = (int)as[i];
			if(l/s == r/s){
				for(int j = l;j <= r;j++)map[j]++;

				int lmin = Integer.MAX_VALUE;
				for(int j = l/s*s;j < l/s*s+s && j < n;j++){
					if(map[j] < lmin){
						lmin = map[j];
					}
				}
				int clus = l/s;
				mininblock[clus][ps[clus]] = lmin;
				wheninblock[clus][ps[clus]] = i;
				ps[clus]++;
			}else{
				{
					for(int j = r/s*s;j <= r;j++)map[j]++;

					int lmin = Integer.MAX_VALUE;
					for(int j = r/s*s;j < r/s*s+s && j < n;j++){
						if(map[j] < lmin){
							lmin = map[j];
						}
					}
					int clus = r/s;
					mininblock[clus][ps[clus]] = lmin;
					wheninblock[clus][ps[clus]] = i;
					ps[clus]++;
				}
				if(0 <= (int)as[i]-m+1){
					for(int j = l;j < l/s*s+s;j++)map[j]++;

					int lmin = Integer.MAX_VALUE;
					for(int j = l/s*s;j < l/s*s+s && j < n;j++){
						if(map[j] < lmin){
							lmin = map[j];
						}
					}
					int clus = l/s;
					mininblock[clus][ps[clus]] = lmin;
					wheninblock[clus][ps[clus]] = i;
					ps[clus]++;
				}
			}
		}
//		for(int i = 0;i < n/s+1;i++){
//			tr(i);
//			tr(Arrays.copyOf(mininblock[i], ps[i]));
//			tr(Arrays.copyOf(wheninblock[i], ps[i]));
//		}

		int ans = 0;
		for(int Q = ni(); Q >= 1;Q--){
			int ql = ni()-1, qr = ni()-1, qx = ni()^ans;
			int time = -Arrays.binarySearch(as, ((long)qx<<32)-1)-1;
			int[] limos = new int[n/s+2];
			for(int i = time/s*s;i < time;i++){
				if(0 > (int)as[i]-m+1){
					int l = Math.max(0, (int)as[i]-m+1);
					int r = (int)as[i];
					if(l/s <= r/s){
						limos[l/s]++;
						limos[r/s]--;
					}
				}else{
					int l = Math.max(0, (int)as[i]-m+1);
					int r = (int)as[i];
					if(l/s+1 <= r/s){
						limos[l/s+1]++;
						limos[r/s]--;
					}
				}
			}
			for(int i = 1;i < n/s+1;i++){
				limos[i] += limos[i-1];
			}
			for(int i = 0;i < n/s+1;i++){
				limos[i] += minblock[time/s][i];
			}
			ans = 999999999;

			if(ql/s == qr/s){
				int clus = ql/s;
				int[] llimos = new int[s+1];
				for(int j = 0;j < ps[clus] && wheninblock[clus][j] < time;j++){
					int l = Math.max((int)as[wheninblock[clus][j]]-m+1-clus*s, 0);
					int r = Math.min(s-1, (int)as[wheninblock[clus][j]]-clus*s);
					llimos[l]++;
					llimos[r+1]--;
				}
				for(int j = 1;j <= s;j++){
					llimos[j] += llimos[j-1];
				}
				for(int j = ql-clus*s;j <= qr-clus*s;j++){
					ans = Math.min(ans, limos[clus] + llimos[j]);
				}
			}else{
				for(int i = ql/s+1;i < qr/s;i++){
					int lind = Arrays.binarySearch(wheninblock[i], 0, ps[i], time-1);
					if(lind < 0)lind = -lind-2;
					if(lind >= 0){
						ans = Math.min(ans, limos[i] + mininblock[i][lind]);
					}else{
						ans = Math.min(ans, limos[i]);
					}
				}

				{
					int clus = ql/s;
					int[] llimos = new int[s+1];
					for(int j = 0;j < ps[clus] && wheninblock[clus][j] < time;j++){
						int l = Math.max((int)as[wheninblock[clus][j]]-m+1-clus*s, 0);
						int r = Math.min((int)as[wheninblock[clus][j]]-clus*s, s-1);
						llimos[l]++;
						llimos[r+1]--;
					}
					for(int j = 1;j <= s;j++){
						llimos[j] += llimos[j-1];
					}
					for(int j = ql-clus*s;j < s && j < n-clus*s;j++){
						ans = Math.min(ans, limos[clus] + llimos[j]);
					}
				}
				{
					int clus = qr/s;
					int[] llimos = new int[s+1];
					for(int j = 0;j < ps[clus] && wheninblock[clus][j] < time;j++){
						int l = Math.max((int)as[wheninblock[clus][j]]-m+1-clus*s, 0);
						int r = Math.min((int)as[wheninblock[clus][j]]-clus*s, s-1);
						llimos[l]++;
						llimos[r+1]--;
					}
					for(int j = 1;j <= s;j++){
						llimos[j] += llimos[j-1];
					}
					for(int j = 0;j <= qr-clus*s;j++){
						ans = Math.min(ans, limos[clus] + llimos[j]);
					}
				}
			}

			out.println(ans);
		}
	}

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

	private byte[] inbuf = new byte[1024];
	private int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


import java.awt.AWTPermission;
import java.io.*;
import java.util.*;

public class E {

  public static void main(String[] args) throws Exception {
    reader = new MyReader(System.in);
    writer = System.out;
    new E().go();
  }

  static MyReader reader;
  static PrintStream writer;

  void go() {
    int n = reader.readInt();
    int k = reader.readInt();
    circles = new Circle[n];
    for(int i=0;i<n;++i) circles[i] = readCircle();
    long mc = maxCut();
    long res = n + k * (mc + mc + k - 1) / 2;
    System.out.println(res);
  }

  private int maxCut() {
    int res = 1;
    for(int i=0;i<circles.length;i++) res = Math.max(res, maxCut(i));
    return res;
  }

  private static final double EPSILON = 1e-10;

  private int maxCut(int a) {
    Circle A = circles[a];
    ArrayList<Angle> angles = new ArrayList<Angle>();
    int cnt = 1;
    int best = 1;
    for(int b=0;b<circles.length;b++) {
      if(b==a) continue;
      Circle B = circles[b];
      if(B.r < A.r) continue;
      double alpha = Math.atan2(B.y - A.y, B.x - A.x);
      double beta = Math.atan2(B.r - A.r, Math.hypot(B.y-A.y, B.x-A.x)) - EPSILON;
      double gamma = Math.atan2(B.r + A.r, Math.hypot(B.y-A.y, B.x-A.x)) - EPSILON;
      double a1 = modulo(alpha-beta);
      double a2 = modulo(alpha+gamma);
      double b1 = modulo(alpha-gamma+Math.PI);
      double b2 = modulo(alpha+beta+Math.PI);
      if(a1 > a2) ++cnt;
      if(b1 > b2) ++cnt;
      angles.add(new Angle(a1, 1));
      angles.add(new Angle(a2, -1));
      angles.add(new Angle(b1, 1));
      angles.add(new Angle(b2, -1));
    }
    Collections.sort(angles);
    for(Angle angle : angles) {
      cnt += angle.d;
      best = Math.max(best, cnt);
    }
    return best;
  }

  private static double modulo(double a) {
    while(a>2*Math.PI) a -= 2*Math.PI;
    while(a<0) a += 2*Math.PI;
    return a;
  }

  private static class Angle implements Comparable<Angle> {
    double a;
    int d;
    Angle(double a, int d) { this.a = a; this.d = d; }
    public int compareTo(Angle o) {
      if(a < o.a) return -1;
      else if(a > o.a) return 1;
      else return 0;
    }
  }

  private Circle readCircle() {
    Circle c = new Circle();
    c.x = reader.readInt();
    c.y = reader.readInt();
    c.r = reader.readInt();
    return c;
  }

  Circle[] circles;

  private static class Circle {
    int x,y,r;
  }

  private static class MyReader {
    private InputStream in;
    private byte[] buf;
    private int bufSize,bufPos;
    private int nextChar;

    public MyReader(InputStream in) {
      this.in = in;
      buf = new byte[16<<10];
      bufSize=0;
      bufPos=0;
      move();
    }

    private void move() {
      if (bufPos==bufSize) {
        try {
          bufSize = in.read(buf);
        } catch(IOException ex) {
          throw new RuntimeException(ex);
        }
        bufPos = 0;
        if (bufSize == -1) {
          nextChar = -1;
          return;
        }
      }
      nextChar = buf[bufPos++];
    }

    public int readInt() {
      skipWhitespace();
      int res = 0;
      boolean minus = false;
      if(nextChar=='-') { minus=true; move(); }
      while(nextChar >= '0' && nextChar <= '9') {
        res = 10*res + (nextChar-'0');
        move();
      }
      if (minus) res = -res;
      return res;
    }
    public String readString() {
      StringBuilder b = new StringBuilder();
      skipWhitespace();
      while(nextChar >= 33) {
        b.append((char)nextChar);
        move();
      }
      return b.toString();
    }

    public void skipWhitespace() {
      while(nextChar==' ' || nextChar=='\n' || nextChar=='\t' || nextChar=='\r') move();
    }
  }

}


import java.awt.AWTPermission;
import java.io.*;
import java.util.*;

public class E {

  public static void main(String[] args) throws Exception {
    reader = new MyReader(System.in);
    writer = System.out;
    new E().go();
  }

  static MyReader reader;
  static PrintStream writer;

  void go() {
    int n = reader.readInt();
    int k = reader.readInt();
    circles = new Circle[n];
    for(int i=0;i<n;++i) circles[i] = readCircle();
    long mc = maxCut();
    long res = n + k * (mc + mc + k - 1) / 2;
    System.out.println(res);
  }

  private int maxCut() {
    int res = 1;
    for(int i=0;i<circles.length;i++) res = Math.max(res, maxCut(i));
    return res;
  }

  private static final double EPSILON = 1e-10;

  private int maxCut(int a) {
    Circle A = circles[a];
    ArrayList<Angle> angles = new ArrayList<Angle>();
    int cnt = 1;
    int best = 1;
    for(int b=0;b<circles.length;b++) {
      if(b==a) continue;
      Circle B = circles[b];
      if(B.r < A.r) continue;
      double alpha = Math.atan2(B.y - A.y, B.x - A.x);
      double beta = Math.asin((B.r - A.r) / Math.hypot(B.y-A.y, B.x-A.x)) - EPSILON;
      double gamma = Math.asin((B.r + A.r) / Math.hypot(B.y-A.y, B.x-A.x)) - EPSILON;
      double a1 = modulo(alpha-beta);
      double a2 = modulo(alpha+gamma);
      double b1 = modulo(alpha-gamma+Math.PI);
      double b2 = modulo(alpha+beta+Math.PI);
      if(a1 > a2) ++cnt;
      if(b1 > b2) ++cnt;
      angles.add(new Angle(a1, 1));
      angles.add(new Angle(a2, -1));
      angles.add(new Angle(b1, 1));
      angles.add(new Angle(b2, -1));
    }
    Collections.sort(angles);
    for(Angle angle : angles) {
      cnt += angle.d;
      best = Math.max(best, cnt);
    }
    return best;
  }

  private static double modulo(double a) {
    while(a>2*Math.PI) a -= 2*Math.PI;
    while(a<0) a += 2*Math.PI;
    return a;
  }

  private static class Angle implements Comparable<Angle> {
    double a;
    int d;
    Angle(double a, int d) { this.a = a; this.d = d; }
    public int compareTo(Angle o) {
      if(a < o.a) return -1;
      else if(a > o.a) return 1;
      else return 0;
    }
  }

  private Circle readCircle() {
    Circle c = new Circle();
    c.x = reader.readInt();
    c.y = reader.readInt();
    c.r = reader.readInt();
    return c;
  }

  Circle[] circles;

  private static class Circle {
    int x,y,r;
  }

  private static class MyReader {
    private InputStream in;
    private byte[] buf;
    private int bufSize,bufPos;
    private int nextChar;

    public MyReader(InputStream in) {
      this.in = in;
      buf = new byte[16<<10];
      bufSize=0;
      bufPos=0;
      move();
    }

    private void move() {
      if (bufPos==bufSize) {
        try {
          bufSize = in.read(buf);
        } catch(IOException ex) {
          throw new RuntimeException(ex);
        }
        bufPos = 0;
        if (bufSize == -1) {
          nextChar = -1;
          return;
        }
      }
      nextChar = buf[bufPos++];
    }

    public int readInt() {
      skipWhitespace();
      int res = 0;
      boolean minus = false;
      if(nextChar=='-') { minus=true; move(); }
      while(nextChar >= '0' && nextChar <= '9') {
        res = 10*res + (nextChar-'0');
        move();
      }
      if (minus) res = -res;
      return res;
    }
    public String readString() {
      StringBuilder b = new StringBuilder();
      skipWhitespace();
      while(nextChar >= 33) {
        b.append((char)nextChar);
        move();
      }
      return b.toString();
    }

    public void skipWhitespace() {
      while(nextChar==' ' || nextChar=='\n' || nextChar=='\t' || nextChar=='\r') move();
    }
  }

}


import static java.lang.Math.*;

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

public class Template {
	BufferedReader in;
	PrintWriter out;
	StringTokenizer st;

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

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

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

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

	class Circle {
		double x, y, r;
		public Circle(double x, double y, double r) {
			this.x=x;
			this.y=y;
			this.r=r;
		}
	}

	int n;
	long k;
	Circle[] a;

	double mod(double a) {
		while (a < 0) a+=PI*2;
		while (a > 2*PI) a-=PI*2;
		return a;
	}
	class Event implements Comparable<Event> {
		double a;
		int type, i;
		Event r;
		public Event(double a, int type) {
			this.a=a;
			this.type = type;
		}

		public int compareTo(Event o) {
			double d = a-o.a;
			if (d>0) return 1;
			if (d<0) return -1;
			return type - o.type;
		}
	}

	int solve(int i) {
		double eps =  1e-14;
		ArrayList<Event> ev = new ArrayList<Event>();
		for (int j=0; j<n; j++) {
			if (i==j) continue;
			double alpha = atan2(a[j].y - a[i].y, a[j].x - a[i].x);
			double d = hypot(a[j].y - a[i].y, a[j].x - a[i].x);
			double beta = asin((a[j].r - a[i].r) / d);
			double gamma = asin((a[j].r + a[i].r) / d);

			double a1 = mod(alpha - beta + eps);
			double a2 = mod(alpha + gamma - eps);
			ev.add(new Event(a1, -1));
			ev.add(new Event(a2, 1));
			ev.get(ev.size() - 1).r = ev.get(ev.size() - 2);
			ev.get(ev.size() - 2).r = ev.get(ev.size() - 1);

			a1 = mod(alpha - gamma + eps + PI);
			a2 = mod(alpha + beta - eps + PI);
			ev.add(new Event(a1, -1));
			ev.add(new Event(a2, 1));
			ev.get(ev.size() - 1).r = ev.get(ev.size() - 2);
			ev.get(ev.size() - 2).r = ev.get(ev.size() - 1);
		}

		Collections.sort(ev);
		int now = 1, best=1;
		for (Event e : ev) {
			if (e.type == -1) now++; else
			if (e.compareTo(e.r) > 0) now--;
			best = max(best, now);
		}
//		System.err.println(best);
		return best;

	}

	public void run() throws Exception {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		Long start = System.currentTimeMillis();

		n = nextInt();
		k = nextLong();
		a = new Circle[n];
		for (int i=0; i<n; i++) {
			a[i] = new Circle(nextInt(), nextInt(), nextInt());
		}

		int ans=1;
		for (int i=0; i<n; i++) {
			ans = max(ans, solve(i));
		}
		long res = k * (k + 1) / 2 + 1;
		res += (ans-1) * (k + 1) + n - ans;
		out.println(res);
		Long end = System.currentTimeMillis();
		//System.out.println((end - start) / 1000.0);
		out.close();
	}

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


import java.awt.AWTPermission;
import java.io.*;
import java.util.*;

public class E {

  public static void main(String[] args) throws Exception {
    reader = new MyReader(System.in);
    writer = System.out;
    new E().go();
  }

  static MyReader reader;
  static PrintStream writer;

  void go() {
    int n = reader.readInt();
    int k = reader.readInt();
    circles = new Circle[n];
    for(int i=0;i<n;++i) circles[i] = readCircle();
    long mc = maxCut();
    long res = n + k * (mc + mc + k - 1) / 2;
    System.out.println(res);
  }

  private int maxCut() {
    int res = 1;
    for(int i=0;i<circles.length;i++) res = Math.max(res, maxCut(i));
    return res;
  }

  private static final double EPSILON = 1e-10;

  private int maxCut(int a) {
    Circle A = circles[a];
    ArrayList<Angle> angles = new ArrayList<Angle>();
    int cnt = 1;
    int best = 1;
    for(int b=0;b<circles.length;b++) {
      if(b==a) continue;
      Circle B = circles[b];
      double alpha = Math.atan2(B.y - A.y, B.x - A.x);
      double beta = Math.asin((B.r - A.r) / Math.hypot(B.y-A.y, B.x-A.x)) - EPSILON;
      double gamma = Math.asin((B.r + A.r) / Math.hypot(B.y-A.y, B.x-A.x)) - EPSILON;
      double a1 = modulo(alpha-beta);
      double a2 = modulo(alpha+gamma);
      double b1 = modulo(alpha-gamma+Math.PI);
      double b2 = modulo(alpha+beta+Math.PI);
      if(a1 > a2) ++cnt;
      if(b1 > b2) ++cnt;
      angles.add(new Angle(a1, 1));
      angles.add(new Angle(a2, -1));
      angles.add(new Angle(b1, 1));
      angles.add(new Angle(b2, -1));
    }
    Collections.sort(angles);
    for(Angle angle : angles) {
      cnt += angle.d;
      best = Math.max(best, cnt);
    }
    return best;
  }

  private static double modulo(double a) {
    while(a>2*Math.PI) a -= 2*Math.PI;
    while(a<0) a += 2*Math.PI;
    return a;
  }

  private static class Angle implements Comparable<Angle> {
    double a;
    int d;
    Angle(double a, int d) { this.a = a; this.d = d; }
    public int compareTo(Angle o) {
      if(a < o.a) return -1;
      else if(a > o.a) return 1;
      else return 0;
    }
  }

  private Circle readCircle() {
    Circle c = new Circle();
    c.x = reader.readInt();
    c.y = reader.readInt();
    c.r = reader.readInt();
    return c;
  }

  Circle[] circles;

  private static class Circle {
    int x,y,r;
  }

  private static class MyReader {
    private InputStream in;
    private byte[] buf;
    private int bufSize,bufPos;
    private int nextChar;

    public MyReader(InputStream in) {
      this.in = in;
      buf = new byte[16<<10];
      bufSize=0;
      bufPos=0;
      move();
    }

    private void move() {
      if (bufPos==bufSize) {
        try {
          bufSize = in.read(buf);
        } catch(IOException ex) {
          throw new RuntimeException(ex);
        }
        bufPos = 0;
        if (bufSize == -1) {
          nextChar = -1;
          return;
        }
      }
      nextChar = buf[bufPos++];
    }

    public int readInt() {
      skipWhitespace();
      int res = 0;
      boolean minus = false;
      if(nextChar=='-') { minus=true; move(); }
      while(nextChar >= '0' && nextChar <= '9') {
        res = 10*res + (nextChar-'0');
        move();
      }
      if (minus) res = -res;
      return res;
    }
    public String readString() {
      StringBuilder b = new StringBuilder();
      skipWhitespace();
      while(nextChar >= 33) {
        b.append((char)nextChar);
        move();
      }
      return b.toString();
    }

    public void skipWhitespace() {
      while(nextChar==' ' || nextChar=='\n' || nextChar=='\t' || nextChar=='\r') move();
    }
  }

}


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

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner scanner = new Scanner(System.in);
		int a = scanner.nextInt();
		int h = scanner.nextInt();
		int w = scanner.nextInt();
		int g = h+a, gn = w+a;
		while (gn>0) {
			int t = gn;
			gn = g%gn;
			g = t;

		}

		int k = 0;
		while(g/(k+1)>=a) {
			k++;
		}

		if (k>0) {
			System.out.println(1.0*g/k-a);
		} else {
			System.out.println(-1);
		}

	}
}


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

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner scanner = new Scanner(System.in);
		int a = scanner.nextInt();
		int h = scanner.nextInt();
		int w = scanner.nextInt();
		int g = h+a, gn = w+a;
		while (gn>0) {
			int t = gn;
			gn = g%gn;
			g = t;

		}

		int k = g/a;

		if (k>0) {
			System.out.println(1.0*g/k-a);
		} else {
			System.out.println(-1);
		}

	}
}


import java.io.*; import java.util.*;
public class VillageMax {

    /**
     * Centroid decomposition problem
     * Answer is twice the sum of the size of the smaller subtree for an edge over all edges
     */
    static ArrayList<Integer> arl[];
    static int N;
    static long ans;
    static int[] siz,par;//Size of subtree
    static int cent=-1;//Centroid
    public static class Pair implements Comparable<Pair>{
        int v; int siz;
        public Pair(int a, int b){
            this.v=a; this.siz=b;
        }
        public int compareTo(Pair other){
            if(this.siz<=other.siz)return -1;
            return 1;

        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        N=Integer.parseInt(br.readLine());

         arl=new ArrayList[N];
         for (int i = 0; i < N; i++) {
            arl[i]=new ArrayList<>();
        }
         int a,b;
         for (int i = 0; i < N-1; i++) {
            StringTokenizer st=new StringTokenizer(br.readLine());
            a=Integer.parseInt(st.nextToken())-1;
            b=Integer.parseInt(st.nextToken())-1;
            arl[a].add(b); arl[b].add(a);
        }
         siz=new int[N];
         par=new int[N];
          for (int i = 0; i < N; i++) {
            par[i]=i;
        }
         Arrays.fill(siz,1);
         init(-1,0);

         dfs(-1,0,true);

         //Now we use rerooting to find the centroid of the tree and the answer
         Arrays.fill(siz,1);//Redo

         init(-1,cent);//Root around center
         TreeSet<Pair> ts=new TreeSet<>();

         for (int i : arl[cent]) {

            ts.add(new Pair(i,siz[i]));

         }

         ArrayList<Integer> arl2[]=new ArrayList[N];
         for (int i = 0; i < N; i++) {
            arl2[i]=new ArrayList<>();
        }
        for (int i = 0; i < N; i++) {
            if(i!=cent){
                arl2[find(i,par)].add(i);
            }
        }

        int[] res=new int[N];
        int sum=N-1;
        while(sum>2){
            Pair p=ts.pollLast();
            Pair q=ts.pollLast();

            res[arl2[q.v].get(q.siz-1)]=arl2[p.v].get(p.siz-1);
            res[arl2[p.v].get(p.siz-1)]=arl2[q.v].get(q.siz-1);
            arl2[q.v].remove(q.siz-1); arl2[p.v].remove(p.siz-1);
            if(q.siz>1){
                ts.add(new Pair(q.v,q.siz-1));
            }
            if(p.siz>1){
                ts.add(new Pair(p.v,p.siz-1));
            }
            sum-=2;
        }
        if(sum==1){
            Pair p=ts.pollLast();
            res[cent]=arl2[p.v].get(0);
            res[arl2[p.v].get(0)]=cent;
        }else{
            Pair p=ts.pollLast();
            Pair q=ts.pollLast();
            res[cent]=arl2[p.v].get(0);
            res[arl2[p.v].get(0)]=arl2[q.v].get(0);
            res[arl2[q.v].get(0)]=cent;
        }
        System.out.println(ans);
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i <N; i++) {
            sb.append(res[i]+1).append(" ");
        }
        System.out.println(sb.toString());
    }
    public static void init(int p, int v){

       for (int i : arl[v]) {
            if(i==p)continue;
            init(v,i);
            siz[v]+=siz[i];
            if(cent>=0 && v!=cent){

                par[i]=v;

            }
        }
    }
    public static void dfs(int p, int v, boolean b){//Rerooting
        if(p>=0){

            ans+=2*Math.min(N-siz[p],siz[p]);

        }
        int max=0; int ind=-1;
        for (int i : arl[v]) {
            if(i==p)continue;
            if(siz[i]>max){
                max=siz[i];
                if(b){//Index is only used for centroid finding
                    ind=i;
                }
            }

        }

        if(b && 2*max>N){
            siz[v]-=siz[ind];
            siz[ind]+=siz[v];
            dfs(v,ind,true);
            siz[ind]-=siz[v];
            siz[v]+=siz[ind];
        }else if(b){

            ind=-1; cent=v;//Centroid found
        }
        for (int i : arl[v]) {
            if(i==p || i==ind)continue;
            siz[v]-=siz[i];
            siz[i]+=siz[v];
            dfs(v,i,false);
            siz[i]-=siz[v];
            siz[v]+=siz[i];
        }
    }
    public static int find(int x, int[] p){
        if(p[x]==x)return x;
        int ans=find(p[x],p);
        p[x]=ans; return ans;
    }
}


import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
    void solve() {
        int n=ni();
        g=new ArrayList[n+1];
        for(int i=1;i<=n;i++) g[i]=new ArrayList<>();
        for(int i=1;i<n;i++){
            int u=ni(),v=ni();
            g[u].add(v); g[v].add(u);
        }
        dp=new long[n+1][2][2];
        dfs(1,-1);
        pw.println(dp[1][1][1]);

    }
    ArrayList<Integer> g[];
    long dp[][][];
    void dfs(int v,int pr){
        int child=0;
        for(int u : g[v]){
            if(u!=pr) {
                dfs(u,v);
                child++;
            }
        }
        if(child==0){
            dp[v][0][0]=dp[v][1][1]=1;
            return;
        }
        long sm=1,sm2=1;
        for(int u : g[v]){
            if(u!=pr) {
                sm = mul(sm, add(dp[u][0][1], dp[u][1][1]));
                sm2=mul(sm2,dp[u][1][1]);
            }
        }
        dp[v][0][0]=sm;
        for(int u : g[v]){
            if(u!=pr){
                dp[v][0][1]=add(dp[v][0][1],mul(dp[u][0][0],mul(sm,modInverse(dp[u][0][1]+dp[u][1][1],M))));
                dp[v][1][1]=add(dp[v][1][1],mul(dp[u][0][0],mul(sm,modInverse(dp[u][0][1]+dp[u][1][1],M))));

            }
        }
        dp[v][1][1]=add(dp[v][1][1],sm2);

    }
    long sub(long a,long b){
        if(a>=M)a%=M;  if(b>=M)b%=M;
        a-=b;
        if(a<0) a+=M;
        return a;
    }
    long mul(long a,long b){
        a*=b;
        if(a>=M) a%=M;
        return a;
    }
    long add(long a,long b){
        if(a>=M)a%=M;  if(b>=M)b%=M;
        a+=b;
        if(a>=M) a-=M;
        return a;
    }
    long modpow(long a, long b,long M)
    {
        long r=1;
        while(b>0)
        {
            if((b&1)>0) r=mul(r,a);
            a=mul(a,a);
            b>>=1;
        }
        return r;
    }

    long modInverse(long A, long M)
    {

        return modpow(A,M-2,M);
    }

    long M = 998244353;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

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

        Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()){
            @Override
            public void run() {
                long s = System.currentTimeMillis();
                solve();

                pw.flush();
                if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
            }
        };
        t.start();
        t.join();
    }

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

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

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

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

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}


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

public class Main
{
	public BufferedReader in;
	public PrintStream out;

	public boolean log_enabled = false;

	int n;
	int[] adj_count;
	int[][] adj_list;

	int[] ch_count;
	int[][] ch_list;

	long[] X, Y, Z;
	boolean[] V;

	long M = 998244353;

	public long modInverse(long a, long n) {
	 long i = n, v = 0, d = 1;
	 while (a>0) {
	  long t = i/a, x = a;
	  a = i % x;
	  i = x;
	  x = d;
	  d = v - t*x;
	  v = x;
	 }
	 v %= n;
	 if (v<0) v = (v+n)%n;
	 return v;
	}

	public void generate_test()
	{
		out.println(300000);
		for (int i=1; i<300000; i++)
		{
			out.printf("%d %d\n", i, i+1);
		}
	}

	public void test()
	{
		n = readInt();
		int[] pars = readIntArray(2*n-2);

		int i,j;

		adj_count = new int[n];
		adj_list = new int[n][];

		ch_count = new int[n];
		ch_list = new int[n][];

		Arrays.fill(adj_count, 0);
		for (i=0; i<n-1; i++)
		{
			adj_count[pars[2*i]-1] ++;
			adj_count[pars[2*i + 1]-1] ++;
		}

		for (i=0; i<n; i++)
		{
			adj_list[i] = new int[adj_count[i]];
			ch_list[i] = new int[adj_count[i]];
			adj_count[i] = 0;
		}

		for (i=0; i<n-1; i++)
		{
			int a = pars[2*i]-1;
			int b = pars[2*i+1]-1;

			adj_list[a][adj_count[a] ++] = b;
			adj_list[b][adj_count[b] ++] = a;
		}

		X = new long[n];
		Y = new long[n];
		Z = new long[n];

		V = new boolean[n];
		Arrays.fill(V, false);

		int[] Q = new int[n];
		Q[0] = 0;
		int p,q_tail = 1;

		for (j=0; j<n; j++)
		{
			p = Q[j];
			V[p] = true;

			ch_count[p] = 0;
			for (i=0; i<adj_count[p]; i++)
			{
				if (!V[adj_list[p][i]])
				{
					ch_list[p][ ch_count[p] ++] = adj_list[p][i];
					Q[q_tail ++] = adj_list[p][i];
				}
			}
		}

		long pz, pxz;

		for (j=n-1; j>=0; j--)
		{
			p = Q[j];

			pz = 1;
			pxz = 1;

			for (i=0; i<ch_count[p]; i++)
			{
				pz = (pz * Z[ch_list[p][i]]) % M;
				pxz = (pxz * (X[ch_list[p][i]] + Z[ch_list[p][i]])) % M;
			}

			Y[p] = pxz;
			X[p] = 0;
			for (i=0; i<ch_count[p]; i++)
			{
				X[p] = (  X[p] + ( Y[ch_list[p][i]] * modInverse( Z[ch_list[p][i]] + X[ch_list[p][i]] % M , M) ) % M  ) % M;
			}
			X[p] = (X[p] * pxz) % M;
			Z[p] = (X[p] + pz) % M;

			logWrite("%d:\tX=%d\tY=%d\tZ=%d\n", p,X[p],Y[p],Z[p]);
		}

		out.println(Z[0]);
	}

	public void dfs(int p)
	{
		V[p] = true;

		int[] childs = new int[adj_count[p]];
		int i, ch_count = 0;
		for (i=0; i<adj_count[p]; i++)
		{
			if (!V[adj_list[p][i]])
			{
				childs[ ch_count ++] = adj_list[p][i];
				dfs(adj_list[p][i]);
			}
		}

		long pz = 1;
		long pxz = 1;

		for (i=0; i<ch_count; i++)
		{
			pz = (pz * Z[childs[i]]) % M;
			pxz = (pxz * (X[childs[i]] + Z[childs[i]])) % M;
		}

		Y[p] = pxz;
		X[p] = 0;
		for (i=0; i<ch_count; i++)
		{
			X[p] = (  X[p] + ( Y[childs[i]] * modInverse( Z[childs[i]] + X[childs[i]] % M , M) ) % M  ) % M;
		}
		X[p] = (X[p] * pxz) % M;
		Z[p] = (X[p] + pz) % M;

		logWrite("%d:\tX=%d\tY=%d\tZ=%d\n", p,X[p],Y[p],Z[p]);
	}

	public void run()
	{
		try
		{
			in = new BufferedReader(new InputStreamReader(System.in));
			out = System.out;

			//in = new BufferedReader(new FileReader("in.txt"));
			//out = new PrintStream(new File("out.txt"));

		}
		catch (Exception e)
		{
			return;
		}

		//while (true)
		{
			//int t = readInt(); for (int i=0; i<t; i++)
			{
				test();
			}
		}
	}

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

	private StringTokenizer tokenizer = null;

	public int readInt()
	{
        return Integer.parseInt(readToken());
    }

    public long readLong()
	{
        return Long.parseLong(readToken());
    }

    public double readDouble()
	{
        return Double.parseDouble(readToken());
    }

	public String readLn()
	{
		try
		{
			String s;
			while ((s = in.readLine()).length()==0);
			return s;
		}
		catch (Exception e)
		{
			return "";
		}
	}

    public String readToken()
	{
		try
		{
			while (tokenizer == null || !tokenizer.hasMoreTokens())
			{
				tokenizer = new StringTokenizer(in.readLine());
			}
			return tokenizer.nextToken();
		}
		catch (Exception e)
		{
			return "";
		}
    }

	public int[] readIntArray(int n)
	{
		int[] x = new int[n];
		readIntArray(x, n);
		return x;
	}

	public void readIntArray(int[] x, int n)
	{
		for (int i=0; i<n; i++)
		{
			x[i] = readInt();
		}
	}

	public void logWrite(String format, Object... args)
	{
		if (!log_enabled)
		{
			return;
		}

		out.printf(format, args);
	}
}


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

public class Main
{
	public BufferedReader in;
	public PrintStream out;

	public boolean log_enabled = false;

	int n;
	int[] adj_count;
	int[][] adj_list;

	long[] X, Y, Z;
	boolean[] V;

	long M = 998244353;

	public long modInverse(long a, long n) {
	 long i = n, v = 0, d = 1;
	 while (a>0) {
	  long t = i/a, x = a;
	  a = i % x;
	  i = x;
	  x = d;
	  d = v - t*x;
	  v = x;
	 }
	 v %= n;
	 if (v<0) v = (v+n)%n;
	 return v;
	}

	public void test()
	{
		n = readInt();
		int[] pars = readIntArray(2*n-2);

		int i,j;

		adj_count = new int[n];
		adj_list = new int[n][];

		Arrays.fill(adj_count, 0);
		for (i=0; i<n-1; i++)
		{
			adj_count[pars[2*i]-1] ++;
			adj_count[pars[2*i + 1]-1] ++;
		}

		for (i=0; i<n; i++)
		{
			adj_list[i] = new int[adj_count[i]];
			adj_count[i] = 0;
		}

		for (i=0; i<n-1; i++)
		{
			int a = pars[2*i]-1;
			int b = pars[2*i+1]-1;

			adj_list[a][adj_count[a] ++] = b;
			adj_list[b][adj_count[b] ++] = a;
		}

		X = new long[n];
		Y = new long[n];
		Z = new long[n];

		V = new boolean[n];
		Arrays.fill(V, false);

		dfs(0);

		out.println(Z[0]);
	}

	public void dfs(int p)
	{
		V[p] = true;

		int[] childs = new int[adj_count[p]];
		int i, ch_count = 0;
		for (i=0; i<adj_count[p]; i++)
		{
			if (!V[adj_list[p][i]])
			{
				childs[ ch_count ++] = adj_list[p][i];
				dfs(adj_list[p][i]);
			}
		}

		long pz = 1;
		long pxz = 1;

		for (i=0; i<ch_count; i++)
		{
			pz = (pz * Z[childs[i]]) % M;
			pxz = (pxz * (X[childs[i]] + Z[childs[i]])) % M;
		}

		Y[p] = pxz;
		X[p] = 0;
		for (i=0; i<ch_count; i++)
		{
			X[p] = (  X[p] + ( Y[childs[i]] * modInverse( Z[childs[i]] + X[childs[i]] % M , M) ) % M  ) % M;
		}
		X[p] = (X[p] * pxz) % M;
		Z[p] = (X[p] + pz) % M;

		logWrite("%d:\tX=%d\tY=%d\tZ=%d\n", p,X[p],Y[p],Z[p]);
	}

	public void run()
	{
		try
		{
			in = new BufferedReader(new InputStreamReader(System.in));
			out = System.out;

			//in = new BufferedReader(new FileReader("in.txt"));
			//out = new PrintStream(new File("out.txt"));

		}
		catch (Exception e)
		{
			return;
		}

		//while (true)
		{
			//int t = readInt(); for (int i=0; i<t; i++)
			{
				test();
			}
		}
	}

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

	private StringTokenizer tokenizer = null;

	public int readInt()
	{
        return Integer.parseInt(readToken());
    }

    public long readLong()
	{
        return Long.parseLong(readToken());
    }

    public double readDouble()
	{
        return Double.parseDouble(readToken());
    }

	public String readLn()
	{
		try
		{
			String s;
			while ((s = in.readLine()).length()==0);
			return s;
		}
		catch (Exception e)
		{
			return "";
		}
	}

    public String readToken()
	{
		try
		{
			while (tokenizer == null || !tokenizer.hasMoreTokens())
			{
				tokenizer = new StringTokenizer(in.readLine());
			}
			return tokenizer.nextToken();
		}
		catch (Exception e)
		{
			return "";
		}
    }

	public int[] readIntArray(int n)
	{
		int[] x = new int[n];
		readIntArray(x, n);
		return x;
	}

	public void readIntArray(int[] x, int n)
	{
		for (int i=0; i<n; i++)
		{
			x[i] = readInt();
		}
	}

	public void logWrite(String format, Object... args)
	{
		if (!log_enabled)
		{
			return;
		}

		out.printf(format, args);
	}
}