记录个人成长历程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 ≤ 50, 0 ≤ q ≤ 100).
Then q lines follow,each representing a fact about the array. i-th linecontains the numbers ti, li, ri and vi for i-th fact (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n, 1 ≤ vi ≤ n, ti 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 1
1 1 3 2
output
5
input
3 2
1 1 3 2
2 1 3 2
output
9
input
3 2
1 1 3 2
2 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 Permutation
int 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;
}
本文介绍了一种算法问题——几乎排列问题,旨在根据一系列约束条件重构一个与排列相似的数组,并计算该数组的成本。文章详细解释了问题背景、输入输出格式及示例,并提供了具体的实现代码。

274

被折叠的 条评论
为什么被折叠?



