ВЫПУСКНАЯ КВАЛИФИКАЦИОННАЯ РАБОТА МАГИСТРА. Силина Дмитрий Игоревича. Бесконфликтная аггрегация даннных на основе дерева в беспроводных сетях.

Size: px
Start display at page:

Download "ВЫПУСКНАЯ КВАЛИФИКАЦИОННАЯ РАБОТА МАГИСТРА. Силина Дмитрий Игоревича. Бесконфликтная аггрегация даннных на основе дерева в беспроводных сетях."

Transcription

1 МИНИСТЕРСТВО ОБРАЗОВАНИЯ И НАУКИ РОССИЙСКОЙ ФЕДЕРАЦИИ ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ АВТОНОМНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ «НОВОСИБИРСКИЙ НАЦИОНАЛЬНЫЙ ИССЛЕДОВАТЕЛЬСКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ» (НОВОСИБИРСКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ, НГУ) Факультет Кафедра Направление подготовки Механико-математический Теоретической кибернетики Прикладная математика ВЫПУСКНАЯ КВАЛИФИКАЦИОННАЯ РАБОТА МАГИСТРА Силина Дмитрий Игоревича Бесконфликтная аггрегация даннных на основе дерева в беспроводных сетях. «К защите допущена» Научный руководитель Заведующий кафедрой, д.ф.-м.н, проф., Ерзин А.И./.. (фамилия, И., О.) / (подпись, МП) 2016г. д.ф.-м.н, проф., в.н.с., им. С.Л. Соболева Ерзин А.И./.. (фамилия, И., О.) / (подпись, МП) 2016г. Дата защиты: 2016г. Новосибирск, 2016

2 Table of contents Introduction 1. Fixed tree case 1.1 Problem statement: 1.2 Linear programming problem formulation 1.3 Complexity 1.4 Polynomial solvable cases 1.5 Branch and Bound 1.6 Alternative approaches 2 Looking for SPT 2.1 Problem overview 2.2. Formulation, bad case 2.3. Numeric experiments Description Data set Algorithm Results Summary List of sources Application A. Source code

3 Introduction This work is about data aggregation in wireless sensor networks (WSN). WSN consists of the set of devices, which collect some data within the covered region. Once data is collected it should be transmitted to the base station. Communication environment is wireless, so a possibility of communication between the nodes directly depends on the transmission power of the sensors and of the physical location. Wireless environment has a limited throughput. It happens because of signals interference. Data goes through the channels (defined by signal frequency) during the sessions. Support for multichannel transmissions complicates the underlying protocols and increases the hardware requirements. Some papers [REF] describe optimization using multi-channel environment, but the most papers are focused on a fixed frequency [1, 2, 3]. One of the interesting problem in WSN is how to deliver the data from the nodes (sensors) to the sink (or base station). Usually, the objective functions are: a power consumption, a data transmission latency, a length of the full-cycle period. The tradeoff between power consumption and time latency was considered in [4]. Data aggregation process can be decomposed into two tasks: to define a topology and to build a schedule. The exact formulation of the problem depends on a lot of model's parameters. On the one hand power consumption is the most important characteristic, but on the other hand it mostly depends on the data flow topology. Scheduling impacts delivering time for one-shot process and latency for continuous one. The problem model studied in this work is defined as: single base station. one-shot [3] aggregation, i.e. data should be collected once. mergeable data - any number of packets can be merged into single one. Note compatible data case is well studied in [2]. data processing time is ignored. data transmission along one edge is a unit. transmissions never fails (except signal interference). interference happens if the receiver within the range of 2+ transmitters which broadcast their data at the same time. It's particular case of Convergecast Problem a problem, where data on sensors in the network are required to be sent and aggregated to the data sink (base station). First part is about scheduling in case of fixed tree topology. Different problem formulations and approaches are studied. The NP-completeness of the problem is proved. Developed different Branch and Bound approaches. Second part is about looking for aggregation tree which is better for scheduling length. Numeric experiments shows that minimum radius SPT are good for Euclidean graphs.

4 1 Fixed tree case 1.1 Problem statement: Consider an oriented graph G(V, E), where veracities and edges represent nodes and possible transmissions respectively. It's called communication graph [Picture 1.1]: We are looking for schedule of minimal length based on a fixed topology. Easy to see that any aggregation topology is a spanning tree ( in. [Picture 1.1, black edges]. This tree defines precedence constrains any station should be scheduled before its parent. The schedule is the time slot assignment to SPT edge, such that all model conditions are met. The schedule length is the number of distinct time slots used by the assignment. First ensure conflict-free assignment. Conflicts (resource constrains) appear between simultaneously transmissions, i.e. between edges. Consider the conflict graph Look at the [Picture 1.2] Cyan edges shows transmissions which conflict with red one.

5 As soon as we know next hop for each station, edge to edge conflict can be reduced to its sources conflict -. There is no reason to keep whole edges of anymore. The final graph is [Picture 1.3]. Now problem can be formulated as:,, t(v) integer function. Solution example is shown on [Picture 1.4]. T= 7, black numbers are values of function Next this problem statement will be referred as [1S]

6 1.2 Linear programming problem formulation: Define variable Unfortunately integer relaxation is useless. [Picture 1.5] demonstrates that any number of stations without precedence constrains can be scheduled in 2 time slots. It happens because of weak limitation:

7 1.3 Complexity Artem Pyatkin and Adil Erzin have proved NP-hardness for the problem described in section 2.1. The paper is not published yet. During analysis of [1S] one more proof was obtained. It s base on reduction from chromatic number of a graph, which is known as NP-hard. 1) Let - instance of chromatic number problem: Graph, find the smallest, such that vertices are colorable in colors, where endpoints for every edge have distinct colors. 2) Create copies of, call them. Define =. Value of k will be defined later. [Picture 1.7]. Easy to see that Let, then Let 3) Add vertices to. Call new graph Obviously chromatic number stays the same, i.e. 4) Build binary tree of height. Height of tree the number of vertices in the longest simple path started at the root. Create by hanging a new node for every leaf of. [Picture 1.8]

8 Consider problem [1S] where aggregation tree is between siblings.. All transmission conflicts are Lemma 1: Binary tree of height can be scheduled in time slots. Proof: by induction over height. Base case: All data are aggregated it the root. Induction step: Let binary tree has feasible schedule, where and uses time slots. Use time slot for the leaf of, if is the left child and - if the right. Unscheduled vertices of are, so use for them. The obtained is free of conflict and uses time slots. 5) Number of leafs in is, and it s the same to the number of vertices in. Let any bijective function. Create is a valid instance of [1S]. For any feasible schedule, holds: Thus, if is colorable in colors, then lemma 1 it can be scheduled in additional Use to schedule leaves; the rest is and by slots.

9 Let s define. is integer, so if < 1, there is only one integer in range ]. Let. Case 1: Case 2:, k =24 Thus, for any instance of chromatic number problem it s possible to build with. Obviously can be done in polynomial time and has polynomial size of, is the number of vertices in graph of. If there is a polynomial time algorithm for [1S] problem statement, then chromatic number is P. Contradiction. Corollary: constant absolute error algorithm for [1S] doesn t exist in class P: Proof:

10 Now, to solve any chromatic number problem it s enough to show that, s.t.: Easy to see that for any. Thus, is polynomial of and it s enough. 1) 2)

11 1.4 Polynomial solvable cases Although problem is NP complete, it's possible to solve restricted cases in polynomial time. Let's allow transmission conflicts, i.e. get rid of resources constrains. Then problem can be solved by calculating recursive function. Actually this function is required scheduling and f(root) it's length. The mean of when node received all packets from its aggregation subtree. is the earliest time Resource constrains may appear between ant pair of nodes, but there is always a conflict between siblings (the pair of node with the same predecessor). Fortunately the problem where every such pair conflict, has polynomial solution: Algorithm P-siblings [Application A: TreeConvergecast.evaluateTree()]: Idea is the same: calculate function for further transmission, i.e. value. which is the earliest time when node is ready received data form every node in corresponding subtree. Let's function which returns array of successors for node in non-descending order of Define - function which gets array and some number. returns the smallest time stamp when all data from first k nodes in be delivered to its common predecessor. Then Proposition 1: and its subtrees can Proposition 2: Proof is obvious by induction over., solves restricted problem optimally. Since g(m, k) optimality is proven, it needs to prove that transmission order based on non-descending values is correct. Lemma 1: if there is scheduling T, then exist scheduling T*, such that siblings send its data in non-descending order. Proof: find the deepest node where requirement is broken. Interchange time assignment between two siblings which break the order. Obviously the scheduling is still feasible and has the same length. Iterate this process until T* obtained. Corollary 1:

