当前位置: 首页 > news >正文

Decode

 计数问题。

考虑纯暴力写法:

    string s; cin>>s; int n=s.size(); s=' '+s; int ans=0; for(int l=1;l<=n;l++)for(int r=l;r<=n;r++)for(int i=l;i<=r;i++)for(int j=i;j<=r;j++)if(count(begin(s)+i,begin(s)+j+1,'1')==count(begin(s)+i,begin(s)+j+1,'0'))ans++; cout<<ans<<endl; 

O(n^5)的复杂度,复杂上天。

考虑L=1,R=n时,满足条件的(x,y)对数的优化写法:

vector<int>pre(n+10); 
for(int i=1;i<=n;i++)
pre[i]=(pre[i-1]+(s[i]=='1'?1:-1)); 
map<int,int>cnt; 
int ans=0; 
for(int i=1;i<=n;i++){ans+=cnt[pre[i]]; cnt[pre[i]]++;
}

复杂度O(nlogn)。

再根据乘法原理 ,可以进一步处理所有[L,R]下(x,y)的对数。

#include<bits/stdc++.h>
using namespace std;
void __p(int x) {cerr<<x;}
void __p(long long x){cerr<<x;}
void __p(long double x){cerr<<x;}
void __p(double x){cerr<<x;}
void __p(string s){cerr<<s;}
void __p(char s){cerr<<s;}
void _print(){cerr<<"]\n";}
template<typename T,typename... V>//定义类模版
void _print(T t,V... v){__p(t);if(sizeof...(v))cerr<<",";_print(v...);}
#define debug(x...) cerr<<"["<<#x<<"] = ["; _print(x);
#define see1 cout<<"-------------\n";
#define see2 cerr<<"-------------\n";
#define io ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int long long 
#define double long double
#define sqrt sqrtl
/*1.进行移位运算时, 1ll<<n ,1后面不要忘了ll否则会溢出
2.数组开太大放到外面,作为全局数组
3.dfs递归深度超过几千层可能会溢出
4.accumulate(begin(a),end(a),0LL); 
*/
const int p=1e9+7; void solve()
{string s; cin>>s; int n=s.size(); s=' '+s; vector<int>pre(n+10); for(int i=1;i<=n;i++)pre[i]=pre[i-1]+(s[i]=='1'?1:-1); int ans=0; map<int,int>cnt; for(int i=0;i<=n;i++){ans=(ans+cnt[pre[i]]*(n-i+1))%p;cnt[pre[i]]=(cnt[pre[i]]+i+1)%p; }cout<<ans<<endl; 
}  signed main()
{ioint t=1;cin>>t; while(t--){solve();}
}for(int i=1;i<=n;i++)
pre[i]=(pre[i-1]+(s[i]=='1'?1:-1)); 
int ans=0; 
for(int i=0;i<=n;i++){ans=(ans+cnt[pre[i]]*(n-i+1))%p;cnt[pre[i]]=(cnt[pre[i]]+i+1)%p;
}
cout<<ans<<endl; 

25/4/30

http://www.xdnf.cn/news/238789.html

相关文章:

  • PixONE 六维力传感器:赋能 OEM 机器人,12 自由度精准感知
  • PC端实现微信扫码登录
  • 【Android】Android签名解析
  • TEN:开启实时语音交互的下一代AI Agent引擎
  • 54.[前端开发-前端工程化]Day01-Node-Node安装-前端模块化
  • 多通道协调加载试验机
  • SpringBoot+Redis全局唯一ID生成器
  • Redis应用场景实战:穿透/雪崩/击穿解决方案与分布式锁深度剖析
  • 【数据链路层深度解析】从帧结构到协议实现
  • git 怎样把本地仓库推送到新建的远程仓库
  • 详细解释C++ 泛型模板中的完美转发(Perfect Forwarding)
  • 【自定义控件实现最大高度和最大宽度实现】
  • 2025年天梯题解(L1-8 + L2)
  • 普通IT的股票交易成长史--20250430午
  • 湖北理元理律师事务所:从法律视角看债务优化的合规实践
  • 【Android】36原生Settings新框架PreferenceFragment
  • 生物化学笔记:神经生物学概论05 感受野 视觉中枢 高级视皮层中的信息走向
  • 文章记单词 | 第51篇(六级)
  • 代码随想录算法训练营第三十天(补)
  • 【mysql】执行过程,背诵版
  • 2025平航杯—团队赛
  • 企业的呼入语音智能体是什么样子?
  • 启动Hadoop集群及集群效果
  • 企业数字化转型新动向日渐明鲜,当以“AI为中心”而驱动
  • 分治算法求序列中第K小数
  • RAII 示例
  • 2025-03 机器人等级考试四级理论真题 4级
  • Dify添加ollama模型失败:NewConnectionError: Failed to establish a new connection
  • MCP与开源社区的共赢之道:携手推动技术创新
  • GRE隧道