Candy Boxes
题目链接:
http://codeforces.com/problemset/problem/488/B
解题思路:
codeforces官方题解:
Let's sort the four numbers in ascending order: a, b, c, d (where x1, x2, x3, x4 are used in problem statement). So .
With some basic math, we can get a: d = 1: 3 and a + d = b + c.
Solution 1:
If n = 0, just output any answer (such as {1, 1, 3, 3}). If n = 1, just output {x, x, 3x, 3x}, where x is the known number. If n = 4, just check whether the four known numbers meet the condition.
If n = 2, let x, y denote the known numbers (x ≤ y). No solution exists if 3x < y. Otherwise we can construct a solution {x, y, 4x - y, 3x}(certainly other solutions may exist).
If n = 3, let x, y, z denote the known numbers (x ≤ y ≤ z). No solution exists if 3x < z. Otherwise the solution can only be {x, y, z, 3x}, or {x, y, x + z - y, z}.
Solution 2:
The known numbers are no larger than 500, so all numbers are no larger than 1500 if solution exists. We enumerate x from 1 to 500, yfrom x to 3x, then {x, y, 4x - y, 3x} is a solution. For each solution, check if it matches the known numbers.
Solution 3:
If n = 0, just output any answer (such as {1, 1, 3, 3}). If n = 1, just output {x, x, 3x, 3x}, where x is the known number. If n = 4, just check whether the four known numbers meet the condition.
Otherwise, we can enumerate the 1 or 2 missing number(s), and check if the four numbers meet the condition.
题目大意:
给你4个数,x1<=x2<=x3<=x4, 且(x1+x2+x3+x4)/2 ==(x2+x3)/2==x4-x1。
已知n<=4个数,现在要构造4-n个数,让这4个数满足上述条件。
算法思想:
由四个数的关系我们可以解得:3*x1==x4,x1+x4==x2+x3。
由于n<=4可以直接分类讨论即可。
但是我的做法是枚举x1,贪心构造满足条件的4个数。
AC代码:
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; int main(){ int n; while(scanf("%d",&n)!=EOF){ int a[5],t; if(n == 0){ printf("YES\n"); printf("1\n1\n3\n3\n"); } else{ scanf("%d",&a[0]); if(n == 1){ printf("YES\n"); printf("%d\n%d\n%d\n",a[0],a[0]*3,a[0]*3); } else if(n == 2){ scanf("%d",&a[1]); sort(a,a+2); if(a[0]*3 < a[1]) printf("NO\n"); else{ printf("YES\n"); printf("%d\n%d\n",a[0]*4-a[1],a[0]*3); } } else if(n == 3){ scanf("%d%d",&a[1],&a[2]); sort(a,a+3); if(a[2] == 3*a[0]){ printf("YES\n"); printf("%d\n",a[0]*4-a[1]); } else if(a[2] < 3*a[0] && a[2] == a[0]*4-a[1]){ printf("YES\n"); printf("%d\n",3*a[0]); } else if(a[2] % 3 == 0 && a[2]/3*4-a[0] == a[1]){ printf("YES\n"); printf("%d\n",a[2]/3); } else printf("NO\n"); } else if(n == 4){ scanf("%d%d%d",&a[1],&a[2],&a[3]); sort(a,a+4); if(a[3] != 3*a[0] || a[2] != a[0]*4-a[1]) printf("NO\n"); else printf("YES\n"); } } } return 0; }