本文整理汇总了C++中std::bitset类的典型用法代码示例。如果您正苦于以下问题:C++ bitset类的具体用法?C++ bitset怎么用?C++ bitset使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了bitset类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: load
inline void load(
Archive & ar,
STD::bitset<Bits> &t,
const unsigned int /* file_version */
){
if (ar.get_flags() & boost::archive::packed_bools) {
const unsigned Bytes = Bits / 8;
for (unsigned int i = 0; i < Bytes; i++){
unsigned char theByte;
ar >> boost::serialization::make_nvp("item", theByte);
const unsigned int count = 8 * i;
t.set(count, theByte & 0x01);
for (unsigned int j = 1; j < 8; j++) {
theByte = theByte >> 1;
t.set(count + j, theByte & 0x01);
}
}
// handle any partial byte
const unsigned extraBits = Bits - 8 * Bytes;
if (extraBits > 0) {
unsigned char theByte;
ar >> boost::serialization::make_nvp("item", theByte);
const unsigned int count = 8 * Bytes;
t.set(count, theByte & 0x01);
for (unsigned int j = 1; j < extraBits; j++) {
theByte = theByte >> 1;
t.set(count + j, theByte & 0x01);
}
}
}
开发者ID:cce,项目名称:serialization,代码行数:30,代码来源:bitset.hpp
示例2: perform_round
std::bitset<BLOCK_SIZE/2> perform_round(const std::bitset<BLOCK_SIZE/2>& data, const std::bitset<ROUND_KEY_SIZE>& round_key) {
// expand/permute data from 32b to 48b using e_table
std::bitset<48> expansion;
for (int i = 0; i < e_table.size(); ++i) {
expansion.set(i, data.test(e_table[i] - 1));
}
expansion ^= round_key;
// perform s-box substitution on expanded data
std::bitset<32> s_box_out = perform_sbox_subst(expansion);
// permute using P table
std::bitset<32> shrinkage;
for (int i = 0; i < p_table.size(); ++i)
shrinkage.set(i, expansion.test(p_table[i] - 1));
return shrinkage;
}
开发者ID:noreirik,项目名称:dat510,代码行数:17,代码来源:Feistel_cipher.cpp
示例3: generateCombinationsForK
void MasksTableGenerator::generateCombinationsForK(
const std::bitset<8> & combination,
unsigned char offset,
unsigned char k,
std::vector<mask_t> & combinationMasks)
{
if (k == 0)
{
combinationMasks.push_back(combination.to_ulong());
return;
}
for (auto i = offset; i < m_numSamples - (k - 1); ++i)
{
auto newCombination = combination;
newCombination.set(i, true);
generateCombinationsForK(newCombination, i + 1, k - 1, combinationMasks);
}
}
开发者ID:lanice,项目名称:glexamples,代码行数:19,代码来源:MasksTableGenerator.cpp
示例4: calc_support
float Apriori::calc_support(std::bitset<NUM> bsdata)
{
float support = 0.0;
unsigned count = 0;
std::bitset<NUM> b;
/*
* 1. std::map<unsigned ,IndexBitSet_t> m_base_dataset;
* (data,vec float) -> (data,bitset)
* */
if(bsdata.none()) return 0.0;
for(auto iter = this->m_base_dataset.begin();
iter!= this->m_base_dataset.end(); iter++){
b.reset();
b |= (this->m_bitset_vec[iter->second] & bsdata) ^ bsdata;
if(b.none()) count++;
}
support = (count*1.0) / (this->m_base_dataset.size() * 1.0);
return support;
}
开发者ID:linails,项目名称:datamining,代码行数:19,代码来源:apriori.cpp
示例5: randomFlip
void BSO::randomFlip(std::bitset<chromoLength> ¶msBS, int type)
{
return; //no change
int pos = 0;
if(type == 0) //flip in all position
{
pos = rand()%chromoLength;
}
else if(type == 1) //flip im only
{
pos = rand()%imLength;
}
else if(type == 2) //flip pf only
{
pos = imLength + rand()%pfLength;
}
paramsBS = paramsBS.flip(pos);
}
开发者ID:simingl,项目名称:IM_Debug_Terran_GA_Micro,代码行数:20,代码来源:BSO.cpp
示例6: bin_to_hex
std::string bin_to_hex(std::bitset<4> bit)
{
if (bit.to_string().compare("0000") == 0) return std::string("0");
if (bit.to_string().compare("0001") == 0) return std::string("1");
if (bit.to_string().compare("0010") == 0) return std::string("2");
if (bit.to_string().compare("0011") == 0) return std::string("3");
if (bit.to_string().compare("0100") == 0) return std::string("4");
if (bit.to_string().compare("0101") == 0) return std::string("5");
if (bit.to_string().compare("0110") == 0) return std::string("6");
if (bit.to_string().compare("0111") == 0) return std::string("7");
if (bit.to_string().compare("1000") == 0) return std::string("8");
if (bit.to_string().compare("1001") == 0) return std::string("9");
if (bit.to_string().compare("1010") == 0) return std::string("A");
if (bit.to_string().compare("1011") == 0) return std::string("B");
if (bit.to_string().compare("1100") == 0) return std::string("C");
if (bit.to_string().compare("1101") == 0) return std::string("D");
if (bit.to_string().compare("1110") == 0) return std::string("E");
if (bit.to_string().compare("1111") == 0) return std::string("F");
else
return std::string("");
}
开发者ID:zhouzhen24,项目名称:Hardware-Programming-Language-Compiler-and-Simulator,代码行数:23,代码来源:bin_to_hex.cpp
示例7: instrumentCallInst
void NullDerefProtectionTransformer::instrumentCallInst(llvm::Instruction*
TheCall, const std::bitset<32>& ArgIndexs) {
llvm::CallSite CS = TheCall;
for (int index = 0; index < 32; ++index) {
if (!ArgIndexs.test(index)) continue;
llvm::Value* Arg = CS.getArgument(index);
if (!Arg) continue;
llvm::Type* ArgTy = Arg->getType();
llvm::BasicBlock* OldBB = TheCall->getParent();
llvm::ICmpInst* Cmp
= new llvm::ICmpInst(TheCall, llvm::CmpInst::ICMP_EQ, Arg,
llvm::Constant::getNullValue(ArgTy), "");
llvm::Instruction* Inst = Builder->GetInsertPoint();
llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst);
OldBB->getTerminator()->eraseFromParent();
llvm::BranchInst::Create(getTrapBB(NewBB), NewBB, Cmp, OldBB);
}
}
开发者ID:agheorghiu,项目名称:root,代码行数:22,代码来源:NullDerefProtectionTransformer.cpp
示例8: expect_op_result
void expect_op_result(
std::string op,
std::bitset<BITS> bits,
quadset<BITS> q1,
quadset<BITS> q2,
quadset<BITS> quad,
speed_tradeoff tradeoff = ACCURATE
) {
for (bitpos i = 0; i < BITS; ++i) {
if (bits.test(i) != quad.test(i)) {
EXPECT_EQ(false, true) << q1.to_string() << ' ' << op << ' '
<< q2.to_string() << " = " << quad.to_string()
<< "; expected " << bits;
}
}
if (tradeoff != FAST) {
if ((BITS & 0x3F) != 0) {
for (bitpos i = BITS; i < ((BITS+63) & ~0x3F); ++i) {
EXPECT_EQ(false, quad.test(i)) << "found set bit (#"
<< i << ") out of set range in " << quad.to_string() << op;
}
}
}
}
开发者ID:perlmonger42,项目名称:hex-cpp,代码行数:24,代码来源:quadset_test.cpp
示例9: remove_unused_locals
void remove_unused_locals(Context const ctx,
std::bitset<kMaxTrackedLocals> usedLocals) {
if (!options.RemoveUnusedLocals) return;
auto const func = ctx.func;
/*
* Removing unused locals in closures requires checking which ones
* are captured variables so we can remove the relevant properties,
* and then we'd have to mutate the CreateCl callsite, so we don't
* bother for now.
*
* Note: many closure bodies have unused $this local, because of
* some emitter quirk, so this might be worthwhile.
*/
if (func->isClosureBody) return;
func->locals.erase(
std::remove_if(
begin(func->locals) + func->params.size(),
end(func->locals),
[&] (const std::unique_ptr<php::Local>& l) {
if (l->id < kMaxTrackedLocals && !usedLocals.test(l->id)) {
FTRACE(2, " removing: {}\n", local_string(borrow(l)));
return true;
}
return false;
}
),
end(func->locals)
);
// Fixup local ids, in case we removed any.
for (auto i = uint32_t{0}; i < func->locals.size(); ++i) {
func->locals[i]->id = i;
}
}
开发者ID:KOgames,项目名称:hhvm,代码行数:36,代码来源:dce.cpp
示例10: if
FF::SearchState FF::Graph::SearchForPatterns(Graph *other, int row, Pattern &pattern, std::list<Pattern> &patterns, std::list<Node*> &affectedNodes, std::bitset<MAX_NODES> &affectedNodesBitset)
{
// Fetch the current node
Node *node = this->m_Nodes[row];
if (affectedNodesBitset[node->Position]) {
return NONE;
}
// Only if the pattern key is of the node's type
if (this->m_Matrix[row][this->m_MatrixLength - 1] >= pattern.RequirementsLength && pattern.Key == node->Type) {
// Create storage for the found matches
std::list<Node*> matches;
int nonTraversableMatches = 0;
// Iterate of the columns for the given row
#pragma omp parallel for ordered schedule(dynamic)
for (unsigned int i = 0 ; i < this->m_Nodes.size() ; ++i) {
// Narrow our matches set by only adding matches that were not yet marked
// as affected
if (!affectedNodesBitset[this->m_Nodes[i]->Position]) {
// If the matrix contains a connection at row,i
if (this->m_Matrix[row][i] == 1) {
// In case of a match
if (pattern.Requirements & (1 << this->m_Nodes[i]->Type.GetId())) {
matches.push_back(this->m_Nodes[i]);
}
// Nothing to do
else {
}
}
} else {
++nonTraversableMatches;
}
}
int s = matches.size() + nonTraversableMatches;
// If the row contains all required types
if (s >= pattern.RequirementsLength && s > 0) {
// Invalidate the pattern
pattern.Key = NullNodeType();
++this->m_PatternsMatched;
// Mark the node as affected
affectedNodesBitset.set(this->m_Nodes[row]->Position);
// Insert the node into the affected nodes list
affectedNodes.push_back(this->m_Nodes[row]);
// Recursively search for more matches
this->SearchInMatches(other, matches, patterns, affectedNodes, affectedNodesBitset);
// Return searchstate
return TRAVERSE;
}
// Row does not contain all required types, but is a leaf
else if (s == 0 && pattern.RequirementsLength == 0) {
// Invalidate the pattern
pattern.Key = NullNodeType();
++this->m_PatternsMatched;
// Mark the node as affected
affectedNodesBitset.set(this->m_Nodes[row]->Position);
// Insert the node into the affected nodes list
affectedNodes.push_back(this->m_Nodes[row]);
// Return searchstate
return LEAF;
}
}
return NONE;
}
开发者ID:ofx,项目名称:graph-implementation,代码行数:79,代码来源:Graph.cpp
示例11: set
bool set(std::bitset<N>& bset, uint32 pos) {
bool old = bset.test(pos);
bset.set(pos);
return old;
}
开发者ID:MathieuTurcotte,项目名称:exact-cover,代码行数:5,代码来源:sudoku_validation.hpp
示例12: serialize
void serialize(output_archive & ar, const std::bitset<N> & bs, unsigned)
{
std::string const bits = bs.to_string();
ar << bits;
}
开发者ID:K-ballo,项目名称:hpx,代码行数:5,代码来源:bitset.hpp
示例13: setEase
namespace Tangram {
const static size_t MAX_WORKERS = 2;
std::mutex m_tilesMutex;
std::mutex m_tasksMutex;
std::mutex m_sceneMutex;
std::queue<std::function<void()>> m_tasks;
std::unique_ptr<TileWorker> m_tileWorker;
std::unique_ptr<TileManager> m_tileManager;
std::shared_ptr<Scene> m_scene;
std::shared_ptr<View> m_view;
std::unique_ptr<Labels> m_labels;
std::unique_ptr<InputHandler> m_inputHandler;
std::shared_ptr<Scene> m_nextScene;
std::vector<Scene::Update> m_sceneUpdates;
std::array<Ease, 4> m_eases;
enum class EaseField { position, zoom, rotation, tilt };
void setEase(EaseField _f, Ease _e) {
m_eases[static_cast<size_t>(_f)] = _e;
requestRender();
}
void clearEase(EaseField _f) {
static Ease none = {};
m_eases[static_cast<size_t>(_f)] = none;
}
static float g_time = 0.0;
static std::bitset<8> g_flags = 0;
static bool g_cacheGlState = false;
AsyncWorker m_asyncWorker;
void initialize(const char* _scenePath) {
// For some unknown reasons, android fails to render the map, if same scene is reloaded, without resetting any of
// the other Tangram global resources, which is what this method does.
// As a work-around, re-initialization of an already loaded scene is done along with resetting all the Tangram
// global resources.
// NOTE: This will be refactored completely with Multiple Tangram Instances work being done in parallel.
if (m_scene && m_scene->path() == _scenePath) {
LOGD("Specified scene is already initalized.");
}
LOG("initialize");
// Create view
m_view = std::make_shared<View>();
// Create a scene object
m_scene = std::make_shared<Scene>(_scenePath);
// Input handler
m_inputHandler = std::make_unique<InputHandler>(m_view);
// Instantiate workers
m_tileWorker = std::make_unique<TileWorker>(MAX_WORKERS);
// Create a tileManager
m_tileManager = std::make_unique<TileManager>(*m_tileWorker);
// Label setup
m_labels = std::make_unique<Labels>();
LOG("finish initialize");
}
void setScene(std::shared_ptr<Scene>& _scene) {
{
std::lock_guard<std::mutex> lock(m_sceneMutex);
m_scene = _scene;
}
auto& camera = m_scene->camera();
m_view->setCameraType(camera.type);
switch (camera.type) {
case CameraType::perspective:
m_view->setVanishingPoint(camera.vanishingPoint.x,
camera.vanishingPoint.y);
if (camera.fovStops) {
m_view->setFieldOfViewStops(camera.fovStops);
} else {
m_view->setFieldOfView(camera.fieldOfView);
}
break;
case CameraType::isometric:
m_view->setObliqueAxis(camera.obliqueAxis.x,
camera.obliqueAxis.y);
break;
case CameraType::flat:
break;
}
if (m_scene->useScenePosition) {
glm::dvec2 projPos = m_view->getMapProjection().LonLatToMeters(m_scene->startPosition);
m_view->setPosition(projPos.x, projPos.y);
//.........这里部分代码省略.........
开发者ID:examyes,项目名称:tangram-es,代码行数:101,代码来源:tangram.cpp
示例14: setAddressAsBinary
//Sets address in the binary form
void IPAddress::setAddressAsBinary(std::bitset<32> ip_address)
{
unsigned long int value = ip_address.to_ulong();
setAddressAsUnsignedLongInt(value);
}
开发者ID:davidxvuong,项目名称:VLSMSubnettingPractice,代码行数:6,代码来源:IPAddress.cpp
示例15: operator
void operator ()(Shuttler& shuttle, const char* name,
std::bitset<N> value) const {
std::uint64_t v = static_cast<std::uint64_t>(value.to_ullong());
shuttle.Send(name, v);
}
开发者ID:eidolonsystems,项目名称:beam,代码行数:5,代码来源:ShuttleBitset.hpp
示例16: AnalizeExport
BOOL CPEParser::AnalizeExport()
{
//флаги наличия имени у функции (определяется заблаговременно, чтобы не было warning'а из-за goto).
static std::bitset<0x10000> NamesFlags;
NamesFlags.reset();
//получить директорию экспорта
PIMAGE_DATA_DIRECTORY pDataDirectory=mpImageOptionalHeader->DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
//если экспорта нет, закончить
if(!pDataDirectory->VirtualAddress || pDataDirectory->Size<sizeof(IMAGE_EXPORT_DIRECTORY)) return TRUE;
//считать дескриптор экспорта
CYBER_ADDRESS DescriptorAddress=mSettings.BaseAddress+pDataDirectory->VirtualAddress;
IMAGE_EXPORT_DIRECTORY Descriptor;
try
{
mpMemory->Data(&Descriptor,DescriptorAddress,sizeof(IMAGE_EXPORT_DIRECTORY));
}
catch(CCyberMemoryPageFaultException)
{
goto error;
}
//создать список экспорта
CImageListExports* pExportsList=new CImageListExports;
//добавить его в список дополнительных объектов
mpExtendMap->insert(std::make_pair(IMAGE_EXTEND_LIST_EXPORTS,pExportsList));
//получить список функций
std::list<CImageListExports::CExportFunction*>* pFunctionsList=pExportsList->GetList();
//получить количество функций и имен
UINT FunctionsCount=Descriptor.NumberOfFunctions;
if(FunctionsCount>0x10000) goto error;
UINT NamesCount=Descriptor.NumberOfNames;
if(NamesCount>0x10000) goto error;
//получить таблицы имен, адресов и ординалов
CYBER_ADDRESS AddressTable=mSettings.BaseAddress+Descriptor.AddressOfFunctions;
CYBER_ADDRESS NamesTable=mSettings.BaseAddress+Descriptor.AddressOfNames;
CYBER_ADDRESS OrdinalsTable=mSettings.BaseAddress+Descriptor.AddressOfNameOrdinals;
//цикл по именам
for(UINT i=0;i<NamesCount;++i)
{
//считать имя, ординал, адрес и форвард функции
LPSTR szName;
LPSTR szForward;
WORD Ordinal;
CYBER_ADDRESS Address;
//флаг форварда
BOOL IsForward=FALSE;
try
{
//считать имя
szName=mpMemory->ReadASCIIZ(mSettings.BaseAddress+mpMemory->Dword(NamesTable+i*sizeof(DWORD)));
//считать ординал
Ordinal=mpMemory->Word(OrdinalsTable+i*sizeof(WORD));
//считать адрес
Address=mpMemory->Dword(AddressTable+Ordinal*sizeof(DWORD));
//если адрес находится в пределах таблицы экспорта, значит, это форвард
if(Address>=pDataDirectory->VirtualAddress && Address<pDataDirectory->VirtualAddress+pDataDirectory->Size)
IsForward=TRUE;
Address+=mSettings.BaseAddress;
if(IsForward)
//считать имя форвард-функции
szForward=mpMemory->ReadASCIIZ(Address);
}
catch(CCyberMemoryPageFaultException)
{
goto error;
}
//указать флаг наличия имени
NamesFlags[Ordinal]=true;
#ifdef UNICODE
//преобразовать строки в Unicode
UINT NameLength=strlen(szName)+1;
LPTSTR szUnicodeName=new TCHAR[NameLength];
MultiByteToWideChar(CP_ACP,0,szName,-1,szUnicodeName,NameLength);
SafeDeleteMassive(szName);
UINT ForwardLength;
LPTSTR szUnicodeForward;
if(IsForward)
{
ForwardLength=strlen(szForward)+1;
szUnicodeForward=new TCHAR[ForwardLength];
MultiByteToWideChar(CP_ACP,0,szForward,-1,szUnicodeForward,ForwardLength);
SafeDeleteMassive(szForward);
}
#define szName szUnicodeName
#define szForward szUnicodeForward
#endif
//добавить функцию в список
if(IsForward)
pFunctionsList->push_back(new CImageListExports::CExportFunction(szName,Ordinal,szForward));
else
pFunctionsList->push_back(new CImageListExports::CExportFunction(szName,Ordinal,Address));
//.........这里部分代码省略.........
开发者ID:revel8n,项目名称:code0,代码行数:101,代码来源:pe_parser.cpp
示例17: initialize
namespace Tangram {
std::unique_ptr<TileManager> m_tileManager;
std::shared_ptr<Scene> m_scene;
std::shared_ptr<View> m_view;
std::unique_ptr<Labels> m_labels;
std::unique_ptr<Skybox> m_skybox;
std::unique_ptr<InputHandler> m_inputHandler;
std::mutex m_tilesMutex;
static float g_time = 0.0;
static std::bitset<8> g_flags = 0;
int log_level = 2;
void initialize(const char* _scenePath) {
if (m_tileManager) {
LOG("Notice: Already initialized");
return;
}
LOG("initialize");
// Create view
m_view = std::make_shared<View>();
// Create a scene object
m_scene = std::make_shared<Scene>();
// Input handler
m_inputHandler = std::unique_ptr<InputHandler>(new InputHandler(m_view));
// Create a tileManager
m_tileManager = TileManager::GetInstance();
// Pass references to the view and scene into the tile manager
m_tileManager->setView(m_view);
// label setup
m_labels = std::unique_ptr<Labels>(new Labels());
loadScene(_scenePath, true);
glm::dvec2 projPos = m_view->getMapProjection().LonLatToMeters(m_scene->startPosition);
m_view->setPosition(projPos.x, projPos.y);
m_view->setZoom(m_scene->startZoom);
LOG("finish initialize");
}
void loadScene(const char* _scenePath, bool _setPositionFromScene) {
LOG("Loading scene file: %s", _scenePath);
auto sceneString = stringFromFile(setResourceRoot(_scenePath).c_str(), PathType::resource);
bool setPositionFromCurrentView = bool(m_scene);
auto scene = std::make_shared<Scene>();
if (SceneLoader::loadScene(sceneString, *scene)) {
m_scene = scene;
m_scene->fontContext()->addFont("FiraSans", "Medium", "");
if (setPositionFromCurrentView && !_setPositionFromScene) {
m_scene->view()->setPosition(m_view->getPosition());
m_scene->view()->setZoom(m_view->getZoom());
}
m_view = m_scene->view();
m_inputHandler->setView(m_view);
m_tileManager->setView(m_view);
m_tileManager->setScene(scene);
}
}
void resize(int _newWidth, int _newHeight) {
LOG("resize: %d x %d", _newWidth, _newHeight);
glViewport(0, 0, _newWidth, _newHeight);
if (m_view) {
m_view->setSize(_newWidth, _newHeight);
}
for (auto& style : m_scene->styles()) {
style->viewportHasChanged();
}
Primitives::setResolution(_newWidth, _newHeight);
while (Error::hadGlError("Tangram::resize()")) {}
}
void update(float _dt) {
g_time += _dt;
m_inputHandler->update(_dt);
//.........这里部分代码省略.........
开发者ID:deepinit-arek,项目名称:tangram-es,代码行数:101,代码来源:tangram.cpp
示例18: OnUserConnect
void OnUserConnect(LocalUser* user)
{
ConfigTag* tag = user->MyClass->config;
std::string vhost = tag->getString("vhost");
std::string replace;
if (vhost.empty())
return;
replace = "$ident";
if (vhost.find(replace) != std::string::npos)
{
std::string ident = user->ident;
if (ident[0] == '~')
ident.erase(0, 1);
SearchAndReplace(vhost, replace, ident);
}
replace = "$account";
if (vhost.find(replace) != std::string::npos)
{
std::string account = GetAccount(user);
if (account.empty())
account = "unidentified";
SearchAndReplace(vhost, replace, account);
}
if (vhost.length() > 64)
{
ServerInstance->Logs->Log("m_conn_vhost", DEFAULT, "m_conn_vhost: vhost in connect block %s is too long", user->MyClass->name.c_str());
return;
}
/* from m_sethost: validate the characters */
for (std::string::const_iterator x = vhost.begin(); x != vhost.end(); x++)
{
if (!hostmap.test(static_cast<unsigned char>(*x)))
{
ServerInstance->Logs->Log("m_conn_vhost", DEFAULT, "m_conn_vhost: vhost in connect block %s has invalid characters", user->MyClass->name.c_str());
return;
}
}
user->ChangeDisplayedHost(vhost.c_str());
}
开发者ID:aszrul,项目名称:inspircd-extras,代码行数:47,代码来源:m_conn_vhost.cpp
示例19: main
int main(){
// do you mind telling us in the problem statement
// that there is more than one test case per input
while(~scanf("%d%d",&N,&M)){
V.clear();
for(int i=1;i<=N;++i){
scanf("%d",W+i);
V.emplace_back(W[i]);
}
std::sort(all(V));
V.erase(std::unique(all(V)),V.end());
for(int i=1;i<=N;++i)
W[i]=std::lower_bound(all(V),W[i])-V.begin();
for(int i=1;i<=N;++i)
adj[i].clear();
for(int i=1,a,b;i<N;++i){
scanf("%d%d",&a,&b);
adj[a].emplace_back(b);
adj[b].emplace_back(a);
}
dfs(1,-1);
build();
for(int i=0,a,b,l;i<M;++i){
scanf("%d%d",&a,&b);
l=lca(a,b);
if(ein[b]<ein[a]) std::swap(a,b);
if(a==l||b==l) qrys[i]={ein[a],ein[b],-1,i};
else qrys[i]={eout[a],ein[b],l,i};
}
std::sort(qrys,qrys+M);
vis.reset();
memset(cnt,0,sizeof cnt);
res=0;
chk(tour[1]);
for(int i=0,l=1,r=1;i<M;++i){
while(r<qrys[i].r) chk(tour[++r]);
while(l>qrys[i].l) chk(tour[--l]);
while(r>qrys[i].r) chk(tour[r--]);
while(l<qrys[i].l) chk(tour[l++]);
if(~qrys[i].lca) chk(qrys[i].lca);
ans[qrys[i].i]=res;
if(~qrys[i].lca) chk(qrys[i].lca);
}
for(int i=0;i<M;printf("%d\n",ans[i++]));
}
}
开发者ID:BinAccel,项目名称:competitive-programming,代码行数:46,代码来源:COT2.cpp
示例20: main
int main()
{
int substr_len;
//use the number of unique characters as number base
int base;
scanf("%d %d", &substr_len, &base);
scanf("%s", str);
int length = strlen(str);
if(length < substr_len)
{
printf("0\n");
return 0;
}
int unique_character = 0;
int index = 0;
while(unique_character < base)
{
if(value[str[index]] == 0)
value[str[index]] = unique_character++;
index++;
}
long rolling_hash = 0;
for(int i = 0; i < substr_len; ++i)
rolling_hash = rolling_hash * base + value[str[i]];
mark[rolling_hash] = 1;
// Calculate hash value for next window of text: Remove leading digit, add trailing digit
// hash(s[i+1 ... i+m] ) = base *(hash(s[i .. s+i-1]) – s[i] * (b^(m-1) ) )+ s[i + m]
//h = pow(base, substr_len - 1)
int h = 1;
for (int i = 0; i < substr_len - 1; i++)
h *= base; //int overflow?
for(int i = 0; i < length - substr_len; i++)
{
rolling_hash = base *(rolling_hash - value[str[i]] * h) + value[str[i + substr_len]];
mark[rolling_hash] = 1;
}
printf("%ld\n", mark.count());
return 0;
};
开发者ID:jflyup,项目名称:POJ,代码行数:46,代码来源:1200.cpp
注:本文中的std::bitset类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论