首页 > 试题广场 >

小苯送礼物

[编程题]小苯送礼物
  • 热度指数:5802 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
小苯是“小红书app”的一名博主,这天他想要给自己的“铁粉”送一些礼物。

他有 n 名粉丝,编号从 1n,但他只能选择其中 k 名送礼物,他决定选择其中对他支持力度最大的前 k 名粉丝。
(如果两名支持力度相同,则优先选择收藏数更多的,如果都一样,则优先选择编号更小的(因为这意味着他关注小苯的时间更早))

具体的:每名粉丝如果每给小苯点一次赞,则他对小苯就增加了 1 点支持力度,如果他每收藏小苯的一篇文章,则他对小苯增加 2 点支持力度。

现在小苯想知道,他应该选择哪 k 名粉丝送出礼物,请你帮帮他吧。

输入描述:
输入包含 n+1行。
第一行两个正整数 n, k\ (1 \leq k \leq n \leq 10^5),分别表示对小苯有过支持的粉丝个数,以及小苯选择送礼的粉丝个数。
接下来 n 行,每行两个整数 x_i, y_i\ (0 \leq x_i, y_i \leq 10^5),表示第 i 位粉丝给小苯点过 x 次赞,收藏过 y 个小苯的文章。


输出描述:
输出包含一行 k 个正整数,表示小苯选择出送礼物的粉丝们的编号。(按照升序输出)
示例1

输入

4 2
1 2
2 1
3 0
1 3

输出

1 4
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
    int commends;
    int collects;
    int supports;
    int id;
} fllower;
int compare_supports(const void*a,const void*b){
    fllower *fa=(fllower*)a;
    fllower *fb=(fllower*)b;
   if (fa->supports != fb->supports)
        return fb->supports - fa->supports;
        else if(fa->collects!=fb->collects)
        return fb->collects - fa->collects;
        else{
            return fa->id-fb->id;
        }

}
int compare_id(const void*a,const void*b){
    fllower *fa=(fllower*)a;
    fllower *fb=(fllower*)b;
    return fa->id-fb->id;
}
    int main() {
        int n, k;
        scanf("%d %d", &n, &k);
        for (int i = 0; i < n; i++) {

        }
        fllower* fl = (fllower*)malloc(n * sizeof(fllower));
        for (int i = 0; i < n; i++) {
            scanf("%d %d", &fl[i].commends, &fl[i].collects);
            fl[i].supports = 2 * fl[i].collects + fl[i].commends;
            fl[i].id = i + 1;
        }
        qsort(fl, n, sizeof(fllower), compare_supports);
        qsort(fl,k,sizeof(fllower),compare_id);
        for (int i = 0; i < k; i++) {
            printf("%d ", fl[i].id);
        }
        return 0;
    }
发表于 2025-10-22 15:58:35 回复(0)
import java.util.*;

public class Main {
    static class Fan {
        int support;  // 支持力度 = 点赞数 + 2*收藏数
        int collect;  // 收藏数,用于支持力度相同时的排序
        int id;       // 粉丝编号

        Fan(int support, int collect, int id) {
            this.support = support;
            this.collect = collect;
            this.id = id;
        }
    }

    public static void main(String[] args) {
        // 使用Scanner接收输入
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();

        Fan[] fans = new Fan[n];
        for (int i = 0; i < n; i++) {
            int x = scanner.nextInt();  // 点赞数
            int y = scanner.nextInt();  // 收藏数
            // 计算支持力度并存储粉丝信息
            fans[i] = new Fan(x + 2 * y, y, i + 1);
        }

        // 自定义排序规则
        Arrays.sort(fans, (a, b) -> {
            // 首先按支持力度降序排列
            if (a.support != b.support) {
                return Integer.compare(b.support, a.support);
            }
            // 支持力度相同则按收藏数降序排列
            if (a.collect != b.collect) {
                return Integer.compare(b.collect, a.collect);
            }
            // 前两者都相同则按编号升序排列
            return Integer.compare(a.id, b.id);
        });

        // 提取前k名粉丝的编号
        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = fans[i].id;
        }

