Yukicoder No.115 遠足のおやつ

http://yukicoder.me/problems/205

考察

買うK個の最小値と最大値を出す.

としてこの中に収まるようにする.辞書順最小にしたいので,左側からdownに近づけていき,その分を右側に持っていく.この操作を可能な限り行い,変化がなくなったら終了.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <cassert>
#include <map>
#include <set>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define INF 1<<30
#define pb push_back
#define mp make_pair

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

int main() {
    int n,d,k;
    cin >> n >> d >> k;

    int sum = 0, t = n;
    rep(i,k) {
        sum += t;
        t--;
    }

    if(d < (k*(k+1))/2 || d > sum) cout << -1 << endl;
    else {
        vector<int> v;
        rep(i,k) v.push_back(d/k);

        int cnt = d % k;
        rep(i,cnt) {
            v[i]++;
        }

        sort(v.begin(),v.end());

        vector<int> down(n), up(n);
        rep(i,n) {
            down[i] = i+1;
            up[i] = n-k+1+i;
        }

        while(true) {
            vector<int> temp(v.begin(),v.end());
            int s = 0, t = v.size()-1;

            while(true) {
                if(s == t) break;

                if(v[s] == down[s] || v[s] == up[s]) {
                    s++;
                    continue;
                }

                if(v[t] == up[t]) {
                    t--;
                    continue;
                }


                int diff;
                if(v[s] >= up[s]) {
                    diff = v[s] - up[s];
                } else {
                    diff = v[s] - down[s];
                }

                while(diff) {
                    if(v[t] + diff <= up[t]) {
                        v[s] -= diff;
                        v[t] += diff;
                        diff = 0;
                    }
                    else {
                        v[s] -= up[t] - v[t];
                        diff -= up[t] - v[t];
                        v[t] = up[t];
                        t--;
                    }

                    if(s == t) break;
                }

            }

            sort(v.begin(),v.end());

            bool flag = true;
            rep(i,k) {
                if(v[i] != temp[i]) flag = false;
            }

            if(flag) break;
        }

        rep(i,v.size()) {
            cout << v[i];

            if(i == v.size()-1) cout << endl;
            else cout << " ";
        }
    }

    return 0;
}
Sep 3rd, 2015