PAT (Advanced Level) Practice A1129 Recommendation System (25 分)(C++)(甲級)(隊列思想、排序)

原題鏈接

#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

typedef struct Node
{
    int data, times;
    Node(int a, int b)
    {
        data = a, times = b;
    }
}Node;
const int MAX = 5e4+10;
int N, K;
int A[MAX];
int T[MAX] = {0};//表示每個數字出現的次數
vector<Node> V;//在隊列中的元素

bool cmp(Node A, Node B)
{
    if(A.times != B.times) return A.times > B.times;
    return A.data < B.data;
}

int main()
{
    scanf("%d %d", &N, &K);
    for(int i=0; i<N; i++) scanf("%d", &A[i]);
    for(int i=1; i<N; i++)
    {
        T[A[i-1]]++;
        int k=0;
        while(k < V.size() && V[k].data != A[i-1]) k++;//查詢是否已經在隊列中
        if(k != V.size()) V[k].times++;//已在,則其次數+1
        else
        {
            if(V.size() < K) V.push_back(Node(A[i-1], T[A[i-1]]));//否則若隊列未滿則直接加入
            else if(T[A[i-1]] > V[V.size()-1].times//或者出現次數比最後一個多,或者出現次數相同,但其數據更小,則替換
                    || (T[A[i-1]] == V[V.size()-1].times && A[i-1] < V[V.size()-1].data))
            {
                V.pop_back();
                V.push_back(Node(A[i-1], T[A[i-1]]));
            }
        }
        sort(V.begin(), V.end(), cmp);//排序後輸出
        printf("%d:", A[i]);
        for(int i=0; i<V.size(); i++) printf(" %d", V[i]);
        printf("\n");
    }
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章