#include <iostream>
#include <fstream>
#include <functional>
#include <climits>
#include <vector>
#include <queue>
#include <list>
using namespace std;
struct Vertices {
int vertex;
int weight;
Vertices(int v, int w) : vertex(v), weight(w) { };
Vertices() { }
};
class CompareGreater {
public:
bool const operator()(Vertices &nodeX, Vertices &nodeY) {
return (nodeX.weight > nodeY.weight) ;
}
};
vector< list<Vertices> > adj;
vector<int> weights;
priority_queue<Vertices, vector<Vertices>, CompareGreater> Q;
int nrVertices, nrEdges;
void Dijkstra(Vertices);
void makeGraph() {
ifstream myFile;
myFile.open("graph.txt");
myFile >> nrVertices >> nrEdges;
adj.resize(nrVertices+1);
int nodeX, nodeY, weight;
for (int i = 1; i <= nrVertices; ++i) {
weights.push_back(INT_MAX);
}
for (int i = 1; i <= nrEdges; ++i) {
myFile >> nodeX >> nodeY >> weight;
adj[nodeX].push_back(Vertices(nodeY, weight));
}
}
void printPath()
{
for (vector<int>::iterator itr = weights.begin()+1; itr != weights.end(); ++itr) {
cout << (*itr) << " "<<endl;
}
}
void Dijkstra(Vertices startNode) {
Vertices currVertex;
weights[startNode.vertex] = 0;
Q.push(startNode);
while (!Q.empty()) {
currVertex = Q.top();
Q.pop();
cout<<"Removed "<<&currVertex<<"from heap"<<endl;
if (currVertex.weight <= weights[currVertex.vertex]) {
for (list<Vertices>::iterator it = adj[currVertex.vertex].begin(); it != adj[currVertex.vertex].end(); ++it)
{
if (weights[it->vertex] > weights[currVertex.vertex] + it->weight) {
weights[it->vertex] = weights[currVertex.vertex] + it->weight;
Q.push(Vertices((it->vertex), weights[it->vertex]));
}
}
}
}
}
int main() {
makeGraph();
Dijkstra(Vertices(1, 0));
printPath();
return 0;
}
So this is my code to implement Dijkstra's algorithm with an adjacency list. With input:
7
2
2 2
4 1
2
4 3
5 10
2
1 4
6 5
4
3 2
5 2
6 8
7 4
1
7 6
0
1
6 1
This means that there exists 7 vertices in order from vertex 1 to 7. Vertex 1 has 2 edges, one to vertex 2 with weight 2, the second to vertex 4 with weight 1. Vertex 2 has 2 edges, the first to vertex 4 with weight 3, the second to vertex 5 with weight 10. Vertex 3 has 2 edges, the first to vertex 1 with weight 4, the second to vertex 6 with weight 5. And so forth.
However, it print out this:
Removed 0xbfb9d7a8from heap
Removed 0xbfb9d7a8from heap
0
4
2147483647
2147483647
2147483647
2147483647
When I need it to print out this:
V1: V2, 2; V4, 1
V2: v4, 3; V5, 10
V3: V1, 4; V6, 5
V4: V3, 2; V5, 2; V6, 8; V7, 4
V5: V7, 6
V6:
V7: V6, 1
Removed minimum 1 from heap
Print heap: V2, d=inf V4., d=inf v3, d= inf v7, d=inf v5......
Please help!!!!!
Related
In this problem, we will say that a permutation is cool is it does not have two adjacent consecutive numbers. Given n, print all the cool permutations of {0, …, n − 1}.
Input
input consists of several cases, each with an n between 1 and 9.
Output
For every case, print in lexicographical order all the cool permutations of {0, …, n − 1}.
I know how to solve the problem that prints all the permutations of { 1, …, n-1 } in lexicographical order. But I do not know how to generate the permutations without two adjacent consecutive numbers.
#include <iostream>
#include <vector>
using namespace std;
void write(const vector<int>& v) {
int s = v.size()-1;
for (int i = 0; i < s; ++i) cout << v[i] << ' ';
cout << v[s] << endl;
}
void generate(vector<int>& v, vector<bool>& u, int i, int n) {
if (i == n) write(v);
else {
for (int s = 1; s <= n; ++s) {
if (not u[s]) {
v[i] = s;
u[s] = true;
generate(v, u, i+1, n);
u[s] = false;
}
}
}
}
int main() {
int n;
while (cin >> n) {
vector<int> v(n);
vector<bool> u(n, false);
generate(v, u, 0, n-1);
cout << endl;
}
}
With this input:
1
2
3
4
5
I expect this output:
0
1 3 0 2
2 0 3 1
0 2 4 1 3
0 3 1 4 2
1 3 0 2 4
1 3 0 4 2
1 4 2 0 3
2 0 3 1 4
2 0 4 1 3
2 4 0 3 1
2 4 1 3 0
3 0 2 4 1
3 1 4 0 2
3 1 4 2 0
4 1 3 0 2
4 2 0 3 1
Thanks in advance!
An inefficient way of generating cool permutations, would be to first generate all permutations, and then to create a method that takes the vector v (who stores a candidate permutation), and evaluate whether this permutation is cool or not. If yes, print, if no, skip it, as #YSC suggested.
Example:
bool isCool(const vector<int>& v)
{
// special case, v.size==2
if(v.size() == 2) {
if(v[0] == v[1] + 1 || v[0] == v[1] - 1) {
return false;
} else {
return true;
}
}
// start from second element to pre-last
// and check if prev and next are adjacent to it
for(size_t i = 1; i < v.size() - 1; ++i) {
if(v[i] == v[i - 1] + 1 || v[i] == v[i - 1] - 1 ||
v[i] == v[i + 1] + 1 || v[i] == v[i + 1] - 1)
return false;
}
return true;
}
and then you would use it like in your generate method:
if (i == n && isCool(v)) write(v);
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
bool ConsecValues(int x, int y)
{
return abs(x - y) == 1;
}
bool HasConsecAdjValues(const vector<int>& v)
{
vector<int>::const_iterator cIter = adjacent_find(v.cbegin(), v.cend(),
ConsecValues);
return cIter != v.end();
}
vector<vector<int>> GetCoolPerms(int n)
{
vector<vector<int>> result;
vector<int> v(n);
iota(v.begin(), v.end(), 0);
do {
if (!HasConsecAdjValues(v))
result.push_back(v);
} while (std::next_permutation(v.begin(), v.end()));
return result;
}
void PrintPerm(const vector<int>& v)
{
for (const auto& num : v)
cout << num;
cout << endl;
}
int main()
{
vector<vector<int>> coolPerms = GetCoolPerms(5);
for (const auto& perm : coolPerms)
PrintPerm(perm);
getchar();
}
I tried to implement this algorithm but there's some logical error. The algorithm is given below.
DFS(G)
1. for each vertex u ∈ G.V
2. u.color = WHITE
3. u.pi = NIL
4. time = 0
5. for each vertex u ∈ G.V
6. if u.color == WHITE
7. DFS-VISIT(G,u)
DFS-VISIT(G,u)
1. time = time + 1
2. u.d = time
3. u.color = GRAY
4. for each v ∈ G.Adj[u]
5. if v.color == WHITE
6. v.pi = u
7. DFS-VISIT(G,v)
8. u.color = BLACK
9. time = time + 1
10. u.f = time
Code:
#include <bits/stdc++.h>
using namespace std;
#define WHITE 0
#define GRAY 1
#define BLACK 2
#define SIZE 100
int Time;
int adj[SIZE][SIZE];
int color[SIZE];
int parent[SIZE];
int d[SIZE];
void dfs_Visit(int G, int u)
{
Time++;
d[u] = Time;
color[u] = GRAY;
for(int i = 0; i < G; i++)
{
if(color[i] == WHITE)
{
parent[i] = u;
dfs_Visit(G, i);
}
}
color[u] = BLACK;
Time++;
cout << u << " ";
}
void dfs(int G)
{
for(int i = 0; i < G; i++)
{
color[i] = WHITE;
parent[i]=NULL;
}
Time=0;
cout << "DFS is ";
for(int i = 0; i < G; i++)
{
if(color[i] == WHITE)
{
dfs_Visit(G, i);
}
}
}
int main()
{
int vertex;
int edge;
cout << "VERTEX & Edge : ";
cin >> vertex >> edge;
cout << "Vertex is : " << vertex <<endl;
cout << "Edge is : " << edge <<endl;
int node1, node2;
for(int i = 0; i < edge; i++)
{
cout << "EDGE " << i << ": ";
cin >> node1 >> node2;
adj[node1][node2] = 1;
adj[node2][node1] = 1;
}
dfs(vertex);
}
Output picture
Inputs:
VERTEX & Edge : 4 5
Vertex is : 4
Edge is : 5
EDGE 0: 0 1
EDGE 1: 1 2
EDGE 2: 2 0
EDGE 3: 0 3
EDGE 4: 2 4
Output:
DFS is 3 2 1 0
And the accepted result is 2 1 3 0
The problem is that you haven't coded DFS-VISIT step 4 correctly
Step 4 says for each v ∈ G.Adj[u] but your code says for(int i=0; i<G; i++). Those aren't the same thing at all. You should only visit the adjacent vertexes.
In fact if you look at your code you never use adj at all. That can't be right.
Is there any built-in instrument in boost::geometry to cut geomtries like on the picture below? My idea is to find an intersection geometries, and substract them from both sources. But it feels like not the best solution, when there's more than 2 intersecting rectangles that shares same area.
So, translating the input data to a isomorphic test case in code:
Live On Coliru
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/io/io.hpp>
#include <iostream>
#include <fstream>
namespace bg = boost::geometry;
namespace bgm = bg::model;
using point = bgm::d2::point_xy<int>;
using poly = bgm::polygon<point>;
using mpoly = bgm::multi_polygon<poly>;
int main()
{
poly a, b, c;
bg::read_wkt("POLYGON((0 0 0 6 6 6 6 0 0 0))", a);
bg::read_wkt("POLYGON((4 -1 4 4 5 4 5 -1 4 -1))", b);
bg::read_wkt("POLYGON((3 -3 3 3 9 3 9 -3 3 -3))", c);
std::cout << bg::wkt(a) << "\n";
std::cout << bg::wkt(b) << "\n";
std::cout << bg::wkt(c) << "\n";
{
std::ofstream svg("output.svg");
boost::geometry::svg_mapper<point> mapper(svg, 400, 400);
mapper.add(a);
mapper.add(b);
mapper.add(c);
mapper.map(a, "fill-opacity:0.2;fill:rgb(0,0,153);stroke:rgb(0,0,200);stroke-width:2");
mapper.map(b, "fill-opacity:0.2;fill:rgb(153,0,0);stroke:rgb(200,0,0);stroke-width:2");
mapper.map(c, "fill-opacity:0.2;fill:rgb(0,153,0);stroke:rgb(0,200,0);stroke-width:2");
}
}
Which reflects the following SVG:
Consider the following code:
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/multi_polygon.hpp>
#include <boost/geometry.hpp>
#include <boost/foreach.hpp>
#include <boost/foreach.hpp>
namespace bg = boost::geometry;
namespace bgm = bg::model;
typedef bgm::d2::point_xy<int> point;
typedef bgm::polygon<point> poly;
typedef bgm::multi_polygon<poly> mpoly;
int main()
{
poly a, b, c;
bg::read_wkt("POLYGON((0 0 0 6 6 6 6 0 0 0))", a);
bg::read_wkt("POLYGON((4 -1 4 4 5 4 5 -1 4 -1))", b);
bg::read_wkt("POLYGON((3 -3 3 3 9 3 9 -3 3 -3))", c);
std::vector<poly> polies;
polies.push_back(a);
polies.push_back(b);
polies.push_back(c);
std::vector<poly> res;
for (size_t i = 0; i < polies.size(); ++i)
{
for (size_t j = i; j < polies.size(); ++j)
{
boost::geometry::model::multi_polygon<poly> output;
boost::geometry::union_(polies[i], polies[j], output);
for (auto it = output.begin(); it != output.end(); ++it)
{
res.push_back(*it);
}
}
}
for (size_t i = 0; i < polies.size(); ++i)
{
for (size_t j = i; j < polies.size(); ++j)
{
boost::geometry::model::multi_polygon<poly> multi;
boost::geometry::sym_difference(polies[i], polies[j], multi);
for (auto it = multi.begin(); it != multi.end(); ++it)
{
res.push_back(*it);
}
}
}
{
std::ofstream svg("output2.svg");
boost::geometry::svg_mapper<point> mapper(svg, 400, 400);
size_t i = 0;
BOOST_FOREACH(poly& p, res)
{
std::stringstream ss;
ss << ++i * 10;
std::stringstream ss2;
ss2 << 255 - i * 10;
mapper.add(p);
mapper.map(p, "fill-opacity:0.2;fill:rgb("+ ss.str() + "," + ss2.str() +",153);stroke:rgb(0,0,200);stroke-width:2");
}
}
return 0;
}
Which produces the following output:
For this, you have to run over all combinations and compute the unions and sym_differences of the initial polygons.
Sorry, the coloring is not as nice as yours.
Does this help?
I want to find all the paths from source to destination using DFS where source is the same as the destination
E.g. Adjacency list for point A to B
0 - 1, 2
1 - 0, 3
2 - 0
3 - 1
So paths for 0 to 0 will be
0 1 0
0 2 0
0 1 3 1 0
Here is a working code that prints all the paths, but some are repeated and some are wrong.
#include <iostream>
#include <list>
#include <vector>
using namespace std;
// This class represents a directed graph using adjacency list representation
class Graph {
private:
// No. of vertices
int V;
// Pointer to an array containing adjacency lists
list<int> *adj;
// A function used by DFS
void DFSUtil(int v, int visited[], vector<int> &vec, int s, int d);
public:
// Constructor
Graph(int V);
// function to add an edge to graph
void addEdge(int v, int w);
// prints DFS traversal of the complete graph
void DFS();
};
Graph::Graph(int V) {
this->V = V;
this->adj = new list<int>[V];
}
void Graph::addEdge(int v, int w) {
// Add w to v’s list
adj[v].push_back(w);
adj[w].push_back(v);
}
Graph construct_graph() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(1, 3);
g.addEdge(0, 2);
return g;
}
void Graph::DFSUtil(int v, int visited[], vector<int> &paths, int s, int d) {
// Increase visited count of current node and add it to path
visited[v]++;
paths.push_back(v);
if((v == d) && (visited[s] == 2) && (paths.size() > 1)){
cout << "Path: ";
for(int i = 0; i < paths.size(); i++) {
cout << paths[i] << " ";
}
cout << endl;
} else {
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i) {
if(visited[*i] < 2) {
DFSUtil(*i, visited, paths, s, d);
}
}
}
if(paths.size() > 1) {
visited[v]--;
paths.pop_back();
}
}
// The function to do DFS traversal. It uses recursive DFSUtil()
void Graph::DFS() {
// Mark all the vertices as not visited
int *visited = new int[V];
for(int i = 0; i < V; i++) {
visited[i] = 0;
}
// store potential path here till destination is reached
vector<int> paths;
// Call the recursive helper function to print DFS traversal
// starting from all vertices one by one
for (int i = 0; i < V; i++) {
if (visited[i] < 2) {
DFSUtil(i, visited, paths, 0, 0);
}
}
}
int main() {
// construct graph
// 0 ----- 1
// | |
// | |
// 2 3
Graph g = construct_graph();
// Time: O(V + E), Space: O(V^2)
g.DFS();
cout << endl;
return 0;
}
This is my output:
Path: 0 1 0
Path: 0 1 3 1 0
Path: 0 2 0
Path: 0 1 0
Path: 0 1 3 1 0
Path: 0 2 0
Path: 0 3 1 0
Path: 0 3 1 3 1 0
This is what i am expecting:
Path: 0 1 0
Path: 0 1 3 1 0
Path: 0 2 0
I was just trying to implement an adjacency list based graph, I'm not able to sort out, why second value appears twice in output print:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
int k = 0;
int n = 0;
cin>>k;
while(k>0){
cin>>n;
//Declare Adjacency List
vector<vector<pair<int, int>>> G;
G.resize(n);
//Add an edge u,v of weight w
while(n>0){
int u=0,v=0,w=0;
cin>>u>>v>>w;
G[u].push_back({v,w});
n--;
}
int i=0;
vector<vector<pair<int,int>>>::iterator it;
vector<pair<int,int>>::iterator it1;
for(it=G.begin() ; it < G.end(); it++,i++ ) {
for (it1=G[i].begin();it1<G[i].end();it1++){
for(pair<int,int> p: G[i]){
cout <<" "<<i<<"-> (w = "<<p.second<<") -> "<<p.first;
}
cout<<endl;
}
}
k--;
}
return 0;
}
Input:
1
5
1 2 2
2 3 1
2 4 4
4 5 3
Output:
0-> (w = 0) -> 0
1-> (w = 2) -> 2
2-> (w = 1) -> 3 2-> (w = 4) -> 4
2-> (w = 1) -> 3 2-> (w = 4) -> 4
4-> (w = 3) -> 5
I want to learn implementation.
Any new implementation will also be welcomed, I want to implement an undirected, weighted graph.
Because of your second for-loop
for (it1=G[i].begin();it1<G[i].end();it1++)
you get a duplicate output.
I assume you use C++11. Here's a slightly improved version of your program. First of all, I have added the option to read in the number of vertices and edges.
#include <iostream>
#include <utility>
#include <vector>
int main() {
int k = 0;
std::cin >> k;
while (k > 0) {
// read in number of nodes and edges
auto n = 0;
auto m = 0;
std::cin >> n >> m;
// Adjacency list
std::vector<std::vector<std::pair<int, int>>> G;
G.resize(n);
// Add an edge (u,v) with weight w
while (m > 0) {
int u=0, v=0, w=0;
std::cin >> u >> v >> w;
G[u].emplace_back(v,w);
--m;
}
// Print out adjacency list
for (auto i = 0; i < G.size(); ++i) {
for (const auto pair: G[i]) {
std::cout << " " << i << "-- (w = " << pair.second << ") --> " << pair.first;
}
std::cout << '\n';
}
--k;
}
return 0;
}
With your example-input
1
5
4
1 2 2
2 3 1
2 4 4
4 5 3
which denotes a graph with 5 vertices and 4 edges we get the following output:
1-- (w = 2) --> 2
2-- (w = 1) --> 3 2-- (w = 4) --> 4
4-- (w = 3) --> 5