12 Any instance of original problem can be transformed into restricted one and any initially feasible solution is still feasible. Thus, P-siblings algorithm provides lower bound on schedule length. Corollary 2: Algorithm can be easily modified to solve the problem once all resource constrains are replaced by precedence ones, i.e. orientation is set for every conflict. 1.5 Branch and Bound

13 Since problem [1S] is NP-complete, it's interesting to try some heuristics. Quality of approximation can be either proved theoretically either estimated during experiment. For the last one it needs to know optimal solution. The most famous way to find exact solution - apply Brach and Bound methodology. Any B&B consists of 2 subtasks: how to branch split a solution space and to bound - estimate lower\upper bounds for a subspace. Lower bounds: Use P-siblings algorithm Perform heuristic, e.g. build scheduling iteratively, on each step schedule maximal independent set of leaves. Upper bounds: : each station transmit on its own time, no conflicts are expected. radius of plus number of transmission conflicts. There is duality between schedule and orientation for conflicts. To orient conflict means to set relative priority for conflicting transmissions. Any solution defines this priority. And once priority for every conflict is chosen it s possible to find optimal solution by Algorithm M-siblings [described in 1.4]. Thus, to obtain UB: first perform random orientation for every conflict (use transitive closure on each step to avoid cycle appearance), next apply M-Siblings algorithm and use result as UB. Branching should met 2 criteria: (1) Branching parameter should be chosen in a way to provide the smallest number of nodes in full B&B tree. (2) Introduce RTFV over solution space the range of minimal size which contains target function for the space. Then, intersection size for RTFVs over branched subspaces should go to zero. The native idea: make branching by choosing node and split space to subspaces, where is the upper bound on optimal schedule for the current space and consists of the schedules with, i.e. assign the exact time slot for some picked node. This approach is weak because of there are several absolute time assignments for the same scheduling order, i.e. it creates spaces which may contains no optimal solution. Further analysis showed that branching based on conflict orientation lead to B&B tree, where leaf number is equal to number of different scheduling. Algorithm was implemented but applicability was incredibly small. There are no interesting cases for heuristic analysis, due to low distance between OPT and random schedules.

14 1.6 Alternative approaches 1) 3-rd party solvers for ILP hasn n been tried. Potentially it can extend number of problems where optimal solution can be gained in adequate time. Therefore it would allow to play with heuristics. 2) Reduction rule: : Let's is feasible solution. It defines orientation for every resource constrain. Check if it has k constrains which reorientation lead us to better scheduling. Obiously the optimal one has no such constains sets for any k. 3) Randomization algorithms. How far random solution from the optimal? 4) Machine learning: try to present data in appropriate way and create Artificial Intelligence which resolves resource conflicts.

15 2 Looking for SPT 2.1 Problem overview Usually topology is chosen based on power efficiency characteristic [5]. Meanwhile, as we have seen aggregation topology is highly impact scheduling characteristics. Therefore it's worth to make next-hop decision carefully. This problem was well studied in [1]. Authors consider tree efficiency as a combination of: - Total tree interference (sum of in rank in communication graph for every edge endpoint in T) - Tree radius Suggested algorithm accept parameter alpha which define relative cost for target functions Formulation, bad case Let's return to the statement [1F], where are resource limitations are only between siblings, call it [2F] formulation. Next chapters are about analysis of applicability of minimumradius spanning trees (rspt) as aggregation tree. Other well-known trees have been checked, but nothing interesting was found. Easy to see that rspt is not the best topology in formulation [1], [Picture 3.1] demonstrates the root cause. Meanwhile for restricted problem rspt looks good. Especially for Euclidian space it has additional meaning - passing the data in base station direction.

16 2.3. Numeric experiments Description Numeric experiment was done for analysis of minr trees for usage as aggregation topology for [F1] problem statement. It s generated a set of problem instances. Next for every instance it went through all possible spanning trees. Optimal schedule was built for every tree. [Results 2.3.4] contains corollaries and hypothesis which leads from experiment Data set Test instance generation: Put N points into unit square randomly Set transmission range to unit. Use 15 iterations of binary search: - Pick left range if graph connected at midpoint - Pick right one otherwise. Check if the. If yes graph instance successfully generated. For every number is 2100 graphs. The limit for, was generated 100 graphs by the described algorithm. The overall was set because of it needs all trees to be generated. By [A. Cayley] theorem, the number of SPT in a complete graph over vertices is that s why most of built graphs are sparse. The number was estimated by Gauss base algorithm for determinant calculation of [Kirchhoff] matrix. Picture 2.2 describes test set structure.

17 2.3.3 Algorithm Tree generation [Application A: TreeGenerator] procedure based on Christofides s algorithm described in [6]. The algorithm was slightly modified to check on each step if there enough edges to finalize the tree. The modification provided 10 times boost for processed data set. Tree evaluation was done by P-siblings algorithm, it has complexity. Picture 2.3 shows algorithm performance [results are from AMD Athlon II, P320, 2.1 Hz, DDR3-1066, 2GB, gcc 4.9 -O3] Results Experiment shows that for any problem instance there is a minr tree which is optimal, i.e. the shortest schedule over some minr tree is optimal for an instance. Average length of optimal schedules for all minr SPTs is in a distance < 0.5 from optimal one. It s interesting all minr trees can be scheduled in at most OPT + 1 time slots. The optimal schedules length distribution can be found on Picture 2.5.

18 Hypothesis 1: for any instance [F2] problem, exists a minr spanning tree R and schedule S over R topology, such that length of S is optimal for the problem. Hypothesis 2: for any instance [F2] problem, doesn t exist a minr spanning tree R and schedule S over R topology, such that length of S greater then optimal + 1.

19 Summary For the problem [F1]: Analyzed linear programming formulation. Developed new proof of NP-hardness. Proved that there is no constant absolute error approximation algorithm. Implemented Branch and Bound algorithm for the problem. For the problem [F2]: Developed software for numeric experiment. Performed experiment which shows that minr trees are applicable as an aggregation topology. Formulated hypothesis.

20 List of sources [1] Evandro de Souza, Ioanis Nikolaidis (2013). An exploration of aggregation convergecast scheduling, Ad Hoc Networks vol.11, Issue 8, November 2013, Pages [2] Hongsik Choi, Ju Wang, Esther A. Hughes (2009). Scheduling for information gathering on sensor network, Wireless Networks vol.15, Issue 1, January [3] Özlem Durmaz Incel, Amitabha Ghosh, Bhaskar Krishnamachari, Krishnakant Chintalapudi (2012). Fast Data Collection in Tree-Based Wireless Sensor Networks, IEEE Transactions on Mobile Computing vol.11 Issue 1, January 2012 [4] Yu Y. Krishnamachari B., Prasanna (2004). V. Energy-latency tradeoffs for data gathering in wireless sensor networks, IEEE INFOCOM vol.1, [5] Gurwinder Kaur, Rachit Mohan Garg (2012). Power Efficient Topologies for Wireless Sensor Networks, IJDPS Vol.3, Issue 5, September 2012 [6] Nicos Christofides (1975). Graph Theory: An Algorithmic Approach, Academic Press, Incorporated, 1975

