Codeforces R278 div2B 分类讨论

Codeforces R278 div2 B
题目链接:
http://www.bnuoj.com/v3/problem_show.php?pid=44377
题意:
四个数满足中位数、平均数、最大数减去最小数相等。
先给出其中的n个,问怎样补齐其他数使得合法。
无合法方案输出-1。
思路:
找出性质:x1 + x4 = x2 + x3和x1 * 3 = x4
然后分类讨论,这里容易漏情况。
源码:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int a[5];
int ans[5];
int main()
{
    int n;
    while(scanf("%d", &n) != EOF){
        for(int i = 1 ; i <= n ; i++) scanf("%d", &a[i]);
        sort(a + 1, a + 1 + n);
        int ok = 1;
        if(n == 0){
            for(int i = 1 ; i <= 4 ; i++) ans[i] = 1;
            for(int i = 3 ; i <= 4 ; i++) ans[i] = 3;
        }
        else if(n == 1){
            ans[1] = a[1];
            ans[2] = ans[3] = 3 * a[1];
        }
        else if(n == 2){
            int tok = 0;
            if(a[1] * 3 >= a[2]) ans[1] = a[1] * 3, ans[2] = a[1] * 4 - a[2], tok = 1;
            else if(a[2] == a[1] * 3) ans[1] = a[1], ans[2] = a[2], tok = 1;
// else if((a[1] + a[2]) % 4 == 0) ans[1] = (a[1] + a[2]) / 4, ans[2] = ans[1] * 3, tok = 1, printf("third");
            else if(a[2] % 3 == 0 && a[2] / 3 <= a[1]) ans[1] = a[2] / 3, ans[2] = a[2] / 3 * 4 - a[1], tok = 1;
            ok = tok;
        }
        else if(n == 3){
            int tok = 0;
            if(4 * a[1] == a[2] + a[3]) tok = 1, ans[1] = 3 * a[1];
            else if(a[3] == 3 * a[1]) tok = 1, ans[1] = 4 * a[1] - a[2];
            else if(a[3] % 3 == 0 && a[3] / 3 * 4 == a[1] + a[2]){
                ans[1] = a[3] / 3, tok = 1;
                if(ans[1] > a[1]) tok = 0;
            }
            if(tok == 0) ok = 0;
        }
        else if(n == 4){
            if(a[2] + a[3] != a[1] + a[4] || a[1] * 3 != a[4]) ok = 0;
        }
        if(ok == 0) printf("NO\n");
        else{
            printf("YES\n");
            for(int i = 1 ; i <= 4 - n ; i++) printf("%d\n", ans[i]);
        }
    }
    return 0;
}

你可能感兴趣的:(Codeforces R278 div2B 分类讨论)