【2】做题心得 - 2026 NOICA #05 - Div 2D / 1B【状态压缩 DP】
其实感觉难点在于不要惧怕 T2。
题目大意就是
首先考虑连续段这个东西的本质:
其中,
你就发现:开头的数量恰好就是连续段的数量,而这些
那么现在我们就转化为了:控制矩阵内
然后转移:预处理
最终时间复杂度
#include<bits/stdc++.h>
using namespace std;
double st_cl=clock();
#define fi first
#define se second
#define ll long long
const int N=1e5+10, M=(1<<18)+5, K=18+5;
int test_id;
int n,m,upd[K][K]; bool a[N][K];
// upd: i->j need contribute
int f[M][K];
// f: chose state; last chose id (0~m, m+1)
void brute_dp(){
for(int i=0;i<=m;++i) for(int j=0;j<=m;++j) upd[i][j]=0;
for(int i=0;i<=m;++i) for(int j=0;j<=m;++j) for(int k=1;k<=n;++k)
if(a[k][i]==0&&a[k][j]==1) upd[i][j]++;
for(int i=0;i<(1<<m);++i) for(int j=0;j<=m;++j) f[i][j]=1e7;
f[0][0]=0;
for(int sta=0;sta<(1<<m);++sta) for(int pre=0;pre<=m;++pre){
if(f[sta][pre]>=1e7) continue;
for(int j=1;j<=m;++j) if(!((sta>>(j-1))&1)){
int nsta=(sta|(1<<(j-1)));
f[nsta][j]=min(f[nsta][j],f[sta][pre]+upd[pre][j]);
}
}
int ans=1e7;
for(int i=1;i<=m;i++) ans=min(ans,f[(1<<m)-1][i]);
cout<<ans<<"\n";
return;
}
void solve(){
cin>>n>>m;
for(int i=1;i<=n;++i) for(int j=1;j<=m;++j){ char ch; cin>>ch; a[i][j]=ch-'0'; }
brute_dp();
return;
}
int main(){
freopen("sheet.in","r",stdin);
freopen("sheet.out","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T; cin>>test_id>>T;
while(T--) solve();
int used_cl=(clock()-st_cl)/CLOCKS_PER_SEC*1000;
if(used_cl>2000) cerr<<"(TLE) ";
cerr<<"Used Time: "<<used_cl<<"ms\n";
return 0;
}