21 Application A. Source code M-siblings TreeGenerator TreeConvergecast.h #pragma once #ifndef TreeConvergecast_h #define TreeConvergecast_h #include "GraphStructures.h" #include<map> class TreeConvergecast { public: TreeConvergecast(); ~TreeConvergecast(); int evaluatetree(tree *tree); int evaluatetree(simpletree *tree); map<int, int>* getschedule(tree *tree); int getradius(simpletree *tree); private: int evaluatevetrex(treenode *node); int getvertexdistance(int id, SimpleTree *tree); std::map<int, int> dp; int *disttoroot; int disttorootsz; ; #endif TreeConvergecast.cpp #pragma once #include "TreeConvergecast.h" #include "GraphStructures.h" #include <cstring> #include <algorithm> #include <iostream> #include <map> TreeConvergecast::TreeConvergecast() { disttorootsz=0; disttoroot=null; TreeConvergecast::~TreeConvergecast() { disttorootsz=0; delete(disttoroot); int TreeConvergecast::evaluateTree(SimpleTree *stree) { Tree *tree = new Tree(*sTree); dp.clear(); int ret = evaluatevetrex(tree->getroot()); delete(tree); return ret; int TreeConvergecast::evaluateTree(Tree *tree) { dp.clear(); return evaluatevetrex(tree->getroot()); map<int, int>* TreeConvergecast::getSchedule(Tree *tree) { evaluatetree(tree); return new map<int, int>(dp); int TreeConvergecast::evaluateVetrex(TreeNode* node) { int id = node->getidx(); if(dp.find(id) == dp.end()) { int ret = 0; vector<int> *childrentimes = new vector<int>(); vector<treenode*> children = node- >GetChildren(); for(vector<treenode*>::iterator it = children.begin(); it!= children.end(); it++) { childrentimes- >push_back(evaluatevetrex(*it)); std::sort(childrentimes->begin(), childrentimes- >end()); for(vector<int>::iterator it = childrentimes- >begin(); it!= childrentimes->end(); it++) { int time = *it; if(ret < time + 1) { ret = time + 1; else { ret++; delete(childrentimes); dp[id] = ret; return dp[id]; int TreeConvergecast::getRadius(SimpleTree *tree) { int sz = tree->size(); if(sz > disttorootsz) { delete(disttoroot); disttorootsz = sz * 2; disttoroot = new int[disttorootsz]; for(int i = 0; i < sz; i++) { disttoroot[i] = -1; int radius = 0; for(int i = 0; i < sz; i++) { int vr = getvertexdistance(i, tree); radius = max(vr, radius); return radius; int TreeConvergecast::getVertexDistance(int id, SimpleTree *tree) { if(disttoroot[id]!= -1) return disttoroot[id]; int prev = tree->at(id); if(id == prev) return disttoroot[id] = 0; return disttoroot[id] = 1 + getvertexdistance(prev, tree);

22 SpanningTreeGenerator.h #pragma once #ifndef SpanningTreeGenerator_h #define SpanningTreeGenerator_h #include "GraphStructures.h" #include "DataKeeper.h" #include<map> //[Christofides] class SpanningTreeGenerator; class DSU; // generates SPT over grah rooted at rootid. class SpanningTreeGenerator { public: SpanningTreeGenerator(int rootidext, Graph* graph); ~SpanningTreeGenerator(); SimpleTree* getnexttree(); long long gettreecount(); private: int nverticies; long long ntrees; long long latestbuildedtreeindex; int rootidext; EdgesSet *edges; long long calctreecount(); int getinternalid(int external); int getexternalid(int internal); std::map<int, int> idconvertor; std::map<int, int> idrevertor; DSU *dsu, *dsu_tmp; vector<int> *pickedstack; bool appendedge(int lastused); int revertlastedge(); bool switchtonexttree(); bool restisclosable(int lastused); SimpleTree* buildtree(dsu *inst); long long determinant(int n, int *arr); long long determinantinteger(int n, int *arr); long long gcd(long long a, long long b); public: SimpleTree* getspt_minw(datakeeper* pdk); // CAUTION - SLOW implementation, don't call frequently SimpleTree* getspt_minww(datakeeper* pdk); // CAUTION - SLOW implementation, don't call frequently SimpleTree* getspt_minr(); // CAUTION - SLOW implementation, don't call frequently ; // disjoint set union class DSU { public: DSU(int nvertecies); ~DSU(); bool addedge(int ida, int idb); void removeedge(int ida, int idb); bool isconnected(); void setasroot(int id, bool updaterootchanges = true); int getprevid(int id); int getrootid(int id); void reset(); void set(dsu *inst); private: // : j -> [root(j), prev(j)] int cntcomponents; int sz; int *rootid; int *previd; ; #endif SpanningTreeGenerator.cpp #pragma once #include "SpanningTreeGenerator.h" #include "GraphStructures.h" #include "GraphAlgorithms.h" #include <algorithm> #include <map> #include <utility> #include <assert.h> #include <iostream> #include <cstring> #include <queue> SpanningTreeGenerator::SpanningTreeGenerator(int rootid, Graph *graph) { this->rootidext = rootid; if(!graph->isconnected()) { throw std::invalid_argument("graph is not connected, cannot build any SpanningTree"); this->nverticies = graph->getverticescount(); edges = new EdgesSet();

