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

#BF0000030. Xếp hàng bò (Layout)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Xếp hàng bò (Layout)

Layout

Source: POJ

Version: Phuoc Hung OJ Extended

Problem Statement

Cows stand in nondecreasing order of their labels, and may share positions. Each like constraint bounds the separation of a<ba<b above by dd; each dislike constraint bounds it below by dd. Maximize the distance from cow 11 to cow nn, or print -1 if impossible, -2 if unbounded.

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

Input

First line n,ml,mdn,ml,md. Then mlml upper-bound triples and mdmd lower-bound triples.

Output

Print the maximum distance, -1 for infeasible constraints, or -2 if unbounded.

Subtasks

  • Subtask 1 (20 points): $2\le n\le12; 0\le ml,md\le20; ml+md\ge1; 1\le a<b\le n; 1\le d\le10^6$.
  • Subtask 2 (30 points): $2\le n\le150; 0\le ml,md\le500; ml+md\ge1; 1\le a<b\le n; 1\le d\le10^6$.
  • Subtask 3 (50 points): $2\le n\le1000; 0\le ml,md\le10000; ml+md\ge1; 1\le a<b\le n; 1\le d\le10^6$.

Examples

Input

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

Output

8

Explanation

The two upper limits give x3−x1≤5+3=8x_3-x_1\le5+3=8. The lower limit requires at least 44. The coordinates (0,5,8)(0,5,8) satisfy all bounds and achieve the maximum 88.