PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BF0000039. Hàng chờ triển lãm thế giới (World Exhibition)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Hàng chờ triển lãm thế giới (World Exhibition)

World Exhibition

Source: HDU

Version: Phuoc Hung OJ Extended

Problem Statement

There are nn people standing in index order along a line, and ties in position are allowed. Upper-bound constraints limit how far liking pairs may be; lower-bound constraints separate disliking pairs. Find the maximum distance from person 11 to person nn, print -1 if infeasible or -2 if unbounded.

All input triples satisfy 1≤a<b≤n1\le a<b\le n. Two people may stand at the same coordinate.

This Extended version removes the leading count of independent test cases.

Input

First line n,X,Yn,X,Y. Then XX triples A,B,CA,B,C (upper bounds) and YY triples (lower bounds).

Output

Print the greatest distance, -1 for impossible, or -2 for unbounded.

Subtasks

  • Subtask 1 (20 points): $2\le n\le12; 0\le X,Y\le20; X+Y\ge1; 1\le A<B\le n; 1\le C\le10^6$.
  • Subtask 2 (30 points): $2\le n\le150; 0\le X,Y\le500; X+Y\ge1; 1\le A<B\le n; 1\le C\le10^6$.
  • Subtask 3 (50 points): $2\le n\le1000; 0\le X,Y\le10000; X+Y\ge1; 1\le A<B\le n; 1\le C\le10^6$.

Examples

Input

3 2 1
1 2 5
2 3 3
1 3 4

Output

8

Explanation

The upper constraints imply x3−x1≤8x_3-x_1\le8. The lower constraint is x3−x1≥4x_3-x_1\ge4. Coordinates (0,5,8)(0,5,8) attain 88, the largest possible distance.