        // 按编号升序排序结果
        Arrays.sort(result);

        // 输出结果
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < k; i++) {
            sb.append(result[i]);
            if (i < k - 1) {
                sb.append(" ");
            }
        }
        System.out.println(sb.toString());

        // 关闭Scanner
        scanner.close();
    }
}

发表于 2025-08-29 20:50:15 回复(0)
n,k = map(int,input().split())

dic = {}
for i in range(1,n+1):
    x,y = map(int,input().split())
    dic[i] = [x+2*y,y]
sorted_keys = sorted(dic.keys(),key=lambda x:(-dic[x][0],-dic[x][1],x))
answer = sorted(sorted_keys[0:k])

print(' '.join(map(str,answer)))
发表于 2025-08-25 23:23:49 回复(0)

主要学习sort自定义函数的写法以及pair对的用法

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int n,k;
    cin>>n>>k;

    vector<pair<int,pair<int,int>>> v;
    for (int i=1; i<=n; i++) {
        int d,s;
        cin>>d>>s;
        int z=d+s*2;
        v.push_back({i,{z,s}});
    }

    sort(v.begin(),v.end(),[](const auto& a,const auto& b){
        if(a.second.first==b.second.first) {
            if(a.second.second==b.second.second){
                return a.first<b.first;
            }else {
                return a.second.second>b.second.second;
            }

        }else {
            return a.second.first>b.second.first;
        }
    });

    vector<int> p(k);

    for (int i=0;i<k ; i++) {
        p[i]=v[i].first;
    }

    sort(p.begin(),p.end());

    for (int i=0; i<k; i++) {
        cout<<p[i]<<" ";
    }
    cout<<endl;

}
发表于 2025-08-06 00:30:54 回复(0)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

struct fan {
    int id;
    int like;
    int bookmark;
    int score;
};

bool cmp( const fan& a, const fan& b) {
    if (a.score != b.score)
        return a.score > b.score; //按score 降序排序
    else if (a.bookmark != b.bookmark)
        return a.bookmark > b.bookmark;//score一样,按抽藏值降序排序
    else
        return a.id < b.id; //score和收藏都一样,按id升序排序
}

int main() {
    int n, k;
    int x, y;
    cin >> n >> k;
    vector<fan> fans(n);
    vector<int> target_num;
    for (int i = 0; i < n; ++i) {
        cin >> fans[i].like >> fans[i].bookmark;
        fans[i].id = i + 1;
        fans[i].score = fans[i].bookmark * 2 + fans[i].like;
    }
    sort(fans.begin(), fans.end(), cmp);
    for (int i = 0; i < k; ++i) {
        target_num.emplace_back(fans[i].id);
    }
    sort(target_num.begin(), target_num.end());
    for (int i : target_num) {
        cout << i << " ";
    }

    return 0;
}

发表于 2026-01-11 21:35:51 回复(0)
n, k = map(int, input().split());fans = []

for i in range(n):
    x, y = map(int, input().split())
    fans.append((x + 2 * y,y,i+1))
fans.sort(key=lambda t: (-t[0], -t[1], t[2]));mm=[];cc=[]  
for i in range(k):
    mm.append(fans[i])
for i in range(k):
    cc.append(mm[i][2])

print(' '.join(str(x) for x in sorted(cc)))
发表于 2026-01-09 18:01:13 回复(0)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

struct fans{
    int id;
    int zan;
    int cang;
    int support;
};

bool comparefans(const fans&a,const fans& b){
    if(a.support==b.support){
        if(a.cang==b.cang){
            return a.id < b.id;
        }
        return a.cang > b.cang;
    }
    return a.support>b.support;
}


int main() {
    int n,k;
    cin>>n>>k;
    vector<fans> f(n);
    for(int i=0;i<n;i++){
        f[i].id = i+1;
        cin>>f[i].zan>>f[i].cang;
        f[i].support = f[i].zan * 1 + f[i].cang * 2;
    }
    sort(f.begin(),f.end(),comparefans);
    vector<int> ans;
    for(int i=0;i<k;i++){
        ans.push_back(f[i].id);
    }
    sort(ans.begin(),ans.end());
    for(auto i:ans){
        cout<<i<<" ";
    }
    cout<<endl;
    return 0;

}
// 64 位输出请用 printf("%lld")

