LGOJ P5020 monetary system

Original title press_here!
Too lazy to pull over the topic

The solution of the problem

Consider the state transition equation:

\ [Dp (i) = dp (i-1) + [a_i is a_1, a_2, ..., a_ {i-1} some linear combination], \ quad i> 1 \]

Wherein, in the square brackets is a proposition which is true \ (1 \) , otherwise \ (0 \) .

Then the memory search

After thinking about how to get violent Last added a memory of or into a knapsack problem ...... anyway, are not AC Guannameduo

Equation can be reduced to:

\[ dp(i)=dp(i-1)+ [!dfs(i-1,a_i)], \quad i > 1 \]

Wherein, dfs(int pos,int rest)in \ (a_ {pos} \) is \ (a_1, a_2, ..., a_ {pos-1} \) at a certain linear combination of the \ (1 \) , otherwise \ (0 \)

code:

#include<bits/stdc++.h>
using namespace std;
inline int read()
{
    char c=getchar();int x=0;
    for(;!isdigit(c);c=getchar());
    for(;isdigit(c);c=getchar())
        x=x*10+c-'0';
    return x;
}
int n,m,a[105],f[105][25005],dp[105];

bool dfs(int pos,int rest)
{
    if(rest==0)return 1;
    if(pos==0)return 0;
    if (f[pos][rest]!=-1)return f[pos][rest];
    bool res=0;
    for(int i=0;rest-i*a[pos]>=0;i++)
        res|=dfs(pos-1,rest-i*a[pos]);
    return f[pos][rest]=res;
}

int main()
{
    int T=read();
    while(T--)
    {
        memset(a,0,sizeof(a));
        n=read();
        for(int i=1;i<=n;i++)a[i]=read();
        sort(a+1,a+n+1);
        memset(f,-1,sizeof(f));
        memset(dp,0,sizeof(dp));
        dp[1]=1;
        for(int i=2;i<=n;i++)dp[i]=dp[i-1]+(!dfs(i-1,a[i]));
        printf("%d\n",dp[n]);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/kion/p/11823925.html