C++ 程式用於查詢團隊成員的索引序列


假設我們有一個包含 n 個元素的陣列 A 和一個數 k。一個班級中有 n 個學生。第 i 個學生評級為 A[i]。我們必須組建一個由 k 名學生組成的團隊,每個團隊成員的評級各不相同。如果不可能,則返回“不可能”,否則返回索引序列。

因此,如果輸入如下:A = [15, 13, 15, 15, 12];k = 3,則輸出將為 [1, 2, 5]。

步驟

為解決此問題,我們將遵循以下步驟 −

Define two large arrays app and ans and fill them with
cnt := 0
n := size of A
   for initialize i := 1, when i <= n, update (increase i by 1), do:
      a := A[i - 1]
      if app[a] is zero, then:
         (increase app[a] by 1)
         increase cnt by 1;
         ans[cnt] := i
if cnt >= k, then:
   for initialize i := 1, when i <= k, update (increase i by 1), do:
      print ans[i]
Otherwise
   return "Impossible"

示例

讓我們看看以下實現方式,以便更好地理解 −

#include <bits/stdc++.h>
using namespace std;

void solve(vector<int> A, int k) {
   int app[101] = { 0 }, ans[101] = { 0 }, cnt = 0;
   int n = A.size();
   for (int i = 1; i <= n; i++) {
      int a = A[i - 1];
      if (!app[a]) {
         app[a]++;
         ans[++cnt] = i;
      }
   }
   if (cnt >= k) {
      for (int i = 1; i <= k; i++)
         cout << ans[i] << ", ";
   }
   else
      cout << "Impossible";
}
int main() {
   vector<int> A = { 15, 13, 15, 15, 12 };
   int k = 3;
   solve(A, k);
}

輸入

{ 15, 13, 15, 15, 12 }, 3

輸出

1, 2, 5,

更新於: 03-Mar-2022

148 次瀏覽

Kickstart Your Career

完成課程即可獲得認證

開始
廣告
© . All rights reserved.