int query(int y, int x) { int r=0; for(;x<root;x=pai(x)) for(int t=y; t<root; t=pai(t)) r+=BIT[t][x]; return r; }
void update2(int ly, int uy, int lx, int ux, int v) { for(;ly<=uy;ly=pai(ly),uy=pai(uy)) { if (ly&1) update1(ly++, lx, ux, v); if (!(uy&1)) update1(uy--, lx, ux, v); } }
void update1(int p, int lx, int ux, int v) { for(;lx<=ux;lx=pai(lx),ux=pai(ux)) { if (lx&1) BIT[p][lx++]+=v; if (!(ux&1)) BIT[p][ux--]+=v; } }
//////////////////////////////////////// //////////////////////////////////////// Dijkstra //////////////////////////////////////// void Graph::dijkstra(int s) { //Verifica se s é uma valor maior que zero s = (s > 0 ? s : 1); //Verficia se é possível aplicar dijkstra no grafo. if(!(this->dijkstrable)) return; std::vector<int> pai(this->n,-1); std::vector<Vertex> verts(this->n); /* Vetor de objetos do tipo Vertex que serão usados pelo dijkstra. */ std::priority_queue<Vertex, std::vector<Vertex>, std::greater<Vertex> > heap; // testado e funciona verts[s-1].value = 0; for(int i = 1; i <= this->n ; i++) // preenchendo os objetos do vetor verts { verts[i-1].index = i; } heap.push(verts[s-1]); // Colocando o primeiro vértice na heap while(!heap.empty()) { Vertex const v = heap.top(); heap.pop(); if(!(verts[v.index-1].mark)) { for(int u = 0; u < vDeg[v.index-1]; u++) { if(this->ws[v.index-1][u] + v.value < verts[this->vec[v.index-1][u]-1].value && !(verts[this->vec[v.index-1][u]-1].mark)) { verts[this->vec[v.index-1][u]-1].value = this->ws[v.index-1][u] + v.value; pai[vec[v.index-1][u]-1] = v.index; heap.push(verts[this->vec[v.index-1][u]-1]); } } } verts[v.index-1].mark = true; } // Escrevendo em arquivo char st [50] = "dijk_"; char ss [11] = {0}; std::sprintf(ss, "%d", s); strcat(st, ss); strcat(st, "_"); std::ofstream outfile; outfile.open(strcat(st,this->path), std::ios::out); for(int i = 0; i<this->n; i++) { outfile << i+1 << ", pai: " <<pai[i] << ", distancia: " << verts[i].value << std::endl; } }
static Array HHVM_FUNCTION(get_included_files) { PackedArrayInit pai(g_context->m_evaledFilesOrder.size()); for (auto& file : g_context->m_evaledFilesOrder) { pai.append(const_cast<StringData*>(file)); } return pai.toArray(); }
static Array HHVM_FUNCTION(get_included_files) { PackedArrayInit pai(g_context->m_evaledFilesOrder.size()); for (auto& file : g_context->m_evaledFilesOrder) { pai.append(file->getFileName()); } return pai.toArray(); }
String HHVM_FUNCTION(exec, const String& command, VRefParam output /* = null */, VRefParam return_var /* = null */) { ShellExecContext ctx; FILE *fp = ctx.exec(command); if (!fp) return empty_string(); StringBuffer sbuf; sbuf.read(fp); Array lines = StringUtil::Explode(sbuf.detach(), "\n").toArray(); int ret = ctx.exit(); if (WIFEXITED(ret)) ret = WEXITSTATUS(ret); return_var = ret; int count = lines.size(); if (count > 0 && lines[count - 1].toString().empty()) { count--; // remove explode()'s last empty line } PackedArrayInit pai(count); for (int i = 0; i < count; i++) { pai.append(lines[i]); } output.wrapped() = pai.toArray(); if (!count || lines.empty()) { return String(); } return HHVM_FN(rtrim)(lines[count - 1].toString()); }
//////////////////////////////////////// //////////////////////////////////////// MST //////////////////////////////////////// // void Graph::mst() { this->findCC(); int s = this->vMax; int cost = 0; std::vector<int> pai(this->n,-1); std::vector<Vertex> verts(this->n); /* Vetor de objetos do tipo Vertex que serão usados pelo prim. */ std::priority_queue<Vertex, std::vector<Vertex>, std::greater<Vertex> > heap; verts[s-1].value = 0; for(int i = 1; i <= this->n ; i++) // preenchendo os objetos do vetor verts { verts[i-1].index = i; } heap.push(verts[s-1]); // Colocando o primeiro vértice na heap while(!heap.empty()) { Vertex const v = heap.top(); heap.pop(); if(!(verts[v.index-1].mark)) { for(int u = 0; u < vDeg[v.index-1]; u++) { if(this->ws[v.index-1][u] < verts[this->vec[v.index-1][u]-1].value && !(verts[this->vec[v.index-1][u]-1].mark)) { verts[this->vec[v.index-1][u]-1].value = this->ws[v.index-1][u]; pai[vec[v.index-1][u]-1] = v.index; heap.push(verts[this->vec[v.index-1][u]-1]); } } } verts[v.index-1].mark = true; } // Escrevendo em arquivo char st [50] = "mst_"; std::ofstream outfile; outfile.open(strcat(st,this->path), std::ios::out); outfile << this->n << std::endl; for(int i = 0; i<this->n; i++) { if (verts[i].value!=DBL_MAX) { if(i == s-1) continue; outfile << i+1 << " " <<pai[i] << " " << verts[i].value << std::endl; cost = cost + verts[i].value; } } outfile << cost << std::endl; }
bool topologicalSort(const AdjacentGraph& adjG, veci &sortingVertice) { std::vector<int> colors(adjG.getSize(), White); std::vector<int> d(adjG.getSize(), NotAcess); std::vector<int> pai(adjG.getSize(), nil); std::vector<int> finish(adjG.getSize(), NotAcess); bool haveCircle = false; int time = 1; for( int i = 0; i < adjG.getSize(); i++ ) { if(colors[i] == White) { colors[i] = Gray; d[i] = time; time += 1; pai[i] = nil; std::cout << "visit " << i << std::endl; DFSAuxliary(adjG, colors, d, pai, finish, i, time, haveCircle); if(haveCircle) return false; } } std::cout << "start " << d << std::endl; std::cout << "finish " << finish << std::endl; typedef std::pair<int, int> finishIndex; std::vector<finishIndex> tmp; for( int i = 0 ; static_cast<unsigned>(i) < finish.size() ; i++ ) { tmp.push_back(std::make_pair(finish[i], i)); } std::sort(tmp.begin(), tmp.end()); for( int i = 0 ; static_cast<unsigned>(i) < tmp.size() ; i++ ) { sortingVertice.push_back(tmp[i].second); } for( int i = 0, j = tmp.size() - 1 ; i < j ; i++, j-- ) { std::swap(sortingVertice[i], sortingVertice[j]); } return true; }
void Graph::dfs(int s) { //Variáveis análogas à BFS std::vector<int> pai(this->n); std::vector<int> level(this->n,-1); std::vector<int> markVec(this->n); std::stack<int> lifo; int v; int degV; pai[s-1] = -1; level[s-1] = 0; lifo.push(s); while(!lifo.empty()) { v = lifo.top(); // first element of the queue degV = vDeg[v-1]; // degV as the degree of current v lifo.pop(); if(markVec[v-1]==0) { markVec[v-1] = 1; std::vector<int> &neigh = this->getAdj(v); for(int i = 0; i<degV; i++) { if(markVec[neigh[i]-1]==0) { lifo.push(neigh[i]); pai[neigh[i]-1] = v; level[neigh[i]-1] = level[v-1] + 1; } } } } ////Escrevendo em arquivo char st [50] = "dfs_"; char ss [11] = {0}; std::sprintf(ss, "%d", s); strcat(st, ss); strcat(st, "_"); std::ofstream outfile; outfile.open(strcat(st,this->path), std::ios::out); for(int i = 0; i<this->n; i++) { outfile << i+1 << ", pai: " <<pai[i] << ", nivel: " << level[i] << std::endl; } }
void heapyfy_push (int index) { if (index >= mh.tamanho) return; int parentNodeIndex = pai(index); int tmp; if (index != 1) { if(mh.pesos[parentNodeIndex] > mh.pesos[index]) { tmp = mh.pesos[parentNodeIndex]; mh.pesos[parentNodeIndex] = mh.pesos[index]; mh.pesos[index] = tmp; heapyfy_push (parentNodeIndex); } } }
//////////////////////////////////////// ////////////////////////////////////////BFS //////////////////////////////////////// void Graph::bfs(int s) { std::vector<int> pai(this->n); // Vetor que armazenará os pais de todos os vértices. Por default, o pai será 0 se não for alcançado std::vector<int> level(this->n,-1); // Vetor que armazenará os níveis de todos os vértices. Caso não seja alcançado, o nível será -1 std::vector<int> markVec(this->n); // Vetor de marcação. Se um vértice for adicionado na fila, ele é marcado std::vector<int> fifo(this->n); // Fila que armazenará os vértices descobertos e que ainda não foram explorados int v; // Vértice que será explorado int degV; // Grau do vértice v int begin = 0; // Posição do primeiro que entrou na fila int end = 0; // Posição onde será colocado o próximo a entrar na fila pai[s-1] = -1; level[s-1] = 0; markVec[s-1] = 1; fifo[end++] = s; while(begin!=end) { v = fifo[begin++]; degV = vDeg[v-1]; std::vector<int> &neigh = this->getAdj(v); //Referência a um vetor, ou seja, não há cópia for(int i = 0; i<degV; i++) { if(markVec[neigh[i]-1]==0) { markVec[neigh[i]-1] = 1; fifo[end++] = neigh[i]; pai[neigh[i]-1] = v; level[neigh[i]-1] = level[v-1] + 1; } } } // Escrevendo em arquivo char st [50] = "bfs_"; char ss [11] = {0}; std::sprintf(ss, "%d", s); strcat(st, ss); strcat(st, "_"); std::ofstream outfile; outfile.open(strcat(st,this->path), std::ios::out); for(int i = 0; i<this->n; i++) { outfile << i+1 << ", pai: " <<pai[i] << ", nivel: " << level[i] << std::endl; } }
/* **************************************************************** * Domain name resolver * **************************************************************** */ void main (int argc, const char *argv[]) { int opt; #if (0) /*******************************************************/ SERVTB *sp; int index; #endif /*******************************************************/ INADDR server_addr; T_BIND bind; /* * Pequena inicialização */ error_msg_to_log++; /* * Verifica se é SUPERUSUÁRIO */ if (geteuid () != 0) error ("$O usuário efetivo não é SUPERUSUÁRIO"); /* * Analisa as opções * * Sintaxe: * port_daemon [-v] <port_server_addr> ... */ while ((opt = getopt (argc, argv, "v")) != EOF) { switch (opt) { case 'v': /* Verbose */ vflag++; break; default: /* Erro */ putc ('\n', stderr); help (); } /* end switch */ } /* end while */ argv += optind; argc -= optind; #if (0) /*******************************************************/ if (argc == 0) help (); #endif /*******************************************************/ /* * Abre os "endpoint"s */ if ((udp_fd = t_open (udp_dev, O_RDWR, (T_INFO *)NULL)) < 0) error ("$*Não consegui abrir \"%s\"", udp_dev); /* * Obtém a porta local */ server_addr.a_port = PMAP_PORT; server_addr.a_addr = 0; bind.addr.len = sizeof (INADDR); bind.addr.maxlen = sizeof (INADDR); bind.addr.buf = &server_addr; if (t_bind (udp_fd, &bind, &bind) < 0) error ("$*Não consegui dar \"t_bind\" UDP"); send_req (); receive_answer (); #if (0) /*******************************************************/ /* * Cria um filho para enviar os pedidos de DNS. * O pai le os datagramas de resposta. */ if ((pidfilho = thread ()) < 0) error ("$*Não consegui criar um novo processo"); if (pidfilho > 0) pai (); else filho (); /* Não retorna */ #endif /*******************************************************/ } /* end port_mapper */
Variant binary_deserialize(int8_t thrift_typeID, PHPInputTransport& transport, const Array& fieldspec) { Variant ret; switch (thrift_typeID) { case T_STOP: case T_VOID: return init_null(); case T_STRUCT: { Variant val; if ((val = fieldspec.rvalAt(PHPTransport::s_class)).isNull()) { throw_tprotocolexception("no class type in spec", INVALID_DATA); skip_element(T_STRUCT, transport); return init_null(); } String structType = val.toString(); ret = createObject(structType); if (ret.isNull()) { // unable to create class entry skip_element(T_STRUCT, transport); return init_null(); } Variant spec = HHVM_FN(hphp_get_static_property)(structType, s_TSPEC, false); if (!spec.is(KindOfArray)) { char errbuf[128]; snprintf(errbuf, 128, "spec for %s is wrong type: %d\n", structType.data(), ret.getType()); throw_tprotocolexception(String(errbuf, CopyString), INVALID_DATA); return init_null(); } binary_deserialize_spec(ret.toObject(), transport, spec.toArray()); return ret; } break; case T_BOOL: { uint8_t c; transport.readBytes(&c, 1); return c != 0; } //case T_I08: // same numeric value as T_BYTE case T_BYTE: { uint8_t c; transport.readBytes(&c, 1); return Variant((int8_t)c); } case T_I16: { uint16_t c; transport.readBytes(&c, 2); return Variant((int16_t)ntohs(c)); } case T_I32: { uint32_t c; transport.readBytes(&c, 4); return Variant((int32_t)ntohl(c)); } case T_U64: case T_I64: { uint64_t c; transport.readBytes(&c, 8); return Variant((int64_t)ntohll(c)); } case T_DOUBLE: { union { uint64_t c; double d; } a; transport.readBytes(&(a.c), 8); a.c = ntohll(a.c); return a.d; } case T_FLOAT: { union { uint32_t c; float d; } a; transport.readBytes(&(a.c), 4); a.c = ntohl(a.c); return a.d; } //case T_UTF7: // aliases T_STRING case T_UTF8: case T_UTF16: case T_STRING: { uint32_t size = transport.readU32(); if (size && (size + 1)) { String s = String(size, ReserveString); char* strbuf = s.mutableData(); transport.readBytes(strbuf, size); s.setSize(size); return s; } else { return empty_string_variant(); } } case T_MAP: { // array of key -> value uint8_t types[2]; transport.readBytes(types, 2); uint32_t size = transport.readU32(); Array keyspec = fieldspec.rvalAt(PHPTransport::s_key, AccessFlags::Error_Key).toArray(); Array valspec = fieldspec.rvalAt(PHPTransport::s_val, AccessFlags::Error_Key).toArray(); String format = fieldspec.rvalAt(PHPTransport::s_format, AccessFlags::None).toString(); if (format.equal(PHPTransport::s_collection)) { ret = newobj<c_Map>(); for (uint32_t s = 0; s < size; ++s) { Variant key = binary_deserialize(types[0], transport, keyspec); Variant value = binary_deserialize(types[1], transport, valspec); collectionSet(ret.getObjectData(), key.asCell(), value.asCell()); } } else { ret = Array::Create(); for (uint32_t s = 0; s < size; ++s) { Variant key = binary_deserialize(types[0], transport, keyspec); Variant value = binary_deserialize(types[1], transport, valspec); ret.toArrRef().set(key, value); } } return ret; // return_value already populated } case T_LIST: { // array with autogenerated numeric keys int8_t type = transport.readI8(); uint32_t size = transport.readU32(); Variant elemvar = fieldspec.rvalAt(PHPTransport::s_elem, AccessFlags::Error_Key); Array elemspec = elemvar.toArray(); String format = fieldspec.rvalAt(PHPTransport::s_format, AccessFlags::None).toString(); if (format.equal(PHPTransport::s_collection)) { auto const pvec = newobj<c_Vector>(); ret = pvec; for (uint32_t s = 0; s < size; ++s) { Variant value = binary_deserialize(type, transport, elemspec); pvec->t_add(value); } } else { PackedArrayInit pai(size); for (auto s = uint32_t{0}; s < size; ++s) { pai.append(binary_deserialize(type, transport, elemspec)); } ret = pai.toArray(); } return ret; } case T_SET: { // array of key -> TRUE uint8_t type; uint32_t size; transport.readBytes(&type, 1); transport.readBytes(&size, 4); size = ntohl(size); Variant elemvar = fieldspec.rvalAt(PHPTransport::s_elem, AccessFlags::Error_Key); Array elemspec = elemvar.toArray(); String format = fieldspec.rvalAt(PHPTransport::s_format, AccessFlags::None).toString(); if (format.equal(PHPTransport::s_collection)) { auto set_ret = makeSmartPtr<c_Set>(); for (uint32_t s = 0; s < size; ++s) { Variant key = binary_deserialize(type, transport, elemspec); if (key.isInteger()) { set_ret->t_add(key); } else { set_ret->t_add(key.toString()); } } ret = Variant(std::move(set_ret)); } else { ArrayInit init(size, ArrayInit::Mixed{}); for (uint32_t s = 0; s < size; ++s) { Variant key = binary_deserialize(type, transport, elemspec); if (key.isInteger()) { init.set(key, true); } else { init.setKeyUnconverted(key, true); } } ret = init.toArray(); } return ret; } }; char errbuf[128]; sprintf(errbuf, "Unknown thrift typeID %d", thrift_typeID); throw_tprotocolexception(String(errbuf, CopyString), INVALID_DATA); return init_null(); }
void colourSampleWidget::paintEvent( QPaintEvent * ) { // create painter QPainter pai( this ); // fill to dark pai.fillRect( rect(), palette().color( QPalette::Shadow ) ); // set up painter font QFont fnt( pai.font() ); fnt.setPixelSize( 8 ); pai.setFont( fnt ); // find maximum component, or 1.0 of all below 1.0 float max( qMax( 1.0f, qMax( qMax( qMax( _col.r(), _col.g() ), _col.b() ), _col.a() ) ) ); // find the pixel heights of the colour bars, with the maximum being foudn from the max above int r( ( _col.r() / max ) * height() ), g( ( _col.g() / max ) * height() ), b( ( _col.b() / max ) * height() ), a( ( _col.a() / max ) * height() ); // no outline pai.setPen( Qt::transparent ); int rectWidth( width()/4 ); // draw the rectangles pai.setBrush( Qt::red ); pai.drawRect( 0, height(), rectWidth, -r ); pai.setBrush( Qt::green ); pai.drawRect( rectWidth, height(), rectWidth, -g ); pai.setBrush( Qt::blue ); pai.drawRect( rectWidth*2, height(), rectWidth, -b ); pai.setBrush( Qt::white ); pai.drawRect( rectWidth*3, height(), rectWidth+1, -a ); // no brush pai.setBrush( Qt::transparent ); // draw a line to indicate the position of 1.0, if there were any values above 1.0 if( max > 1.0 ) { QColor col( Qt::black ); col.setAlpha( 64 ); pai.setPen( col ); pai.drawLine( 0, height() - ( height() / max ), width(), height() - ( height() / max ) ); } // draw the text float values on the bars pai.setPen( Qt::black ); pai.drawText( 0, 0, rectWidth, height(), Qt::AlignCenter, QString::number( _col.r(), 'g', 3 ) ); pai.drawText( rectWidth, 0, rectWidth, height(), Qt::AlignCenter, QString::number( _col.g(), 'g', 3 ) ); pai.drawText( rectWidth*2, 0, rectWidth, height(), Qt::AlignCenter, QString::number( _col.b(), 'g', 3 ) ); pai.drawText( rectWidth*3, 0, rectWidth, height(), Qt::AlignCenter, QString::number( _col.a(), 'g', 3 ) ); // draw a frame around the rectandle cause it looks nice QColor col( Qt::white ); col.setAlpha( 128 ); pai.setPen( col ); pai.drawRect( QRect( rect().topLeft(), rect().size()-QSize( 1, 1 ) ) ); }
//////////////////////////////////////// //////////////////////////////////////// Distance //////////////////////////////////////// void Graph::distance(int s,int t) { //Verifica se s e t são valores maiores que zero s = (s > 0 ? s : 1); t = (t > 0 ? t : 1); //Verficia se é possível aplicar dijkstra no grafo. if(!(this->dijkstrable && this->pesos)) return bfs(s); std::vector<int> pai(this->n,-1); std::vector<Vertex> verts(this->n); /* Vetor de objetos do tipo Vertex que serão usados pelo dijkstra. */ std::priority_queue<Vertex, std::vector<Vertex>, std::greater<Vertex> > heap; // testado e funciona verts[s-1].value = 0; for(int i = 1; i <= this->n ; i++) // preenchendo os objetos do vetor verts { verts[i-1].index = i; } heap.push(verts[s-1]); // Colocando o primeiro vértice na heap while(!heap.empty()) { Vertex const v = heap.top(); heap.pop(); if (verts[v.index-1].index == t) break; if(!(verts[v.index-1].mark)) { for(int u = 0; u < vDeg[v.index-1]; u++) { if(this->ws[v.index-1][u] + v.value < verts[this->vec[v.index-1][u]-1].value && !(verts[this->vec[v.index-1][u]-1].mark)) { verts[this->vec[v.index-1][u]-1].value = this->ws[v.index-1][u] + v.value; pai[vec[v.index-1][u]-1] = v.index; heap.push(verts[this->vec[v.index-1][u]-1]); } } } verts[v.index-1].mark = true; } // Escrevendo em arquivo char st [50] = "dist_"; char ss1 [11] = {0}; char ss2 [11] = {0}; std::sprintf(ss1, "%d", s); std::sprintf(ss2, "%d", t); strcat(st, ss1); strcat(st, "_"); strcat(st, ss2); strcat(st, "_"); std::ofstream outfile; outfile.open(strcat(st,this->path), std::ios::out); outfile << "distância entre " << s << " e " << t << " = " << verts[t-1].value << std::endl; outfile << "Caminho:" << std::endl; int x = t; outfile << x << std::endl; while (x!=s) { outfile << pai[x-1] << std::endl; x = pai[x-1]; } outfile.close(); }
ArrayData *ArrayData::CreateRef(Variant& value) { PackedArrayInit pai(1); pai.appendRef(value); return pai.create(); }