发表于 2026-01-06 16:24:06 回复(0)
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct fans {
    int number;
    int likes;
    int collect;
    int score;
};

bool cmp(const fans & a,const fans & b){
    if(a.score != b.score){
        return a.score > b.score;
    }
    else if (a.collect != b.collect){
        return a.collect > b.collect;
    }
    else return a.number < b.number;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, k;
    cin >> n >> k;
    vector<fans>numbers(n);
    for (int i = 0; i < n; i++) {
        cin >> numbers[i].likes >> numbers[i].collect;
        numbers[i].number = i + 1;
        numbers[i].score = numbers[i].likes + numbers[i].collect * 2;
    }
    sort(numbers.begin(),numbers.end(),cmp);
    vector<int>res;
    for(int i = 0; i < k;i++){
        int tmp;
        tmp = numbers[i].number;
        res.push_back(tmp);
    }
    sort(res.begin(),res.end());
    for(int i = 0; i < k;i++){
        cout<<res[i];
        if(i != k - 1){
            cout<<' ';
        }
    }
}



    // 64 位输出请用 printf("%lld")
发表于 2025-12-25 20:31:11 回复(0)
import heapq

def main():
    import sys
    input = sys.stdin.read().split()  # 快速读取输入(适配大数据)
    ptr = 0
    n, k = int(input[ptr]), int(input[ptr+1])
    ptr += 2
   
    # 构造堆:存储 (-支持力度, -收藏数, 编号),利用小顶堆找前k大
    heap = []
    for idx in range(1, n+1):
        x = int(input[ptr])
        y = int(input[ptr+1])
        ptr += 2
        support = x + 2 * y  # 计算支持力度
        # 堆元素:(-支持力度, -收藏数, 编号),小顶堆会优先弹出“更小”的元组(即更差的粉丝)
        if len(heap) < k:
            heapq.heappush(heap, ( support, idx ))
        else:
            # 仅当当前粉丝比堆顶更优时,替换堆顶
            if support > heap[0][0]:
                heapq.heappop(heap)
                heapq.heappush(heap, ( support, idx ))
   
    # 提取堆中所有粉丝编号,并按升序排序
    selected = [item[1] for item in heap]
    selected.sort()
   
    # 输出结果(按升序)
    print(' '.join(map(str, selected)))

if __name__ == "__main__":
    main()
发表于 2025-12-23 23:16:17 回复(0)
#include 
#include 
#include 
using namespace std;
struct fans {
    int id;     //粉丝序号
    int like;   //点赞数
    int cang;   //收藏数
    int point;  //支持力度
};
bool compare(fans f1, fans f2)
{
    if ((f1.point == f2.point) && (f1.cang == f2.cang)&&(f1.like==f2.like))
        return f1.id < f2.id;
    if ((f1.point == f2.point) && (f1.cang == f2.cang))
        return f1.like > f2.like;
    if (f1.point == f2.point)
        return f1.cang > f2.cang;
    return f1.point > f2.point;
}
int main() {
    int n, k;
    while (cin >> n >> k) { // 注意 while 处理多个 case
        vector v;
        fans ftmp;
        int x, y;
        for (int i = 0; i < n; ++i)
        {
            cin >> x >> y;
            ftmp.id = i + 1;
            ftmp.like = x;
            ftmp.cang = y;
            ftmp.point = x + 2 * y;
            v.push_back(ftmp);
        }
        sort(v.begin(),v.end(),compare);
        sort(v.begin(), v.begin() + k, [](fans a, fans b) {return a.id < b.id; });
        for (int i = 0; i < k; ++i)
        {
            cout << v[i].id << " ";
        }
        cout << endl;
    }
}
// 64 位输出请用 printf("%lld")
发表于 2025-12-17 21:39:04 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int fansNum = in.nextInt();
            int goodsNum = in.nextInt();
            List<UpInfo> list = new ArrayList<>();

            for (int i = 0; i < fansNum; i++) {
                int like = in.nextInt();
                int have = in.nextInt();
                list.add(new UpInfo(i + 1, like, have, like + 2 * have)); 
            }

            Collections.sort(list, new Comparator<UpInfo>() {
                public int compare(UpInfo fanA, UpInfo fanB) {
                    if (fanA.up != fanB.up) {
                        return fanB.up - fanA.up;
                    } else {
                        if (fanA.haveNum != fanB.haveNum) {
                            return fanB.haveNum - fanA.haveNum;
                        } else {
                            return fanA.id - fanB.id;
                        }
                    }
                }
            });

            List<Integer> res = new ArrayList<>();
            for (int i = 0; i < goodsNum; i++) {
                res.add(list.get(i).id);
            }
            Collections.sort(res);

            for (int num : res) System.out.print(num + " ");
        }
    }
}

