首页 > 试题广场 >

小红书推荐系统

[编程题]小红书推荐系统
  • 热度指数:3180 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
小红书有一个推荐系统,可以根据用户搜索的关键词推荐用户希望获取的内容。
现在给定小红的搜索记录(记录为分词后的结果),我们认为当一个单词出现的次数不少于3次时,该单词为“用户期望搜索的单词”,即称为关键词。请你根据小红的记录,输出小红的用户画像对应的所有关键词。

输入描述:
一行字符串,仅由小写字母和空格组成。代表小红的搜索记录。
字符串长度不超过100000。


输出描述:
小红所有的关键词。每行输入一个。你需要按照搜索频次从高到低输出。频次相同的,你需要按字典序升序输出。
示例1

输入

kou red game red ok who game red karaoke yukari kou red red nani kou can koukou ongakugame game

输出

red
game
kou
#include <functional>
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

int main() {
    string s;
    unordered_map<string, int> mp;
    while (cin >> s) {
        mp[s]++;
    }
    vector<pair<string, int>> v;
    for (auto a : mp) {
        if (a.second >= 3) {
            v.push_back({a.first, a.second});
        }
    }
    sort(v.begin(), v.end(), [](const auto & a, const auto & b) {
        return a.second == b.second ? a.first<b.first: a.second>b.second;
    });
    for (auto a : v) {
        cout << a.first << endl;
    }
}
发表于 2025-08-06 14:15:16 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 读取整行搜索记录
        String line = scanner.nextLine();
        // 按空格分割成单词数组
        String[] words = line.split(" ");
        
        // 统计每个单词出现的次数
        Map<String, Integer> countMap = new HashMap<>();
        for (String word : words) {
            countMap.put(word, countMap.getOrDefault(word, 0) + 1);
        }
        
        // 筛选出出现次数不少于3次的单词(关键词)
        List<Map.Entry<String, Integer>> keywords = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            if (entry.getValue() >= 3) {
                keywords.add(entry);
            }
        }
        
        // 自定义排序规则:
        // 1. 按出现次数从高到低排序
        // 2. 次数相同的按字典序升序排序
        Collections.sort(keywords, (a, b) -> {
            if (!a.getValue().equals(b.getValue())) {
                return b.getValue() - a.getValue(); // 次数降序
            } else {
                return a.getKey().compareTo(b.getKey()); // 字典序升序
            }
        });
        
        // 输出结果
        for (Map.Entry<String, Integer> entry : keywords) {
            System.out.println(entry.getKey());
        }
    }
}

发表于 2025-08-31 14:13:15 回复(0)
import java.util.*;
import java.math.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String input = in.nextLine();
        String[] str = input.split(" ");
        HashMap<String, Integer> zimu = new HashMap<>();
        for (int i = 0; i < str.length; i++) {
            if (zimu.containsKey(str[i])) {
                zimu.put(str[i], zimu.get(str[i]) + 1);
            } else {
                zimu.put(str[i], 1);
            }
        }

        List<String> keyWords = new ArrayList<>();
        for (Map.Entry<String, Integer> c : zimu.entrySet()) {
            if (c.getValue() >= 3) {
                keyWords.add(c.getKey());
            }
        }

        keyWords.sort((a, b)-> {
            int com = zimu.get(b).compareTo(zimu.get(a));
            return com != 0 ? com : a.compareTo(b);

        });
        for (String word : keyWords) {
            System.out.println(word);
        }
    }
}


