vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { // Start typing your C/C++ solution below // DO NOT write int main() function dict.insert(start); dict.insert(end); vector<string> vdict(dict.begin(), dict.end()); // vector dictionary: id -> word mapping in dict unordered_map<string, int> ids; // index dictionary: word -> id mapping in vdict vector<vector<int> > prev(dict.size()); // store the previous words in BFS vector<int> distance(dict.size(), -1); // store the distance from start // build string - index mapping, transfer problem to graph search // use interger instead of string to eliminate cost of string matching for(int i = 0; i < vdict.size(); i++) ids[vdict[i]] = i; // find the index of start and end words int vbeg=0, vend=0; while(vdict[vbeg] != start) vbeg++; while(vdict[vend] != end) vend++; // use queue for BFS to search path from start to end queue<int> que; que.push(vbeg); distance[vbeg]=0; while(!que.empty()){ int now = que.front(); que.pop(); if(now == vend){ break; } int d = distance[now]+1; vector<int> adj; ids.erase(vdict[now]); for(int i = 0; i < vdict[now].size(); i ++){ char w = vdict[now][i]; for(char j = 'a'; j <= 'z'; j ++){ vdict[now][i] = j; if(ids.count(vdict[now])){ adj.push_back(ids[vdict[now]]); } vdict[now][i] = w; } } for(int i = 0; i < adj.size(); i ++){ if(distance[adj[i]] == -1){ distance[adj[i]] = d; que.push(adj[i]); prev[adj[i]].push_back(now); } else if(distance[adj[i]] == d){ prev[adj[i]].push_back(now); } } } results.clear(); path.clear(); genpath(vbeg, vend, vdict, prev, path); return results; }
/* * add_pack: * Pick up an object and add it to the pack. If the argument is non-null * use it as the linked_list pointer instead of gettting it off the ground. */ void add_pack(struct linked_list *item, int silent) { struct linked_list *ip, *lp; struct object *obj, *op; int exact, from_floor; if (item == NULL) { from_floor = TRUE; if ((item = find_obj(hero.y, hero.x)) == NULL) return; } else from_floor = FALSE; obj = (struct object *) ldata(item); /* * Link it into the pack. Search the pack for a object of similar type * if there isn't one, stuff it at the beginning, if there is, look for one * that is exactly the same and just increment the count if there is. * it that. Food is always put at the beginning for ease of access, but * is not ordered so that you can't tell good food from bad. First check * to see if there is something in thr same group and if there is then * increment the count. */ if (obj->o_group) { for (ip = pack; ip != NULL; ip = next(ip)) { op = (struct object *) ldata(ip); if (op->o_group == obj->o_group) { /* * Put it in the pack and notify the user */ op->o_count++; if (from_floor) { detach(lvl_obj, item); mvaddch(hero.y, hero.x, (roomin(&hero) == NULL ? PASSAGE : FLOOR)); } discard(item); item = ip; goto picked_up; } } } /* * Check if there is room */ if (inpack == MAXPACK-1) { msg("You can't carry anything else."); return; } /* * Check for and deal with scare monster scrolls */ if (obj->o_type == SCROLL && obj->o_which == S_SCARE) if (obj->o_flags & ISFOUND) { msg("The scroll turns to dust as you pick it up."); detach(lvl_obj, item); mvaddch(hero.y, hero.x, FLOOR); return; } else obj->o_flags |= ISFOUND; inpack++; if (from_floor) { detach(lvl_obj, item); mvaddch(hero.y, hero.x, (roomin(&hero) == NULL ? PASSAGE : FLOOR)); } /* * Search for an object of the same type */ exact = FALSE; for (ip = pack; ip != NULL; ip = next(ip)) { op = (struct object *) ldata(ip); if (obj->o_type == op->o_type) break; } if (ip == NULL) { /* * Put it at the end of the pack since it is a new type */ for (ip = pack; ip != NULL; ip = next(ip)) { op = (struct object *) ldata(ip); if (op->o_type != FOOD) break; lp = ip; } } else { /* * Search for an object which is exactly the same */ while (ip != NULL && op->o_type == obj->o_type) { if (op->o_which == obj->o_which) { exact = TRUE; break; } lp = ip; if ((ip = next(ip)) == NULL) break; op = (struct object *) ldata(ip); } } if (ip == NULL) { /* * Didn't find an exact match, just stick it here */ if (pack == NULL) pack = item; else { lp->l_next = item; item->l_prev = lp; item->l_next = NULL; } } else { /* * If we found an exact match. If it is a potion, food, or a * scroll, increase the count, otherwise put it with its clones. */ if (exact && ISMULT(obj->o_type)) { op->o_count++; discard(item); item = ip; goto picked_up; } if ((item->l_prev = prev(ip)) != NULL) item->l_prev->l_next = item; else pack = item; item->l_next = ip; ip->l_prev = item; } picked_up: /* * Notify the user */ obj = (struct object *) ldata(item); if (notify && !silent) { if (!terse) addmsg("You now have "); msg("%s (%c)", inv_name(obj, !terse), pack_char(obj)); } if (obj->o_type == AMULET) amulet = TRUE; }
void erase(set<SetElem>::iterator it) { if (it != data.begin()) prev(it)->next = it->next; data.erase(it); }
bool findNodeOrientation (const TrigCyclIter &cur, bool convex, bool convexInit) { TrigCyclIter prev( cur ); --prev; TrigCyclIter next( cur ); ++next; return findNodeOrientation( *prev, *cur, *next, convex, convexInit ); }
void maktab(void) /* define the tab stops of the table */ { int icol, ilin, tsep, k, ik, vforml, il, s, text; char *ss; for (icol = 0; icol < ncol; icol++) { doubled[icol] = acase[icol] = 0; Bprint(&tabout, ".nr %2s 0\n", reg(icol, CRIGHT)); for (text = 0; text < 2; text++) { if (text) Bprint(&tabout, ".%2s\n.rm %2s\n", reg(icol, CRIGHT), reg(icol, CRIGHT)); for (ilin = 0; ilin < nlin; ilin++) { if (instead[ilin] || fullbot[ilin]) continue; vforml = ilin; for (il = prev(ilin); il >= 0 && vspen(table[il][icol].col); il = prev(il)) vforml = il; if (fspan(vforml, icol)) continue; if (filler(table[ilin][icol].col)) continue; if ((flags[icol][stynum[ilin]] & ZEROW) != 0) continue; switch (ctype(vforml, icol)) { case 'a': acase[icol] = 1; ss = table[ilin][icol].col; s = (int)(uintptr)ss; if (s > 0 && s < 128 && text) { if (doubled[icol] == 0) Bprint(&tabout, ".nr %d 0\n.nr %d 0\n", S1, S2); doubled[icol] = 1; Bprint(&tabout, ".if \\n(%c->\\n(%d .nr %d \\n(%c-\n", s, S2, S2, (int)s); } case 'n': if (table[ilin][icol].rcol != 0) { if (doubled[icol] == 0 && text == 0) Bprint(&tabout, ".nr %d 0\n.nr %d 0\n", S1, S2); doubled[icol] = 1; if (real(ss = table[ilin][icol].col) && !vspen(ss)) { s = (int)(uintptr)ss; if (tx(s) != text) continue; Bprint(&tabout, ".nr %d ", TMP); wide(ss, FN(vforml, icol), SZ(vforml, icol)); Bprint(&tabout, "\n"); Bprint(&tabout, ".if \\n(%d<\\n(%d .nr %d \\n(%d\n", S1, TMP, S1, TMP); } if (text == 0 && real(ss = table[ilin][icol].rcol) && !vspen(ss) && !barent(ss)) { Bprint(&tabout, ".nr %d \\w%c%s%c\n", TMP, F1, ss, F1); Bprint(&tabout, ".if \\n(%d<\\n(%d .nr %d \\n(%d\n", S2, TMP, S2, TMP); } continue; } case 'r': case 'c': case 'l': if (real(ss = table[ilin][icol].col) && !vspen(ss)) { s = (int)(uintptr)ss; if (tx(s) != text) continue; Bprint(&tabout, ".nr %d ", TMP); wide(ss, FN(vforml, icol), SZ(vforml, icol)); Bprint(&tabout, "\n"); Bprint(&tabout, ".if \\n(%2s<\\n(%d .nr %2s \\n(%d\n", reg(icol, CRIGHT), TMP, reg(icol, CRIGHT), TMP); } } } } if (acase[icol]) { Bprint(&tabout, ".if \\n(%d>=\\n(%2s .nr %2s \\n(%du+2n\n", S2, reg(icol, CRIGHT), reg(icol, CRIGHT), S2); } if (doubled[icol]) { Bprint(&tabout, ".nr %2s \\n(%d\n", reg(icol, CMID), S1); Bprint(&tabout, ".nr %d \\n(%2s+\\n(%d\n", TMP, reg(icol, CMID), S2); Bprint(&tabout, ".if \\n(%d>\\n(%2s .nr %2s \\n(%d\n", TMP, reg(icol, CRIGHT), reg(icol, CRIGHT), TMP); Bprint(&tabout, ".if \\n(%d<\\n(%2s .nr %2s +(\\n(%2s-\\n(%d)/2\n", TMP, reg(icol, CRIGHT), reg(icol, CMID), reg(icol, CRIGHT), TMP); } if (cll[icol][0]) { Bprint(&tabout, ".nr %d %sn\n", TMP, cll[icol]); Bprint(&tabout, ".if \\n(%2s<\\n(%d .nr %2s \\n(%d\n", reg(icol, CRIGHT), TMP, reg(icol, CRIGHT), TMP); } for (ilin = 0; ilin < nlin; ilin++) if (k = lspan(ilin, icol)) { ss = table[ilin][icol-k].col; if (!real(ss) || barent(ss) || vspen(ss) ) continue; Bprint(&tabout, ".nr %d ", TMP); wide(table[ilin][icol-k].col, FN(ilin, icol - k), SZ(ilin, icol - k)); for (ik = k; ik >= 0; ik--) { Bprint(&tabout, "-\\n(%2s", reg(icol - ik, CRIGHT)); if (!expflg && ik > 0) Bprint(&tabout, "-%dn", sep[icol-ik]); } Bprint(&tabout, "\n"); Bprint(&tabout, ".if \\n(%d>0 .nr %d \\n(%d/%d\n", TMP, TMP, TMP, k); Bprint(&tabout, ".if \\n(%d<0 .nr %d 0\n", TMP, TMP); for (ik = 1; ik <= k; ik++) { if (doubled[icol-k+ik]) Bprint(&tabout, ".nr %2s +\\n(%d/2\n", reg(icol - k + ik, CMID), TMP); Bprint(&tabout, ".nr %2s +\\n(%d\n", reg(icol - k + ik, CRIGHT), TMP); } } } if (textflg) untext(); /* if even requested, make all columns widest width */ if (evenflg) { Bprint(&tabout, ".nr %d 0\n", TMP); for (icol = 0; icol < ncol; icol++) { if (evenup[icol] == 0) continue; Bprint(&tabout, ".if \\n(%2s>\\n(%d .nr %d \\n(%2s\n", reg(icol, CRIGHT), TMP, TMP, reg(icol, CRIGHT)); } for (icol = 0; icol < ncol; icol++) { if (evenup[icol] == 0) /* if column not evened just retain old interval */ continue; if (doubled[icol]) Bprint(&tabout, ".nr %2s (100*\\n(%2s/\\n(%2s)*\\n(%d/100\n", reg(icol, CMID), reg(icol, CMID), reg(icol, CRIGHT), TMP); /* that nonsense with the 100's and parens tries to avoid overflow while proportionally shifting the middle of the number */ Bprint(&tabout, ".nr %2s \\n(%d\n", reg(icol, CRIGHT), TMP); } } /* now adjust for total table width */ for (tsep = icol = 0; icol < ncol; icol++) tsep += sep[icol]; if (expflg) { Bprint(&tabout, ".nr %d 0", TMP); for (icol = 0; icol < ncol; icol++) Bprint(&tabout, "+\\n(%2s", reg(icol, CRIGHT)); Bprint(&tabout, "\n"); Bprint(&tabout, ".nr %d \\n(.l-\\n(%d\n", TMP, TMP); if (boxflg || dboxflg || allflg) /* tsep += 1; */ {} else tsep -= sep[ncol-1]; Bprint(&tabout, ".nr %d \\n(%d/%d\n", TMP, TMP, tsep); Bprint(&tabout, ".if \\n(%d<0 .nr %d 0\n", TMP, TMP); } else Bprint(&tabout, ".nr %d 1n\n", TMP); Bprint(&tabout, ".nr %2s 0\n", reg(-1, CRIGHT)); tsep = (boxflg || allflg || dboxflg || left1flg) ? 2 : 0; if (sep[-1] >= 0) tsep = sep[-1]; for (icol = 0; icol < ncol; icol++) { Bprint(&tabout, ".nr %2s \\n(%2s+((%d*\\n(%d)/2)\n", reg(icol, CLEFT), reg(icol - 1, CRIGHT), tsep, TMP); Bprint(&tabout, ".nr %2s +\\n(%2s\n", reg(icol, CRIGHT), reg(icol, CLEFT)); if (doubled[icol]) { /* the next line is last-ditch effort to avoid zero field width */ /*Bprint(&tabout, ".if \\n(%2s=0 .nr %2s 1\n",reg(icol,CMID), reg(icol,CMID));*/ Bprint(&tabout, ".nr %2s +\\n(%2s\n", reg(icol, CMID), reg(icol, CLEFT)); /* Bprint(&tabout, ".if n .if \\n(%s%%24>0 .nr %s +12u\n",reg(icol,CMID), reg(icol,CMID)); */ } tsep = sep[icol] * 2; } if (rightl) Bprint(&tabout, ".nr %s (\\n(%s+\\n(%s)/2\n", reg(ncol - 1, CRIGHT), reg(ncol - 1, CLEFT), reg(ncol - 2, CRIGHT)); Bprint(&tabout, ".nr TW \\n(%2s\n", reg(ncol - 1, CRIGHT)); tsep = sep[ncol-1]; if (boxflg || allflg || dboxflg) Bprint(&tabout, ".nr TW +((%d*\\n(%d)/2)\n", tsep, TMP); Bprint(&tabout, ".if t .if (\\n(TW>\\n(.l .tm Table at line %d file %s is too wide - \\n(TW units\n", iline - 1, ifile); /* * Used to be: ".if t .if (\\n(TW+\\n(.o)>7.65i .tm Table at line %d file %s is too wide - \\n(TW units\n", iline - 1, ifile); * but that gives warnings where none are necessary (or desired) [sape] */ }
bool Vertex::angleIsConvex() { SkPoint vPrev = prev()->point() - point(), vNext = next()->point() - point(); // TODO(turk): There might be overflow in fixed-point. return SkPoint::CrossProduct(vNext, vPrev) >= 0; }
void convert_arc(const dimeEntity *entity, const dimeState *state, dxfLayerData *layerData, dxfConverter *converter) { dimeArc *arc = (dimeArc*) entity; dimeMatrix matrix; state->getMatrix(matrix); dimeVec3f e = arc->getExtrusionDir(); dxfdouble thickness = arc->getThickness(); if (e != dimeVec3f(0,0,1)) { dimeMatrix m; dimeEntity::generateUCS(e, m); matrix.multRight(m); } e = dimeVec3f(0,0,1); dimeVec3f center; arc->getCenter(center); dimeParam param; if (arc->getRecord(38, param)) { center[2] = param.double_data; } dxfdouble radius = arc->getRadius(); double end = arc->getEndAngle(); while (end < arc->getStartAngle()) { end += 360.0; } double delta = DXFDEG2RAD(end - arc->getStartAngle()); if (delta == 0.0) { #ifndef NDEBUG fprintf(stderr,"ARC with startAngle == endAngle!\n"); #endif end += 2*M_PI; delta = DXFDEG2RAD(end - arc->getStartAngle()); } int ARC_NUMPTS = converter->getNumSub(); if (ARC_NUMPTS <= 0) { // use maxerr ARC_NUMPTS = calc_num_sub(converter->getMaxerr(), radius); } // find the number of this ARC that fits inside 2PI int parts = (int) DXFABS((2*M_PI) / delta); // find # pts to use for arc // add one to avoid arcs with 0 line segments int numpts = ARC_NUMPTS / parts + 1; if (numpts > ARC_NUMPTS) numpts = ARC_NUMPTS; double inc = delta / numpts; double rad = DXFDEG2RAD(arc->getStartAngle()); int i; dimeVec3f v; dimeVec3f prev(center[0] + radius * cos(rad), center[1] + radius * sin(rad), center[2]); rad += inc; for (i = 1; i < numpts; i++) { v = dimeVec3f(center[0] + radius * cos(rad), center[1] + radius * sin(rad), center[2]); if (thickness == 0.0) { layerData->addLine(prev, v, &matrix); } else { layerData->addQuad(prev, v, v + e * thickness, prev + e * thickness, &matrix); } prev = v; rad += inc; } rad = DXFDEG2RAD(end); v = dimeVec3f(center[0] + radius * cos(rad), center[1] + radius * sin(rad), center[2]); if (thickness == 0.0) { layerData->addLine(prev, v, &matrix); } else { layerData->addQuad(prev, v, v + e * thickness, prev + e * thickness, &matrix); } }
void Posture::toWelcome(int i) { int count = 0; ModelVideo model; if (i > models.size() - 1 || i == -1) { if (i == -1) models.clear(); m_pmPageManager.GetModel(models, i); if (i != -1) { m_iPage = i / MAXATONCE; count = models.size() - (m_iPage)*MAXATONCE; } else { i = 0; m_iPage = 0; count = models.size(); } } else { m_iPage = i / MAXATONCE; if (models.size() < i + MAXATONCE) { count = models.size() - i; } else { count = MAXATONCE; } } switch (count) { case 0: return; case 1: m_wwPosWin = new WelcomeWindow(this, count, models[i], model, model, model); CloseCurrentWindow(); break; case 2: m_wwPosWin = new WelcomeWindow(this, count, models[i], models[i+1], model, model); CloseCurrentWindow(); break; case 3: m_wwPosWin = new WelcomeWindow(this, count, models[i], models[i+1], models[i+2], model); CloseCurrentWindow(); break; case 4: m_wwPosWin = new WelcomeWindow(this, count, models[i], models[i+1], models[i+2], models[i+3]); CloseCurrentWindow(); break; } this->setCentralWidget(m_wwPosWin); m_wtCurrentWin = WELCOME; modelList.clear(); connect(m_wwPosWin, SIGNAL(display(const ModelVideo&)), this, SLOT(toDisplay(const ModelVideo&))); connect(m_wwPosWin, SIGNAL(toProfileMode(const QString&)), this, SLOT(toProfileMode(const QString&))); connect(m_wwPosWin, SIGNAL(prev()), this, SLOT(prevWelcome())); connect(m_wwPosWin, SIGNAL(next()), this, SLOT(nextWelcome())); connect(m_wwPosWin, SIGNAL(toUpload()), this, SLOT(toUploadMode())); connect(m_wwPosWin, SIGNAL(toHome()), this, SLOT(toHomeWin())); connect(m_wwPosWin, SIGNAL(logout()), this, SLOT(logout())); connect(m_wwPosWin, SIGNAL(refresh()), this, SLOT(firstToHome())); this->setFixedSize(WINDOW_W*xscale, WINDOW_H*yscale); this->move((QApplication::desktop()->width() - WINDOW_W*xscale) / 2, (QApplication::desktop()->height() - WINDOW_H*yscale) / 2); }
void PlayerControls::setupButtons(QMenu *appMenu) { QHBoxLayout *layout = new QHBoxLayout(); QHBoxLayout *leftLayout = new QHBoxLayout(); leftLayout->setAlignment(Qt::AlignLeft); QHBoxLayout *centerLayout = new QHBoxLayout(); centerLayout->setAlignment(Qt::AlignCenter); QHBoxLayout *rightLayout = new QHBoxLayout(); rightLayout->setAlignment(Qt::AlignRight); // Menu button m_wbAppMenu = new StyledButton(QIcon(QPixmap(":icons/menu")), tr("Menu")); m_wbAppMenu->setFixedHeight(28); m_wbAppMenu->setIconSize(QSize(16, 16)); m_wbAppMenu->setMenu(appMenu); // Prev m_wbPrev = new StyledButton(QIcon(QPixmap(":icons/prev")), "Prev"); m_wbPrev->setFixedHeight(28); m_wbPrev->setIconSize(QSize(16, 16)); connect(m_wbPrev, SIGNAL(clicked()), SIGNAL(prev())); // Play m_wbPlay = new StyledButton(QIcon(QPixmap(":icons/play")), "Play"); m_wbPlay->setFixedHeight(28); m_wbPlay->setIconSize(QSize(16, 16)); m_wbPlay->setCheckable(true); connect(m_wbPlay, SIGNAL(clicked()), SIGNAL(play())); // Next m_wbNext = new StyledButton(QIcon(QPixmap(":icons/next")), "Next"); m_wbNext->setFixedHeight(28); m_wbNext->setIconSize(QSize(16, 16)); m_wbNext->setLayoutDirection(Qt::RightToLeft); connect(m_wbNext, SIGNAL(clicked()), SIGNAL(next())); // Shuffle m_wbShuffle = new StyledButton(QIcon(QPixmap(":icons/circle_empty")), "Shuffle"); m_wbShuffle->setCheckable(true); m_wbShuffle->setFixedHeight(28); m_wbShuffle->setIconSize(QSize(16, 16)); setShuffle(Settings::instance()->getValue("player/shuffle").toInt()); connect(m_wbShuffle, SIGNAL(clicked()), SLOT(setShuffle())); // Repeat m_wbRepeat = new StyledButton(QIcon(QPixmap(":icons/circle_empty")), "Repeat"); m_wbRepeat->setCheckable(true); m_wbRepeat->setFixedHeight(28); m_wbRepeat->setIconSize(QSize(16, 16)); setRepeat(Settings::instance()->getValue("player/repeat").toInt()); connect(m_wbRepeat, SIGNAL(clicked()), SLOT(setRepeat())); // Status m_wbStatus = new StyledButton(QIcon(QPixmap(":icons/vk")), ""); m_wbStatus->setCheckable(true); m_wbStatus->setFixedSize(28,28); m_wbStatus->setIconSize(QSize(20, 20)); m_wbStatus->setTransparent(true); connect(m_wbStatus, SIGNAL(clicked(bool)), SLOT(setStatusState(bool))); setStatusState(Settings::instance()->getValue("player/status").toBool()); m_wbLastfm = new StyledButton(QIcon(QPixmap(":icons/lf")), ""); m_wbLastfm->setCheckable(true); m_wbLastfm->setFixedSize(28,28); m_wbLastfm->setIconSize(QSize(20, 20)); m_wbLastfm->setTransparent(true); connect(m_wbLastfm, SIGNAL(clicked(bool)), SLOT(setLastfmState(bool))); setLastfmState(Settings::instance()->getValue("lastfm/scrobbling").toBool()); layout->addLayout(leftLayout); layout->addLayout(centerLayout); layout->addLayout(rightLayout); leftLayout->addWidget(m_wbAppMenu); centerLayout->addWidget(m_wbShuffle); centerLayout->addSpacing(20); centerLayout->addWidget(m_wbPrev); centerLayout->addWidget(m_wbPlay); centerLayout->addWidget(m_wbNext); centerLayout->addSpacing(20); centerLayout->addWidget(m_wbRepeat); rightLayout->addWidget(m_wbStatus); rightLayout->addWidget(m_wbLastfm); m_mainLayout->addLayout(layout, 2, 1); m_mainLayout->setAlignment(layout, Qt::AlignTop); bool isAcc = Settings::instance()->getValue("general/account_use").toBool(); if(!isAcc) { m_wbStatus->setDisabled(true); } }
void operator--(int) { prev(); }
static int handle_event_prev() { return (prev()); }
static int triangulate(int n, const int* verts, int* indices, int* tris) { int ntris = 0; int* dst = tris; // The last bit of the index is used to indicate if the vertex can be removed. for (int i = 0; i < n; i++) { int i1 = next(i, n); int i2 = next(i1, n); if (diagonal(i, i2, n, verts, indices)) indices[i1] |= 0x80000000; } while (n > 3) { int minLen = -1; int mini = -1; for (int i = 0; i < n; i++) { int i1 = next(i, n); if (indices[i1] & 0x80000000) { const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4]; const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4]; int dx = p2[0] - p0[0]; int dy = p2[2] - p0[2]; int len = dx*dx + dy*dy; if (minLen < 0 || len < minLen) { minLen = len; mini = i; } } } if (mini == -1) { // Should not happen. /* printf("mini == -1 ntris=%d n=%d\n", ntris, n); for (int i = 0; i < n; i++) { printf("%d ", indices[i] & 0x0fffffff); } printf("\n");*/ return -ntris; } int i = mini; int i1 = next(i, n); int i2 = next(i1, n); *dst++ = indices[i] & 0x0fffffff; *dst++ = indices[i1] & 0x0fffffff; *dst++ = indices[i2] & 0x0fffffff; ntris++; // Removes P[i1] by copying P[i+1]...P[n-1] left one index. n--; for (int k = i1; k < n; k++) indices[k] = indices[k+1]; if (i1 >= n) i1 = 0; i = prev(i1,n); // Update diagonal flags. if (diagonal(prev(i, n), i1, n, verts, indices)) indices[i] |= 0x80000000; else indices[i] &= 0x0fffffff; if (diagonal(i, next(i1, n), n, verts, indices)) indices[i1] |= 0x80000000; else indices[i1] &= 0x0fffffff; } // Append the remaining triangle. *dst++ = indices[0] & 0x0fffffff; *dst++ = indices[1] & 0x0fffffff; *dst++ = indices[2] & 0x0fffffff; ntris++; return ntris; }
void CalendarEventCoordinator::UpdateNodes( float dt ) { // Now issue events as they come up, including anything currently in the past or present while( parent->GetSimulationTime().time >= times_and_coverages.begin()->first) { int grandTotal = 0; int limitPerNode = -1; // intervention class names for informative logging std::ostringstream intervention_name; intervention_name << std::string( json::QuickInterpreter(intervention_config._json)["class"].As<json::String>() ); auto qi_as_config = Configuration::CopyFromElement( (intervention_config._json), "campaign" ); _di = InterventionFactory::getInstance()->CreateIntervention(qi_as_config); // including deeper information for "distributing" interventions (e.g. calendars) formatInterventionClassNames( intervention_name, &json::QuickInterpreter(intervention_config._json) ); // Only visit individuals if this is NOT an NTI. Check... // Check to see if intervention is an INodeDistributable... INodeDistributableIntervention *ndi = InterventionFactory::getInstance()->CreateNDIIntervention(qi_as_config); INodeDistributableIntervention *ndi2 = nullptr; LOG_DEBUG_F("[UpdateNodes] limitPerNode = %d\n", limitPerNode); for (auto nec : cached_nodes) { if (ndi) { throw NotYetImplementedException( __FILE__, __LINE__, __FUNCTION__ ); #if 0 ndi2 = InterventionFactory::getInstance()->CreateNDIIntervention( qi_as_config ); if(ndi2) { float duration = -1; if (times_and_coverages.size() > 1) { auto iter = times_and_coverages.end(); //A node-targeted intervention issued through the calender coordinator lasts until the next NDI. //Is there an overlap of one day here? Should there be a -1? duration = (float)(prev(iter,2)->first - prev(iter, 1)->first); } INodeDistributableInterventionParameterSetterInterface* pNDIPSI = nullptr; if (s_OK == ndi2->QueryInterface(GET_IID(INodeDistributableInterventionParameterSetterInterface), (void**)&pNDIPSI) ) { pNDIPSI->SetDemographicCoverage(times_and_coverages.begin()->second); pNDIPSI->SetMaxDuration(duration); } if (!ndi2->Distribute( nec, this ) ) { LOG_INFO_F("UpdateNodes() distributed '%s' intervention to node %d\n", intervention_name.str().c_str(), nec->GetId().data ); } ndi2->Release(); } #endif } else { try { // For now, distribute evenly across nodes. int totalIndivGivenIntervention = nec->VisitIndividuals( this, limitPerNode ); grandTotal += totalIndivGivenIntervention; LOG_INFO_F( "UpdateNodes() gave out %d interventions at node %d\n", totalIndivGivenIntervention, nec->GetId().data ); } catch( const json::Exception &e ) { throw GeneralConfigurationException( __FILE__, __LINE__, __FUNCTION__, e.what() ); } } } delete qi_as_config; qi_as_config = nullptr; times_and_coverages.erase(times_and_coverages.begin()); LOG_DEBUG_F("%d Distributions remaining from CalendarEventCoordinator\n", times_and_coverages.size()); if( times_and_coverages.empty() ) { LOG_DEBUG_F("Signaling for disposal of CalendarEventCoordinator\n"); distribution_complete = true; // we're done, signal disposal ok break; } } return; }
/// @par /// /// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour. /// Contours will form simple polygons. /// /// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be /// re-assigned to the zero (null) region. /// /// Partitioning can result in smaller than necessary regions. @p mergeRegionArea helps /// reduce unecessarily small regions. /// /// See the #rcConfig documentation for more information on the configuration parameters. /// /// The region data will be available via the rcCompactHeightfield::maxRegions /// and rcCompactSpan::reg fields. /// /// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions. /// /// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf, const int borderSize, const int minRegionArea, const int mergeRegionArea) { rcAssert(ctx); ctx->startTimer(RC_TIMER_BUILD_REGIONS); const int w = chf.width; const int h = chf.height; unsigned short id = 1; rcScopedDelete<unsigned short> srcReg = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP); if (!srcReg) { ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount); return false; } memset(srcReg,0,sizeof(unsigned short)*chf.spanCount); const int nsweeps = rcMax(chf.width,chf.height); rcScopedDelete<rcSweepSpan> sweeps = (rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP); if (!sweeps) { ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps); return false; } // Mark border regions. if (borderSize > 0) { // Make sure border will not overflow. const int bw = rcMin(w, borderSize); const int bh = rcMin(h, borderSize); // Paint regions paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++; paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++; paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++; paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++; chf.borderSize = borderSize; } rcIntArray prev(256); // Sweep one line at a time. for (int y = borderSize; y < h-borderSize; ++y) { // Collect spans from this row. prev.resize(id+1); memset(&prev[0],0,sizeof(int)*id); unsigned short rid = 1; for (int x = borderSize; x < w-borderSize; ++x) { const rcCompactCell& c = chf.cells[x+y*w]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) { const rcCompactSpan& s = chf.spans[i]; if (chf.areas[i] == RC_NULL_AREA) continue; // -x unsigned short previd = 0; if (rcGetCon(s, 0) != RC_NOT_CONNECTED) { const int ax = x + rcGetDirOffsetX(0); const int ay = y + rcGetDirOffsetY(0); const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0); if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai]) previd = srcReg[ai]; } if (!previd) { previd = rid++; sweeps[previd].rid = previd; sweeps[previd].ns = 0; sweeps[previd].nei = 0; } // -y if (rcGetCon(s,3) != RC_NOT_CONNECTED) { const int ax = x + rcGetDirOffsetX(3); const int ay = y + rcGetDirOffsetY(3); const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3); if (srcReg[ai] && (srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai]) { unsigned short nr = srcReg[ai]; if (!sweeps[previd].nei || sweeps[previd].nei == nr) { sweeps[previd].nei = nr; sweeps[previd].ns++; prev[nr]++; } else { sweeps[previd].nei = RC_NULL_NEI; } } } srcReg[i] = previd; } } // Create unique ID. for (int i = 1; i < rid; ++i) { if (sweeps[i].nei != RC_NULL_NEI && sweeps[i].nei != 0 && prev[sweeps[i].nei] == (int)sweeps[i].ns) { sweeps[i].id = sweeps[i].nei; } else { sweeps[i].id = id++; } } // Remap IDs for (int x = borderSize; x < w-borderSize; ++x) { const rcCompactCell& c = chf.cells[x+y*w]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) { if (srcReg[i] > 0 && srcReg[i] < rid) srcReg[i] = sweeps[srcReg[i]].id; } } } ctx->startTimer(RC_TIMER_BUILD_REGIONS_FILTER); // Filter out small regions. chf.maxRegions = id; if (!filterSmallRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg)) return false; ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FILTER); // Store the result out. for (int i = 0; i < chf.spanCount; ++i) chf.spans[i].reg = srcReg[i]; ctx->stopTimer(RC_TIMER_BUILD_REGIONS); return true; }
vector<vector<int>> fourSum(vector<int>& nums, int target) { // method 1 // 先排序然后左右夹逼 // time complexity O(n^3) space complexity O(1) vector<vector<int>> result; if (nums.size() < 4) return result; sort(nums.begin(), nums.end()); auto last = nums.end(); for (auto a = nums.begin(); a < prev(last, 3); ++a) { // prev之前3个位置 for (auto b = next(a); b < prev(last, 2); ++b) { // next(b)b的下一个位置 auto c = next(b); auto d = prev(last); // last前一个位置 while (c < d) { if (*a + *b + *c + *d < target) { ++c; } else if (*a + *b + *c + *d > target) --d; else{ result.push_back({ *a, *b, *c, *d }); ++c; --d; } } } } sort(result.begin(), result.end()); // vector排序? result.erase(unique(result.begin(), result.end()), result.end()); // unique()从输入序列中“删除”所有相邻的重复元素 return result; // 把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址 // method 2 // average O(n^2)worst O(n^4) space O(n^2) vector<vector<int>> result; if (nums.size() < 4) return result; sort(nums.begin(), nums.end()); unordered_multimap<int, pair<int, int>> cache; for (int i = 0; i + 1 < nums.size(); ++i) for (int j = i + 1; j < nums.size(); ++j) cache.insert(make_pair(nums[i] + nums[j], make_pair(i, j))); for (auto i = cache.begin(); i != cache.end(); ++i) { int x = target - i->first; auto range = cache.equal_range(x); for (auto j = range.first; j != range.second; ++j) { auto a = i->second.first; auto b = i->second.second; auto c = j->second.first; auto d = j->second.second; if (a != c && a != d && b != c && b != d) { // a b c d 是序号 vector<int> vec = { nums[a], nums[b], nums[c], nums[d] }; sort(vec.begin(), vec.end()); result.push_back(vec); } } } sort(result.begin(), result.end()); result.erase(unique(result.begin(), result.end()), result.end()); return result; }
int main(){ int nr=3, em=0, stack_nr=0, i; struct node root, *temp; char let, what,no; double number; void *v; double p; struct stack m_stack; m_stack.next=NULL; m_stack.value=NULL; root.next=NULL; root.father=NULL; root.name=NULL; root.prev=NULL; print_help(); while(1){ scanf("%c", &let); if(let=='A'){ em=0; scanf("%c%c", &no, &what); if(what=='I'){ scanf("%d %d",&nr, &em); add(&root, what, nr, em, 0); } if(what=='D'){ scanf("%lf %d",&number, &em); add(&root, what, &number, em, 0); } if(what=='S'){ scanf("%d", &stack_nr); add(&root, what, &m_stack, 1, stack_nr); } if(what=='C'){ char *mes=(char*)malloc(sizeof(char)*20); scanf("%s", mes); scanf("%d", &em); add(&root, what, mes, em, 0); } } else if(let=='D'){ em=0; scanf("%c%c", &no, &what); if(what=='I'){ scanf("%d %d",&nr, &em); delete_all(&root, what, nr, em, 0); } if(what=='D'){ scanf("%lf %d",&number, &em); delete_all(&root, what, &number, em, 0); } if(what=='S'){ scanf("%d", &stack_nr); delete_all(&root, what, &m_stack, 1, stack_nr); } if(what=='C'){ char *mes=(char*)malloc(sizeof(char)*20); scanf("%s", mes); scanf("%d", &em); delete_all(&root, what, mes, em, 0); free(mes); } } else if(let=='P'){ scanf("%c%c",&no, &what); if(what=='I'){ scanf("%d",&nr); temp=prev(&root, what, nr,0); if(temp!=NULL) print_node(*temp); } if(what=='D'){ scanf("%lf",&number); temp=prev(&root, what, &number,0); if(temp!=NULL) print_node(*temp); } if(what=='S'){ scanf("%d", &stack_nr); temp=prev(&root, what, 1,stack_nr); if(temp!=NULL) print_node(*temp); } if(what=='C'){ char *mes=(char*)malloc(sizeof(char)*20); scanf("%s", mes); temp=prev(&root,what, mes,0); if(temp!=NULL) print_node(*temp); free(mes); } } else if(let=='N'){ scanf("%c%c",&no, &what); if(what=='I'){ scanf("%d",&nr); temp=next(&root, what, nr,0); if(temp!=NULL) print_node(*temp); } if(what=='D'){ scanf("%lf",&number); temp=next(&root, what, &number,0); if(temp!=NULL) print_node(*temp); } if(what=='S'){ scanf("%d", &stack_nr); temp=next(&root, what, 1,stack_nr); if(temp!=NULL) print_node(*temp); } if(what=='C'){ char *mes=(char*)malloc(sizeof(char)*20); scanf("%s", mes); temp=next(&root,what, mes,0); if(temp!=NULL) print_node(*temp); free(mes); } printf("next"); } else if(let=='B'){ scanf_s("%d%d%d",&nr, &em, &stack_nr); for(i=0; i<em; i++) stack_push(&root, nr, stack_nr); } else if(let=='C'){ scanf_s("%d%d", &em, &stack_nr); for(i=0; i<em; i++) stack_pop(&root, stack_nr); } else if(let=='S'){ print_all(root); printf("\n"); } else if(let=='H'){ print_help(); } else if(let=='Q'){ break; } } return 0; }
// Remove this Vertex from the { prev, next } linked list. void delink() { Vertex *p = prev(), *n = next(); p->setNext(n); n->setPrev(p); }
/*! * \brief Postdecrement the iterator * \return an iterator the position prior to the decrement. */ iterator operator--(int) { iterator prev(*this); --i; return prev; }
Vertex::VertexType Vertex::classify(Vertex **e0, Vertex **e1) { VertexType type; SkPoint vPrev, vNext; vPrev.fX = prev()->point().fX - point().fX; vPrev.fY = prev()->point().fY - point().fY; vNext.fX = next()->point().fX - point().fX; vNext.fY = next()->point().fY - point().fY; // This can probably be simplified, but there are enough potential bugs, // we will leave it expanded until all cases are tested appropriately. if (vPrev.fY < 0) { if (vNext.fY > 0) { // Prev comes from above, Next goes below. type = MONOTONE; *e0 = prev(); *e1 = this; } else if (vNext.fY < 0) { // The are both above: sort so that e0 is on the left. type = CONCAVE; if (SkPoint::CrossProduct(vPrev, vNext) <= 0) { *e0 = this; *e1 = prev(); } else { *e0 = prev(); *e1 = this; } } else { DebugPrintf("### py < 0, ny = 0\n"); if (vNext.fX < 0) { type = CONCAVE; *e0 = this; // flat to the left *e1 = prev(); // concave on the right } else { type = CONCAVE; *e0 = prev(); // concave to the left *e1 = this; // flat to the right } } } else if (vPrev.fY > 0) { if (vNext.fY < 0) { // Next comes from above, Prev goes below. type = MONOTONE; *e0 = this; *e1 = prev(); } else if (vNext.fY > 0) { // They are both below: sort so that e0 is on the left. type = CONVEX; if (SkPoint::CrossProduct(vPrev, vNext) <= 0) { *e0 = prev(); *e1 = this; } else { *e0 = this; *e1 = prev(); } } else { DebugPrintf("### py > 0, ny = 0\n"); if (vNext.fX < 0) { type = MONOTONE; *e0 = this; // flat to the left *e1 = prev(); // convex on the right - try monotone first } else { type = MONOTONE; *e0 = prev(); // convex to the left - try monotone first *e1 = this; // flat to the right } } } else { // vPrev.fY == 0 if (vNext.fY < 0) { DebugPrintf("### py = 0, ny < 0\n"); if (vPrev.fX < 0) { type = CONCAVE; *e0 = prev(); // flat to the left *e1 = this; // concave on the right } else { type = CONCAVE; *e0 = this; // concave on the left - defer *e1 = prev(); // flat to the right } } else if (vNext.fY > 0) { DebugPrintf("### py = 0, ny > 0\n"); if (vPrev.fX < 0) { type = MONOTONE; *e0 = prev(); // flat to the left *e1 = this; // convex on the right - try monotone first } else { type = MONOTONE; *e0 = this; // convex to the left - try monotone first *e1 = prev(); // flat to the right } } else { DebugPrintf("### py = 0, ny = 0\n"); // First we try concave, then monotone, then convex. if (vPrev.fX <= vNext.fX) { type = CONCAVE; *e0 = prev(); // flat to the left *e1 = this; // flat to the right } else { type = CONCAVE; *e0 = this; // flat to the left *e1 = prev(); // flat to the right } } } return type; }
/*! * \brief Postincrement the iterator * \return an iterator the position prior to the increment. */ iterator operator++(int) { iterator prev(*this); ++i; return prev; }
char *OpenDDLParser::parseDataList( char *in, char *end, Value::ValueType type, Value **data, size_t &numValues, Reference **refs, size_t &numRefs ) { *data = ddl_nullptr; numValues = numRefs = 0; if( ddl_nullptr == in || in == end ) { return in; } in = lookForNextToken( in, end ); if( *in == '{' ) { ++in; Value *current( ddl_nullptr ), *prev( ddl_nullptr ); while( '}' != *in ) { current = ddl_nullptr; in = lookForNextToken( in, end ); if ( Value::ddl_ref == type ) { std::vector<Name*> names; in = parseReference( in, end, names ); if ( !names.empty() ) { Reference *ref = new Reference( names.size(), &names[ 0 ] ); *refs = ref; numRefs = names.size(); } } else if ( Value::ddl_none == type ) { if (isInteger( in, end )) { in = parseIntegerLiteral( in, end, ¤t ); } else if (isFloat( in, end )) { in = parseFloatingLiteral( in, end, ¤t ); } else if (isStringLiteral( *in )) { in = parseStringLiteral( in, end, ¤t ); } else if (isHexLiteral( in, end )) { in = parseHexaLiteral( in, end, ¤t ); } } else { switch(type){ case Value::ddl_int8: case Value::ddl_int16: case Value::ddl_int32: case Value::ddl_int64: case Value::ddl_unsigned_int8: case Value::ddl_unsigned_int16: case Value::ddl_unsigned_int32: case Value::ddl_unsigned_int64: in = parseIntegerLiteral( in, end, ¤t, type); break; case Value::ddl_half: case Value::ddl_float: case Value::ddl_double: in = parseFloatingLiteral( in, end, ¤t, type); break; case Value::ddl_string: in = parseStringLiteral( in, end, ¤t ); break; default: break; } } if( ddl_nullptr != current ) { if( ddl_nullptr == *data ) { *data = current; prev = current; } else { prev->setNext( current ); prev = current; } ++numValues; } in = getNextSeparator( in, end ); if( ',' != *in && Grammar::CloseBracketToken[ 0 ] != *in && !isSpace( *in ) ) { break; } } ++in; } return in; }
void rayCast(Vector2i src, Vector2i dst, RAY_CALLBACK callback, void *data) { if (!callback(src, 0, data) || src == dst) // Start at src. { return; // Callback gave up after the first point, or there are no other points. } Vector2i srcM = map_coord(src); Vector2i dstM = map_coord(dst); Vector2i step, tile, cur, end; initSteps(srcM.x, dstM.x, tile.x, step.x, cur.x, end.x); initSteps(srcM.y, dstM.y, tile.y, step.y, cur.y, end.y); Vector2i prev(0, 0); // Dummy initialisation. bool first = true; Vector2i nextX(0, 0), nextY(0, 0); // Dummy initialisations. bool canX = tryStep(tile.x, step.x, cur.x, end.x, nextX.x, nextX.y, src.x, src.y, dst.x, dst.y); bool canY = tryStep(tile.y, step.y, cur.y, end.y, nextY.y, nextY.x, src.y, src.x, dst.y, dst.x); while (canX || canY) { int32_t xDist = abs(nextX.x - src.x) + abs(nextX.y - src.y); int32_t yDist = abs(nextY.x - src.x) + abs(nextY.y - src.y); Vector2i sel; Vector2i selTile; if (canX && (!canY || xDist < yDist)) // The line crosses a vertical grid line next. { sel = nextX; selTile = tile; canX = tryStep(tile.x, step.x, cur.x, end.x, nextX.x, nextX.y, src.x, src.y, dst.x, dst.y); } else // The line crosses a horizontal grid line next. { assert(canY); sel = nextY; selTile = tile; canY = tryStep(tile.y, step.y, cur.y, end.y, nextY.y, nextY.x, src.y, src.x, dst.y, dst.x); } if (!first) { // Find midpoint. Vector2i avg = (prev + sel) / 2; // But make sure it's on the right tile, since it could be off-by-one if the line passes exactly through a grid intersection. avg.x = std::min(std::max(avg.x, world_coord(selTile.x)), world_coord(selTile.x + 1) - 1); avg.y = std::min(std::max(avg.y, world_coord(selTile.y)), world_coord(selTile.y + 1) - 1); if (!worldOnMap(avg) || !callback(avg, iHypot(avg), data)) { return; // Callback doesn't want any more points, or we reached the edge of the map, so return. } } prev = sel; first = false; } // Include the endpoint. if (!worldOnMap(dst)) { return; // Stop, since reached the edge of the map. } callback(dst, iHypot(dst), data); }
void TestSorterOwnerContainer::manyOrderedNodes() { csjp::Object<Char> ch(NULL); CharContainer c1, c2; TESTSTEP("Fill a container with ordered letters."); unsigned c; for(c='a'; c <= 'z'; c++){ c1.add(new Char(c)); } VERIFY(c1.size() == 'z'-'a'+1); VERIFY(c1.empty() == false); IN_SAFEMODE(c1.validity()); for(c='a'; c <= 'z'; c++){ /*MSG("c1.has(%c)", c);*/ VERIFY(c1.has(Char(c))); } for(c='a'; c <= 'z'; c++){ VERIFY(c1.index(Char(c)) == c-'a'); } for(c='a'; c <= 'z'; c++){ VERIFY(c1.queryAt(c-'a') == Char(c)); } TESTSTEP("C++11 foreach"); Char prev('a'-1); unsigned i = 0; for(const auto& c : c1){ //printf("Char: %c at %u\n", c.data, i); VERIFY(prev < c); i++; } //printf("i: %u\n", i); VERIFY(i == c1.size()); TESTSTEP("Fill a second container with every second letter."); /* second half sized container */ for(c='a'; c <= 'z'; c++){ if(c%2) c2.add(new Char(c)); } IN_SAFEMODE(c2.validity()); VERIFY(c1 != c2); TESTSTEP("Copy constructing."); /* copy constructing */ CharContainer c3(c1); IN_SAFEMODE(c3.validity()); VERIFY(c3.size() == c1.size()); VERIFY(c3 == c1); TESTSTEP("Copying."); /* assignement */ c1 = c2; IN_SAFEMODE(c1.validity()); VERIFY(c1.size() == c2.size()); VERIFY(c1 == c2); TESTSTEP("Remove every second letter from copy constructed container."); /* remove */ for(c='z'; c >= 'a'; c--){ if(!(c%2)) c3.removeAt(c-'a'); IN_SAFEMODE(c3.validity()); } IN_SAFEMODE(c3.validity()); VERIFY(c3.size() == c2.size()); VERIFY(c3 == c2); TESTSTEP("Clear the copy constructed container."); /* clear */ c3.clear(); VERIFY(c3.size() == 0); VERIFY(c3.empty() == true); IN_SAFEMODE(c3.validity()); }
up() { page = prev(page - 1); if (line > 1) line--; }
TextIterator TextIterator::operator ++ (int) { TextIterator prev(*this); operator ++ (); return prev; }
static bool CollectLayerRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf, const int borderSize, unsigned short* srcReg, rcLayerRegionMonotone*& regs, int& nregs) { const int w = chf.width; const int h = chf.height; const int nsweeps = chf.width; rcScopedDelete<rcLayerSweepSpan> sweeps = (rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP); if (!sweeps) { ctx->log(RC_LOG_ERROR, "CollectLayerRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps); return false; } // Partition walkable area into monotone regions. rcIntArray prev(256); unsigned short regId = 0; for (int y = borderSize; y < h-borderSize; ++y) { prev.resize(regId+1); memset(&prev[0],0,sizeof(int)*regId); unsigned short sweepId = 0; for (int x = borderSize; x < w-borderSize; ++x) { const rcCompactCell& c = chf.cells[x+y*w]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) { const rcCompactSpan& s = chf.spans[i]; if (chf.areas[i] == RC_NULL_AREA) continue; unsigned short sid = 0xffff; // -x if (rcGetCon(s, 0) != RC_NOT_CONNECTED) { const int ax = x + rcGetDirOffsetX(0); const int ay = y + rcGetDirOffsetY(0); const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0); if (chf.areas[ai] != RC_NULL_AREA && srcReg[ai] != 0xffff) sid = srcReg[ai]; } if (sid == 0xffff) { sid = sweepId++; sweeps[sid].nei = 0xffff; sweeps[sid].ns = 0; } // -y if (rcGetCon(s,3) != RC_NOT_CONNECTED) { const int ax = x + rcGetDirOffsetX(3); const int ay = y + rcGetDirOffsetY(3); const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3); const unsigned short nr = srcReg[ai]; if (nr != 0xffff) { // Set neighbour when first valid neighbour is encoutered. if (sweeps[sid].ns == 0) sweeps[sid].nei = nr; if (sweeps[sid].nei == nr) { // Update existing neighbour sweeps[sid].ns++; prev[nr]++; } else { // This is hit if there is nore than one neighbour. // Invalidate the neighbour. sweeps[sid].nei = 0xffff; } } } srcReg[i] = sid; } } // Create unique ID. for (int i = 0; i < sweepId; ++i) { // If the neighbour is set and there is only one continuous connection to it, // the sweep will be merged with the previous one, else new region is created. if (sweeps[i].nei != 0xffff && prev[sweeps[i].nei] == sweeps[i].ns) { sweeps[i].id = sweeps[i].nei; } else { sweeps[i].id = regId++; } } // Remap local sweep ids to region ids. for (int x = borderSize; x < w-borderSize; ++x) { const rcCompactCell& c = chf.cells[x+y*w]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) { if (srcReg[i] != 0xffff) srcReg[i] = sweeps[srcReg[i]].id; } } } // Allocate and init layer regions. nregs = (int)regId; regs = (rcLayerRegionMonotone*)rcAlloc(sizeof(rcLayerRegionMonotone)*nregs, RC_ALLOC_TEMP); if (!regs) { ctx->log(RC_LOG_ERROR, "CollectLayerRegionsMonotone: Out of memory 'regs' (%d).", nregs); return false; } memset(regs, 0, sizeof(rcLayerRegionMonotone)*nregs); for (int i = 0; i < nregs; ++i) { regs[i].layerId = 0xffff; regs[i].ymin = 0xffff; regs[i].ymax = 0; } rcIntArray lregs(64); // Find region neighbours and overlapping regions. for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { const rcCompactCell& c = chf.cells[x+y*w]; lregs.resize(0); for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) { const rcCompactSpan& s = chf.spans[i]; const unsigned short ri = srcReg[i]; if (ri == 0xffff) continue; regs[ri].ymin = rcMin(regs[ri].ymin, s.y); regs[ri].ymax = rcMax(regs[ri].ymax, s.y); // Collect all region layers. lregs.push(ri); // Update neighbours for (int dir = 0; dir < 4; ++dir) { if (rcGetCon(s, dir) != RC_NOT_CONNECTED) { const int ax = x + rcGetDirOffsetX(dir); const int ay = y + rcGetDirOffsetY(dir); const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir); const unsigned short rai = srcReg[ai]; if (rai != 0xffff && rai != ri) addUnique(regs[ri].neis, rai); } } } // Update overlapping regions. const int nlregs = lregs.size(); for (int i = 0; i < nlregs-1; ++i) { for (int j = i+1; j < nlregs; ++j) { if (lregs[i] != lregs[j]) { rcLayerRegionMonotone& ri = regs[lregs[i]]; rcLayerRegionMonotone& rj = regs[lregs[j]]; addUnique(ri.layers, lregs[j]); addUnique(rj.layers, lregs[i]); } } } } } return true; }
//----------------------------------------------------------------------------- void CameraSpline::value(F32 t, CameraSpline::Knot *result, bool skip_rotation) { // Do some easing in and out for t. if(!gBuilding) { F32 oldT = t; if(oldT < 0.5f) { t = 0.5f - (mSin( (0.5 - oldT) * M_PI ) / 2.f); } if((F32(size()) - 1.5f) > 0.f && oldT - (F32(size()) - 1.5f) > 0.f) { oldT -= (F32(size()) - 1.5f); t = (F32(size()) - 1.5f) + (mCos( (0.5f - oldT) * F32(M_PI) ) / 2.f); } } // Verify that t is in range [0 >= t > size] // AssertFatal(t >= 0.0f && t < (F32)size(), "t out of range"); Knot *p1 = getKnot((S32)mFloor(t)); Knot *p2 = next(p1); F32 i = t - mFloor(t); // adjust t to 0 to 1 on p1-p2 interval if (p1->mPath == Knot::SPLINE) { Knot *p0 = (p1->mType == Knot::KINK) ? p1 : prev(p1); Knot *p3 = (p2->mType == Knot::KINK) ? p2 : next(p2); result->mPosition.x = mCatmullrom(i, p0->mPosition.x, p1->mPosition.x, p2->mPosition.x, p3->mPosition.x); result->mPosition.y = mCatmullrom(i, p0->mPosition.y, p1->mPosition.y, p2->mPosition.y, p3->mPosition.y); result->mPosition.z = mCatmullrom(i, p0->mPosition.z, p1->mPosition.z, p2->mPosition.z, p3->mPosition.z); } else { // Linear result->mPosition.interpolate(p1->mPosition, p2->mPosition, i); } if (skip_rotation) return; buildTimeMap(); // find the two knots to interpolate rotation and velocity through since some // knots are only positional S32 start = (S32)mFloor(t); S32 end = (p2 == p1) ? start : (start + 1); while (p1->mType == Knot::POSITION_ONLY && p1 != front()) { p1 = prev(p1); start--; } while (p2->mType == Knot::POSITION_ONLY && p2 != back()) { p2 = next(p2); end++; } if (start == end) { result->mRotation = p1->mRotation; result->mSpeed = p1->mSpeed; } else { F32 c = getDistance(t); F32 d1 = getDistance((F32)start); F32 d2 = getDistance((F32)end); if (d1 == d2) { result->mRotation = p2->mRotation; result->mSpeed = p2->mSpeed; } else { i = (c-d1)/(d2-d1); if(p1->mPath == Knot::SPLINE) { Knot *p0 = (p1->mType == Knot::KINK) ? p1 : prev(p1); Knot *p3 = (p2->mType == Knot::KINK) ? p2 : next(p2); F32 q,w,e; q = mCatmullrom(i, 0, 1, 1, 1); w = mCatmullrom(i, 0, 0, 0, 1); e = mCatmullrom(i, 0, 0, 1, 1); QuatF a; a.interpolate(p0->mRotation, p1->mRotation, q); QuatF b; b.interpolate(p2->mRotation, p3->mRotation, w); result->mRotation.interpolate(a, b, e); result->mSpeed = mCatmullrom(i, p0->mSpeed, p1->mSpeed, p2->mSpeed, p3->mSpeed); } else { result->mRotation.interpolate(p1->mRotation, p2->mRotation, i); result->mSpeed = (p1->mSpeed * (1.0f-i)) + (p2->mSpeed * i); } } } }
// e - supply(positive) and demand(negative). // c[i] - edges that goes from node i. first is the second nod // x - the flow is returned in it NUM_T operator()(std::vector<NUM_T>& e, const std::vector< std::list< edge<NUM_T> > >& c, std::vector< std::list< edge0<NUM_T> > >& x) { //for (NODE_T i=0; i<e.size(); ++i) cout << e[i]<< " "; //cout << endl; //tictoc_all_function.tic(); assert(e.size()==c.size()); assert(x.size()==c.size()); _num_nodes= (NODE_T)e.size(); _nodes_to_Q.resize(_num_nodes); // init flow {for (NODE_T from=0; from<_num_nodes; ++from) { {for (typename std::list< edge<NUM_T> >::const_iterator it= c[from].begin(); it!=c[from].end(); ++it) { x[from].push_back( edge0<NUM_T> (it->_to, it->_cost, 0) ); x[it->_to].push_back( edge0<NUM_T> (from, -it->_cost,0) ); }} // it }} // from // reduced costs for forward edges (c[i,j]-pi[i]+pi[j]) // Note that for forward edges the residual capacity is infinity std::vector< std::list< edge1<NUM_T> > > r_cost_forward(_num_nodes); {for (NODE_T from=0; from<_num_nodes; ++from) { {for (typename std::list< edge<NUM_T> >::const_iterator it= c[from].begin(); it!=c[from].end(); ++it) { r_cost_forward[from].push_back( edge1<NUM_T>(it->_to,it->_cost) ); }} }} // reduced costs and capacity for backward edges (c[j,i]-pi[j]+pi[i]) // Since the flow at the beginning is 0, the residual capacity is also zero std::vector< std::list< edge2<NUM_T> > > r_cost_cap_backward(_num_nodes); {for (NODE_T from=0; from<_num_nodes; ++from) { {for (typename std::list< edge<NUM_T> >::const_iterator it= c[from].begin(); it!=c[from].end(); ++it) { r_cost_cap_backward[ it->_to ].push_back( edge2<NUM_T>(from,-it->_cost,0) ); }} // it }} // from // Max supply TODO:demand?, given U?, optimization-> min out of demand,supply NUM_T U= 0; {for (NODE_T i=0; i<_num_nodes; ++i) { if (e[i]>U) U= e[i]; }} NUM_T delta= static_cast<NUM_T>(pow(2.0l,ceil(log(static_cast<long double>(U))/log(2.0)))); std::vector< NUM_T > d(_num_nodes); std::vector< NODE_T > prev(_num_nodes); delta= 1; //while (delta>=1) { // delta-scaling phase //cout << "delta==" << delta << endl; //tictoc_while_true.tic(); while (true) { //until we break when S or T is empty NUM_T maxSupply= 0; NODE_T k=0; for (NODE_T i=0; i<_num_nodes; ++i) { if (e[i]>0) { if (maxSupply<e[i]) { maxSupply= e[i]; k= i; } } } if (maxSupply==0) break; delta= maxSupply; NODE_T l; //tictoc_shortest_path.tic(); compute_shortest_path(d,prev, k,r_cost_forward,r_cost_cap_backward , e,l); //tictoc_shortest_path.toc(); //--------------------------------------------------------------- // find delta (minimum on the path from k to l) //delta= e[k]; //if (-e[l]<delta) delta= e[k]; NODE_T to= l; do { NODE_T from= prev[to]; assert(from!=to); // residual typename std::list< edge2<NUM_T> >::iterator itccb= r_cost_cap_backward[from].begin(); while ( (itccb!=r_cost_cap_backward[from].end()) && (itccb->_to!=to) ) { ++itccb; } if (itccb!=r_cost_cap_backward[from].end()) { if (itccb->_residual_capacity<delta) delta= itccb->_residual_capacity; } to= from; } while (to!=k); //--------------------------------------------------------------- //--------------------------------------------------------------- // augment delta flow from k to l (backwards actually...) to= l; do { NODE_T from= prev[to]; assert(from!=to); // TODO - might do here O(n) can be done in O(1) typename std::list< edge0<NUM_T> >::iterator itx= x[from].begin(); while (itx->_to!=to) { ++itx; } itx->_flow+= delta; // update residual for backward edges typename std::list< edge2<NUM_T> >::iterator itccb= r_cost_cap_backward[to].begin(); while ( (itccb!=r_cost_cap_backward[to].end()) && (itccb->_to!=from) ) { ++itccb; } if (itccb!=r_cost_cap_backward[to].end()) { itccb->_residual_capacity+= delta; } itccb= r_cost_cap_backward[from].begin(); while ( (itccb!=r_cost_cap_backward[from].end()) && (itccb->_to!=to) ) { ++itccb; } if (itccb!=r_cost_cap_backward[from].end()) { itccb->_residual_capacity-= delta; } // update e e[to]+= delta; e[from]-= delta; to= from; } while (to!=k); //--------------------------------------------------------------------------------- } // while true (until we break when S or T is empty) //tictoc_while_true.toc(); //cout << "while true== " << tictoc_while_true.totalTimeSec() << endl; //delta= delta/2; //} // (delta-scaling phase) // compute distance from x //cout << endl << endl; NUM_T dist= 0; {for (NODE_T from=0; from<_num_nodes; ++from) { {for (typename std::list< edge0<NUM_T> >::const_iterator it= x[from].begin(); it!=x[from].end(); ++it) { // if (it->_flow!=0) cout << from << "->" << it->_to << ": " << it->_flow << "x" << it->_cost << endl; dist+= (it->_cost*it->_flow); }} // it }} // from //tictoc_all_function.toc(); //cout << "operator() time==" << tictoc_all_function.totalTimeSec() << endl; //cout << "compute_shortest_path_time==" << tictoc_shortest_path.totalTimeSec() << endl; //cout << "tmp_tic_toc== " << tmp_tic_toc.totalTimeSec() << endl; return dist; } // operator()
bool LapDetector::seed(const QVector<GeoCoordinate>* coords) { if (coords == NULL || coords->size() <= 0) return false; qreal minx, maxx; qreal miny, maxy; minx = maxx = coords->at(0).longitude(); miny = maxy = coords->at(0).latitude(); foreach(const GeoCoordinate& c, *coords) { qreal x = c.longitude(); qreal y = c.latitude(); if (minx > x) minx = x; else if (maxx < x) maxx = x; if (miny > y) miny = y; else if (maxy < y) maxy = y; } qreal dx = maxx - minx; qreal dy = maxy - miny; qreal delta = qMin(dx, dy); qreal ratio = 100 / delta; dx = dx * ratio / 30; dy = dy * ratio / 30; // FIXME // qreal zsize = GeoCoordinate::getDegreeEquivalence(15) * ratio; qreal zsize = 0.0002 * ratio; qDebug() << "delta : " << delta << 100/delta; qDebug() << "dx, dy : " << dx << dy; qDebug() << "zsize : "<< zsize; this->zones = new QVector< QVector<Zone*>* >; int nbVert = qCeil((maxy - miny) * ratio / zsize); int nbHor = qCeil((maxx - minx) * ratio / zsize); for (int i(0); i < nbHor; i++) { QVector<Zone*>* zone = new QVector<Zone*>; this->zones->append(zone); for (int j(0); j < nbVert; j++) zone->append(new Zone); } int index(0); DataPoint* prev(NULL); foreach(const GeoCoordinate& c, *coords) { qreal sx = (c.longitude() - minx) * ratio; qreal sy = (c.latitude() - miny) * ratio; // int x = qFloor(sx / dx); // int y = qFloor(sy / dy); int x = qFloor(sx / zsize); int y = qFloor(sy / zsize); Zone* zone = this->zones->at(x)->at(y); if (prev == NULL || ! zone->contains(prev)) { QTime tm; c.time(tm); DataPoint* np = new DataPoint(x, y, tm, index); zone->add(np); timeline.append(zone); prev = np; index ++; } } return true; }
char *OpenDDLParser::parseHeader( char *in, char *end ) { if( ddl_nullptr == in || in == end ) { return in; } Text *id( ddl_nullptr ); in = OpenDDLParser::parseIdentifier( in, end, &id ); #ifdef DEBUG_HEADER_NAME dumpId( id ); #endif // DEBUG_HEADER_NAME in = lookForNextToken( in, end ); if( ddl_nullptr != id ) { // store the node DDLNode *node( createDDLNode( id, this ) ); if( ddl_nullptr != node ) { pushNode( node ); } else { std::cerr << "nullptr returned by creating DDLNode." << std::endl; } delete id; Name *name(ddl_nullptr); in = OpenDDLParser::parseName(in, end, &name); if( ddl_nullptr != name && ddl_nullptr != node ) { const std::string nodeName( name->m_id->m_buffer ); node->setName( nodeName ); delete name; } Property *first(ddl_nullptr); in = lookForNextToken(in, end); if (*in == Grammar::OpenPropertyToken[0]) { in++; Property *prop(ddl_nullptr), *prev(ddl_nullptr); while (*in != Grammar::ClosePropertyToken[0] && in != end) { in = OpenDDLParser::parseProperty(in, end, &prop); in = lookForNextToken(in, end); if (*in != Grammar::CommaSeparator[0] && *in != Grammar::ClosePropertyToken[0]) { logInvalidTokenError(in, Grammar::ClosePropertyToken, m_logCallback); return ddl_nullptr; } if (ddl_nullptr != prop && *in != Grammar::CommaSeparator[0]) { if (ddl_nullptr == first) { first = prop; } if (ddl_nullptr != prev) { prev->m_next = prop; } prev = prop; } } ++in; } // set the properties if (ddl_nullptr != first && ddl_nullptr != node) { node->setProperties(first); } } return in; }