📌  相关文章
📜  每次迭代后求出剩余摇杆的总和

📅  最后修改于: 2021-04-26 18:32:29             🧑  作者: Mango

在阵列ARR不同长度的棒的给定的N个,任务是确定正在每次迭代之后留下棒的计数的总和。在每次迭代中,从剩余的棍子上剪下最短棍子的长度。
例子:

Input: N = 6, arr = {5, 4, 4, 2, 2, 8}
Output: 7
Explanation:
Iteration 1: 
Initial arr = {5, 4, 4, 2, 2, 8}
Shortest stick = 2
arr with reduced length = {3, 2, 2, 0, 0, 6}
Remaining sticks = 4

Iteration 2: 
arr = {3, 2, 2, 4}
Shortest stick = 2
Left stick = 2

Iteration 3: 
arr = {1, 2}
Shortest stick = 1
Left stick = 1

Iteration 4: 
arr = {1}
Min length = 1
Left stick = 0

Input: N = 8, arr = {1, 2, 3, 4, 3, 3, 2, 1}
Output: 11

方法:解决此问题的方法是对数组进行排序,然后遍历并找到相同长度的最小长度棒,并在每个步骤中相应地更新总和,最后返回总和。

C++
// C++ program to find the sum of
// remaining sticks after each iterations
 
#include 
using namespace std;
 