class UpInfo {
    public int id;
    public int likeNum;
    public int haveNum;
    public int up;
    public UpInfo(int id, int likeNum, int haveNum, int up) {
        this.id = id;
        this.likeNum = likeNum;
        this.haveNum = haveNum;
        this.up = up;
    }
}

发表于 2025-12-03 16:58:53 回复(0)
n, k = map(int, input().split())
fans = []

for i in range(1, n + 1):
    dz, sc = map(int, input().split())
    support = dz + sc * 2
    fans.append((support, sc, i))


fans.sort(key=lambda x: (-x[0], -x[1], x[2]))
selected = [fans[i][2] for i in range(k)]
selected.sort()
print(' '.join(map(str, selected)))

发表于 2025-11-26 15:05:13 回复(0)
n, k = map(int, input().split())
lis1 = []
for i in range(n):
    a, b = map(int, input().split())
    lis1.append([i+1, a + 2*b])
# 先按支持力度降序,取前k个,再按编号升序
lis1 = sorted(lis1, key=lambda x: -x[1])
lis2 = sorted(lis1[:k], key=lambda x: x[0])
print(' '.join(str(j) for j, val in lis2))
有一组用例过不了,不知道为啥
发表于 2025-11-16 16:42:08 回复(0)
n,k = map(int,input().split())
li = []
for i in range(n):
    x,y = map(int,input().split())
    zcd = x+2*y
    li.append([i+1,zcd,y])
li_sorted = sorted(li,key = lambda m:(-m[1],-m[2],m[0]))
result = sorted([row[0] for row in li_sorted][:k])
print(' '.join(map(str,result)))
发表于 2025-10-03 13:39:59 回复(0)
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String[] line1 = bf.readLine().split(" ");
        int n = Integer.parseInt(line1[0]), k = Integer.parseInt(line1[1]);
        ArrayList<Fan> list = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            String[] line = bf.readLine().split(" ");
            list.add(new Fan(i, Integer.parseInt(line[0]), Integer.parseInt(line[1])));
        }
        list.sort(new Comparator<Fan>() {
            @Override
            public int compare(Fan o1, Fan o2) {
                int i = o2.score - o1.score;
                i = i == 0 ? o2.col - o1.col : i;
                i = i == 0 ? o1.id - o2.id : i;
                return i;
            }
        });
        int[] ids = new int[k];
        for (int i = 0; i < k; i++) {
            ids[i] = list.get(i).id;
        }
        Arrays.sort(ids);
        System.out.println(Arrays.stream(ids).boxed().map(String::valueOf).collect(Collectors.joining(" ")));
    }
}
class Fan {
    int id;
    int zan;//点赞数
    int col;//收藏数
    int score;
    public Fan(int id, int zan, int col) {
        this.id = id;
        this.zan = zan;
        this.col = col;
        this.score = zan * 1 + col * 2;
    }
}

