Bridge Crossing - Classic Puzzle Problem - The classic puzzle of finding the minimum amount of time required to cross a bridge given that only two people can cross the bridge at any one time.
Since they have only one flashlight (it's dark and they need the flashlight), the two people move at the speed of the slower one.

Constraints - Upto 6 people (although it should work for a higher number of people)

Input - Number of people (up to 6 tested) &amp; Sorted vector of time required by each person to cross the bridge.

Output - Minimum time possible

int main()
{
  vector&lt;int&gt; v; int n; int time;
  int items;
  int k = 2;
  cin&gt;&gt;items;
  for (int i = 0; i &lt; items; i++)
  {
    cin &gt;&gt; n;
    v.push_back(n);
   }

  if (v.size() == 1)
  {
    cout &lt;&lt; v[0];
    return 0;
  }
  int last = v.size() - 1;
  time = v[0] + v[1] + v[last] + v[1];

  while (last-k &gt;= 2)
  {
    time += v[0] + v[last - k];
    k++;
  }
  time = time + v[1];

  cout &lt;&lt; time;
  return 0;
}


Note : Code will not work for 2 people, missed a special case.
The overwhelming first impression I get from your code is that without the text description above, I wouldn't have a clue what it is you're trying to do.  A lot of these types of problems have some kind of prompting which helps, however your code doesn't have that, its only output is time after it's finished.

The two main improvements I'd suggest are:


Put your code in a function that defines an interface.
Use variable names that have some kind of meaning.


Implementing these two basics would go a long way to making your code easier to follow.

For example, your vector v might be people?!?

You could have a method calculate_minimum_time_to_cross_bridge, which took in a list of people and returned the time.

Whilst your variable names might have meaning to you, they have no meaning a new reader without context.

One final point is that whilst you can do this:

vector&lt;int&gt; v; int n; int time;


It's generally considered bad form.  One declaration per line means the declarations are less likely to get lost.