发表于 2025-07-22 23:08:12 回复(0)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    string str;
    while (getline(cin, str)){
        vector<string> subStrVec;
        string subStr = "";
        for (int i = 0; i < str.size(); i++){
            if (str[i] != ' ') {
                subStr.push_back(str[i]);
                if (i == str.size()-1) {
                    subStrVec.push_back(subStr);
                    subStr.clear();
                }
            } else {
                subStrVec.push_back(subStr);
                subStr.clear();
            }
        }
        // 去重
        vector<string> uniqueSubStrVce;
        for (int i = 0; i < subStrVec.size(); i++) {
            auto it = std::find(uniqueSubStrVce.begin(),uniqueSubStrVce.end(),subStrVec[i]);
            if (it == uniqueSubStrVce.end()) {
                uniqueSubStrVce.push_back(subStrVec[i]);
            }
        }
        // 统计个数
        vector<pair<string,int>> pairVec;
        for (int i = 0; i < uniqueSubStrVce.size(); i++) {
            int num = std::count(subStrVec.begin(),subStrVec.end(),uniqueSubStrVce[i]);
            if (num >= 3) {
                pairVec.push_back(make_pair(uniqueSubStrVce[i], num));
            }
        }
        // 排序
        std::sort(pairVec.begin(),pairVec.end(), [](pair<string,int> _pairA, pair<string,int> _pairB){
            string _subStrA = _pairA.first;
            string _subStrB = _pairB.first;
            int _numA = _pairA.second;
            int _numB = _pairB.second;
            bool res = false;
            if (_numA > _numB) {
                res = true;
            } else if (_numA == _numB) {
                if (_subStrA < _subStrB) {
                    res = true;
                }
            }
            return res;
        });
        // 输出
        for (auto mix : pairVec) {
            cout << mix.first << endl;
        }
    }
}

