The following code works 100% using Xcode, but when i run the code using the Autograder, i got the following error Time out error, probably infinite loop C++ as showing in the image below.
Does this means that my arrays are too small?
Input:
4 6
Women Conservatives Neocons Veterans
Trump Women 1
Trump Conservatives 1
Trump Neocons 5
Women Neocons 1
Neocons Veterans 5
Conservatives Veterans 1
Output:
8
Here's My code:
#include <iostream>
#include <algorithm>
#include <string>
#include <stdlib.h>
#include <vector>
#include <ctime>
#include <map>
using namespace std;
/*map Group Name to a Integer
useful for representation of graph
*/
map <string, int> nameToNumber;
/*
adjacency matrix to represent graph
this will work since number of nodes is less
*/
int graph[301][301];
/*
recursion to find if target is reachable from src in graph
par == parent of src.. useful to keep track of visited nodes
*/
bool reachable(int src, int target, int par = -1)
{
if (src == target) return true;
bool isReachable = false;
for (int i = 0; i < 100; ++i)
{
if (i != par && graph[src][i] != 0 && reachable(i, target, src))
{
isReachable = true;
}
}
return isReachable;
}
int main()
{
int n, m;
cin >> n >> m;
// add names to map
for (int i = 0; i < n; ++i) {
string name;
cin >> name;
nameToNumber[name] = i;
}
vector <pair<int, pair<int, int>>> edges;
// input edges
for (int i = 0; i < m; ++i)
{
string u, v; int w;
cin >> u >> v >> w;
edges.push_back(make_pair(w, make_pair(nameToNumber[v], nameToNumber[u])));
}
// sort edges based in increasing weights
sort(edges.begin(), edges.end());
int cost = 0;
for (int i = 0; i < edges.size(); ++i) {
int u = edges[i].second.first;
int v = edges[i].second.second;
int w = edges[i].first;
// check if u-v edge causes cycle
if (!reachable(u, v)) {
graph[u][v] = 1;
cost += w;
}
}
cout << cost ;
return 0;
}
Everytime i run my code using the Autograder i get the following error Time out error, probably infinite loop.
CLICK HERE
Related
I am making a program in which
the program takes 3 numbers as input: "l", "r" and "a".
I get all the values of "x" between l and r, (l and r inclusive).
example, l = 1, r = 3, x values are 1, 2, 3. so now I have a function, f(n) = ((x/a) + (x % a)),(note: [x/a] is rounded down to an integer). so I have implemented this in c++ and my code is below.
#include<iostream>
using namespace std;
int main()
{
int l;
int r;
int a;
cin>>l>>r>>a;
int nums[(r-l)+2];
int answers[(r-l)+2];
for (int i = 1; i < (r-l)+2; i++)
{
nums[i] = i;
}
for (int i = 1; i < sizeof(nums)/sizeof(nums[0])-1; i++)
{
answers[i] = ((nums[i]/a) + (nums[i] % a));
}
int j = 0;
j = answers[0];
for (int i = 0; i < sizeof(answers); i++)
{
if (j < answers[i])
{
j = answers[i];
}
}
cout<<j;
}
but whenever I run this code, I get huge random numbers like 230984084 and all.So please point out what's wrong with my Code. Thanks in advance.
Request from Levi to post my comment as answer:
The point is that one of the successes of C++ is that it started from C, but it moved on quite a bit and the code in your question is still mostly C-code. Here is an example how it could be handled in C++ with more knowledge needed but less chance for errors:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <numeric>
int main()
{
std::cout << "Give 'left', 'right' and 'process' values: \n";
int l, r, a;
std::cin >> l >> r >> a;
std::vector<int> nums((r-l)+2);
std::vector<int> answers;
// fill container with ascending numbers
std::iota(nums.begin(), nums.end(), 1);
// transform as needed
std::transform(nums.begin(), nums.end(), std::back_inserter(answers), [a](int i) { return i/a + i%a; });
// find maximum element in container (returns iterator to element)
auto maxv = std::max_element(answers.begin(), answers.end());
std::cout << *maxv;
}
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef long long int ll;
int main()
{
string s;
cin >> s;
map<char, int,greater <int>> m;
m['A'] = 1;
m['C'] = 1;
m['G'] = 1;
m['T'] = 1;
for(ll i = 0; i < s.length()-1; i++)
{
if(s[i] == s[i+1]) //ATTCGGGA
m[s[i]]++;
}
for(auto it = m.begin(); it != m.end(); it++)
{
cout <<it->first <<" " <<it->second<<endl;
}
//cout <<it->second<<endl;
return 0;
}
my desired output should be
G 3
T 2
A 1
C 1
but its showing
T 2
G 3
C 1
A 1
I dont know why this is happening as i have already mentioned it to be greater in the orderedmap.
Please kindly solve the issue?
you could just simply use a queue.
If you want to do it with a map use a multi_map(); and use the int as the key and the char as the value that way u will sort them according to the int value
I'm tackling with a problem where I have to find the minimum number as well as the points such that all the given line segments would have atleast one point in their span.
Input is of the format - number of line segments followed by start,finish of each.
Output required is of the form - number of points along with its value
My approach: I am sorting the line segments in ascending order of finish values, iterating over them, adding them to the output list: and then comparing line segment start points with that end point. If the given start point is <=, we remove that start,end pair.
My code:
#include <algorithm>
#include <iostream>
#include <climits>
#include <vector>
using std::vector;
struct Segment {
int start, end;
};
struct less_than_key
{
inline bool operator() (const Segment& struct1, const Segment& struct2)
{
return (struct1.end < struct2.end);
}
};
vector<int> optimal_points(vector<Segment> &segments) {
vector<int> points;
sort(segments.begin(),segments.end(),less_than_key());
vector<Segment> ss = segments;
vector<int> output;
int p=0;
int t=0;
while(segments.size()!=0)
{
int m = segments[p].end;
int q=0;
output.push_back(m);
while(t==0)
{
if(q>=segments.size())
{
t=t+1;
continue;
}
if(segments[q].start<=m)
{
segments.erase(segments.begin()+q);
q=q-1;
}
q=q+1;
}
}
return output;
}
int main() {
int n;
std::cin >> n;
vector<Segment> segments(n);
for (size_t i = 0; i < segments.size(); ++i) {
std::cin >> segments[i].start >> segments[i].end;
}
vector<int> points = optimal_points(segments);
std::cout << points.size() << "\n";
for (size_t i = 0; i < points.size(); ++i) {
std::cout << points[i] << " ";
}
}
This code is working for very particular inputs and resulting in infinite loops in some. The logic should work perfectly on paper but my code is bugging out somewhere.
Running data -
Input -
3
1 3
2 5
3 6
Output -
1
3
Works correctly as the point 3 will result in each segment having a point.
I was doing a course on Coursera where they asked to implement DFS to see if two vertices of a graph are connected. I came up with the code and it gives the correct output on my laptop but it gives incorrect output on their grader. I've been breaking my head for days on this problem and have absolutely no idea where I've gone wrong. The code is as follows:
#include<iostream>
#include<vector>
using namespace std;
class Graph
{
public:
vector<int> adj; //adjacency list
void add(int a)
{
adj.push_back(a);
}
void DFS(bool visited[],int n,Graph G[],int v)
{
for(int i=0;i<G[v].adj.size();i++)
{
int vert=G[v].adj[i];
if(visited[vert]==false)
{
visited[vert]=true;
DFS(visited,n,G,vert);
}
}
}
};
int main()
{
int n,m;
cin>>n>>m;//No. of vertices,number of edges
bool visited[n];
for(int i=0;i<n;i++)
visited[n]=false;
Graph G[n];
for(int i=0;i<m;i++)
{
int u,v;
cin>>u>>v; //The vertices joined by two edges
G[u-1].add(v-1);
G[v-1].add(u-1);
}
int k,l;
cin>>k>>l; //The vertices to be checked if they are connected
G[k-1].DFS(visited,n,G,k-1);
if(visited[l-1]==true)
cout<<1;
else
cout<<0;
}
Grader Output:
Failed case #2/16: (Wrong answer)
Input:
4 2
1 2
3 2
1 4
Your output:
1
Correct output:
0
(Time used: 0.00/1.00, memory used: 7839744/536870912.)
If I run the above case in my laptop, it gives the output as 0, the expected answer. I asked the question on the forum and they say that there is some memory leak which I can't identify. Please help.
If you're writing a Graph class, then you should really encapsulate all functionality inside that class. You're not supposed to overwhelm the main function. It makes your code convoluted. Plus you don't have to pass around a lot things in case of a function call. Avoid using using namespace std; as it will lead to namespace collision. To avoid writing std::cout or std::cin, consider using std::cout and using std::cin. I refactored your code and now it gives correct output:
#include <iostream>
#include <cstring>
#include <vector>
using std::cout;
using std::cin;
class Graph
{
public:
static constexpr int MAXN = 100;
std::vector <int> adj[MAXN + 1]; //adjacency list
int visited[Graph::MAXN + 1]; // for 1 based indexing
Graph(){
for(int i = 0 ; i <= MAXN ; ++i) adj[i].clear();
memset(visited, 0, sizeof(visited));
}
void addEdge(bool isDirected, int u, int v)
{
adj[u].push_back(v);
if(!isDirected) adj[v].push_back(u);
}
void takeInput(bool isDirected, int nodes, int edges){
for(int i = 0 ; i < edges ; i++){
int u,v; cin >> u >> v;
addEdge(isDirected, u, v);
}
}
void DFS(int source)
{
visited[source] = 1;
for(int i = 0 ; i < adj[source].size() ; ++i){
int adjNode = adj[source][i];
if(visited[adjNode] == 0){
DFS(adjNode);
}
}
}
bool isConnected(int source, int destination){
DFS(source - 1);
return visited[destination - 1];
}
};
int main()
{
int nodes, edges;
cin >> nodes >> edges;//No. of vertices,number of edges
Graph g;
g.takeInput(false, nodes, edges);
int source, destination;
cin >> source >> destination; //The vertices to be checked if they are connected
cout << g.isConnected(source, destination) << '\n';
return 0;
}
So i was trying to make the challage: Breadth First Search: Shortest Reach on HackerRank, but i keep getting the bad alloc exception when the tests have great numbers of node/edges. The program works on the first test, so i don't think, it's something wrong with the implementation.
So here is the implementation:
(sorry for the indentation , my first question)
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <limits.h>
using namespace std;
int main() {
//test numbers
int t;
//the cost
int cost = 6;
cin >> t;
//for each test
for (int nt = 0; nt < t; ++nt) {
int n, e;
int snode;
queue <int> *que = new queue<int>();
//read the node/edges
cin >> n >> e;
//distance/visited/parents arrays/adjlist vector
int dist[n + 1] = {-1};
bool visited[n + 1] = {false};
int parents[n + 1] = {-1};
vector< vector<int> > adjList(n + 1);
//read into the adjlist, unoriented graph, each edge has 6 weight
for (int ne = 0; ne < e; ++ne) {
int x, y;
cin >> x >> y;
adjList[x].push_back(y);
adjList[y].push_back(x);
}
//read the starting node
cin >> snode;
dist[snode] = 0;
//do actual bfs
que->push(snode);
visited[snode] = true;
while(!que->empty()) {
int c_node = que->front();
que->pop();
for (int i = 0; i < adjList[c_node].size(); ++i) {
if (visited[adjList[c_node].at(i)] == false) {
que->push(adjList[c_node].at(i));
parents[adjList[c_node].at(i)] = c_node;
dist[adjList[c_node].at(i)] = dist[parents[adjList[c_node].at(i)]] + cost;
visited[adjList[c_node].at(i)] == true;
}
}
}
//print at output the distance from the starting node to each other node
//if unreachable, print -1
for (int i = 1; i < n + 1; ++i) {
if (i == snode) {
} else if (dist[i] == 0 && i != snode) {
cout << "-1 ";
} else {
cout << dist[i] << " ";
}
}
cout << "\n";
}
return 0;
}
Am i doing something wrong, i haven't seen anyone else complain on this matter in the discussion section of the site.
How can i avoid the exception to be thrown and from where does it come?
Thank you!
I don't know, exactly, what is the cause of your exception; and I don't know ho to reproduce your problem because depends (I suppose) from the input values. A lot of input values, I suppose.
But I see some weak points (IMHO) of your code, so I try to point your attention to them.
1) you alloc a std::queue in your for cycle
queue <int> *que = new queue<int>();
but you never free it; it's a waste of memory
2) you're using C-style variable-length arrays
int dist[n + 1] = {-1};
bool visited[n + 1] = {false};
int parents[n + 1] = {-1};
They aren't valid C++ standard code. I suggest you the use of standard containers (std::vector or std::queue).
3) you're initializing your C-style variable-length arrays with a initializers lists with only an element (-1 or false). I suppose your intention was initialize all n+1 elements with -1 and false. But this syntax initialize only the first element of the array with -1 and false.
If you want to initialize all n+1 element to -1 and false, the solution is (again) use standard containers; by example
std::vector<int> dist(n+1, -1);
std::vector<bool> visited(n+1, false);
std::vector<int> parents(n+1, -1);
4) you access arrays without bounds checking. By example:
cin >> snode;
dist[snode] = 0;
where snode is a int variable; if you insert a negative value, or a value over n, you write dist out of its bounds, devastating the memory. This, I suppose, can explain your "bad alloc exception".
Suggestion: use standard containers (again) instead of C-style array and use at() (that perform bounds checking) instead []; so
cin >> snode;
dist.at(snode) = 0;
5) sorry for my bad English (ok, I'm joking: this isn't one of your weak points; this is one of mine).