B. Restoring Painting
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it.
- The painting is a square 3 × 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers.
- The sum of integers in each of four squares 2 × 2 is equal to the sum of integers in the top left square 2 × 2.
- Four elements a, b, c and d are known and are located as shown on the picture below.
Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong.
Two squares are considered to be different, if there exists a cell that contains two different integers in different squares.
Input
The first line of the input contains five integers n, a, b, c and d (1 ≤ n ≤ 100 000, 1 ≤ a, b, c, d ≤ n) — maximum possible value of an integer in the cell and four integers that Vasya remembers.
Output
Print one integer — the number of distinct valid squares.
Examples
input
Copy
2 1 1 1 2
output
Copy
2
input
Copy
3 3 1 2 3
output
Copy
6
Note
Below are all the possible paintings for the first sample.
Codeforces (c) Copyright 2010-2022 Mike Mirzayanov
The only programming contests Web 2.0 platform
Server time: Apr/09/2022 12:14:00UTC+8 (h1).
Desktop version, switch to mobile version.
Supported by
翻译
小 V 在玩填数游戏,游戏在 3×3 的正方形中进行。
9 个格子中的数字都为 1∼n 的整数,不同格子中的数字可以相同。
正方形可以划分出 4 个 2×2 的小正方形,这四个正方形中的数之和相同。
如图所示,a, b, c, d 的值是已知的。
现在 小 V 想知道,剩下的 5 个数一共有多少种填法。
题意及思路
可以很容易得到,四周数字的填写与中间数字无关,因而我们枚举中间数 e 为1~n
所以可以知道每次枚举e时,a,b,c,d,e是固定值,因而四周数的相对差是相同的
所以根据n的大小得出四周数的范围,因为四个方块的和相同,则与:a+b, a+c, b+d, c+d有关
经过分析,四周数的范围与其中的 最大值max 与 最小值min 有关
范围大小是最大和减最小和加一,可以得出每次枚举的四周数范围为n-(max-min+1)+1
因为我们知道当差值过大以至于大于n时没有答案,所以每次枚举结果为max(n-(max-min+1)+1, 0)
因为枚举中间数, 所以次数即为n,答案为 n * max(n-(max-min+1)+1, 0)
AC代码:
#include<bits/stdc++.h>
#define ll long long
#define sz(_s) (int)_s.size()
using namespace std;
int main(){
long long a,b,c,d,n;
cin>>n>>a>>b>>c>>d;
int mx=max(max(a+b,a+c),max(d+b,d+c));
int mn=min(min(a+b,a+c),min(d+b,d+c));
long long ans=n*(n-mx+mn);
if(ans<0) cout<<0;
else cout<<ans;
return 0;
}
//ACplease!!!
/* printf(" \n");
printf(" \n");
printf(" * * * * * * * * * * * * \n");
printf(" * * * * * * * * \n");
printf(" * * * * * * * * \n");
printf(" * * * * * \n");
printf(" * * * * * \n");
printf(" * * * * * \n");
printf(" * * * * * \n");
printf(" * * * * * \n");
printf(" * * * * * \n");
printf(" * * * * * * * * * * * * * * * * * * * * * * * * \n");
*/