Cod sursa(job #2097602)

Utilizator georgerapeanuRapeanu George georgerapeanu Data 31 decembrie 2017 22:08:28
Problema Ghiozdan Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.06 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];
int D[75005],stq,drq;
void computedp(int i,int weight,int mid,int W){
    for(int j = 0;j <= W;j++){
            dp[i & 1][j] = 1 << 28;
    }
    if(!fr[weight]){
        for(int j = 0;j <= W;j++){
            dp[i & 1][j] = dp[(i & 1) ^ 1][j];
            ant[i & 1][j] = (i <= mid ? j : ant[(i & 1) ^ 1][j]);
        }
        return ;
    }
    for(int r = 0;r < weight;r++){
        stq = 1;
        drq = 0;
        for(int j = r;j <= W;j += weight){
            while(stq <= drq && j - D[stq] > fr[weight] * weight){
                stq++;
            }
            while(stq <= drq && dp[(i & 1) ^ 1][D[drq]] - (D[drq] / weight) >= dp[(i & 1) ^ 1][j] - (j / weight)){
                drq--;
            }
            D[++drq] = j;
            dp[i & 1][j] = dp[(i & 1) ^ 1][D[stq]] - (D[stq] / weight) + (j / weight);
            ant[i & 1][j] = (i <= mid ? j : ant[(i & 1) ^ 1][D[stq]]);
        }
    }
}
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,W);
    }
    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,W);
    }
    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;
}