普及组的最后一题233
差一点被普及组的题卡掉,泪流满面······
今天上午自己找了3个题,凑了一次模拟赛,这是最后一题也是最难的一题(?)
然而最难的题A掉了,中档题只有40。
好了,不扯废话了。
这题据说是状压DP,然而我并没有想出什么状压做法来。
既然题目让选行又选列,那我们就分开来考虑。
先看行,我们用dfs处理出二进制下的子集来,别担心,最坏情况C(16,8),大概是1.2W,完全跑得过来。
在我们获得选哪些行之后,把选择的行拷到一个新数组中(我用的是now数组),然后暴力处理每一列上下间所付出的代价(此时已固定),注意是每一列(costline[])。
然后我们枚举列,处理每两列之间横向的代价(costrow[][])
然后在新数组中跑DP,刚开始居然设计了DP[i][j][k][l],感觉自己没救了,
然后感觉很不甘心,二进制枚举都做完了,难道还要在DP上TLE吗,
于是改进了方程DP[i][j]表示当前选i列,最后是第j行,然后方程就明显了。
dp[i][j]=min(dp[i][j],dp[i-1][k]+costline[j]+costrow[k][j]) (1<=k<j)
别忘了初始化和memset。
然后就A掉了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdlib>
using namespace std;
int way[20000][20];
int a[100][100];
int now[100][100];
int costrow[100][100];
int costline[100];
int dp[100][100];
int choose[100];
int n,m,r,c;
int cnt;
inline int ra()
{
int x=0;char ch=getchar();int flag=1;//ch=getchar();
while(ch>'9'||ch<'0'){x*=10;x+=ch-'0';ch=getchar();}
while(ch>='0'&&ch<='9'){x*=10;x+=ch-'0';ch=getchar();}
return x*flag;
}
void dfs(int lo,int now,int total)
{
if(now==total)
{
cnt++;
for(int i=1;i<=n;i++)
way[cnt][i]=choose[i];
return;
}
if(n-lo+1<total-now)return;
choose[lo]=1;
dfs(lo+1,now+1,total);
choose[lo]=0;
dfs(lo+1,now,total);
return;
}
int main()
{
int ans=0x7fffffff;
n=ra();m=ra();r=ra();c=ra();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)a[i][j]=ra();
dfs(1,0,r);
for(int i=1;i<=cnt;i++)
{ //now矩阵sum行,m列
memset(costline,0,sizeof(costline));
memset(costrow,0,sizeof(costrow));
memset(dp,0x3f,sizeof(dp));
int sum=0;
for(int j=1;j<=n;j++)
if(way[i][j])memcpy(now[++sum],a[j],sizeof(a[j]));
/* cout<<"sum==="<<sum<<endl;
for(int k=1;k<=sum;k++)
{
for(int j=1;j<=m;j++)cout<<now[k][j]<<' ';
cout<<endl;
}*/
for(int j=1;j<=m;j++)
for(int k=2;k<=sum;k++)
costline[j]+=abs(now[k][j]-now[k-1][j]);
/* for(int j=1;j<=m;j++)cout<<costline[j]<<" ";
cout<<endl;*/
for(int l=1;l<=m;l++)
for(int j=l+1;j<=m;j++)
for(int k=1;k<=sum;k++)costrow[l][j]+=abs(now[k][l]-now[k][j]);
/* for(int l=1;l<=m;l++)
{
for(int j=l+1;j<=m;j++)cout<<costrow[l][j]<<' ';
cout<<endl;
}*/
for(int i=0;i<=m;i++)dp[0][i]=0;
for(register int total=1;total<=c;total++)
for(register int now=total;now<=m;now++)
for(register int last=0;last<now;last++)
dp[total][now]=min(dp[total][now],dp[total-1][last]+costline[now]+costrow[last][now]);
for(int i=c;i<=m;i++)ans=min(ans,dp[c][i]);
/* cout<<ans<<endl;
cout<<"----------------------------------------------"<<endl;
for(int i=1;i<=m;i++)cout<<dp[c][i]<<' ';
cout<<endl;*/
}
/* cout<<"ans==========="<<ans<<endl;*/
cout<<ans<<endl;
return 0;
}
),