title: How to fix segmentation fault in this program
body: <p>Im solving this question but cannot get correct output it show segmentation fault
   <a href="https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/practice-problems/algorithm/agitated-chandan/description/" rel="nofollow noreferrer">https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/practice-problems/algorithm/agitated-chandan/description/</a></p>
  
  <p>This is the code that i write for this program </p>
  
  <pre><code>#include&lt;bits/stdc++.h&gt;
  using namespace std;
  
  int main()
  {
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
      int visited[100001], dist[100001];
      int largest;
  
      int t, x, y, w, i, z, k;
      int large;
      cin &gt;&gt; t;
      while (t--)
  
      {
          int large = 0;
          int n;
          cin &gt;&gt; n;
          vector&lt;pair&lt;int, int&gt;&gt; adj[n];
  
          for (i = 1; i &lt; n; i++)
          {
              cin &gt;&gt; x &gt;&gt; y &gt;&gt; w;
              adj[x].push_back(make_pair(y, w));
              adj[y].push_back(make_pair(x, w));
          }
          queue&lt;int&gt; q;
          for (k = 1; k &lt;= n; k++)
          {
              q.push(k);
              for (i = 1; i &lt;= n; i++)
              {
                  visited[i] = -1;
                  dist[i] = 0;
              }
              largest = 0;
              while (!q.empty())
              {
  
                  z = q.front();
                  visited[z] = 1;
                  q.pop();
  
                  for (i = 0; i &lt; adj[z].size(); i++)
                  {
  
                      if (visited[adj[z][i].first] == -1)
                      {
                          dist[adj[z][i].first] = dist[z] + adj[z][i].second;
  
                          if (largest &lt; dist[adj[z][i].first])
                          {
                              largest = dist[adj[z][i].first];
                          }
                          q.push(adj[z][i].first);
                          visited[adj[z][i].first] = 1;
                      }
                  }
  
              }
  
              if (large &lt; largest)
              {
                  large = largest;
              }
          }
          if (large &lt; 100)
          {
              cout &lt;&lt; 0 &lt;&lt; " ";
  
          }
          if (large &gt; 100 &amp;&amp; large &lt; 1000)
          {
              cout &lt;&lt; 100 &lt;&lt; " ";
  
          }
          if (large &gt; 1000 &amp;&amp; large &lt; 10000)
          {
              cout &lt;&lt; 1000 &lt;&lt; " ";
  
          }
          if (large &gt; 10000)
          {
              cout &lt;&lt; 10000 &lt;&lt; " ";
  
          }
          cout &lt;&lt; large;
      }
  }
  </code></pre>
  
  <p>I expect output be
  0 8
  Just heck the logic is it write or wrong</p>