https://vjudge.net/contest/297216?tdsourcetag=s_pctim_aiomsg#problem/D
#include<bits/stdc++.h> using namespace std; int a[1005]; int f[1005]; int main() { int n,m; while(scanf("%d",&n)&&n!=0) { memset(f,0,sizeof(f)); for(int i=1; i<=n; i++) scanf("%d",&a[i]); scanf("%d",&m); sort(a+1,a+1+n); for(int i=1; i<=n-1; i++) for(int j=m-5; j>=a[i]; j--) { f[j]=max(f[j],f[j-a[i]]+a[i]); } if(m<5) printf("%d\n",m); else printf("%d\n",m-f[m-5]-a[n]); // cout<<m-f[n-1][m-5]-a[n]<<endl; } }