发表于 2025-09-21 18:01:41 回复(0)
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct node{
    int id;
    int like;
    int collect;
    int support;
};
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int n,k,x,y;
    cin>>n>>k;
    vector<node> vec(n);
    for(int i=0;i<n;i++){
        cin>>vec[i].like>>vec[i].collect;
        vec[i].id=i+1;
        vec[i].support=vec[i].like+2*vec[i].collect;
    }
    sort(vec.begin(),vec.end(),[](auto const& x,auto const&y){
        if(x.support==y.support&&x.collect==y.collect&&x.like==y.like)
        return x.id<y.id;
        if(x.support==y.support&&x.collect==y.collect)
        return x.like>y.like;
        if(x.support==y.support)
        return x.collect>y.collect;
        return x.support>y.support;
    });
    sort(vec.begin(),vec.begin()+k,[](auto const& x,auto const&y){return x.id<y.id;});
    for(int i=0;i<k;i++)
    cout<<vec[i].id<<' ';
}

发表于 2025-09-17 21:34:22 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        PriorityQueue<fans> maxHeap = new PriorityQueue<>((a, b) -> a.support == b.support ? a.have == b.have ? a.num - b.num : b.have - a.have : b.support - a.support);
        int n = in.nextInt();
        int k = in.nextInt();
        for(int i = 0; i < n; i++){
            int good = in.nextInt();
            int have = in.nextInt();
            fans fan = new fans(i + 1, good, have);
            maxHeap.add(fan);
        }
        List<Integer> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < k; i++){
            list.add(maxHeap.poll().num);
        }
        Collections.sort(list);
        for(int i = 0; i < k; i++)
            sb.append(list.get(i)).append(" ");
        sb.deleteCharAt(sb.length() - 1);
        System.out.println(sb.toString());
    }
    static class fans{
        public int num;
        public int support;
        public int good;
        public int have;
        public fans(int num, int good, int have){
            this.num = num;
            this.good = good;
            this.have = have;
            this.support = good + 2 * have;
        }
    }
}
发表于 2025-09-04 23:37:23 回复(0)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct People{
    int num;
    int zan;
    int shou;
    int score=zan+shou*2;
    People(int x,int y,int z):num(x),zan(y),shou(z){}
};

static bool Compare(People p1,People p2){
    if(p1.score==p2.score)
    {
        if(p1.shou==p2.shou){
            return p1.num<p2.num;
        }
        return p1.shou>p2.shou;
    }
    return p1.score>p2.score;
}

int main() {
    int people,luck,x,y;
    cin>>people>>luck;
    vector<People> li;
    vector<int> num;
    for(int i=1;i<=people;i++){
        cin>>x>>y;
        li.push_back(People(i,x,y));
    }
    sort(li.begin(),li.end(),Compare);
    for(int i=0;i<luck;i++){
        num.push_back(li[i].num);
    }
    sort(num.begin(),num.end());
    for(auto n:num){
        cout<<n<<' ';
    }
    return 0;
}
发表于 2025-08-30 22:11:45 回复(0)
n,k = map(int,input().split())
numbers_list = []
for i in range(1,n + 1):
    sub_list = list(map(int,input().split()))
    sub_list.append(i)
    sub_list.append(sub_list[0]+2*sub_list[1])
    numbers_list.append(sub_list)
sort_list = sorted(numbers_list,key=lambda x:[-x[3],-x[1],x[2]])
sub_l = []
for i in range(k):
    sub_l.append(sort_list[i][2])
sort_l = sorted(sub_l)
sort_l = [str(i) for i in sort_l]
print(" ".join(sort_l))

发表于 2025-08-23 22:17:04 回复(0)
import sys
data = sys.stdin.read().split()
n_num,k_num = int(data[0]),int(data[1])
total_list = []
index = 2
for i in range(1,n_num+1):
    zan = int(data[index])
    cang = int(data[index+1])
    du = zan+2*cang
    total_list.append([i,cang,du])
    index += 2
total_list = sorted(total_list,key=lambda x:(-x[2],-x[1],x[0]))
result = [char[0] for char in total_list[0:k_num]]
result.sort()
print(' '.join(map(str,result)))

发表于 2025-08-22 21:34:37 回复(0)