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,
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
javascript
PHP