I'm trying to create an n-ary tree by taking user inputs. "t" would be number of test cases, "n" number of nodes in each n-ary trees and "e" number of edges.
#include<iostream>
#include <vector>
#include <unordered_map>
using namespace std; //Algo problem, so using it here
struct Node{
int key;
vector<Node*> child;
};
Node* newNode(int key){
Node* node = new Node;
node->key = key;
return node;
}
int main() {
int t, n, e;
cin>>t;
while(t--) {
cin>>n>>e;
unordered_map<int, Node*> map1, map2;
vector<Node*> node1, node2;
int node1Src[n], node1Dest[n], node2Src[n], node2Dest[n];
for(int i = 0; i < e; ++i){
cin>>node1Src[i]>>node1Dest[i];
}
for(int i = 0; i < e; ++i){
cin>>node2Src[i]>>node2Dest[i];
}
Node* tempSrc, *tempDest;
for(int i = 0; i < e; ++i){
if(map1.find(node1Src[i]) == map1.end()){
tempSrc = newNode(node1Src[i]);
map1.insert({node1Src[i], tempSrc});
node1.push_back(tempSrc);
}
tempSrc = map1[node1Src[i]];
if(map1.find(node1Dest[i]) == map1.end()){
tempDest = newNode(node1Dest[i]);
map1.insert({node1Dest[i], tempDest});
node1.push_back(tempDest);
}
tempDest = map1[node1Dest[i]];
tempSrc->child.push_back(tempDest);
}
for(int i = 0; i < e; ++i){
if(map2.find(node2Src[i]) == map2.end()){
tempSrc = newNode(node2Src[i]);
map2.insert({node2Src[i], tempSrc});
node2.push_back(tempSrc);
}
tempSrc = map2[node2Src[i]];
if(map1.find(node2Dest[i]) == map2.end()){
tempDest = newNode(node2Dest[i]);
map2.insert({node2Dest[i], tempDest});
node2.push_back(tempDest);
}
tempDest = map2[node2Dest[i]];
tempSrc->child.push_back(tempDest);
}
}
return 0;
}
Inside the final for loop the last line where I'm trying to push the Node to the vector, I'm getting a segmentation fault. On debugging, I got EXC_BAD_ACCESS (code=1, address=0x10).
Aucun commentaire:
Enregistrer un commentaire