家庭作业:一组位中的快速操作(表示为字符数组)
homework: fast manipulations in a set of bits (represented as a character array)
现场
面试中有一些练习题占用了我很多时间......
以下代码仅跨越 8/11 测试用例。 其余的它超过了时间限制。 如果您能提出一些优化建议,我将不胜感激
问题如下.....
there are two binary numbers of length n
there are three kinds of operation
set_a idx x : it sets A[idx] = x
set_b idx x : sets B[idx] = x
get_c idx : Print C[idx], where C=A+B, and 0<=idx
Sample Input
5 5
00000
11111
set_a 0 1
get_c 5
get_c 1
set_b 2 0
get_c 5
Sample Output
100
所以我需要优化get_c操作
void reverse(char*a, int len)
{
//this function reverses the string
}
void get_c(int i)
{
k = i-1;
f = 0;
while (k>=0)
{
if (a[k] == '1' && b[k] == '1')
{
f = 1;
break;
}
else if (a[k] == '0' && b[k] == '0')
break;
--k;
}
if (f==0)
cout<<(a[i] == b[i]?0:1);
else if (f==1)
cout<<(a[i] == b[i]?1:0);
}
int main()
{
scanf("%d %d", &n, &q); // n = number of bits in number, q = number of operations
// enter the strings a and b
reverse(a, n);
reverse(b, n);
while (q--)
{
scanf("%s", query);
scanf("%d", &idx);
if (query is get_c)
{
get_c(idx);
}
else if (query is set_a)
{
cin>>x;
a[idx] = x;
}
else if (query is set_b)
{
cin>>x;
b[idx] = x;
}
}
return 0;
}
似乎您已经使用数组实现了二进制数,而将它们简单地实现为数字并使用位掩码和位移查询/修改它们会更快。这将消除您在get_c
中使用迭代方法的需要;您的get_c
函数将是恒定时间而不是线性时间。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 如何将ampl中的集合表示为c++中的向量
- std::is_base_of表示ctor编译错误
- 输入中的字符串数未知(以字母表示)
- 对字符串进行位操作
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 我可以在 C++ 中的函数体之外进行操作吗?
- c++模板来表示多项式
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 询问在设计我的手臂模拟器功能表示格式1
- 对字符数组中的元素执行逐位操作
- CMakeLists.txt中的命名空间表示法
- 如何在directx/c++中进行平移/缩放操作
- 为表示一个或多个操作的C++函数的int参数寻找类型安全的替换
- 如何在C++中操作和表示二进制数
- 家庭作业:一组位中的快速操作(表示为字符数组)
- 位操作- c++如何表示负值