Painting the balls SGU - 183

定义 dp[i][j] 表示最后一个在位置i 倒数第二个在j时候的代价
这个复杂度是O(n*m*m)的 所以需要优化

转移的时候是枚举ijk 三个点
优化实际上就是固定了中间那个点j 移动最后面的点i
往前移动i的同时用f[j][i-m]更新最小值
同时这个最小值也能更新新的f[i][j]

优化后的复杂度为O(n*m)

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define pb push_back
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define sld(n) scanf("%lld",&n)
#define sldd(n,m) scanf("%lld%lld",&n,&m)
#define slddd(n,m,k) scanf("%lld%lld%lld",&n,&m,&k)
#define sf(n) scanf("%lf",&n)
#define sff(n,m) scanf("%lf%lf",&n,&m)
#define sfff(n,m,k) scanf("%lf%lf%lf",&n,&m,&k)
#define ss(str) scanf("%s",str)
#define ansn() printf("%d\n",ans)
#define lansn() printf("%lld\n",ans)
#define r0(i,n) for(int i=0;i<(n);++i)
#define r1(i,e) for(int i=1;i<=e;++i)
#define rn(i,e) for(int i=e;i>=1;--i)
#define mst(abc,bca) memset(abc,bca,sizeof abc)
#define lowbit(a) (a&(-a))
#define all(a) a.begin(),a.end()
#define pii pair
#define pll pair
#define mp(aa,bb) make_pair(aa,bb)
#define lrt rt<<1
#define rrt rt<<1|1
#define X first
#define Y second
#define PI (acos(-1.0))
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
//const ll mod = 1000000007 ;
const double eps=1e-9;
const int inf=0x3f3f3f3f;
//const ll infl = 100000000000000000;//1e17
const int maxn=  1e5+20;
const int maxm = 1e2+20;
//muv[i]=(p-(p/i))*muv[p%i]%p;
int in(int &ret) {
    char c;
    int sgn ;
    if(c=getchar(),c==EOF)return -1;
    while(c!='-'&&(c<'0'||c>'9'))c=getchar();
    sgn = (c=='-')?-1:1;
    ret = (c=='-')?0:(c-'0');
    while(c=getchar(),c>='0'&&c<='9')ret = ret*10+(c-'0');
    ret *=sgn;
    return 1;
}

int f[maxm][maxm];
int c[maxn];
int main() {
#ifdef LOCAL
    freopen("input.txt","r",stdin);
//    freopen("output.txt","w",stdout);
#endif // LOCAL

    int n,m;
    sdd(n,m);
    r1(i,n)sd(c[i]);
    for(int i=1;i<=m;++i)
    {
        for(int j=1;jfor(int j=2;jint mn = inf ;
        for(int i = j-1+m;i>j&&i>m;--i)
        {
            mn = min(mn,f[j%maxm][(i-m)%maxm]);
            f[i%maxm][j%maxm] = mn + c[i];
        }
    }
    int ans = inf;
    for(int i=n-m+1;i<=n;++i)
    {
        for(int j=i+1;j<=n;++j)
            ans = min(ans,f[j%maxm][i%maxm]);
    }
    ansn();
    return 0;
}

你可能感兴趣的:(dp,思维)