/* principale */ int main(){ int i, j; graphe g; g.n=4; int pere[g.n]; int lambda[g.n]; /*initialiser graphe*/ graphe_init(&g); addArc(0,1,&g,2); addArc(0,2,&g,3); addArc(1,4,&g,7); addArc(2,4,&g,8); affiche(&g); /*dfsx0 dfsx0(&g, &x0, &suffixe[]);*/ /*explore explore(&g, &x, &marque[MAX_VERTEX_NUM], &suffixe[MAX_VERTEX_NUM], &k); */ Dijkstra(&g, 0, pere, lambda); printf("\n\n\n"); for(i =0; i<3; i++){ printf("père de %d:%d et lambda :%d\n",i,pere[i],lambda[i]); } return 0; }
void GridGraph::resize(int rows, int cols) { reset(); rows_ = rows; cols_ = cols; for (int y = 0; y < rows; ++y) { for (int x = 0; x < cols; ++x) { VertexNumber v = getVertex(y, x); if (x < cols - 1) addArc(v, v + 1); if (y < rows - 1) addArc(v, v + cols); } } arcs.resize((rows - 1) * (cols - 1)); for (int y = 0; y < rows - 1; ++y) { for (int x = 0; x < cols - 1; ++x) { auto& a = arcs[(cols - 1) * y + x]; a.resize(4); a[0] = getArc(getVertex(y, x), getVertex(y, x + 1)); a[1] = getArc(getVertex(y, x), getVertex(y + 1, x)); a[2] = getArc(getVertex(y, x + 1), getVertex(y + 1, x + 1)); a[3] = getArc(getVertex(y + 1, x), getVertex(y + 1, x + 1)); } } setup(); }
// Adds an undirected edge to the Graph G from u to v // Pre: 1 <= u <= getOrder(G), 1 <= v <= getOrder(G) void addEdge(Graph G, int u, int v) { if(u < 1 || u > getOrder(G) || v < 1 || v > getOrder(G)) { printf("Graph Error: calling addEdge() with verticies out of bounds\n"); exit(1); } addArc(G, u, v); addArc(G, v, u); G->size--; }
/* Pre: 1<=u<=n, 1<=v<=n */ void addEdge(Graph G, int u, int v){ if(G == NULL){ printf("Graph Error: calling addEdge() on NULL Graph reference!\n"); exit(1); }else if(u<1 || u>getOrder(G) || v<1 || v>getOrder(G)){ printf("Graph Error: a vertex is not within bounds of the Graph!\n"); exit(1); } addArc(G,u,v); addArc(G,v,u); }
void MFGraph::add_terminals() { int rightMostStart = -1; int rightMostEnd = -1; // find childless nodes for (ListDigraph::NodeIt n(mfGraph); n != INVALID; ++n) { if (countOutArcs(mfGraph, n) == 0) { childless[n] = true; if (read_map[n] && read_map[n]->start() > rightMostStart) { rightMostStart = read_map[n]->start(); rightMostEnd = rightMostStart + read_map[n]->length(); // std::cout << "rightMostEnd" << rightMostEnd << std::endl; } } } int leftMostStart = rightMostStart; // find parentless nodes for (ListDigraph::NodeIt n(mfGraph); n != INVALID; ++n) { if (countInArcs(mfGraph, n) == 0) { parentless[n] = true; if (read_map[n] && read_map[n]->start() < leftMostStart) { leftMostStart = read_map[n]->start(); } } } // now add the fake source and sink MethylRead *source_read = new MethylRead(leftMostStart - 1, 1); source = addNode("s", 0, source_read); fake[source] = true; for (ListDigraph::NodeIt n(mfGraph); n != INVALID; ++n) { if (parentless[n]) { addArc(source, n, read_map[n]->start() - source_read->start()); } } // MethylRead *sink_read = new MethylRead(rightMostStart , rightMostEnd- rightMostStart+1); MethylRead *sink_read = new MethylRead(rightMostEnd + 1 , 1); sink = addNode("t", 0, sink_read); fake[sink] = true; for (ListDigraph::NodeIt n(mfGraph); n != INVALID; ++n) { if (childless[n]) { addArc(n, sink, sink_read->start() - read_map[n]->start()); //addArc(n, sink, 1); } } }
/*main------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { //input validation if (argc != 2) { printf("Usage: %s output\n", argv[0]); exit(1); } //open file FILE *out; out = fopen(argv[1], "w"); //new graph Graph G = newGraph(10); Graph T; List S = newList(); int i; for (i = 1; i <= 9; i++) { addArc(G, i, i + 1); } addArc(G, 1, 2); //add graph and print out the adjacency fields for (i = 1; i <= getOrder(G); i++) { append(S, i); } fprintf(out, "\nThe adjacency list of G is:\n"); printGraph(out, G); //Run DFS and get the transpose DFS(G, S); T = transpose(G); fprintf(out, "\nTranspose of G is:\n"); printGraph(out, T); //print out fields fprintf(out, "Order of G is %d\n", getOrder(G)); fprintf(out, "Size of G is %d.\n", getSize(G)); fprintf(out, "Parent of 10 is %d.\n", getParent(G, 10)); fprintf(out, "Parent of 3 is %d.\n", getParent(G, 3)); fprintf(out, "Discover time of 1 is %d.\n", getDiscover(G, 1)); fprintf(out, "Finish time of 1 is %d.\n", getFinish(G, 1)); fprintf(out, "Discover time of 9 is %d.\n", getDiscover(G, 9)); fprintf(out, "Finish time of 9 is %d.\n", getFinish(G, 9)); //close file fclose(out); //exit return (0); }
void SimpleDirectedGraph::deleteNode(int nodeId, bool always_add_shortcut) { Node& node = m_nodes[nodeId]; if (node.m_deleted) return; // Already deleted node. // Delete the links from other nodes to this node. for (size_t i = 0; i < node.m_predecessors.size(); ++i) { deleteArcFromSuccessors(node.m_predecessors[i], nodeId); } for (size_t i = 0; i < node.m_successors.size(); ++i) { deleteArcFromPredecessors(nodeId, node.m_successors[i]); } // Add shortcut arcs. for (size_t j = 0; j < node.m_predecessors.size(); ++j) { for (size_t i = 0; i < node.m_successors.size(); ++i) { if (always_add_shortcut) { addArc(node.m_predecessors[j], node.m_successors[i]); } else { addShortcutArcIfNeeded(node.m_predecessors[j], node.m_successors[i]); } } } // Clear the node. node.m_deleted = true; node.m_predecessors.clear(); node.m_successors.clear(); }
TransCFG::TransCFG(FuncId funcId, const ProfData* profData, const SrcDB& srcDB, const TcaTransIDMap& jmpToTransID) { assertx(profData); // add nodes for (auto tid : profData->funcProfTransIDs(funcId)) { assertx(profData->transRegion(tid) != nullptr); // This will skip DV Funclets if they were already // retranslated w/ the prologues: if (!profData->optimized(profData->transSrcKey(tid))) { int64_t weight = profData->absTransCounter(tid); addNode(tid, weight); } } // add arcs for (TransID dstId : nodes()) { SrcKey dstSK = profData->transSrcKey(dstId); RegionDesc::BlockPtr dstBlock = profData->transRegion(dstId)->entry(); FTRACE(5, "TransCFG: adding incoming arcs in dstId = {}\n", dstId); TransIDSet predIDs = findPredTrans(dstId, profData, srcDB, jmpToTransID); for (auto predId : predIDs) { if (hasNode(predId)) { auto predPostConds = profData->transRegion(predId)->blocks().back()->postConds(); SrcKey predSK = profData->transSrcKey(predId); if (preCondsAreSatisfied(dstBlock, predPostConds) && predSK.resumed() == dstSK.resumed()) { FTRACE(5, "TransCFG: adding arc {} -> {} ({} -> {})\n", predId, dstId, showShort(predSK), showShort(dstSK)); addArc(predId, dstId, TransCFG::Arc::kUnknownWeight); } } } } // infer arc weights bool changed; do { changed = false; for (TransID tid : nodes()) { int64_t nodeWeight = weight(tid); if (inferredArcWeight(inArcs(tid), nodeWeight)) changed = true; if (inferredArcWeight(outArcs(tid), nodeWeight)) changed = true; } } while (changed); // guess weight for non-inferred arcs for (TransID tid : nodes()) { for (auto arc : outArcs(tid)) { if (arc->weight() == Arc::kUnknownWeight) { arc->setGuessed(); int64_t arcWgt = std::min(weight(arc->src()), weight(arc->dst())) / 2; arc->setWeight(arcWgt); } } } }
// addEdge(): inserts a new edge joining u to v and v to u (bidirectional) // Preconditions: 1<=u<=getOrder(G), 1<=v<=getOrder(G) void addEdge(Graph G, int u, int v) { if(G == NULL) { printf("Graph Error: calling addEdge() on NULL Graph reference\n"); exit(1); } if(u<1 || u>getOrder(G)) { printf("Graph Error: calling addEdge() with out of bounds 'u' value\n"); exit(1); } if(v<1 || v>getOrder(G)) { printf("Graph Error: calling addEdge() with out of bounds 'v' value\n"); exit(1); } addArc(G, u, v); addArc(G, v, u); }
int main() { int n, m; while (EOF != scanf("%d%d", &n, &m)) { if (n == 0) break; memset(V, 0, sizeof(V)); nA = 0; for (int i = 0, a, b; i < m; ++i) { scanf("%d%d", &a, &b); addArc(a-1, b-1); } init_sc_tarjan(); for (int i = 0; i < n; ++i) { if (vis[i] == 0) sc_tarjan(i); } memset(oud, 0, sizeof(oud)); for (int i = 0; i < n; ++i) { int u = id[i]; for (Arc *a = V[i]; a; a = a->next) { int v = id[a->to]; if (u != v) { ++oud[u]; } } } bool first = true; for (int i = 0; i < n; ++i) { if (oud[id[i]] == 0) { if (first) first = false; else putchar(' '); printf("%d", i + 1); } } puts(""); } }
void Path::addArcTo(const FloatPoint& p1, const FloatPoint& p2, float radius) { FloatPoint p0(m_path.currentPosition()); FloatPoint p1p0((p0.x() - p1.x()), (p0.y() - p1.y())); FloatPoint p1p2((p2.x() - p1.x()), (p2.y() - p1.y())); float p1p0_length = sqrtf(p1p0.x() * p1p0.x() + p1p0.y() * p1p0.y()); float p1p2_length = sqrtf(p1p2.x() * p1p2.x() + p1p2.y() * p1p2.y()); double cos_phi = (p1p0.x() * p1p2.x() + p1p0.y() * p1p2.y()) / (p1p0_length * p1p2_length); // The points p0, p1, and p2 are on the same straight line (HTML5, 4.8.11.1.8) // We could have used areCollinear() here, but since we're reusing // the variables computed above later on we keep this logic. if (qFuzzyCompare(qAbs(cos_phi), 1.0)) { m_path.lineTo(p1); return; } float tangent = radius / tan(acos(cos_phi) / 2); float factor_p1p0 = tangent / p1p0_length; FloatPoint t_p1p0((p1.x() + factor_p1p0 * p1p0.x()), (p1.y() + factor_p1p0 * p1p0.y())); FloatPoint orth_p1p0(p1p0.y(), -p1p0.x()); float orth_p1p0_length = sqrt(orth_p1p0.x() * orth_p1p0.x() + orth_p1p0.y() * orth_p1p0.y()); float factor_ra = radius / orth_p1p0_length; // angle between orth_p1p0 and p1p2 to get the right vector orthographic to p1p0 double cos_alpha = (orth_p1p0.x() * p1p2.x() + orth_p1p0.y() * p1p2.y()) / (orth_p1p0_length * p1p2_length); if (cos_alpha < 0.f) orth_p1p0 = FloatPoint(-orth_p1p0.x(), -orth_p1p0.y()); FloatPoint p((t_p1p0.x() + factor_ra * orth_p1p0.x()), (t_p1p0.y() + factor_ra * orth_p1p0.y())); // calculate angles for addArc orth_p1p0 = FloatPoint(-orth_p1p0.x(), -orth_p1p0.y()); float sa = acos(orth_p1p0.x() / orth_p1p0_length); if (orth_p1p0.y() < 0.f) sa = 2 * piDouble - sa; // anticlockwise logic bool anticlockwise = false; float factor_p1p2 = tangent / p1p2_length; FloatPoint t_p1p2((p1.x() + factor_p1p2 * p1p2.x()), (p1.y() + factor_p1p2 * p1p2.y())); FloatPoint orth_p1p2((t_p1p2.x() - p.x()), (t_p1p2.y() - p.y())); float orth_p1p2_length = sqrtf(orth_p1p2.x() * orth_p1p2.x() + orth_p1p2.y() * orth_p1p2.y()); float ea = acos(orth_p1p2.x() / orth_p1p2_length); if (orth_p1p2.y() < 0) ea = 2 * piDouble - ea; if ((sa > ea) && ((sa - ea) < piDouble)) anticlockwise = true; if ((sa < ea) && ((ea - sa) > piDouble)) anticlockwise = true; m_path.lineTo(t_p1p0); addArc(p, radius, sa, ea, anticlockwise); }
void process (Graph graph, char** linebuf) { for (int i = 1;;) { char *row, *col; row = __strtok_r (linebuf[i++], " ", &col); if (atoi (row) == 0 && atoi (col) == 0) break; addArc (graph, atoi (row), atoi (col)); } }
void RegionDesc::copyArcsFrom(const RegionDesc& srcRegion) { for (auto const b : srcRegion.m_blocks) { auto bid = b->id(); for (auto succId : srcRegion.succs(bid)) { addArc(bid, succId); } } }
void SimpleDirectedGraph::addShortcutArcIfNeeded(int source, int target) { SimpleDirectedGraph::BFIterator it(*this, 2, true); it.addNode(source); int node; while (it.read(&node)) { if (node == target) return; } addArc(source, target); }
int main() { int runs, n, m; scanf("%d", &runs); while (runs--) { nA = 0; memset(V, 0, sizeof(V)); scanf("%d%d", &n, &m); for (int i = 0, a, b; i < m; ++i) { scanf("%d%d", &a, &b); addArc(a, b); } init_tarjan(); for (int i = 1; i <= n; ++i) { if (vis[i] == 0) { tarjan(i); } } memset(mat, 0, sizeof(mat)); memset(ind, 0, sizeof(ind)); for (int i = 1; i <= n; ++i) { for (Arc *a = V[i]; a; a = a->next) { int u = id[i], v = id[a->to]; if (u != v && false == mat[u][v]) { mat[u][v] = true; ++ind[v]; } } } // top sort top = -1; for (int i = 0; i < sc_cnt; ++i) { if (ind[i] == 0) vstack[++top] = i; } int cnt = 0; while (cnt < sc_cnt) { int u = vstack[top--]; ord[cnt++] = u; for (int v = 0; v < sc_cnt; ++v) { if (mat[u][v]) { --ind[v]; if (ind[v] == 0) vstack[++top] = v; } } } bool ans = true; for (int i = 0; i < cnt-1; ++i) { if (false == mat[ord[i]][ord[i+1]]) { ans = false; break; } } puts(ans ? "Yes" : "No"); } return 0; }
void Path::addPieSegment (const float x, const float y, const float width, const float height, const float fromRadians, const float toRadians, const float innerCircleProportionalSize) { float radiusX = width * 0.5f; float radiusY = height * 0.5f; const Point<float> centre (x + radiusX, y + radiusY); startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians)); addArc (x, y, width, height, fromRadians, toRadians); if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f) { closeSubPath(); if (innerCircleProportionalSize > 0) { radiusX *= innerCircleProportionalSize; radiusY *= innerCircleProportionalSize; startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians)); addArc (centre.x - radiusX, centre.y - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians); } } else { if (innerCircleProportionalSize > 0) { radiusX *= innerCircleProportionalSize; radiusY *= innerCircleProportionalSize; addArc (centre.x - radiusX, centre.y - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians); } else { lineTo (centre); } } closeSubPath(); }
TransCFG::TransCFG(FuncId funcId, const ProfData* profData, const SrcDB& srcDB, const TcaTransIDMap& jmpToTransID) { assert(profData); // add nodes for (TransID tid = 0; tid < profData->numTrans(); tid++) { if (profData->transKind(tid) == TransProfile && profData->transRegion(tid) != nullptr && profData->transFuncId(tid) == funcId) { int64_t counter = profData->transCounter(tid); int64_t weight = RuntimeOption::EvalJitPGOThreshold - counter; addNode(tid, weight); } } // add arcs for (TransID dstId : nodes()) { SrcKey dstSK = profData->transSrcKey(dstId); const SrcRec* dstSR = srcDB.find(dstSK); FTRACE(5, "TransCFG: adding incoming arcs in dstId = {}\n", dstId); TransIDSet predIDs = findPredTrans(dstSR, jmpToTransID); for (auto predId : predIDs) { if (hasNode(predId)) { FTRACE(5, "TransCFG: adding arc {} -> {}\n", predId, dstId); addArc(predId, dstId, TransCFG::Arc::kUnknownWeight); } } } // infer arc weights bool changed; do { changed = false; for (TransID tid : nodes()) { int64_t nodeWeight = weight(tid); if (inferredArcWeight(inArcs(tid), nodeWeight)) changed = true; if (inferredArcWeight(outArcs(tid), nodeWeight)) changed = true; } } while (changed); // guess weight or non-inferred arcs for (TransID tid : nodes()) { for (auto arc : outArcs(tid)) { if (arc->weight() == Arc::kUnknownWeight) { arc->setGuessed(); int64_t arcWgt = std::min(weight(arc->src()), weight(arc->dst())) / 2; arc->setWeight(arcWgt); } } } }
ResidualNetwork::ResidualNetwork(const FlowNetwork &g) : ResidualNetwork(g.getNumNodes()) { // FlowNetwork stores each arc once for (const Arc &arc : g) { addArc(arc.getSrcId(), arc.getDstId(), arc.getCapacity(), arc.getCost()); } // clone balances for (uint32_t id = 1; id <= num_nodes; id++) { balances[id] = g.getBalance(id); } }
void readG (Graph &g) { int n; scanf("%d", &n); initG(g, n); int v, w, cost; while (1) { scanf("%d", &v); if (v == 0) break; scanf("%d %d", &w, &cost); addArc(g, v, w, cost); } }
void xsCanvasContext::arc(float x, float y, float radius, float startAngle, float endAngle, xsBool anticlockwise) { //MTK support only 0-360 angle. xsArc *arc = static_cast<xsArc *>(xsArc::createInstance()); arc ->x = x; arc ->y = y; arc ->radius = radius; arc ->startAngle = startAngle; arc ->endAngle = endAngle; arc ->anticlockwise = anticlockwise; arc ->lineWidth = lineWidth; arc ->strokeColor = strokeColor; arc ->fillColor = fillColor; addArc(arc); }
GraphRef copyGraph(GraphRef G){ int i, j; GraphRef Q = newGraph(G->order); for(i=1;i<=G->order;i++){ if(!isEmpty(G->adj[i])){ moveTo(G->adj[i], 0); for(j=0;j<getLength(G->adj[i]);j++){ addArc(Q, i, getCurrent(G->adj[i])); if(j<getLength(G->adj[i])-1){ moveNext(G->adj[i]); } } } } return(Q); }
//Returns a reference to a new graph object representing the transpose of G Graph transpose(Graph G){ if( G == NULL ) { printf("Graph Error: calling transpose() on NULL Graph reference\n"); exit(1); } Graph H; H=newGraph(getOrder(G)); for(int i=1; i <= getOrder(G); i++) { if(length(G->vneighbor[i]) != 0) { moveTo(G->vneighbor[i], 0); while(getIndex(G->vneighbor[i]) > -1) { addArc(H, getElement(G->vneighbor[i]),i); moveNext(G->vneighbor[i]); } } } return H; }
void Graph::readAdjacencyList(std::istream& is) { reset(); VertexNumber v1 = 1; VertexNumber v2; vMax = v1; while (is) { char c; while (isspace(c = is.get())) { if (c == '\n') ++v1; } if (!is) break; is.unget(); is >> v2; if (v1 < v2) addArc(v1, v2); } setup(); }
void MFGraph::regularize() { // // int rightMostEnd = -1; // // find childless nodes // for (ListDigraph::NodeIt n(mfGraph); n != INVALID; ++n) { // if (countOutArcs(mfGraph, n) == 0) { // childless[n] = true; // if (read_map[n] && read_map[n]->start() > rightMostStart) { // rightMostEnd = rightMostStart + read_map[n]->length(); // // } // } // } // add the lambda edges int lamcnt = 0; for (ListDigraph::InArcIt arc(mfGraph, sink); arc != INVALID; ++arc, ++lamcnt) { std::stringstream nodename; nodename << "lambda_" << lamcnt; ListDigraph::Node newNode = addNode(nodename.str(), 0); ListDigraph::Node node = mfGraph.source(arc); MethylRead read = MethylRead(*read_map[node]); int start = read_map[node]->start(); int end = read_map[node]->end(); //int newEnd = max(start, min(end, rightMostEnd - rLen)); //ListDigraph::Arc newArc = addArc(node, newNode, 1); ListDigraph::Arc newArc = addArc(node, newNode, end - start + 1); mfGraph.changeSource(arc, newNode); childless[node] = false; childless[newNode] = true; } }
void DRW_Hatch::parseCode(int code, dxfReader *reader){ switch (code) { case 2: name = reader->getString(); break; case 70: solid = reader->getInt32(); break; case 71: associative = reader->getInt32(); break; case 72: /*edge type*/ if (ispol){ //if is polyline is a as_bulge flag break; } else if (reader->getInt32() == 1){ //line addLine(); } else if (reader->getInt32() == 2){ //arc addArc(); } else if (reader->getInt32() == 3){ //elliptic arc addEllipse(); } else if (reader->getInt32() == 4){ //spline addSpline(); } break; case 10: if (pt) pt->basePoint.x = reader->getDouble(); else if (pline) { plvert = pline->addVertex(); plvert->x = reader->getDouble(); } break; case 20: if (pt) pt->basePoint.y = reader->getDouble(); else if (plvert) plvert ->y = reader->getDouble(); break; case 11: if (line) line->secPoint.x = reader->getDouble(); else if (ellipse) ellipse->secPoint.x = reader->getDouble(); break; case 21: if (line) line->secPoint.y = reader->getDouble(); else if (ellipse) ellipse->secPoint.y = reader->getDouble(); break; case 40: if (arc) arc->radious = reader->getDouble(); else if (ellipse) ellipse->ratio = reader->getDouble(); break; case 41: scale = reader->getDouble(); break; case 42: if (plvert) plvert ->bulge = reader->getDouble(); break; case 50: if (arc) arc->staangle = reader->getDouble(); else if (ellipse) ellipse->staparam = reader->getDouble(); break; case 51: if (arc) arc->endangle = reader->getDouble(); else if (ellipse) ellipse->endparam = reader->getDouble(); break; case 52: angle = reader->getDouble(); break; case 73: if (arc) arc->isccw = reader->getInt32(); else if (pline) pline->flags = reader->getInt32(); break; case 75: hstyle = reader->getInt32(); break; case 76: hpattern = reader->getInt32(); break; case 77: doubleflag = reader->getInt32(); break; case 78: deflines = reader->getInt32(); break; case 91: loopsnum = reader->getInt32(); looplist.reserve(loopsnum); break; case 92: loop = new DRW_HatchLoop(reader->getInt32()); looplist.push_back(loop); if (reader->getInt32() & 2) { ispol = true; clearEntities(); pline = new DRW_LWPolyline; loop->objlist.push_back(pline); } else ispol = false; break; case 93: if (pline) pline->vertexnum = reader->getInt32(); else loop->numedges = reader->getInt32();//aqui reserve break; case 98: //seed points ?? clearEntities(); break; default: DRW_Point::parseCode(code, reader); break; } }
int main(int argc, char * argv[]){ int count=0; int u, v, index, sccNum; FILE *in, *out; char line[MAX_LEN]; char* token; Graph G = NULL; Graph T = NULL; List S = newList(); // This list is our stack that determins the order of the vertices List R = newList(); // check command line for correct number of arguments if( argc != 3 ){ printf("Usage: %s <input file> <output file>\n", argv[0]); exit(1); } // open files for reading and writing in = fopen(argv[1], "r"); out = fopen(argv[2], "w"); if( in==NULL ){ printf("Unable to open file %s for reading\n", argv[1]); exit(1); } if( out==NULL ){ printf("Unable to open file %s for writing\n", argv[2]); exit(1); } /* read each line of input file, then count and print tokens */ // Assemble a graph object G using newGraph() and addArc() while(fgets(line, MAX_LEN, in) != NULL) { count++; // char *strtok(char *str, const char *delim) breaks string str into // a series of tokens using the delimitrer delim. This function returns a pointer to the // last token found in string. A null pointer is returned if there are no tokens left to retrieve. token = strtok(line, " \n"); // int atoi(const char *str), This function returns the converted integral number as an int value. // If no valid conversion could be performed, it returns zero. // It converts char to int. if(count == 1) { // Takes in the first number as a token, sets a graph of that size G = newGraph(atoi(token)); } else { // Here we want to read in both numbers u = atoi(token); token = strtok(NULL, " \n"); v = atoi(token); if( u != 0 || v != 0) { addArc(G, u, v); } else if (u == 0 && v == 0) { break; } } } // Print the adjacency list representation of G to the output file printGraph(out, G); fprintf(out, "\n"); // creating our Stack for(int i = 1; i <= getOrder(G); i++) { append(S, i); } // Run DFS on G and G-Transpose, processing the vertices in the second call // by decreasing finish times from the first call DFS(G, S); T = transpose(G); DFS(T, S); // Determine the strong components of G // Print the strong components of G to the output file in topologically sorted order. // Everytime a vertex has a NIL parent in the transpose of G, we have a SCC sccNum = 0; for(int i = 1; i <= getOrder(G); i++) { if(getParent(T, i) == NIL) sccNum++; } fprintf(out, "G contains %d strongly connected components:\n", sccNum); index = 1; moveTo(S, length(S) - 1 ); while(getIndex(S) != -1 && index <= sccNum) { fprintf(out, "Component %d:", index); while(getParent(T, getElement(S)) != NIL) { prepend(R, getElement(S)); movePrev(S); } prepend(R, getElement(S)); printReverse(out, T, R); movePrev(S); index++; fprintf(out, "\n"); } freeList(&S); freeList(&R); freeGraph(&G); freeGraph(&T); /* close files */ fclose(in); fclose(out); return(0); }
RegionDescPtr selectHotTrace(HotTransContext& ctx, TransIDSet& selectedSet, TransIDVec* selectedVec /* = nullptr */) { auto region = std::make_shared<RegionDesc>(); TransID tid = ctx.tid; TransID prevId = kInvalidTransID; selectedSet.clear(); if (selectedVec) selectedVec->clear(); TypedLocations accumPostConds; // Maps from BlockIds to accumulated post conditions for that block. // Used to determine if we can add branch-over edges by checking the // pre-conditions of the successor block. hphp_hash_map<RegionDesc::BlockId, TypedLocations> blockPostConds; auto numBCInstrs = ctx.maxBCInstrs; FTRACE(1, "selectHotTrace: starting with maxBCInstrs = {}\n", numBCInstrs); while (!selectedSet.count(tid)) { auto rec = ctx.profData->transRec(tid); auto blockRegion = rec->region(); if (blockRegion == nullptr) break; // Break if region would be larger than the specified limit. if (blockRegion->instrSize() > numBCInstrs) { FTRACE(2, "selectHotTrace: breaking region at Translation {} because " "size would exceed of maximum translation limit\n", tid); break; } // If the debugger is attached, only allow single-block regions. if (prevId != kInvalidTransID && isDebuggerAttachedProcess()) { FTRACE(2, "selectHotTrace: breaking region at Translation {} " "because of debugger is attached\n", tid); break; } // Break if block is not the first and it corresponds to the main // function body entry. This is to prevent creating multiple // large regions containing the function body (starting at various // DV funclets). if (prevId != kInvalidTransID) { auto const func = rec->func(); auto const bcOffset = rec->startBcOff(); if (func->base() == bcOffset) { FTRACE(2, "selectHotTrace: breaking region because reached the main " "function body entry at Translation {} (BC offset {})\n", tid, bcOffset); break; } } if (prevId != kInvalidTransID) { auto sk = rec->srcKey(); if (ctx.profData->optimized(sk)) { FTRACE(2, "selectHotTrace: breaking region because next sk already " "optimized, for Translation {}\n", tid); break; } } bool hasPredBlock = !region->empty(); RegionDesc::BlockId predBlockId = (hasPredBlock ? region->blocks().back().get()->id() : 0); auto const& newFirstBlock = blockRegion->entry(); auto newFirstBlockId = newFirstBlock->id(); // Add blockRegion's blocks and arcs to region. region->append(*blockRegion); numBCInstrs -= blockRegion->instrSize(); assertx(numBCInstrs >= 0); if (hasPredBlock) { region->addArc(predBlockId, newFirstBlockId); } selectedSet.insert(tid); if (selectedVec) selectedVec->push_back(tid); const auto lastSk = rec->lastSrcKey(); if (breaksRegion(lastSk)) { FTRACE(2, "selectHotTrace: breaking region because of last instruction " "in Translation {}: {}\n", tid, opcodeToName(lastSk.op())); break; } auto outArcs = ctx.cfg->outArcs(tid); if (outArcs.size() == 0) { FTRACE(2, "selectHotTrace: breaking region because there's no successor " "for Translation {}\n", tid); break; } auto newLastBlock = blockRegion->blocks().back(); discardPoppedTypes(accumPostConds, blockRegion->entry()->initialSpOffset()); mergePostConds(accumPostConds, newLastBlock->postConds()); blockPostConds[newLastBlock->id()] = accumPostConds; TransCFG::ArcPtrVec possibleOutArcs; for (auto arc : outArcs) { auto dstRec = ctx.profData->transRec(arc->dst()); auto possibleNext = dstRec->region()->entry(); if (preCondsAreSatisfied(possibleNext, accumPostConds)) { possibleOutArcs.emplace_back(arc); } } if (possibleOutArcs.size() == 0) { FTRACE(2, "selectHotTrace: breaking region because postcondition check " "pruned all successors of Translation {}\n", tid); break; } auto maxWeight = std::numeric_limits<int64_t>::min(); TransCFG::Arc* maxArc = nullptr; for (auto arc : possibleOutArcs) { if (arc->weight() >= maxWeight) { maxWeight = arc->weight(); maxArc = arc; } } assertx(maxArc != nullptr); prevId = tid; tid = maxArc->dst(); } FTRACE(3, "selectHotTrace: before chainRetransBlocks:\n{}\n", show(*region)); region->chainRetransBlocks(); FTRACE(3, "selectHotTrace: after chainRetransBlocks:\n{}\n", show(*region)); return region; }
RegionDescPtr selectHotTrace(TransID triggerId, const ProfData* profData, TransCFG& cfg, TransIDSet& selectedSet, TransIDVec* selectedVec) { auto region = std::make_shared<RegionDesc>(); TransID tid = triggerId; TransID prevId = kInvalidTransID; selectedSet.clear(); if (selectedVec) selectedVec->clear(); PostConditions accumPostConds; // Maps BlockIds to the set of BC offsets for its successor blocks. // Used to prevent multiple successors with the same SrcKey for now. // This can go away once task #4157613 is done. hphp_hash_map<RegionDesc::BlockId, SrcKeySet> succSKSet; // Maps from BlockIds to accumulated post conditions for that block. // Used to determine if we can add branch-over edges by checking the // pre-conditions of the successor block. hphp_hash_map<RegionDesc::BlockId, PostConditions> blockPostConds; while (!selectedSet.count(tid)) { RegionDescPtr blockRegion = profData->transRegion(tid); if (blockRegion == nullptr) break; // If the debugger is attached, only allow single-block regions. if (prevId != kInvalidTransID && isDebuggerAttachedProcess()) { FTRACE(2, "selectHotTrace: breaking region at Translation {} " "because of debugger is attached\n", tid); break; } // Break if block is not the first and requires reffiness checks. // Task #2589970: fix translateRegion to support mid-region reffiness checks if (prevId != kInvalidTransID) { auto nRefDeps = blockRegion->blocks[0]->reffinessPreds().size(); if (nRefDeps > 0) { FTRACE(2, "selectHotTrace: breaking region because of refDeps ({}) at " "Translation {}\n", nRefDeps, tid); break; } } // Break if block is not the first and it corresponds to the main // function body entry. This is to prevent creating multiple // large regions containing the function body (starting at various // DV funclets). if (prevId != kInvalidTransID) { const Func* func = profData->transFunc(tid); Offset bcOffset = profData->transStartBcOff(tid); if (func->base() == bcOffset) { FTRACE(2, "selectHotTrace: breaking region because reached the main " "function body entry at Translation {} (BC offset {})\n", tid, bcOffset); break; } } if (prevId != kInvalidTransID) { auto sk = profData->transSrcKey(tid); if (profData->optimized(sk)) { FTRACE(2, "selectHotTrace: breaking region because next sk already " "optimized, for Translation {}\n", tid); break; } } // Break trace if translation tid cannot follow the execution of // the entire translation prevId. This can only happen if the // execution of prevId takes a side exit that leads to the // execution of tid. if (prevId != kInvalidTransID) { Op* lastInstr = profData->transLastInstr(prevId); const Unit* unit = profData->transFunc(prevId)->unit(); OffsetSet succOffs = findSuccOffsets(lastInstr, unit); if (!succOffs.count(profData->transSrcKey(tid).offset())) { if (HPHP::Trace::moduleEnabled(HPHP::Trace::pgo, 2)) { FTRACE(2, "selectHotTrace: WARNING: Breaking region @: {}\n", show(*region)); FTRACE(2, "selectHotTrace: next translation selected: tid = {}\n{}\n", tid, show(*blockRegion)); FTRACE(2, "\nsuccOffs = {}\n", folly::join(", ", succOffs)); } break; } } if (region->blocks.size() > 0) { auto& newBlock = blockRegion->blocks.front(); auto newBlockId = newBlock->id(); auto predBlockId = region->blocks.back().get()->id(); if (!RuntimeOption::EvalHHIRBytecodeControlFlow) { region->addArc(predBlockId, newBlockId); } else { // With bytecode control-flow, we add all forward arcs in the TransCFG // that are induced by the blocks in the region, as a simple way // to expose control-flow for now. // This can go away once Task #4075822 is done. auto newBlockSrcKey = blockRegion->blocks.front().get()->start(); if (succSKSet[predBlockId].count(newBlockSrcKey)) break; region->addArc(predBlockId, newBlockId); succSKSet[predBlockId].insert(newBlockSrcKey); assert(hasTransId(newBlockId)); auto newTransId = getTransId(newBlockId); for (auto iOther = 0; iOther < region->blocks.size(); iOther++) { auto other = region->blocks[iOther]; auto otherBlockId = other.get()->id(); if (!hasTransId(otherBlockId)) continue; auto otherTransId = getTransId(otherBlockId); auto otherBlockSrcKey = other.get()->start(); if (cfg.hasArc(otherTransId, newTransId) && !other.get()->inlinedCallee() && // Task #4157613 will allow the following check to go away !succSKSet[otherBlockId].count(newBlockSrcKey) && preCondsAreSatisfied(newBlock, blockPostConds[otherBlockId])) { region->addArc(otherBlockId, newBlockId); succSKSet[otherBlockId].insert(newBlockSrcKey); } // When Eval.JitLoops is set, insert back-edges in the // region if they exist in the TransCFG. if (RuntimeOption::EvalJitLoops && cfg.hasArc(newTransId, otherTransId) && // Task #4157613 will allow the following check to go away !succSKSet[newBlockId].count(otherBlockSrcKey)) { region->addArc(newBlockId, otherBlockId); succSKSet[newBlockId].insert(otherBlockSrcKey); } } } } region->blocks.insert(region->blocks.end(), blockRegion->blocks.begin(), blockRegion->blocks.end()); region->arcs.insert(region->arcs.end(), blockRegion->arcs.begin(), blockRegion->arcs.end()); if (cfg.outArcs(tid).size() > 1) { region->setSideExitingBlock(blockRegion->blocks.front()->id()); } selectedSet.insert(tid); if (selectedVec) selectedVec->push_back(tid); Op lastOp = *(profData->transLastInstr(tid)); if (breaksRegion(lastOp)) { FTRACE(2, "selectHotTrace: breaking region because of last instruction " "in Translation {}: {}\n", tid, opcodeToName(lastOp)); break; } auto outArcs = cfg.outArcs(tid); if (outArcs.size() == 0) { FTRACE(2, "selectHotTrace: breaking region because there's no successor " "for Translation {}\n", tid); break; } auto lastNewBlock = blockRegion->blocks.back(); discardPoppedTypes(accumPostConds, blockRegion->blocks[0]->initialSpOffset()); mergePostConds(accumPostConds, lastNewBlock->postConds()); blockPostConds[lastNewBlock->id()] = accumPostConds; TransCFG::ArcPtrVec possibleOutArcs; for (auto arc : outArcs) { RegionDesc::BlockPtr possibleNext = profData->transRegion(arc->dst())->blocks[0]; if (preCondsAreSatisfied(possibleNext, accumPostConds)) { possibleOutArcs.emplace_back(arc); } } if (possibleOutArcs.size() == 0) { FTRACE(2, "selectHotTrace: breaking region because postcondition check " "pruned all successors of Translation {}\n", tid); break; } auto maxWeight = std::numeric_limits<int64_t>::min(); TransCFG::Arc* maxArc = nullptr; for (auto arc : possibleOutArcs) { if (arc->weight() >= maxWeight) { maxWeight = arc->weight(); maxArc = arc; } } assert(maxArc != nullptr); prevId = tid; tid = maxArc->dst(); } return region; }
int main (int argc, char* argv[]){ // temporary string holder char line[MAX_LEN]; // checks for correct command line inputs if(argc != 3) { printf("Invalid number of inputs"); exit(1); } // opens the file FILE* input = fopen(argv[1], "r"); FILE* output = fopen(argv[2], "w"); // checks if files have been open and or created if(input == NULL){ printf("Unable to open file %s for reading\n", argv[1]); return 1; } else if (output == NULL){ printf("Unable to open file %s for reading\n", argv[2]); return 1; } // read each line of input file, then count and print tokens fgets(line, MAX_LEN, input); int numVertex = 0; sscanf(line, "%d", &numVertex); List S = newList(); for (int i = 1; i <= numVertex; i++) append(S, i); // Graph creation Graph G = newGraph(numVertex); while( fgets(line, MAX_LEN, input) != NULL) { int vert1 = 0; int vert2 = 0; sscanf(line, "%d %d", &vert1, &vert2); if(vert1 == 0 && vert2 == 0) break; addArc(G, vert1, vert2); } DFS(G, S); fprintf(output, "Adjacency list representation of G:\n"); printGraph(output, G); Graph T = transpose(G); DFS(T, S); //counts the number of Scc int numScc = 0; for(moveTo(S, 0); getIndex(S) >= 0; moveNext(S)){ if(getParent(T, getElement(S)) == NIL) numScc ++ ; } // puts the components into array list of size # of scc List Scc[numScc]; int i = numScc; for(moveTo(S, 0); getIndex(S) >= 0; moveNext(S)){ if(getParent(T, getElement(S)) == NIL){ i--; Scc[i] = newList(); } if(i == numScc) break; append(Scc[i], getElement(S)); } // prints out scc's fprintf(output, "\nG contains %d strongly connected components:", numScc); for(int j = 0; j < numScc; j++){ fprintf(output, "\n"); fprintf(output, "Component %d: ", j + 1); printList(output, Scc[j]); freeList(&(Scc[j])); } // frees all the necessary items fprintf(output, "\n"); freeGraph(&G); freeGraph(&T); freeList(&S); fclose(input); fclose(output); return(0); }
void addEdge(int n1,int n2,graphe *pg, int valeur){ addArc(n1,n2,pg,valeur); addArc(n2,n1,pg,valeur); }