// Function to calculate
// sum of remaining sticks
// after each iteration
int sum(vector &arr, int n)
{
    int sum = 0;
    sort(arr.begin(),arr.end());
    int prev=0,count=1,s=arr.size();
    int i=1;
    while(i ar{ 5, 4, 4, 2, 2, 8 };
 
    int ans = sum(ar, n);
 
    cout << ans << '\n';
 
    return 0;
}


C++
// C++ program to find the sum of
// remaining sticks after each iterations
 
#include 
using namespace std;
 
// Function to calculate
// sum of remaining sticks
// after each iteration
int sum(int ar[], int n)
{
    map mp;
 
    // storing frequency of stick length
    for (int i = 0; i < n; i++) {
        mp[ar[i]]++;
    }
 
    int sum = 0;
 
    for (auto p : mp) {
        n -= p.second;
        sum += n;
    }
 
    return sum;
}
 
// Driver code
int main()
{
 
    int n = 6;
    int ar[] = { 5, 4, 4, 2, 2, 8 };
 
    int ans = sum(ar, n);
 
    cout << ans << '\n';
 
    return 0;
}


Java
// Java program to find the sum of
// remaining sticks after each iterations
import java.util.HashMap;
import java.util.Map;
 
class GFG
{
     
    // Function to calculate
    // sum of remaining sticks
    // after each iteration
    static int sum(int ar[], int n)
    {
        HashMap mp = new HashMap<>();
     
        for (int i = 0; i < n; i++)
        {
            mp.put(ar[i], 0);
        }
         
        // storing frequency of stick length
        for (int i = 0; i < n; i++)
        {
            mp.put(ar[i], mp.get(ar[i]) + 1) ;
        }
     
        int sum = 0;
     
        for(Map.Entry p : mp.entrySet())
        {
            n -= (int)p.getValue();
            sum += n;
        }
        return sum;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 6;
        int ar[] = { 5, 4, 4, 2, 2, 8 };
     
        int ans = sum(ar, n);
     
        System.out.println(ans);
     
    }
}
 
// This code is contributed by kanugargng


Python 3
# Python proagram to find sum
# of remaining sticks
 
# Function to calculate
# sum of remaining sticks
# after each iteration
def sum(ar, n):
  mp = dict()
 
  for i in ar:
    if i in mp:
      mp[i]+= 1
    else:
      mp[i] = 1
   
  mp = sorted(list(mp.items()))
   
  sum = 0
   
  for pair in mp:
    n-= pair[1]
    sum+= n
 
  return sum
# Driver code
def main():
  n = 6
  ar = [5, 4, 4, 2, 2, 8]
  ans = sum(ar, n)
  print(ans)
 
 
main()


C#
// C# program to find the sum of
// remaining sticks after each iterations
using System;
using System.Collections.Generic;            
 
class GFG
{
     
    // Function to calculate
    // sum of remaining sticks
    // after each iteration
    static int sum(int []ar, int n)
    {
        SortedDictionary mp = new SortedDictionary();
 
        // storing frequency of stick length
        for (int i = 0; i < n; i++)
        {
            if(!mp.ContainsKey(ar[i]))
                mp.Add(ar[i], 0);
            else
                mp[ar[i]] = 0;
        }
         
        // storing frequency of stick length
        for (int i = 0; i < n; i++)
        {
            if(!mp.ContainsKey(ar[i]))
                mp.Add(ar[i], 1);
            else
                mp[ar[i]] = ++mp[ar[i]];
        }
         
        int sum = 0;
     
        foreach(KeyValuePair p in mp)
        {
            n -= p.Value;
            sum += n;
        }
        return sum;
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int n = 6;
        int []ar = { 5, 4, 4, 2, 2, 8 };
     
        int ans = sum(ar, n);
     
        Console.WriteLine(ans);
    }
}
 
// This code is contributed by 29AjayKumar


时间复杂度 O(Nlog(N)) ,其中N是棒数。

另一种方法:

  • 将摇杆长度的频率存储在地图中
  • 在每次迭代中
    • 找到最小长度的棍子的频率
    • 从每个摇杆的频率降低最小长度摇杆的频率
    • 将非零摇杆的计数加到结果摇杆上。

下面是上述方法的实现:

C++

// C++ program to find the sum of
// remaining sticks after each iterations
 
#include 
using namespace std;
 
// Function to calculate
// sum of remaining sticks
// after each iteration
int sum(int ar[], int n)
{
    map mp;
 
    // storing frequency of stick length
    for (int i = 0; i < n; i++) {
        mp[ar[i]]++;
    }
 
    int sum = 0;
 
    for (auto p : mp) {
        n -= p.second;
        sum += n;
    }
 
    return sum;
}
 
// Driver code
int main()
{
 
    int n = 6;
    int ar[] = { 5, 4, 4, 2, 2, 8 };
 
    int ans = sum(ar, n);
 
    cout << ans << '\n';
 
    return 0;
}

Java

// Java program to find the sum of
// remaining sticks after each iterations
import java.util.HashMap;
import java.util.Map;
 
class GFG
{
     
    // Function to calculate
    // sum of remaining sticks
    // after each iteration
    static int sum(int ar[], int n)
    {
        HashMap mp = new HashMap<>();
     
        for (int i = 0; i < n; i++)
        {
            mp.put(ar[i], 0);
        }
         
        // storing frequency of stick length
        for (int i = 0; i < n; i++)
        {
            mp.put(ar[i], mp.get(ar[i]) + 1) ;
        }
     
        int sum = 0;
     
        for(Map.Entry p : mp.entrySet())
        {
            n -= (int)p.getValue();
            sum += n;
        }
        return sum;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 6;
        int ar[] = { 5, 4, 4, 2, 2, 8 };
     
        int ans = sum(ar, n);
     
        System.out.println(ans);
     
    }
}
 
// This code is contributed by kanugargng

的Python 3

# Python proagram to find sum
# of remaining sticks
 
# Function to calculate
# sum of remaining sticks
# after each iteration
def sum(ar, n):
  mp = dict()
 
  for i in ar:
    if i in mp:
      mp[i]+= 1
    else:
      mp[i] = 1
   
  mp = sorted(list(mp.items()))
   
  sum = 0
   
  for pair in mp:
    n-= pair[1]
    sum+= n
 
  return sum
# Driver code
def main():
  n = 6
  ar = [5, 4, 4, 2, 2, 8]
  ans = sum(ar, n)
  print(ans)
 
 
main()

C#

// C# program to find the sum of
// remaining sticks after each iterations
using System;
using System.Collections.Generic;            
 
class GFG
{
     
    // Function to calculate
    // sum of remaining sticks
    // after each iteration
    static int sum(int []ar, int n)
    {
        SortedDictionary mp = new SortedDictionary();
 
        // storing frequency of stick length
        for (int i = 0; i < n; i++)
        {
            if(!mp.ContainsKey(ar[i]))
                mp.Add(ar[i], 0);
            else
                mp[ar[i]] = 0;
        }
         
        // storing frequency of stick length
        for (int i = 0; i < n; i++)
        {
            if(!mp.ContainsKey(ar[i]))
                mp.Add(ar[i], 1);
            else
                mp[ar[i]] = ++mp[ar[i]];
        }
         
        int sum = 0;
     
        foreach(KeyValuePair p in mp)
        {
            n -= p.Value;
            sum += n;
        }
        return sum;
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int n = 6;
        int []ar = { 5, 4, 4, 2, 2, 8 };
     
        int ans = sum(ar, n);
     
        Console.WriteLine(ans);
    }
}
 
// This code is contributed by 29AjayKumar
输出:
7

时间复杂度: O(Nlog(N))  其中N是棒数

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”