[二幂拆分] hihoCoder Challenge 29 B. 快速乘法 & BZOJ 1111[POI2007]四进制的天平Wag

参考这里
这是个经典问题,我们考虑记忆化搜索的过程,那么每次一个状态x,会产生新状态 ~x+1什么的,而这个状态数总数是 O(logn)
举个链接中的例子
1010110 –> 10110 –> 110 -> 10
0101010 –> 1010
所产生的所有串的数目刚好是x的位数减去末尾的0的数目

那么我们就可以直接写一个记忆化搜索,然而这不优美
可以直接从低向上DP,u d分别表示 后缀 x 和 ~x+1的答案

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
using namespace std;

const int N=1000005;

int n;
char s[N];

int main(){
  freopen("t.in","r",stdin);
  freopen("t.out","w",stdout);
  scanf("%s",s+1); n=strlen(s+1);
  int r=n,l=1;
  while (l<=n && s[l]=='0') l++;
  while (r && s[r]=='0') r--;
  if (!r) return printf("0"),0;
  int u=1,d=1;
  for (int i=r-1;i>=l;i--)
    if (s[i]=='1')
      u=min(u,d)+1;
    else
      d=min(u,d)+1;
  printf("%d\n",2*u-1);
  return 0;
}

BZOJ这题是个4进制 不过还是一样的
就是需要点细节

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
using namespace std;
typedef pair<int,int> abcd;

const int N=10005;
const int P=1e9;

char s[N]; int n;
int b[N],a[N];
int m;

abcd Min(abcd A,abcd B){
  if (A.first==B.first) return abcd(A.first,(A.second+B.second)%P);
  return min(A,B);
}
abcd operator + (abcd &A,int B){
  return abcd(A.first+B,A.second);
}

int main(){
  freopen("t.in","r",stdin);
  freopen("t.out","w",stdout);
  scanf("%s",s+1); n=strlen(s+1);
  for (int i=1;i<=n;i++) b[i]=s[n-i+1]-'0';
  while (n){
    int rest=0,t;
    for (int i=n;i;i--)
      t=rest,rest=(rest*10+b[i])%4,b[i]=(t*10+b[i])/4;
    while (n>0 && b[n]==0) n--;
    a[++m]=rest;
  }
  int l=1;
  while (a[l]==0) l++;
  abcd u=Min(abcd(a[l],1),abcd(4-a[l]+1,1)),d=Min(abcd(3-a[l]+1,1),abcd(4-(3-a[l]+1)+1,1));
  for (int i=l+1;i<=m;i++){
    abcd nu,nd;
    nu=Min(u+a[i],d+(3-a[i]+1));
    nd=Min(d+(3-a[i]),u+(3-(3-a[i])+1));
    u=nu; d=nd;
  }
  printf("%d\n",u.second);
  return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值