Ejemplo n.º 1
0
int dijkstra(const AdjList& graph, const vertex_t src, const vertex_t dst) {
	vector<uint32_t> minCostTo(graph.size(), numeric_limits<uint32_t>::max());

	priority_queue<Path> pq;
	pq.push(Path(src, 0));
	minCostTo[src] = 0;

	while (!pq.empty()) {
		Path p = pq.top();
		pq.pop();

		if (p.total > minCostTo[p.node]) {
			continue;
		}

		if (p.node == dst) {
			return p.total;
		}

		const vector<Edge>& edges = graph.edges(p.node);
		for (vector<Edge>::const_iterator eIt(edges.begin()), eItEnd(edges.end()); eIt != eItEnd; ++eIt) {
			const vertex_t tgt = eIt->dst;
			if (p.total + eIt->weight < minCostTo[tgt]) {
				minCostTo[tgt] = p.total + eIt->weight;
				pq.push(Path(tgt, minCostTo[tgt]));
			}
		}
	}

	return -1;
}
Ejemplo n.º 2
0
Archivo: main.cpp Proyecto: palmerc/lab
void dijkstra(AdjList &G, int start)
{
   VertexList V;
   list<int> S; // Discovered shortest paths
   list<int> Q; // Pool of unknown vertices
   
   V[start] = Vertex(0, 0, 1);
   S.push_back(start);
   for(AdjList::iterator i = G.begin(); i != G.end(); ++i)
      if (i->first != start)
      {
         V[i->first] = Vertex(INT_MAX, 0, 0);
         Q.push_back(i->first);
      }
   cout << "Shortest path discovered " << start << endl;
   while (!Q.empty())
   {
      int u = extract_min(G, V, S);
      cout << "Shortest path discovered " << u << endl;
      V[u].known = 1;
      S.push_back(u);
      Q.remove(u);
   }
   print_out(V);
}
Ejemplo n.º 3
0
int solve(const int src, const int dst, const int num, const AdjList& graph) {
	int visited[graph.getSz()];
	fill (visited, visited + graph.getSz(), 0);

	queue<int> q;
	q.push(src);
	visited[src] = numeric_limits<int>::max();

	// aim to maximise visited[dst]
	while (!q.empty()) {
		const int currNode = q.front();
		const int currScore = visited[currNode];
		q.pop();

		for (size_t i = 0; i < graph.getLinks(currNode).size(); ++i) {
			const int tgtNode = graph.getLinks(currNode)[i].dst;
			const int tgtScore = min(currScore, graph.getLinks(currNode)[i].weight);

			if (visited[tgtNode] < tgtScore) {
				visited[tgtNode] = tgtScore;
				q.push(tgtNode);
			}
		}
	}

	double f = num / (double)(visited[dst] - 1);
	return f == (int) f ? f : f + 1;
}
Ejemplo n.º 4
0
void floodFill(int i, int j, int color) {
  if((i < 0) || (j < 0) || (i > (int) adjList.size()) || (j > (int) (adjList[i]).size()) || ((visited[i])[j]) || (color != 2)) {
    if(color == 3 && !((visited[i])[j])) {
      area++;
      //std::cout << "calling flood fillx " << i << " , " << j << std::endl;
      floodFill3(i, j, 3);
    } else {
      return;
    }
  }

  ((visited[i])[j]) = true;
  if(((i - 1) >= 0) && (j >= 0) && ((i - 1) < (int) adjList.size()) && (j < (int) (adjList[i]).size())) {
    floodFill(i - 1, j, ((adjList[i - 1])[j]).second);
  }

  if(((i + 1) >= 0) && (j >= 0) && ((i + 1) < (int) adjList.size()) && (j < (int) (adjList[i]).size())) {
    floodFill(i + 1, j, ((adjList[i + 1])[j]).second);
  }

  if((i >= 0) && ((j - 1) >= 0) && (i < (int) adjList.size()) && ((j - 1) < (int) (adjList[i]).size())) {
    floodFill(i, j - 1, ((adjList[i])[j - 1]).second);
  }

  if((i >= 0) && ((j + 1) >= 0) && (i < (int) adjList.size()) && ((j + 1) < (int) (adjList[i]).size())) {
    floodFill(i, j + 1, ((adjList[i])[j + 1]).second);
  }
}
Ejemplo n.º 5
0
void AlienDictionary::topologicalSort() {
    //and perform topological sort
    vector<VisitType> visited(adjList.size(), UNVISITED);

    for (int i=0;i<adjList.size(); i++) {
        if (visited[i] == PERM) continue;
        dfs(i, visited);
    }
}
Ejemplo n.º 6
0
void print_AdjList(AdjList &adj_list) {
        for(AdjList::iterator it = adj_list.begin(); it != adj_list.end(); ++it) {
                vector<int> exist_list = it->second;
                cout << " " << it->first << " -> ";
                for(int i = 0; i < exist_list.size(); i++) {
                        cout << " " << exist_list[i] << ",";
                }
                cout << endl;
        }
}
Ejemplo n.º 7
0
int solve(const AdjList& graph) {
	if (graph.getSize() == 1) {
		return 1;
	}

	AdjList sTree(graph.getSize());
	dfs(graph, 0, CreateSpanningTree(sTree));

	map<pair<vertex_t, bool>, int> eval;
	return min(vertex_cover(sTree, 0, true, eval), vertex_cover(sTree, 0, false, eval));
}
Ejemplo n.º 8
0
int main( int argc, char ** argv ) {
    AdjList G;
    G.read(argv[1]);
    int lowest = 10000;
    int tmp = 10000;
    for(int i = 0; i < 10000; i++ ) {
	tmp = G.run_karger();
	if( tmp < lowest ) { lowest = tmp; };
    };
    cout << "result " << lowest << endl;
};
void augmentPath(AdjList& graph, const vertex_t sink,
		const vector<uint32_t>& parent, uint32_t flow) {
	vertex_t curr = sink;

	while (parent[curr] != curr) {
		Edge* e = graph.getEdge(parent[curr], curr);
		assert(e);
		e->weight -= flow;

		e = graph.getEdge(curr, parent[curr]);
		assert(e);
		e->weight += flow;

		curr = parent[curr];
	}
}
uint32_t bfs(const AdjList& graph, const vertex_t src, const vertex_t dst,
		vector<uint32_t>& parent) {
	fill(parent.begin(), parent.end(), numeric_limits<uint32_t>::max());
	queue<pair<vertex_t, uint32_t> > q;
	parent[src] = src;
	q.push(make_pair(src, INFINITY));

	while (!q.empty()) {
		const pair<vertex_t, uint32_t> node = q.front();
		q.pop();

		if (node.first == dst) {
			return node.second;
		}

		const vector<Edge>& edges = graph.edges(node.first);
		for (vector<Edge>::const_iterator eIt(edges.begin()), eItEnd(edges.end()); eIt != eItEnd; ++eIt) {
			if (parent[eIt->dst] != numeric_limits<uint32_t>::max()) { // visited
				continue;
			}

			if (!eIt->weight) {
				continue;
			}
			assert(eIt->weight > 0);

			parent[eIt->dst] = node.first;
			q.push(make_pair(eIt->dst, min(node.second, eIt->weight)));
		}
	}

	return 0;
}
Ejemplo n.º 11
0
std::vector< std::pair<int, unsigned> >& AdjList::operator [](int i)
{
    return G[i];
}

