在围绕Compiler Explorer进行测试时,我尝试了以下无溢出函数来计算 2 个无符号 32 位整数的平均值:
uint32_t average_1(uint32_t a, uint32_t b)
{
if(a < b){
a ^= b;
b ^= a;
a ^= b;
}
return b + (a - b) / 2;
}
Run Code Online (Sandbox Code Playgroud)
被编译成这样:(与激活的-O1, -O2,-O3优化相同)
average_1:
cmp edi, esi
jnb .L2
mov eax, edi
mov edi, esi
mov esi, eax
.L2:
sub edi, esi
shr edi
lea eax, [rdi+rsi]
ret
Run Code Online (Sandbox Code Playgroud)
其中代码的交换部分经过优化,可以使用mov具有 1 个附加寄存器的指令。
我已经阅读了这些问题:
并得到:
现在我正在尝试解决 UVa 问题 843:https ://onlinejudge.org/index.php?option = com_onlinejudge & Itemid =8& page = show_problem&problem = 784
这是我尝试过的 C++ 代码。
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
void decode(int start, std::string& match);
bool canMatch(std::string& match, std::string w, std::string d);
bool hasConflict(std::string match);
int N;
std::vector<std::string> dict; // Dictionary for allowed words
std::vector<std::string> words; // List of words that is in a line for decrypting
std::set<std::string> exist; // Set of `dict` for faster searching
std::set<std::string>::iterator it; // …Run Code Online (Sandbox Code Playgroud)