Cod sursa(job #2097599)

Utilizator georgerapeanuRapeanu George georgerapeanu Data 31 decembrie 2017 21:57:05
Problema Ghiozdan Scor 60
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <cstdio>
#include <cassert>
#include <algorithm>
#include <deque>
using namespace std;
FILE *f = fopen("ghiozdan.in","r");
FILE *g = fopen("ghiozdan.out","w");
int N,W;
int fr[205];
int dp[2][75005];
int ant[2][75005];
deque<int> D;
void computedp(int i,int weight,int mid){
    for(int j = 0;j <= W;j++){
            dp[i & 1][j] = 1 << 28;
    }
    for(int r = 0;r < weight;r++){
        D.clear();
        for(int j = r;j <= W;j += weight){
            while(!D.empty() && j - D.front() > fr[weight] * weight){
                D.pop_front();
            }
            while(!D.empty() && dp[(i & 1) ^ 1][D.back()] - (D.back() / weight) >= dp[(i & 1) ^ 1][j] - (j / weight)){
                D.pop_back();
            }
            D.push_back(j);
            dp[i & 1][j] = dp[(i & 1) ^ 1][D.front()] - (D.front() / weight) + (j / weight);
            ant[i & 1][j] = (i <= mid ? j : ant[(i & 1) ^ 1][D.front()]);
        }
    }
}
void solve(int st,int dr,int W){
    if(st == dr || !W){
        for(int i = st;i <= W;i += st){
            fprintf(g,"%d\n",st);
        }
        return ;
    }
    int mid = (st + dr) / 2;
    for(int j = 0;j <= W;j++){
            dp[(st & 1) ^ 1][j] = 1 << 28;
    }
    dp[(st & 1) ^ 1][0] = 0;
    for(int i = st;i <= dr;i++){
        computedp(i,i,mid);
    }
    int tmp = ant[dr & 1][W];
    solve(st,mid,tmp);
    solve(mid + 1,dr,W - tmp);
}
int main()
{
    fscanf(f,"%d %d",&N,&W);
    for(int i = 1;i <= N;i++){
        int x;
        fscanf(f,"%d",&x);
        fr[x]++;
    }
    for(int j = 1;j <= W;j++){
            dp[0][j] = 1 << 28;
    }
    for(int i = 1;i <= 200;i++){
        computedp(i,i,0);
    }
    while(dp[0][W] == 1 << 28){
        W--;
    }
    fprintf(g,"%d %d\n",W,dp[0][W]);
    solve(1,200,W);
    fclose(f);
    fclose(g);
    return 0;
}