23 for(vector<graphedge*>::iterator it = graph- >_aedges.begin(); it!= graph->_aedges.end(); it++) { int a = (*it)->getv1idx(); int b = (*it)->getv2idx(); GraphVertex *internala = new GraphVertex(getInternalId(a)); GraphVertex *internalb = new GraphVertex(getInternalId(b)); edges->push_back(new GraphEdge(internalA, internalb)); this->ntrees = calctreecount(); latestbuildedtreeindex = 0L; dsu = new DSU(graph->GetVerticesCount()); dsu_tmp = new DSU(graph->GetVerticesCount()); pickedstack = new vector<int>(); SpanningTreeGenerator::~SpanningTreeGenerator() { delete(dsu); delete(dsu_tmp); delete(pickedstack); for(vector<graphedge*>::iterator it = edges- >begin(); it!= edges->end(); it++) { GraphEdge *edge = (*it); delete(edge->getv1()); delete(edge->getv2()); delete(edge); delete(edges); SimpleTree* SpanningTreeGenerator::getNextTree() { if(switchtonexttree()){ latestbuildedtreeindex++; if(latestbuildedtreeindex % == 0) { cout << "New tree builded " << latestbuildedtreeindex << "out of " << ntrees << " " << * latestbuildedtreeindex / ntrees << endl; return buildtree(dsu); return NULL; SimpleTree* SpanningTreeGenerator::buildTree(DSU *inst) { SimpleTree* ret = new SimpleTree(); inst->setasroot(getinternalid(this->rootidext), true); for(int i = 0; i < nverticies; i++) { int internal = getinternalid(i); int prev = inst->getprevid(internal); ret->push_back(getexternalid(prev)); return ret; long long SpanningTreeGenerator::getTreeCount() { return ntrees; long long SpanningTreeGenerator::calcTreeCount() { int n = nverticies - 1; int arr[n][n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) arr[i][j] = 0; for(vector<graphedge*>::iterator it = edges- >begin(); it!= edges->end(); it++) { int a = (*it)->getv1idx(); int b = (*it)->getv2idx(); if(a < n && b < n) { arr[a][b]--; arr[b][a]--; if(a < n) arr[a][a]++; if (b < n) arr[b][b]++; // cout << " " << endl; // for(int i = 0; i < n; i++) { // cout << endl; // for(int j = 0; j < n; j++) { // cout << arr[i][j] << " "; // // // cout << " " << endl; long long ret = determinant(n, &arr[0][0]); return ret; int SpanningTreeGenerator::getInternalId(int external) { if(idconvertor.find(external) == idconvertor.end()) { int newid = idconvertor.size(); idconvertor[external] = newid; idrevertor[newid] = external; // cout << "Added mapping: " << external << " -> " << newid << endl; return idconvertor[external]; int SpanningTreeGenerator::getExternalId(int internal) { if(idrevertor.find(internal) == idconvertor.end()) { throw std::invalid_argument("element with id: " + std::to_string(internal) + " hasn't been mapped"); return idrevertor[internal];

24 bool SpanningTreeGenerator::appendEdge(int lastused){ if(lastused < -1) { throw std::invalid_argument("lastused [" + std::to_string(lastused) + "] should be >= -1"); // cout << "point Z " << lastused << " " << edges->size() << endl; for(vector<graphedge*>::size_type i = lastused + 1; i < edges->size(); i++) { int a = (*edges)[i]->getv1idx(); int b = (*edges)[i]->getv2idx(); // cout << "point 0 " << a << " " << b << endl; // cout.flush(); if(dsu->addedge(a, b)) { pickedstack->push_back(i); // cout << "appended " << a << " " << b << endl; return true; // cout << "cannot append " << endl; return false; int SpanningTreeGenerator::revertLastEdge() { //cout << pickedstack->size() << "???????????? " << endl; if(pickedstack->begin() == pickedstack->end()) return -1; int edgedid = pickedstack->back(); GraphEdge *edge = (*edges)[edgedid]; pickedstack->pop_back(); dsu->removeedge(edge->getv1idx(), edge- >GetV2Idx()); // cout << "reverted " << edge->getv1idx() << " " << edge->getv2idx() << endl; return edgedid; bool SpanningTreeGenerator::switchToNextTree() { bool prebuilded = true; while(appendedge(-1)) { prebuilded = false; if(!prebuilded && dsu->isconnected()) { return true; int index = -1; while((index = revertlastedge()) >= 0) { if(!restisclosable(index)) continue; while(appendedge(index)); // add as many edges as possible if(dsu->isconnected()){ return true; return false; bool SpanningTreeGenerator::restIsClosable(int lastused) { dsu_tmp->set(dsu); for(vector<graphedge*>::size_type i = lastused + 1; i < edges->size(); i++) { int a = (*edges)[i]->getv1idx(); int b = (*edges)[i]->getv2idx(); dsu_tmp->addedge(a, b); if(dsu_tmp->isconnected()) return true; return false; // utils long long SpanningTreeGenerator::gcd(long long a, long long b) { return a == 0? b : gcd(b % a, a); double dabs(double x) { return x > 0? x : -x; long long SpanningTreeGenerator::determinant(int n, int *arr1) { double *arr = new double[n * n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) arr[i * n + j] = arr1[n * i + j]; int *rowindexes = new int[n]; for(int i = 0; i < n; i++) rowindexes[i] = i; const double eps = 1e-9; double multiplicator = 1L; for(int diag = 0; diag < n; diag++) { int j = diag + 1; while(j < n ) { if(dabs(arr[rowindexes[j] * n + diag]) > dabs(arr[rowindexes[diag] * n + diag])) { int tmp = rowindexes[diag]; rowindexes[diag] = rowindexes[j]; rowindexes[j] = tmp; j++; if(dabs(arr[rowindexes[diag] * n + diag]) < eps) return 0; // all the rest rows contains 0 in [diag]- column. multiplicator *= arr[rowindexes[diag] * n + diag];

25 for(int row = diag + 1; row < n; row++) { double A = arr[rowindexes[diag] * n + diag]; double B = arr[rowindexes[row] * n + diag]; if(dabs(b) < eps) continue; for(int col = diag; col < n; col++) { arr[rowindexes[row] * n + col] = arr[rowindexes[row] * n + col] - arr[rowindexes[diag] * n + col] * B / A; multiplicator = dabs(multiplicator); delete(rowindexes); delete(arr); if(multiplicator > 1L << 60) return 1L << 60; return (long long) (multiplicator + 0.5); // other trees::: SimpleTree* SpanningTreeGenerator::getSPT_minR() { dsu_tmp->reset(); queue<int> qu; qu.push(getinternalid(this->rootidext)); while(!qu.empty()) { int v = qu.front(); qu.pop(); for(vector<graphedge*>::size_type i = 0; i < edges->size(); i++) { int a = (*edges)[i]->getv1idx(); int b = (*edges)[i]->getv2idx(); if(a == v b == v) { int c = a ^ b ^ v; if(dsu_tmp->addedge(v, c)) qu.push(c); if(!dsu_tmp->isconnected()) throw std::invalid_argument("minr is not connected"); return buildtree(dsu_tmp); SimpleTree* SpanningTreeGenerator::getSPT_minW(DataKeeper *pdk) { dsu_tmp->reset(); bool changed = true; while(changed) { changed = false; GraphEdge *best=null; double weight = -1; for(vector<graphedge*>::size_type i = 0; i < edges->size(); i++) { int a = (*edges)[i]->getv1idx(); int b = (*edges)[i]->getv2idx(); if(dsu_tmp->getrootid(a) == dsu_tmp- >getrootid(b)) continue; int exta = getexternalid(a); int extb = getexternalid(b); double tmp = pdk->getweight(exta, extb); if(weight < 0 tmp < weight) { weight = tmp; best = (*edges)[i]; if(best!= NULL) { dsu_tmp->addedge(best->getv1idx(), best- >GetV2Idx()); changed = true; if(!dsu_tmp->isconnected()) throw std::invalid_argument("minw is not connected"); return buildtree(dsu_tmp); SimpleTree* SpanningTreeGenerator::getSPT_minWW(DataKeep er *pdk) { dsu_tmp->reset(); bool changed = true; while(changed) { changed = false; GraphEdge *best=null; double weight = -1; for(vector<graphedge*>::size_type i = 0; i < edges->size(); i++) { int a = (*edges)[i]->getv1idx(); int b = (*edges)[i]->getv2idx(); if(dsu_tmp->getrootid(a) == dsu_tmp- >getrootid(b)) continue; int exta = getexternalid(a); int extb = getexternalid(b); double tmp = pdk->getweight(exta, extb); tmp *= tmp; if(weight < 0 tmp < weight) { weight = tmp; best = (*edges)[i]; if(best!= NULL) { dsu_tmp->addedge(best->getv1idx(), best- >GetV2Idx()); changed = true; if(!dsu_tmp->isconnected()) throw std::invalid_argument("minww is not connected"); return buildtree(dsu_tmp);

26 // DSU // BUILD tree, setasroot(getinternalid(this->rootid)), create simple tree based on DSU prev DSU::DSU(int nvertecies) { sz = nvertecies; previd = new int[sz]; rootid = new int[sz]; reset(); DSU::~DSU() { delete(previd); delete(rootid); bool DSU::addEdge(int ida, int idb) { if(rootid[ida] == rootid[idb]) return false; if(rand() & 1) { int tmp = ida; ida = idb; idb = tmp; int ra = rootid[ida]; int rb = rootid[idb]; setasroot(idb, false); // root changed: need to update rb -> idb previd[idb] = ida; // trees merged: need to update idb -> ra for(int i = 0; i < sz; i++) if(rootid[i] == rb) rootid[i] = ra; cntcomponents--; return true; void DSU::removeEdge(int ida, int idb) { if(rootid[ida]!= rootid[idb]) throw std::invalid_argument("dsu: cannot remove edged. Vertecies in the different components " + std::to_string(ida) + "[root:" + std::to_string(rootid[ida]) + "], " + std::to_string(idb) + "[root:" + std::to_string(rootid[idb]) + "]"); if(previd[idb]!= ida) { int tmp = ida; ida = idb; idb = tmp; if(previd[idb]!= ida) { throw std::invalid_argument("dsu: cannot remove edged. Vertecies are not neighbours " + std::to_string(ida) + "[prev:" + std::to_string(previd[ida]) + "], " + std::to_string(idb) + "[prev:" + std::to_string(previd[idb]) + "]"); cntcomponents++; previd[idb] = idb; vector<int> queue; queue.push_back(idb); while(!queue.empty()) { int elem = queue.back(); queue.pop_back(); rootid[elem] = idb; for(int i = 0; i < sz; i++) if(previd[i] == elem && rootid[i]!= idb) queue.push_back(i); bool DSU::isConnected() { return cntcomponents == 1; void DSU::setAsRoot(int id, bool updaterootchanges) { int from = id; int pos = previd[id]; previd[id] = id; while(from!= pos) { int next = previd[pos]; previd[pos] = from; from = pos; pos = next; if(updaterootchanges) { int tmp = rootid[id]; for(int i = 0; i < sz; i++) if(rootid[i] == tmp) rootid[i] = id; int DSU::getPrevId(int id) { return previd[id]; int DSU::getRootId(int id) { return rootid[id]; void DSU::reset() { cntcomponents = sz; for(int i = 0; i < sz; i++) rootid[i] = previd[i] = i; void DSU::set(DSU *inst) { if(sz!= inst->sz) throw std::invalid_argument("dsu: cannot fill - size mismatch" + std::to_string(inst->sz) + " ->" + std::to_string(sz)); std::memcpy(rootid, inst->rootid, sz * sizeof(int)); std::memcpy(previd, inst->previd, sz * sizeof(int)); cntcomponents = inst->cntcomponents;

CS521 \ Notes for the Final Exam

CS521 \ Notes for the Final Exam CS521 \ Notes for final exam 1 Ariel Stolerman Asymptotic Notations: CS521 \ Notes for the Final Exam Notation Definition Limit Big-O ( ) Small-o ( ) Big- ( ) Small- ( ) Big- ( ) Notes: ( ) ( ) ( ) ( )

More information

CS102 Binary Search Trees

CS102 Binary Search Trees CS102 Binary Search Trees Prof Tejada 1 To speed up insertion, removal and search, modify the idea of a Binary Tree to create a Binary Search Tree (BST) Binary Search Trees Binary Search Trees have one

More information

Binary Heaps in Dynamic Arrays

Binary Heaps in Dynamic Arrays Yufei Tao ITEE University of Queensland We have already learned that the binary heap serves as an efficient implementation of a priority queue. Our previous discussion was based on pointers (for getting

More information

Distributed Data Aggregation Scheduling in Wireless Sensor Networks

Distributed Data Aggregation Scheduling in Wireless Sensor Networks Distributed Data Aggregation Scheduling in Wireless Sensor Networks Bo Yu, Jianzhong Li, School of Computer Science and Technology, Harbin Institute of Technology, China Email: bo yu@hit.edu.cn, lijzh@hit.edu.cn

More information

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements B-Trees 1 B-Trees nodes with many children a type node a class for B-trees 2 manipulating a B-tree an elaborate example the insertion algorithm removing elements MCS 360 Lecture 35 Introduction to Data

More information

V Advanced Data Structures

V Advanced Data Structures V Advanced Data Structures B-Trees Fibonacci Heaps 18 B-Trees B-trees are similar to RBTs, but they are better at minimizing disk I/O operations Many database systems use B-trees, or variants of them,

More information

Properties of red-black trees

Properties of red-black trees Red-Black Trees Introduction We have seen that a binary search tree is a useful tool. I.e., if its height is h, then we can implement any basic operation on it in O(h) units of time. The problem: given

More information

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof. Priority Queues 1 Introduction Many applications require a special type of queuing in which items are pushed onto the queue by order of arrival, but removed from the queue based on some other priority

More information

Figure 4.1: The evolution of a rooted tree.

Figure 4.1: The evolution of a rooted tree. 106 CHAPTER 4. INDUCTION, RECURSION AND RECURRENCES 4.6 Rooted Trees 4.6.1 The idea of a rooted tree We talked about how a tree diagram helps us visualize merge sort or other divide and conquer algorithms.

More information

Topology Control in 3-Dimensional Networks & Algorithms for Multi-Channel Aggregated Co

Topology Control in 3-Dimensional Networks & Algorithms for Multi-Channel Aggregated Co Topology Control in 3-Dimensional Networks & Algorithms for Multi-Channel Aggregated Convergecast Amitabha Ghosh Yi Wang Ozlem D. Incel V.S. Anil Kumar Bhaskar Krishnamachari Dept. of Electrical Engineering,

More information

Priority Queues. Chapter 9

Priority Queues. Chapter 9 Chapter 9 Priority Queues Sometimes, we need to line up things according to their priorities. Order of deletion from such a structure is determined by the priority of the elements. For example, when assigning

More information

V Advanced Data Structures

V Advanced Data Structures V Advanced Data Structures B-Trees Fibonacci Heaps 18 B-Trees B-trees are similar to RBTs, but they are better at minimizing disk I/O operations Many database systems use B-trees, or variants of them,

More information

CONVERGECAST, namely the many-to-one flow of data

CONVERGECAST, namely the many-to-one flow of data IEEE/ACM TRANSACTIONS ON NETWORKING, VOL. 19, NO. 6, DECEMBER 2011 1731 Multichannel Scheduling and Spanning Trees: Throughput Delay Tradeoff for Fast Data Collection in Sensor Networks Amitabha Ghosh,

More information

Treewidth and graph minors

Treewidth and graph minors Treewidth and graph minors Lectures 9 and 10, December 29, 2011, January 5, 2012 We shall touch upon the theory of Graph Minors by Robertson and Seymour. This theory gives a very general condition under

More information

IJREAT International Journal of Research in Engineering & Advanced Technology, Volume 1, Issue 2, April-May, 2013 ISSN:

IJREAT International Journal of Research in Engineering & Advanced Technology, Volume 1, Issue 2, April-May, 2013 ISSN: Fast Data Collection with Reduced Interference and Increased Life Time in Wireless Sensor Networks Jayachandran.J 1 and Ramalakshmi.R 2 1 M.Tech Network Engineering, Kalasalingam University, Krishnan koil.

More information

/ Approximation Algorithms Lecturer: Michael Dinitz Topic: Linear Programming Date: 2/24/15 Scribe: Runze Tang

/ Approximation Algorithms Lecturer: Michael Dinitz Topic: Linear Programming Date: 2/24/15 Scribe: Runze Tang 600.469 / 600.669 Approximation Algorithms Lecturer: Michael Dinitz Topic: Linear Programming Date: 2/24/15 Scribe: Runze Tang 9.1 Linear Programming Suppose we are trying to approximate a minimization

More information

We will show that the height of a RB tree on n vertices is approximately 2*log n. In class I presented a simple structural proof of this claim:

We will show that the height of a RB tree on n vertices is approximately 2*log n. In class I presented a simple structural proof of this claim: We have seen that the insert operation on a RB takes an amount of time proportional to the number of the levels of the tree (since the additional operations required to do any rebalancing require constant

More information

3 No-Wait Job Shops with Variable Processing Times

3 No-Wait Job Shops with Variable Processing Times 3 No-Wait Job Shops with Variable Processing Times In this chapter we assume that, on top of the classical no-wait job shop setting, we are given a set of processing times for each operation. We may select

More information

International Journal of Scientific & Engineering Research, Volume 4, Issue 7, July ISSN

International Journal of Scientific & Engineering Research, Volume 4, Issue 7, July ISSN International Journal of Scientific & Engineering Research, Volume 4, Issue 7, July-2013 1472 DYNAMIC AND EFFICIENT TREE-BASED DATA COLLECTION IN WIRELESS SENSOR NETWORKS S.Thivyan Ravi Kumar, B.Maheswari,

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

Advanced Set Representation Methods

Advanced Set Representation Methods Advanced Set Representation Methods AVL trees. 2-3(-4) Trees. Union-Find Set ADT DSA - lecture 4 - T.U.Cluj-Napoca - M. Joldos 1 Advanced Set Representation. AVL Trees Problem with BSTs: worst case operation

More information

Greedy Algorithms CHAPTER 16

Greedy Algorithms CHAPTER 16 CHAPTER 16 Greedy Algorithms In dynamic programming, the optimal solution is described in a recursive manner, and then is computed ``bottom up''. Dynamic programming is a powerful technique, but it often

More information

Main Memory and the CPU Cache

Main Memory and the CPU Cache Main Memory and the CPU Cache CPU cache Unrolled linked lists B Trees Our model of main memory and the cost of CPU operations has been intentionally simplistic The major focus has been on determining

More information

18.3 Deleting a key from a B-tree

18.3 Deleting a key from a B-tree 18.3 Deleting a key from a B-tree B-TREE-DELETE deletes the key from the subtree rooted at We design it to guarantee that whenever it calls itself recursively on a node, the number of keys in is at least

More information

On The Complexity of Virtual Topology Design for Multicasting in WDM Trees with Tap-and-Continue and Multicast-Capable Switches

On The Complexity of Virtual Topology Design for Multicasting in WDM Trees with Tap-and-Continue and Multicast-Capable Switches On The Complexity of Virtual Topology Design for Multicasting in WDM Trees with Tap-and-Continue and Multicast-Capable Switches E. Miller R. Libeskind-Hadas D. Barnard W. Chang K. Dresner W. M. Turner

More information

We assume uniform hashing (UH):

We assume uniform hashing (UH): We assume uniform hashing (UH): the probe sequence of each key is equally likely to be any of the! permutations of 0,1,, 1 UH generalizes the notion of SUH that produces not just a single number, but a

More information

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17 01.433/33 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/2/1.1 Introduction In this lecture we ll talk about a useful abstraction, priority queues, which are

More information

CONVERGECAST, namely, the collection of data from a set of

CONVERGECAST, namely, the collection of data from a set of 86 IEEE TRANSACTIONS ON MOBILE COMPUTING, VOL. 11, NO. 1, JANUARY 2012 Fast Data Collection in Tree-Based Wireless Sensor Networks Özlem Durmaz Incel, Amitabha Ghosh, Bhaskar Krishnamachari, and Krishnakant

More information

CSE 417 Branch & Bound (pt 4) Branch & Bound

CSE 417 Branch & Bound (pt 4) Branch & Bound CSE 417 Branch & Bound (pt 4) Branch & Bound Reminders > HW8 due today > HW9 will be posted tomorrow start early program will be slow, so debugging will be slow... Review of previous lectures > Complexity

More information

Design and Analysis of Algorithms

Design and Analysis of Algorithms CSE 101, Winter 018 D/Q Greed SP s DP LP, Flow B&B, Backtrack Metaheuristics P, NP Design and Analysis of Algorithms Lecture 8: Greed Class URL: http://vlsicad.ucsd.edu/courses/cse101-w18/ Optimization

More information

CMSC 341 Leftist Heaps

CMSC 341 Leftist Heaps CMSC 341 Leftist Heaps Based on slides from previous iterations of this course Today s Topics Review of Min Heaps Introduction of Left-ist Heaps Merge Operation Heap Operations Review of Heaps Min Binary

More information

Solving NP-hard Problems on Special Instances

Solving NP-hard Problems on Special Instances Solving NP-hard Problems on Special Instances Solve it in poly- time I can t You can assume the input is xxxxx No Problem, here is a poly-time algorithm 1 Solving NP-hard Problems on Special Instances

More information

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology Introduction Chapter 4 Trees for large input, even linear access time may be prohibitive we need data structures that exhibit average running times closer to O(log N) binary search tree 2 Terminology recursive

More information

void insert( Type const & ) void push_front( Type const & )

void insert( Type const & ) void push_front( Type const & ) 6.1 Binary Search Trees A binary search tree is a data structure that can be used for storing sorted data. We will begin by discussing an Abstract Sorted List or Sorted List ADT and then proceed to describe

More information

Chapter 5. Binary Trees

Chapter 5. Binary Trees Chapter 5 Binary Trees Definitions and Properties A binary tree is made up of a finite set of elements called nodes It consists of a root and two subtrees There is an edge from the root to its children

More information

Solutions to relevant spring 2000 exam problems

Solutions to relevant spring 2000 exam problems Problem 2, exam Here s Prim s algorithm, modified slightly to use C syntax. MSTPrim (G, w, r): Q = V[G]; for (each u Q) { key[u] = ; key[r] = 0; π[r] = 0; while (Q not empty) { u = ExtractMin (Q); for

More information

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures

More information

A set of nodes (or vertices) with a single starting point

A set of nodes (or vertices) with a single starting point Binary Search Trees Understand tree terminology Understand and implement tree traversals Define the binary search tree property Implement binary search trees Implement the TreeSort algorithm 2 A set of

More information

Delay Efficient Data Gathering in Sensor Networks

Delay Efficient Data Gathering in Sensor Networks Delay Efficient Data Gathering in Sensor Networks Xianjin Zhu, Bin Tang, and Himanshu Gupta Department of Computer Science, State University of New York at Stony Brook, Stony Brook, NY 11794 {xjzhu, bintang,

More information

binary tree empty root subtrees Node Children Edge Parent Ancestor Descendant Path Depth Height Level Leaf Node Internal Node Subtree

binary tree empty root subtrees Node Children Edge Parent Ancestor Descendant Path Depth Height Level Leaf Node Internal Node Subtree Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees called the left and right subtrees which are disjoint

More information

Approximation Algorithms

Approximation Algorithms Approximation Algorithms Given an NP-hard problem, what should be done? Theory says you're unlikely to find a poly-time algorithm. Must sacrifice one of three desired features. Solve problem to optimality.

More information

Fast Data Collection with Interference and Life Time in Tree Based Wireless Sensor Networks

Fast Data Collection with Interference and Life Time in Tree Based Wireless Sensor Networks Vol. 3, Issue. 5, Sep - Oct. 2013 pp-2667-2673 ISSN: 2249-6645 Fast Data Collection with Interference and Life Time in Tree Based Wireless Sensor Networks I. Shalini 1, B. Vamsee Mohan 2, T. Bharath Manohar

More information

ECE 250 Algorithms and Data Structures

ECE 250 Algorithms and Data Structures ECE 250 Algorithms and Data Structures Sections 001 and 002 FINAL EXAMINATION Douglas Wilhelm Harder dwharder@uwaterloo.ca EIT 4018 x37023 2014-04-16T09:00P2H30M Rooms: PAC 7, 8 If you are writing a supplemental

More information

Practice Problems for the Final

Practice Problems for the Final ECE-250 Algorithms and Data Structures (Winter 2012) Practice Problems for the Final Disclaimer: Please do keep in mind that this problem set does not reflect the exact topics or the fractions of each

More information

Introduction to Algorithms Third Edition

Introduction to Algorithms Third Edition Thomas H. Cormen Charles E. Leiserson Ronald L. Rivest Clifford Stein Introduction to Algorithms Third Edition The MIT Press Cambridge, Massachusetts London, England Preface xiü I Foundations Introduction

More information

Foundations of Computer Science Spring Mathematical Preliminaries

Foundations of Computer Science Spring Mathematical Preliminaries Foundations of Computer Science Spring 2017 Equivalence Relation, Recursive Definition, and Mathematical Induction Mathematical Preliminaries Mohammad Ashiqur Rahman Department of Computer Science College

More information

Questions from the material presented in this lecture

Questions from the material presented in this lecture Advanced Data Structures Questions from the material presented in this lecture January 8, 2015 This material illustrates the kind of exercises and questions you may get at the final colloqium. L1. Introduction.

More information

Search Trees. Undirected graph Directed graph Tree Binary search tree

Search Trees. Undirected graph Directed graph Tree Binary search tree Search Trees Undirected graph Directed graph Tree Binary search tree 1 Binary Search Tree Binary search key property: Let x be a node in a binary search tree. If y is a node in the left subtree of x, then

More information

Chapter 14 Scheduling Algorithms for Tree-Based Data Collection in Wireless Sensor Networks

Chapter 14 Scheduling Algorithms for Tree-Based Data Collection in Wireless Sensor Networks Chapter 14 Scheduling Algorithms for Tree-Based Data Collection in Wireless Sensor Networks Ozlem Durmaz Incel, Amitabha Ghosh, and Bhaskar Krishnamachari Abstract Data collection is a fundamental operation

More information

CS 6783 (Applied Algorithms) Lecture 5

CS 6783 (Applied Algorithms) Lecture 5 CS 6783 (Applied Algorithms) Lecture 5 Antonina Kolokolova January 19, 2012 1 Minimum Spanning Trees An undirected graph G is a pair (V, E); V is a set (of vertices or nodes); E is a set of (undirected)

More information

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I MCA 312: Design and Analysis of Algorithms [Part I : Medium Answer Type Questions] UNIT I 1) What is an Algorithm? What is the need to study Algorithms? 2) Define: a) Time Efficiency b) Space Efficiency

More information

Chapter 11: Graphs and Trees. March 23, 2008

Chapter 11: Graphs and Trees. March 23, 2008 Chapter 11: Graphs and Trees March 23, 2008 Outline 1 11.1 Graphs: An Introduction 2 11.2 Paths and Circuits 3 11.3 Matrix Representations of Graphs 4 11.5 Trees Graphs: Basic Definitions Informally, a

More information

implementing the breadth-first search algorithm implementing the depth-first search algorithm

implementing the breadth-first search algorithm implementing the depth-first search algorithm Graph Traversals 1 Graph Traversals representing graphs adjacency matrices and adjacency lists 2 Implementing the Breadth-First and Depth-First Search Algorithms implementing the breadth-first search algorithm

More information

Routing algorithms. Jan Lönnberg, 51101M. October 2, Based on G. Tel: Introduction to Distributed Algorithms, chapter 4.

Routing algorithms. Jan Lönnberg, 51101M. October 2, Based on G. Tel: Introduction to Distributed Algorithms, chapter 4. Routing algorithms Jan Lönnberg, 51101M October 2, 2002 Based on G. Tel: Introduction to Distributed Algorithms, chapter 4. 1 Contents Introduction Destination-based routing Floyd-Warshall (single processor)

More information

Energy-efficient routing algorithms for Wireless Sensor Networks

Energy-efficient routing algorithms for Wireless Sensor Networks Energy-efficient routing algorithms for Wireless Sensor Networks Chao Peng Graduate School of Information Science Japan Advanced Institute of Science and Technology March 8, 2007 Presentation Flow Introduction

More information

Analysis of Algorithms - Greedy algorithms -

Analysis of Algorithms - Greedy algorithms - Analysis of Algorithms - Greedy algorithms - Andreas Ermedahl MRTC (Mälardalens Real-Time Reseach Center) andreas.ermedahl@mdh.se Autumn 2003 Greedy Algorithms Another paradigm for designing algorithms

More information

Integer Programming ISE 418. Lecture 7. Dr. Ted Ralphs

Integer Programming ISE 418. Lecture 7. Dr. Ted Ralphs Integer Programming ISE 418 Lecture 7 Dr. Ted Ralphs ISE 418 Lecture 7 1 Reading for This Lecture Nemhauser and Wolsey Sections II.3.1, II.3.6, II.4.1, II.4.2, II.5.4 Wolsey Chapter 7 CCZ Chapter 1 Constraint

More information

Outline. Introduction. Outline. Introduction (Cont.) Introduction (Cont.)

Outline. Introduction. Outline. Introduction (Cont.) Introduction (Cont.) An Energy-Efficient Distributed Algorithm for Minimum-Latency Aggregation Scheduling in Wireless Sensor Networks Yingshu Li, Longjiang Guo, and Sushil K. Prasad Department of Computer Science, Georgia

More information

FINAL EXAM SOLUTIONS

FINAL EXAM SOLUTIONS COMP/MATH 3804 Design and Analysis of Algorithms I Fall 2015 FINAL EXAM SOLUTIONS Question 1 (12%). Modify Euclid s algorithm as follows. function Newclid(a,b) if a

More information

2-3 Tree. Outline B-TREE. catch(...){ printf( "Assignment::SolveProblem() AAAA!"); } ADD SLIDES ON DISJOINT SETS

2-3 Tree. Outline B-TREE. catch(...){ printf( Assignment::SolveProblem() AAAA!); } ADD SLIDES ON DISJOINT SETS Outline catch(...){ printf( "Assignment::SolveProblem() AAAA!"); } Balanced Search Trees 2-3 Trees 2-3-4 Trees Slide 4 Why care about advanced implementations? Same entries, different insertion sequence:

More information

Chapter 9 Graph Algorithms

Chapter 9 Graph Algorithms Chapter 9 Graph Algorithms 2 Introduction graph theory useful in practice represent many real-life problems can be slow if not careful with data structures 3 Definitions an undirected graph G = (V, E)

More information

Discrete mathematics II. - Graphs

Discrete mathematics II. - Graphs Emil Vatai April 25, 2018 Basic definitions Definition of an undirected graph Definition (Undirected graph) An undirected graph or (just) a graph is a triplet G = (ϕ, E, V ), where V is the set of vertices,

More information

11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions

11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions Introduction Chapter 9 Graph Algorithms graph theory useful in practice represent many real-life problems can be slow if not careful with data structures 2 Definitions an undirected graph G = (V, E) is

More information

Greedy Algorithms. Textbook reading. Chapter 4 Chapter 5. CSci 3110 Greedy Algorithms 1/63

Greedy Algorithms. Textbook reading. Chapter 4 Chapter 5. CSci 3110 Greedy Algorithms 1/63 CSci 3110 Greedy Algorithms 1/63 Greedy Algorithms Textbook reading Chapter 4 Chapter 5 CSci 3110 Greedy Algorithms 2/63 Overview Design principle: Make progress towards a solution based on local criteria

More information

Dual Power Management for Network Connectivity in Wireless Sensor Networks

Dual Power Management for Network Connectivity in Wireless Sensor Networks Dual Power Management for Network Connectivity in Wireless Sensor Networks Yanxia Rong, Hongsik Choi and Hyeong-Ah Choi Department of Computer Science George Washington University Washington DC Department

More information

CS599: Convex and Combinatorial Optimization Fall 2013 Lecture 14: Combinatorial Problems as Linear Programs I. Instructor: Shaddin Dughmi

CS599: Convex and Combinatorial Optimization Fall 2013 Lecture 14: Combinatorial Problems as Linear Programs I. Instructor: Shaddin Dughmi CS599: Convex and Combinatorial Optimization Fall 2013 Lecture 14: Combinatorial Problems as Linear Programs I Instructor: Shaddin Dughmi Announcements Posted solutions to HW1 Today: Combinatorial problems

More information

CS 161 Lecture 11 BFS, Dijkstra s algorithm Jessica Su (some parts copied from CLRS) 1 Review

CS 161 Lecture 11 BFS, Dijkstra s algorithm Jessica Su (some parts copied from CLRS) 1 Review 1 Review 1 Something I did not emphasize enough last time is that during the execution of depth-firstsearch, we construct depth-first-search trees. One graph may have multiple depth-firstsearch trees,

More information

Algorithms. Red-Black Trees

Algorithms. Red-Black Trees Algorithms Red-Black Trees Red-Black Trees Balanced binary search trees guarantee an O(log n) running time Red-black-tree Binary search tree with an additional attribute for its nodes: color which can

More information

Multi-channel TDMA Scheduling in Wireless Sensor Networks

Multi-channel TDMA Scheduling in Wireless Sensor Networks Multi-channel TDMA Scheduling in Wireless Sensor Networks Ozge Uyanik and Ibrahim Korpeoglu Bilkent University Department of Computer Engineering 06800, Ankara, Turkey {ouyanik,korpe}@cs.bilkent.edu.tr

More information

Lecture 13. Reading: Weiss, Ch. 9, Ch 8 CSE 100, UCSD: LEC 13. Page 1 of 29

Lecture 13. Reading: Weiss, Ch. 9, Ch 8 CSE 100, UCSD: LEC 13. Page 1 of 29 Lecture 13 Connectedness in graphs Spanning trees in graphs Finding a minimal spanning tree Time costs of graph problems and NP-completeness Finding a minimal spanning tree: Prim s and Kruskal s algorithms

More information

COMP : Trees. COMP20012 Trees 219

COMP : Trees. COMP20012 Trees 219 COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural

More information

Constraint Satisfaction Problems

Constraint Satisfaction Problems Constraint Satisfaction Problems CE417: Introduction to Artificial Intelligence Sharif University of Technology Spring 2013 Soleymani Course material: Artificial Intelligence: A Modern Approach, 3 rd Edition,

More information

Search and Optimization

Search and Optimization Search and Optimization Search, Optimization and Game-Playing The goal is to find one or more optimal or sub-optimal solutions in a given search space. We can either be interested in finding any one solution

More information

Huffman Coding. Version of October 13, Version of October 13, 2014 Huffman Coding 1 / 27

Huffman Coding. Version of October 13, Version of October 13, 2014 Huffman Coding 1 / 27 Huffman Coding Version of October 13, 2014 Version of October 13, 2014 Huffman Coding 1 / 27 Outline Outline Coding and Decoding The optimal source coding problem Huffman coding: A greedy algorithm Correctness

More information

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging.

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging. Priority Queue, Heap and Heap Sort In this time, we will study Priority queue, heap and heap sort. Heap is a data structure, which permits one to insert elements into a set and also to find the largest

More information

On 2-Subcolourings of Chordal Graphs

On 2-Subcolourings of Chordal Graphs On 2-Subcolourings of Chordal Graphs Juraj Stacho School of Computing Science, Simon Fraser University 8888 University Drive, Burnaby, B.C., Canada V5A 1S6 jstacho@cs.sfu.ca Abstract. A 2-subcolouring

More information

Solutions to Exam Data structures (X and NV)

Solutions to Exam Data structures (X and NV) Solutions to Exam Data structures X and NV 2005102. 1. a Insert the keys 9, 6, 2,, 97, 1 into a binary search tree BST. Draw the final tree. See Figure 1. b Add NIL nodes to the tree of 1a and color it

More information

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT... Steven J. Zeil July 11, 2013 Contents 1 Definition: Binary Search Trees 2 1.1 The Binary Search Tree ADT.................................................... 3 2 Implementing Binary Search Trees 7 2.1 Searching

More information

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages Priority Queues and Binary Heaps See Chapter 21 of the text, pages 807-839. A priority queue is a queue-like data structure that assumes data is comparable in some way (or at least has some field on which

More information

Diversity Coloring for Distributed Storage in Mobile Networks

Diversity Coloring for Distributed Storage in Mobile Networks Diversity Coloring for Distributed Storage in Mobile Networks Anxiao (Andrew) Jiang and Jehoshua Bruck California Institute of Technology Abstract: Storing multiple copies of files is crucial for ensuring

More information

February 24, :52 World Scientific Book - 9in x 6in soltys alg. Chapter 3. Greedy Algorithms

February 24, :52 World Scientific Book - 9in x 6in soltys alg. Chapter 3. Greedy Algorithms Chapter 3 Greedy Algorithms Greedy algorithms are algorithms prone to instant gratification. Without looking too far ahead, at each step they make a locally optimum choice, with the hope that it will lead

More information

Analysis of Algorithms

Analysis of Algorithms Analysis of Algorithms Concept Exam Code: 16 All questions are weighted equally. Assume worst case behavior and sufficiently large input sizes unless otherwise specified. Strong induction Consider this

More information

Lecture 8: The Traveling Salesman Problem

Lecture 8: The Traveling Salesman Problem Lecture 8: The Traveling Salesman Problem Let G = (V, E) be an undirected graph. A Hamiltonian cycle of G is a cycle that visits every vertex v V exactly once. Instead of Hamiltonian cycle, we sometimes

More information

Solution to CSE 250 Final Exam

Solution to CSE 250 Final Exam Solution to CSE 250 Final Exam Fall 2013 Time: 3 hours. December 13, 2013 Total points: 100 14 pages Please use the space provided for each question, and the back of the page if you need to. Please do

More information

An O (mlogn)-time Algorithm for the Maximal Planar Subgraph Problem

An O (mlogn)-time Algorithm for the Maximal Planar Subgraph Problem An O (mlogn)-time Algorithm for the Maximal Planar Subgraph Problem Jiazhen Cai 1 Courant Institute, NYU New York, NY 10012 Xiaofeng Han Department of Computer Science Princeton University Princeton, NJ

More information

Approximability Results for the p-center Problem

Approximability Results for the p-center Problem Approximability Results for the p-center Problem Stefan Buettcher Course Project Algorithm Design and Analysis Prof. Timothy Chan University of Waterloo, Spring 2004 The p-center

More information

Chapter 9 Graph Algorithms

Chapter 9 Graph Algorithms Introduction graph theory useful in practice represent many real-life problems can be if not careful with data structures Chapter 9 Graph s 2 Definitions Definitions an undirected graph is a finite set

More information

Λέων-Χαράλαμπος Σταματάρης

Λέων-Χαράλαμπος Σταματάρης Λέων-Χαράλαμπος Σταματάρης INTRODUCTION Two classical problems of information dissemination in computer networks: The broadcasting problem: Distributing a particular message from a distinguished source

More information

A generalization of Mader s theorem

A generalization of Mader s theorem A generalization of Mader s theorem Ajit A. Diwan Department of Computer Science and Engineering Indian Institute of Technology, Bombay Mumbai, 4000076, India. email: aad@cse.iitb.ac.in 18 June 2007 Abstract

More information

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree Chapter 4 Trees 2 Introduction for large input, even access time may be prohibitive we need data structures that exhibit running times closer to O(log N) binary search tree 3 Terminology recursive definition

More information

CMSC 341 Lecture 15 Leftist Heaps

CMSC 341 Lecture 15 Leftist Heaps Based on slides from previous iterations of this course CMSC 341 Lecture 15 Leftist Heaps Prof. John Park Review of Heaps Min Binary Heap A min binary heap is a Complete binary tree Neither child is smaller

More information

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example. Trees, Binary Search Trees, and Heaps CS 5301 Fall 2013 Jill Seaman Tree: non-recursive definition Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every node (except

More information

1 i n (p i + r n i ) (Note that by allowing i to be n, we handle the case where the rod is not cut at all.)

1 i n (p i + r n i ) (Note that by allowing i to be n, we handle the case where the rod is not cut at all.) Dynamic programming is a problem solving method that is applicable to many different types of problems. I think it is best learned by example, so we will mostly do examples today. 1 Rod cutting Suppose

More information

Exercises: Disjoint Sets/ Union-find [updated Feb. 3]

Exercises: Disjoint Sets/ Union-find [updated Feb. 3] Exercises: Disjoint Sets/ Union-find [updated Feb. 3] Questions 1) Suppose you have an implementation of union that is by-size and an implementation of find that does not use path compression. Give the

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees Computer Science 0 Data Structures Siena College Fall 08 Topic Notes: Trees We ve spent a lot of time looking at a variety of structures where there is a natural linear ordering of the elements in arrays,

More information

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages Priority Queues and Binary Heaps See Chapter 21 of the text, pages 807-839. A priority queue is a queue-like data structure that assumes data is comparable in some way (or at least has some field on which

More information

CPSC 536N: Randomized Algorithms Term 2. Lecture 10

CPSC 536N: Randomized Algorithms Term 2. Lecture 10 CPSC 536N: Randomized Algorithms 011-1 Term Prof. Nick Harvey Lecture 10 University of British Columbia In the first lecture we discussed the Max Cut problem, which is NP-complete, and we presented a very

More information

Connected Point Coverage in Wireless Sensor Networks using Robust Spanning Trees

Connected Point Coverage in Wireless Sensor Networks using Robust Spanning Trees Connected Point Coverage in Wireless Sensor Networks using Robust Spanning Trees Pouya Ostovari Department of Computer and Information Siences Temple University Philadelphia, Pennsylvania, USA Email: ostovari@temple.edu

More information

Binary Tree Node Relationships. Binary Trees. Quick Application: Expression Trees. Traversals

Binary Tree Node Relationships. Binary Trees. Quick Application: Expression Trees. Traversals Binary Trees 1 Binary Tree Node Relationships 2 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the

More information

Binary Trees. For example: Jargon: General Binary Trees. root node. level: internal node. edge. leaf node. Data Structures & File Management

Binary Trees. For example: Jargon: General Binary Trees. root node. level: internal node. edge. leaf node. Data Structures & File Management Binary Trees 1 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the root, which are disjoint from

More information