0

我正在做在线挑战,必须做到以下几点。

村子里有一场比赛。因此,在第一行输入两个数字 N(即有多少人将参加比赛)和 K(其中有多少人可以进入第 2 阶段)。

之后,我们在两个阶段为每个候选人输入 N 次选票。

示例输入:

5 3
9 2
3 10
5 6
8 4
6 5

正如你所看到的,我们输入N=5, K=3,这意味着 5 个候选者,所以 5 个额外的行,其中 3 个进入第 2 阶段。

在我们对数组进行排序后,得票最多的候选人是 6、8 和 9 的候选人。所以他们将进入第 2 阶段。获胜者是在第 2 阶段中得票最多的候选人。在这种情况下,6 有 5 票,这是最多的(8 有 4,9 有 2),因此我们输出 6 的索引,即 5。

到目前为止我得到了什么:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int arr[50],nizabackup[50],n,k,niza2[50],saveindex[50],indexp=0;
    cin >> n >> k;
    for(int i=0;i<n;i++)
    {
        cin >> arr[i] >> niza2[i];
        nizabackup[i] = arr[i];
    }
    sort(arr,arr+n);
    for(int j=n;j>=k;j--)
    {
        for(int k=0;k<n;k++)
        {
            if(arr[j]==nizabackup[k])
            {
                saveindex[0]=k;
                indexp++;
            }
        }
    }
    sort(saveindex,saveindex+indexp);
    cout << saveindex[indexp];
    return 0;
}

我需要提示该怎么做以及其他问题——为什么我的调试器没有读取第二个 for 循环?

4

1 回答 1

3

好的,替代实现。还有更多设置,但请先阅读main,看看实际逻辑有多简单。

#include <vector>
#include <iostream>
#include <algorithm>

struct Contestant {
    int index;
    int firstVote;
    int secondVote;
    Contestant(int i, int v1, int v2) : index(i), firstVote(v1), secondVote(v2)
    {}
};
// return true if l should come before r in sorted result
bool byFirstVote(Contestant const &l, Contestant const &r) {
    return l.firstVote > r.firstVote; // sort by first vote
}
bool bySecondVote(Contestant const &l, Contestant const &r) {
    return l.secondVote > r.secondVote; // sort by second vote
}

int main()
{
    int n, k;
    std::cin >> n >> k;
    // populate a single vector of {index, firstVote, secondVote}
    std::vector<Contestant> contestants;
    for(int i=0; i<n; i++) {
        int v1, v2;
        std::cin >> v1 >> v2;
        contestants.push_back(Contestant(i+1, v1, v2));
    }
    // sort all by firstVote, then sort first k by secondVote
    std::sort(contestants.begin(), contestants.end(), byFirstVote);
    std::sort(contestants.begin(), contestants.begin()+k, bySecondVote);
    std::cout << contestants.front().index << std::endl;
}

我将索引(根据您的示例从 1 开始,而不是 0)和两个投票都存储在一个结构中。

然后,我只需更改排序的字段。

于 2013-03-28T12:56:44.720 回答