|
- #include<iostream>
- #include<cmath>
- #include<cstring>
- #define FOR(i,a,b) for(int i=a;i<=b;i++)
- using namespace std;
- const int N=18,INF=0x7ffff;
- int m,n,a,b,jz[N][N],h[N],f[N][N],cnt,l[N],l_[N][N],ans=INF;
- void ycl()
- {
- memset(l,0,sizeof(l));
- memset(l_,0,sizeof(l_));
- FOR(i,1,n)FOR(j,1,cnt-1)
- l[i]+=abs(jz[h[j+1]][i]-jz[h[j]][i]);
- FOR(i,2,n)FOR(j,1,i-1)FOR(k,1,cnt)
- l_[i][j]+=abs(jz[h[k]][i]-jz[h[k]][j]);
- }
- void dp()
- {
- int minn=INF;
- FOR(i,1,n)
- {
- minn=min(i,b);
- FOR(j,1,minn)
- {
- if(j==1)f[i][j]=l[i];
- else if(j==i)f[i][j]=f[i-1][j-1]+l[i]+l_[i][j-1];
- else
- {
- f[i][j]=INF;
- FOR(k,j-1,i-1)f[i][j]=min(f[i][j],f[k][j-1]+l[i]+l_[i][k]);
- }
- }
- if(minn==b)ans=min(ans,f[i][b]);
- }
- return;
- }
- void mj(int x,int y)
- {
- if(!y)
- {
- ycl();
- dp();
- return;
- }
- if((m-x+1)<y)return;
- FOR(i,x,m)
- {
- h[++cnt]=i;
- mj(i+1,y-1);
- h[cnt--]=0;
- }
- }
- int main()
- {
- cin>>m>>n>>a>>b;
- FOR(i,1,m)FOR(j,1,n)cin>>jz[i][j];
- mj(1,a);
- cout<<ans<<endl;
- return 0;
- }
复制代码 |
|