发表于 2025-12-11 20:32:58 回复(0)
提供一般不会有人用的做法
(在复杂度比stl劣的情况下代码更长
Trie树
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
struct Trie{
    vector<vector<int>>a;
    vector<int>cnt;
    int idx,n;
    Trie(int n):n(n+1),idx(0){
        a=vector< vector<int> >(n+1,vector<int>(26));
        cnt.resize(n+1);
    }
    void insert(const string &s){
        int p=0;
        for(char c:s){
            if(!a[p][c-'a']){
                a[p][c-'a']=(++idx);
            }
            p=a[p][c-'a'];
        }
        cnt[p]++;
    }
    ll ask(const string &s){
        int p=0;
        for(char c:s){
            if(!a[p][c-'a']){
                return 0;
            }
            p=a[p][c-'a'];
        }
        return cnt[p];
    }
};
int main(){
    cin.tie(0)->ios::sync_with_stdio(false);
    string s;
    vector<string>a;
    int siz=0;
    while(cin>>s){
        siz+=s.size();
        a.push_back(s);
    }
    Trie T(siz+1);
    for(const string &x:a) T.insert(x);    
    sort(a.begin(),a.end());
    a.erase(unique(a.begin(),a.end()),a.end());
    sort(a.begin(),a.end(),[&](const string &x,const string &y){
        int dx=T.ask(x);
        int dy=T.ask(y);
        if(dx!=dy) return dx>dy;
        return x<y;
    });    
    for(const string &x:a){
        if(T.ask(x)>=3) cout<<x<<endl;
        else break;
    }
    return 0;
}
字符串哈希(采用了三模)
被卡掉的概率几乎为0
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
using u64=unsigned long long;
using ll=long long;
const ll mod1=1e9+7;
const ll mod2=1234567891LL;
const int base=131;
struct HashPair{
    ll h1,h2;u64 h3;
    friend bool operator<(HashPair x,HashPair y){
        if(x.h1!=y.h1) return x.h1<y.h1;
        if(x.h2!=y.h2) return x.h2<y.h2;
        return x.h3<y.h3;
    }
};
HashPair Init(const string &s){
    ll hash1=0;
    ll hash2=0;
    u64 hash3=0;
    for(char c:s) {
        hash1=(hash1*base%mod1+(c-'a'+1))%mod1;
        hash2=(hash2*base%mod2+(c-'a'+1))%mod2;
        hash3=(hash3*base+(c-'a'+1));
    }
    return {hash1,hash2,hash3};
}
int main(){
    cin.tie(0)->ios::sync_with_stdio(false);
    string s;
    vector<HashPair>res;
    vector<pair<string,int>>a;
    while(cin>>s){
        HashPair T=Init(s);
        res.emplace_back(T);
        a.emplace_back(s,0);
    }
    sort(res.begin(),res.end());
    auto ask=[&](string &s) ->int {
        HashPair T=Init(s);
        return upper_bound(res.begin(),res.end(),T)-lower_bound(res.begin(),res.end(),T);
    };
    sort(a.begin(),a.end());
    a.erase(unique(a.begin(),a.end()),a.end());//排序去重
    for(int i=0;i<a.size();i++) a[i].second=ask(a[i].first);
    sort(a.begin(),a.end(),[&](pair<string,int> &x,pair<string,int> &y){
        if(x.second!=y.second) return x.second>y.second;
        return x.first<y.first;
    });
    for(int i=0;i<a.size();i++){
        if(a[i].second>=3) cout<<a[i].first<<endl;
        else break;
    }
    return 0;
}


发表于 2025-11-10 01:51:46 回复(0)
s=input().split( )
s.sort() ## 输入 线按排序,在统计
table={}

for i in s:
    if i in table:
        table[i]+=1
    else:
        table[i]=1
data=dict((sorted(table.items(),key=lambda x:x[1],reverse=True)))

for k,v in data.items():
    if v>=3:
        print(k)
发表于 2025-10-24 15:34:10 回复(0)
li = input().split()
dic = {}
for i in li:
    if i in dic.keys():
        dic[i] += 1
    else:
        dic[i] = 1
dic_new = {x:dic[x] for x in dic if dic[x] >=3}
dic_sorted = sorted(dic_new,key=lambda x:(-dic[x],x))
for i in dic_sorted:
    print(i)
发表于 2025-10-03 15:01:33 回复(0)
from collections import defaultdict
import sys

a = input().split()
word_dict = defaultdict(int)
for word in a:
    word_dict[word] += 1

sorted_ = sorted(word_dict.items(), key= lambda x :(-x[1], x[0])) # 值降序,键升序
key_words = []
for item in sorted_:
    if item[1] >= 3:
        key_words.append(item[0]) # 字符串列表,频率降序,且都大于等于3次
for item in key_words:
    print(item)

发表于 2025-09-20 16:21:41 回复(0)
问这道题的代码问什么不可以再vscode中编译

发表于 2025-09-17 14:38:15 回复(0)
import sys

for line in sys.stdin:
    a = line.split()
    strs=list(map(str,a))
    s_dict={}
    for s in strs:
        if s in s_dict:
            s_dict[s]+=1
        else: s_dict[s]=1

num_dict={}
for k,v in s_dict.items():
    if v>=3:
        if v not in num_dict:
            num_dict[v]=[k]
        else:
            num_dict[v].append(k)

for v in sorted(num_dict.keys())[::-1]:
    for s in sorted(num_dict[v]):
        print(s)
发表于 2025-09-14 19:00:47 回复(0)
s = input().split()

dic = {}
for item in s:
    if item not in dic.keys():
        dic[item] = 1
    else:
        dic[item] += 1
sorted_dic_keys = sorted(dic.keys(), key=lambda x:(-dic[x],x))

for key in sorted_dic_keys:
    if dic[key]>=3:
        print(key)
    else:
        break
发表于 2025-08-26 12:18:01 回复(0)
import java.util.*;
import java.util.stream.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] keys = in.nextLine().split(" ");
        HashMap<String, Integer> map  = new HashMap<String, Integer>();
        for (String key : keys) {
            map.put(key, map.getOrDefault(key, 0) + 1);
        }
        List<String> list = map.entrySet().stream()
                            .filter(entry -> entry.getValue() >= 3)
                            .sorted(Comparator.comparing(Map.Entry<String, Integer>::getValue,
                                    Collections.reverseOrder())
                                    .thenComparing(Map.Entry<String, Integer>::getKey))
                            .map(Map.Entry<String, Integer>::getKey)
                            .collect(Collectors.toList());

        for (String key : list) {
            System.out.println(key);
        }

    }
}


发表于 2025-08-17 20:49:25 回复(0)
import sys
words =  input().strip().split()
words.sort()
out = {}
for word in words:
    if word not in out.keys():
        out[word] = 1
    else:
        out[word] =  out[word] + 1

outsort = sorted(out.items(),key = lambda x: x[1],reverse=True)
for o in outsort:
    if o[1] >=3:
        print(o[0])


发表于 2025-08-15 11:56:49 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        String[] s = in.nextLine().trim().split(" ");
        HashMap<String, Integer> map = new HashMap<>();
        for (String string : s) {
            if (map.containsKey(string)) {
                map.put(string, map.getOrDefault(string, 0) + 1);
            } else {
                map.put(string, 1);
            }
        }
        //ArrayList
        ArrayList<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if (o1.getValue().compareTo(o2.getValue()) != 0) {
                    return o2.getValue().compareTo(o1.getValue());
                }
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> entry : entries) {
            if (entry.getValue() >= 3) {
                linkedHashMap.put(entry.getKey(), entry.getValue());
            }
        }
        for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey());
        }

    }
}
发表于 2025-08-14 15:42:35 回复(0)