C++ program to find indices of soldiers who can form reconnaissance unit

C++Server Side ProgrammingProgramming

<p>Suppose we have an array A with n elements. There are n soldiers standing on a circle. For ith soldier, the height is A[i]. A reconnaissance unit can be made of such two adjacent soldiers, whose heights difference is minimal. So each of them will be less noticeable with the other. We have to find the indices of the pair of soldiers that can form a reconnaissance unit.</p><p>So, if the input is like A = [10, 12, 13, 15, 10], then the output will be (5, 1).</p><h2>Steps</h2><p>To solve this, we will follow these steps &minus;</p><pre class="prettyprint notranslate">n := size of A D := |A[0] - A[n - 1]| H := n for initialize i := 1, when i &lt; n, update (increase i by 1), do: &nbsp; &nbsp;if D &gt; |A[i] - A[i - 1]|, then: &nbsp; &nbsp; &nbsp; D := |A[i] - A[i - 1]| &nbsp; &nbsp; &nbsp; H := i print H and (H mod n)</pre><h2>Example</h2><p>Let us see the following implementation to get better understanding &minus;</p><pre class="demo-code notranslate language-cpp" data-lang="cpp">#include &lt;bits/stdc++.h&gt; using namespace std; void solve(vector&lt;int&gt; A) { &nbsp; &nbsp;int n = A.size(); &nbsp; &nbsp;int D = abs(A[0] - A[n - 1]); &nbsp; &nbsp;int H = n; &nbsp; &nbsp;for (int i = 1; i &lt; n; i++) { &nbsp; &nbsp; &nbsp; if (D &gt; abs(A[i] - A[i - 1])) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;D = abs(A[i] - A[i - 1]); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;H = i; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;cout &lt;&lt; H &lt;&lt; &quot;, &quot; &lt;&lt; (H % n) + 1; } int main() { &nbsp; &nbsp;vector&lt;int&gt; A = { 10, 12, 13, 15, 10 }; &nbsp; &nbsp;solve(A); }</pre><h2>Input</h2><pre class="result notranslate">{ 10, 12, 13, 15, 10 }</pre><h2>Output</h2><pre class="result notranslate">5, 1</pre>
raja
Updated on 03-Mar-2022 08:02:06

Advertisements