std::istream& operator>> (std::istream& in, AdjList &list)
{
    int n, m;
    in >> n >> m;
    list.resize(n);
    Edge edge;
    for (int i = 0; i < m; ++i)
    {
        in >> edge;
        list.addEdge(edge, false);
    }
    return in;
}
// calculate flow on the graph
void edmonds_karp(AdjList& graph, const vertex_t source, const vertex_t sink) {
	vector<uint32_t> parent(graph.size());
	while (true) {
		uint32_t augment = bfs(graph, source, sink, parent);
		if (!augment) {
			break;
		}

		augmentPath(graph, sink, parent, augment);
	}
}
Ejemplo n.º 13
0
void dfs(const AdjList& graph, vertex_t root, T func) {
	vector<int> isVisited(graph.getSize());
	stack<int> s;
	s.push(root);
	isVisited[root] = true;

	while (!s.empty()) {
		vertex_t curr = s.top();
		s.pop();

		const vector<int>& links = graph.getLinks(curr);
		for (size_t i = 0; i < links.size(); ++i) {
			vertex_t next = links[i];
			if (!isVisited[next]) {
				isVisited[next] = true;
				s.push(next);
				func.visitNode(curr, next);
			}
		}
	}
}
Ejemplo n.º 14
0
int main() {
	int nEmployees;

	while (cin >> nEmployees) {
		if (!nEmployees) break;

		string bigBoss;
		cin >> bigBoss;

		AdjList graph;
		string name, boss;
		for (int i = 1; i < nEmployees; ++i) {
			cin >> name >> boss;
			graph.link(boss, name);
		}

		cache.clear();
		pair<int, bool> result = countMaxIndepSet(bigBoss, true, graph);
		cout << result.first << " " << (result.second ? "Yes" : "No") << endl;
	}
	return 0;
}
Ejemplo n.º 15
0
pair<int, bool> countMaxIndepSet(const string& root, bool canSelect, const AdjList& graph) {
	if (!graph.hasLinked(root)) {
		return canSelect ? make_pair(1, true) : make_pair(0, true);
	}

	map<pair<string, bool>, pair<int, bool> >::const_iterator it = cache.find(make_pair(root, canSelect));
	if (it != cache.end()) {
		return it->second;
	}

	pair<int, bool> resultWithout = make_pair(0, true);
	// assume not selected
	for (int i = 0; i < (int)graph.getLinked(root).size(); ++i) {
		pair<int, bool> c = countMaxIndepSet(graph.getLinked(root)[i], true, graph);
		resultWithout.first += c.first;
		resultWithout.second &= c.second;
	}

	pair<int, bool> resultWith = make_pair(0, true);
	if (canSelect) {
		++resultWith.first;
		for (int i = 0; i < (int)graph.getLinked(root).size(); ++i) {
			pair<int, bool> c = countMaxIndepSet(graph.getLinked(root)[i], false, graph);
			resultWith.first += c.first;
			resultWith.second &= c.second;
		}
	}

	if (resultWithout.first > resultWith.first) {
		return cache[make_pair(root, canSelect)] = resultWithout;
	}
	else if (resultWithout.first < resultWith.first) {
		return cache[make_pair(root, canSelect)] = resultWith;
	}
	else { // same
		return cache[make_pair(root, canSelect)] = make_pair(resultWith.first, false);
	}
}
Ejemplo n.º 16
0
int get_DAG(AdjList &adj_list, TaskDAG &dag, string clientid) {
        InDegree indegree;
        for(AdjList::iterator it = adj_list.begin(); it != adj_list.end(); ++it) {
                vector<int> exist_list = it->second;
                int source_vertex = it->first;
                if(indegree.find(source_vertex) == indegree.end()) {
                        indegree[source_vertex] = 0;
                }

                stringstream adj_ss;
                for(int i = 0; i < exist_list.size(); i++) {
                        int dest_vertex = exist_list[i];

                        // add each vertex to string
                        adj_ss << exist_list[i] << clientid << "\'";

                        // update indegree count of each vertex in adjacency list
                        if(indegree.find(dest_vertex) == indegree.end()) {
                                indegree[dest_vertex] = 1;
                        }
                        else {
                                indegree[dest_vertex] = indegree[dest_vertex] + 1;
                        }
			if(dag.find(dest_vertex) != dag.end()) {
                                TaskDAG_Value &value = dag[dest_vertex];
                                value.first = indegree[dest_vertex];
                        }
                }
                adj_ss << "\"";
                string adjliststring(adj_ss.str()); // list of vertices delimited by \' with a final \"

                // store info into DAG
                TaskDAG_Value value(indegree[source_vertex], adjliststring);
                dag[source_vertex] = value;
        }

        return indegree.size();
}
uint32_t findMinCut(const AdjList& graph, const vertex_t src, const vertex_t sink) {
	// dfs from the src, find uncrossable edges
	stack<vertex_t> s;
	vector<bool> isVisited(graph.size(), false);
	s.push(src);
	isVisited[src] = true;

	set<pair<vertex_t, vertex_t> > vedges;
	while (!s.empty()) {
		const vertex_t curr = s.top(); s.pop();
		const vector<Edge>& edges = graph.edges(curr);
		for (vector<Edge>::const_iterator it(edges.begin()), itEnd(edges.end()); it != itEnd; ++it) {
			if (!it->weight) {
				vedges.insert(make_pair(curr < it->dst ? curr : it->dst,
						curr < it->dst ? it->dst : curr));
				continue;
			}

			if (isVisited[it->dst]) {
				continue;
			}
			isVisited[it->dst] = true;
			s.push(it->dst);
		}
	}

	uint32_t r = 0;
	for (set<pair<vertex_t, vertex_t> >::const_iterator it(vedges.begin()), itEnd(vedges.end());
			it != itEnd;
			++it) {
		if (isVisited[it->first] + isVisited[it->second] == 1 &&
				(it->second == src || it->second == sink)) { // check to not process back edges
			++r;
		}
	}

	return r;
}
Ejemplo n.º 18
0
void AlienDictionary::addDependency(char from, char to) {
    auto fit = charToNode.find(from);
    if (fit == charToNode.end()) { 
        charToNode.insert(make_pair(from, nodeCtr)); 
        nodeToChar.insert(make_pair(nodeCtr, from));
        nodeCtr++;
        adjList.push_back(Bucket());
    }

    auto tit = charToNode.find(to);
    if (tit == charToNode.end()) {
        charToNode.insert(make_pair(to, nodeCtr));
        nodeToChar.insert(make_pair(nodeCtr, to));
        nodeCtr++;
        adjList.push_back(Bucket());
    }

    if (from == to) return;

    if (adjList[charToNode[from]].find(charToNode[to]) != adjList[charToNode[from]].end()) return;

    adjList[charToNode[from]].insert(charToNode[to]);
}
Ejemplo n.º 19
0
int main()
{
	printf("SHIPPING ROUTES OUTPUT\n");
	int ds, m, n, p, arr[26][26] = {-1};
	cin >> ds;
	int tot = ds;
	while (ds > 0) {
		ds--;
		adjlist.empty();

		printf("DATA SET %d\n", tot - ds);
		cin >> m >> n >>p;
		
		string wh;
		for (int i = 0; i < m; ++i) {
			cin >> wh;
			arr[wh[0] - 'A'][wh[1] - 'B'] = i;
		}

		string legL, legR;
		int index;
		for (int j = 0; j < n; ++j) {
			cin >> legL >> legR;
			//index = arr[legL[0] - 'A'][legL[1] - 'A'];
			adjlist[arr[legL[0] - 'A'][legL[1] - 'A']].push_back(make_pair(arr[legR[0] - 'A'][legR[1] - 'A'], 0));
			adjlist[arr[legR[0] - 'A'][legR[1] - 'A']].push_back(make_pair(arr[legL[0] - 'A'][legL[1] - 'A'], 0));
		}

		int size;
		string qa, qb;
		for (int k = 0; k < p; ++k) {
			cin >> size >> qa >> qb;

			int res = Legs(arr[qa[0] - 'A'][qa[1] - 'A'], arr[qb[0] - 'A'][qb[1] - 'A']);
			if (res >= 0)
				cout << "$" << (size * res * 100) << endl;
			else cout << "NO SHIPMENT POSSIBLE" << endl;
		}
	}

	cout << "END OF OUTPUT";
	cin.get();
	return 0;
}
Ejemplo n.º 20
0
int vertex_cover(const AdjList& graph, vertex_t root, bool include, map<pair<vertex_t, bool>, int>& eval) {
	map<pair<vertex_t, bool>, int>::const_iterator it = eval.find(make_pair(root, include));
	if (it != eval.end()) {
		return it->second;
	}

	const vector<int>& links = graph.getLinks(root);
	int s;
	if (!include) { // have to include child
		s = 0;
		for (size_t i = 0; i < links.size(); ++i) {
			s += vertex_cover(graph, links[i], true, eval);
		}
	}
	else { // may or may not include child
		s = 1;
		for (size_t i = 0; i < links.size(); ++i) {
			s += min(vertex_cover(graph, links[i], true, eval), vertex_cover(graph, links[i], false, eval));
		}
	}

	return eval[make_pair(root, include)] = s;
}
Ejemplo n.º 21
0
Archivo: main.cpp Proyecto: palmerc/lab
int main(int argc, char* argv[])
{
   ifstream in;
   in.open(argv[1]);
   boost::regex re_start("^\\s*s\\s+(\\d+)\\s*$", boost::regex::perl);
   boost::regex re_vertex("^\\s*v\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*$", boost::regex::perl);
   boost::cmatch matches;
   AdjList G;
   int start;
   string str;

   getline(in, str);
   while ( in )
   {
      if (boost::regex_match(str.c_str(), matches, re_start))
         start = boost::lexical_cast<int>(matches[1]);
      else if (boost::regex_match(str.c_str(), matches, re_vertex))
      {
         int vertex = boost::lexical_cast<int>(matches[1]);
         int node = boost::lexical_cast<int>(matches[2]);
         int weight = boost::lexical_cast<int>(matches[3]);
         // if node doesn't exist, create a linked list and attach the next item
         if (G.find(vertex) == G.end()) // key doesn't exist
            G[vertex] = new list<AdjNode>;
         // if it does exist just add the next item and distance to the appropriate node
         G[vertex]->push_back(AdjNode(node, weight));
      }
      getline(in, str);
   }
   in.close();

   dijkstra(G, start);
   cout << "Loops " << loop << endl;
   for (AdjList::iterator i = G.begin(); i != G.end() ; ++i)
      delete i->second;
   G.clear();

   return 0;
}
Ejemplo n.º 22
0
int main(int argc, char *argv[]) {


  std::string input;
  int width;
  int height;
  int row = 0;
  int attempt = 0;

  while(std::getline(std::cin, input)) {
    char c = input.at(0);
    if(c == '.' || c == 'X' || c == '*') {
      ++row;
      neighbors.clear();
      for(int pos = 0; pos < (int) input.length(); ++pos) {
        VertexWeight vertexWeight;
        vertexWeight.first = pos;
        char temp = input.at(pos);
        if(temp == '.') {
          vertexWeight.second = 1;
        } else if(temp == '*') {
          vertexWeight.second = 2;
        } else {
          vertexWeight.second = 3;
        }
        neighbors.push_back(vertexWeight);
      }
      adjList.push_back(neighbors);
      if(height == row) {
        visited.clear();
        for(int index = 0; index < height; ++index) {
          visited.push_back(std::vector<bool>(width, false));
        }
        for(int i = 0; i < height; ++i) {
          for(int j = 0; j < width; ++j) {
            if((visited[i])[j] == false && ((adjList[i])[j]).second != 1) {
              area = 0;
              floodFill(i, j, ((adjList[i])[j]).second);
              if(area)
              areas.push_back(area);
            }
          }
        }

        std::cout << "Throw " << ++attempt << std::endl;
        std::sort(areas.begin(), areas.end());
        int numAreas = (int)areas.size() - 1;
        for(std::vector<int>::iterator it = areas.begin(); it != areas.end(); ++it) {
          std::cout << *it;
          if(numAreas--) {
            std::cout << " ";
          }
        }
        std::cout << std::endl;
        std::cout << std::endl;
      }
    } else {
      row = 0;

      std::stringstream sbuf;
      sbuf << input;
      sbuf >> width >> height;

      adjList.clear();
      areas.clear();

      if(width == 0 && height == 0) {
        break;
      }
    }
  }
  return 0;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Correct usage is: ./inputTest <filepath>\n"); 
        return 0;
    }
    char* filename = argv[1];
    AdjMatrix adjM (filename);
    AdjList adjL (filename);

    int size = adjM.getSize();


    // Prints out the adjacency matrix (to check)
    printf("The adjancency matrix is:\n");
    for (int i=0; i < size; i++) {
        for (int j=0; j < size; j++) {
            if (adjM.edgeExists(i,j)){
                printf("1 ");
            }else{
                printf("0 ");
            }
        }
        printf("\n");
    }

    printf("\n");

    // Prints out the adjaceny list (to check)
    printf("The adjancency list is:\n");
    for (int i=0; i < size; i++) {
        printf("%d ", i);
        for (int j=0; j < size; j++) {
            if (adjL.edgeExists(i,j)) {
                printf("->%d", j);
            }
        }
        printf("\n");
    }

    int countl=0;
    int countm=0;
    for (int i=0; i<size; i++) {
        for (int j=0; j<size; j++) {
            bool m = adjM.edgeExists(i, j);
            bool l = adjL.edgeExists(i, j);
            assert(m==l);
            if (l) {
                countl++;
            }
            if (m) {
                countm++;
            }
        }
    }
    printf("final list count was: %d\n", countl);
    printf("final matrix count was: %d\n", countm);
    printf("success\n");

    return 0;

}
Ejemplo n.º 24
0
int main(int argc, char** argv) {
    AdjList *al = new AdjList;
    cout << "Adding Vertices 1,2,3,4,5,6\n";
    al->addVertex("1");
    al->addVertex("2");
    al->addVertex("3");
    al->addVertex("4");
    al->addVertex("5");
    al->addVertex("6");
    cout << "\nAdding duplicate vertex:\n";
    al->addVertex("1");
    
    cout << "\nAdding valid edges 1->2,1->3,2->4,2->5,3->2,3->5,5->4,4->6,5->6\n";
    al->addEdge("1","2");
    al->addEdge("1","3");
    al->addEdge("2","4");
    al->addEdge("2","5");
    al->addEdge("3","2");
    al->addEdge("3","5");
    al->addEdge("5","4");
    al->addEdge("4","6");
    al->addEdge("5","6");
    cout << "\nAdding invalid edges:\n";
    al->addEdge("1","A");
    al->addEdge("A","4");
    
    cout << "\nPrinting Graph:\n";
    al->printGraph();
    
    cout << "\nTraversing Graph in BFS from valid source:\n";
    al->traverseBFS("1");
    
    cout << "\nTraversing Graph in BFS from invalid source:\n";
    al->traverseBFS("A");
    
    cout << "\nTraversing Graph in DFS:\n";
    al->traverseDFS();
    
    if(al->isDAG()){
        cout << "Graph is a DAG\n";
    }else{
        cout << "Graph is NOT a DAG\n";
    }
    
    cout << "\nMaking a copy graph\n";
    AdjList *copy = al->copyGraph();
    
    cout << "\nDeleting valid vertex 2 from original\n";
    al->deleteVertex("2");
    
    cout << "\nDeleting invalid vertex from original:\n";
    al->deleteVertex("2");
    
    cout << "\nPrinting Copied Graph:\n";
    copy->printGraph();
    
    cout << "\nPrinting Original Graph:\n";
    al->printGraph();
    
    cout << "\nTraversing Original Graph in BFS from valid source:\n";
    al->traverseBFS("1");
    
    cout << "\nTraversing Original Graph in BFS from invalid source:\n";
    al->traverseBFS("2");
    
    cout << "\nTraversing Original Graph in DFS:\n";
    al->traverseDFS();
    
    cout << "\nDeleting valid edge 4->6 from Original Graph\n";
    al->deleteEdge("4","6");
    
    cout << "\nDeleting invalid edge 4->6 from Original Graph\n";
    al->deleteEdge("4","6");
    cout << "\nDeleting invalid edge 1->2 from Original Graph\n";
    al->deleteEdge("1","2");
    
    cout << "\nPrinting Original Graph:\n";
    al->printGraph();
    
    cout << "\nPrinting Copied Graph:\n";
    copy->printGraph();
    
    cout << "\nTraversing Copied Graph in BFS from valid source:\n";
    copy->traverseBFS("1");
    
    cout << "\nTraversing Copied Graph in DFS:\n";
    copy->traverseDFS();
    
    cout << "\nDeleting Vertices from original graph:\n";
    al->deleteVertices();
    
    cout << "\nAdding Vertices and edges to form cycle to original graph:\n";
    al->addVertex("1");
    al->addVertex("2");
    al->addEdge("1","2");
    al->addEdge("2","1");
    
    cout << "\nPrinting original Graph:\n";
    al->printGraph();
    
    cout << "\nTraversing Original Graph in BFS from valid source:\n";
    al->traverseBFS("1");
    
    cout << "\nTraversing Original Graph in BFS from invalid source:\n";
    al->traverseBFS("3");
    
    cout << "\nTraversing Original Graph in DFS:\n";
    al->traverseDFS();
    
    if(al->isDAG()){
        cout << "Original Graph is a DAG\n";
    }else{
        cout << "Original Graph is NOT a DAG\n";
    }
    
    cout << "\nPrinting Copied Graph:\n";
    copy->printGraph();
    
    if(copy->isDAG()){
        cout << "Copied Graph is a DAG\n";
    }else{
        cout << "Copied Graph is NOT a DAG\n";
    }
    
    cout << endl;
    
    delete al;
    delete copy;
    
    return 0;
}
Ejemplo n.º 25
0
void get_adjlist(int num_tasks, AdjList &adj_list, int DAG_choice) {

	#define MAX_CHILDREN 100

	if(DAG_choice == 0) { // bag of tasks
		for (int i = 0; i < num_tasks; i++) { // New nodes of 'higher' rank than all nodes generated till now
                	// Edges from old nodes ('nodes') to new ones ('new_nodes')
	                vector<int> new_list;
        	        adj_list.insert(make_pair(i, new_list));
        	}
	}

	else if(DAG_choice == 1) { // random DAG
		#define MIN_PER_RANK 1 // Nodes/Rank: How 'fat' the DAG should be
        	#define MAX_PER_RANK 5
	        #define MIN_RANKS 3    // Ranks: How 'tall' the DAG should be
        	#define MAX_RANKS 5
	        #define PERCENT 30     // Chance of having an Edge

        	srand (time (NULL));
	        int height = floor(sqrt(num_tasks));    //height = MIN_RANKS + (rand () % (MAX_RANKS - MIN_RANKS + 1));
        	int new_nodes = ceil(sqrt(num_tasks));  //new_nodes = MIN_PER_RANK + (rand () % (MAX_PER_RANK - MIN_PER_RANK + 1));
	        int nodes = 0;

        	for (int i = 0; i < height; i++) { // New nodes of 'higher' rank than all nodes generated till now
                	// Edges from old nodes ('nodes') to new ones ('new_nodes')
	                for (int j = 0; j < nodes; j++) {
        	                for (int k = 0; k < new_nodes; k++) {
                	                if ( (rand () % 100) < PERCENT) {
                        	                if(adj_list.find(j) == adj_list.end()) {
                                	                vector<int> new_list;
                                        	        new_list.push_back(k + nodes);
                                                	adj_list.insert(make_pair(j, new_list));
	                                        }
        	                                else {
                	                                vector<int> &exist_list = adj_list[j];
							if(exist_list.size() < MAX_CHILDREN)
	                        	                        exist_list.push_back(k + nodes);
                                	        }
                                        	if(adj_list.find(k + nodes) == adj_list.end()) {
	                                               	adj_list.insert(make_pair(k + nodes, vector<int>()));
	                                        }
        	                        }
                	        }
                	}
	                nodes += new_nodes; // Accumulate into old node set
        	}
	}

	else if(DAG_choice == 2) { // pipeline DAG
		int nodes = 0;
        	int num_pipeline = floor(sqrt(num_tasks));
	        int pipeline_height = ceil(sqrt(num_tasks));

        	for (int i = 0; i < num_pipeline; i++) {
                	for (int j = 0; j < pipeline_height; j++) { // New nodes of 'higher' rank than all nodes generated till now
	                // Edges from old nodes ('nodes') to new ones ('new_nodes')
        	                if(adj_list.find(nodes) == adj_list.end()) {
                	                vector<int> new_list;
                        	        new_list.push_back(nodes+1);
                                	adj_list.insert(make_pair(nodes, new_list));
	                        }
        	                else {
                	                vector<int> &exist_list = adj_list[nodes];
                        	        exist_list.push_back(nodes+1);
	                        }
        	                if(adj_list.find(nodes+1) == adj_list.end()) {
                	                adj_list.insert(make_pair(nodes+1, vector<int>()));
                        	}
	                        nodes++; // Accumulate into old node set
        	        }
                	nodes++;
        	}
	}

	else if(DAG_choice == 3) { // fan in DAG
	        AdjList adj_list1;
	        adj_list1.insert(make_pair(0, vector<int>()));
	        int index = 0; int count = pow(MAX_CHILDREN, 0);
        	int num_level = floor(log(num_tasks)/log(MAX_CHILDREN));
	        int j = 0; int num = 1;
	        while(j <= num_level) {
                	while(index < count) {
        	                vector<int> &exist_list = adj_list1[index];
	                        for (int i = num; i < num+MAX_CHILDREN; i++) {
                                	exist_list.push_back(i);
                        	        if(adj_list1.find(i) == adj_list1.end()) {
                	                        adj_list1.insert(make_pair(i, vector<int>()));
        	                        }
	                                if(i >= num_tasks) {
                                	        index = count; j = num_level+1; break;
                        	        }
                	        } num += MAX_CHILDREN;
        	                index++;
	                }
                	count += pow(MAX_CHILDREN, ++j);
        	}

		for(AdjList::iterator it = adj_list1.begin(); it != adj_list1.end(); ++it) {
        	        int vertex = it->first;
	                if(adj_list.find(vertex) == adj_list.end()) {
                        	adj_list.insert(make_pair(vertex, vector<int>()));
                	}
        	        vector<int> &alist = it->second; int alist_size = alist.size();
	                for(int i = 0; i < alist_size; i++) {
                        	int v = alist[i];
                	        if(adj_list.find(v) == adj_list.end()) {
        	                        adj_list.insert(make_pair(v, vector<int>()));
	                        }
	                        vector<int> &exist_list = adj_list[v]; exist_list.push_back(vertex);
                	}
        	}
	}

	else if(DAG_choice == 4) { // fan out DAG
	        adj_list.insert(make_pair(0, vector<int>()));
        	int index = 0; int count = pow(MAX_CHILDREN, 0);
	        int num_level = floor(log(num_tasks)/log(MAX_CHILDREN));
        	int j = 0; int num = 1;
	        while(j <= num_level) {
        	        while(index < count) {
                	        vector<int> &exist_list = adj_list[index];
                        	for (int i = num; i < num+MAX_CHILDREN; i++) {
                                	exist_list.push_back(i);
	                                if(adj_list.find(i) == adj_list.end()) {
        	                                adj_list.insert(make_pair(i, vector<int>()));
                	                }
                        	        if(i >= num_tasks)
                                	        return;
	                        } num += MAX_CHILDREN;
        	                index++;
                	}
        	        count += pow(MAX_CHILDREN, ++j);
	        }
	}

	else {
		cout << "Enter proper choice for DAG" << endl;
		exit(1);
	}
}