F. Almost Permutation

来源:互联网 发布:新手淘宝刷手机单步骤 编辑:程序博客网 时间:2024/06/08 17:01
记录个人成长历程
M201709301624
(题目来自网络)

F. AlmostPermutation

time limit pertest

3 seconds

memory limit pertest

512 megabytes

input

standard input

output

standard output

Recently Ivannoticed an array a while debugginghis code. Now Ivan can't remember this array, but the bug he was trying to fixdidn't go away, so Ivan thinks that the data from this array might help him toreproduce the bug.

Ivan clearlyremembers that there were n elementsin the array, and each element was not less than 1 and notgreater than n. Also he remembers q factsabout the array. There are two types of facts that Ivan remembers:

·      1 li ri vi — foreach x such that li ≤ x ≤ ri ax ≥ vi;

·      2 li ri vi — foreach x such that li ≤ x ≤ ri ax ≤ vi.

Also Ivan thinksthat this array was a permutation, but he is not so sure about it. He wants torestore some array that corresponds to the qfacts that heremembers and is very similar to permutation. Formally, Ivan has denotedthe cost of array as follows:

, where cnt(i) is thenumber of occurences of i in thearray.

Help Ivan todetermine minimum possible cost of thearray that corresponds to the facts!

Input

The first linecontains two integer numbers n and q (1 ≤ n ≤ 500 ≤ q ≤ 100).

Then q lines follow,each representing a fact about the array. i-th linecontains the numbers tiliri and vi for i-th fact (1 ≤ ti ≤ 21 ≤ li ≤ ri ≤ n1 ≤ vi ≤ nti denotesthe type of the fact).

Output

If the facts arecontroversial and there is no array that corresponds to them, print -1. Otherwise,print minimum possible cost of thearray.

Examples

input

3 0

output

3

input

3 11 1 3 2

output

5

input

3 21 1 3 22 1 3 2

output

9

input

3 21 1 3 22 1 3 1

output

-1

#include <stdio.h>#include <stdlib.h>#include <math.h>int max(int a, int b){return (a>b)?a:b;}int min(int a, int b){return (a>b)?b:a;}int main(){//F.Almost Permutationint n,q;scanf("%d%d",&n,&q);//待检测输入是否合理 int x_max=n;int x_min=1;int ax_max=n;int ax_min=1;int t,l,r,v;for(int i=1; i<=q; i++){scanf("%d%d%d%d",&t,&l,&r,&v);//待检测输入是否合理 x_max=min(x_max,r);x_min=max(x_min,l);if(t==1)ax_min=(max(ax_min,v));else if(t==2)ax_max=min(ax_max,v);}if(x_max>=x_min && ax_max>=ax_min){/*int x_len=x_max-x_min+1;int ax_len=ax_max-ax_min+1;if(x_len<=ax_len){//可用数值(ax_len)多于位数(x_len) //最小情况为全部相异 printf("%d",x_len);}else{//可用数值(ax_len)少于位数(x_len) //最小情况为同一数字尽量少 //yu个数有shang+1个值 //每个ax至少出现shang次,至多出现shang+1次 int yu=x_len % ax_len; int shang =(x_len-yu)/ax_len;int cost=yu*pow(shang+1,2)+(ax_len-yu)*pow(shang,2);printf("%d\n",cost);}*///解决x_len>ax_len的情况的方法可兼容x_len<=ax_len的情况,于是写成 int x_len=x_max-x_min+1;int ax_len=ax_max-ax_min+1;int yu=x_len % ax_len; int shang =(x_len-yu)/ax_len;int cost=yu*pow(shang+1,2)+(ax_len-yu)*pow(shang,2);printf("%d\n",cost);}else{printf("-1\n");}return 0;}

原创粉丝点击