L2-009 抢红包 - java

题目解析

给定n个人发出的红包给谁抢走了
求出n个人按照收入金额从高到低的递减顺序输出每个人的编号和收入金额

如果收入金额有并列,则按抢到红包的个数递减输出;
如果还有并列,则按个人编号递增输出。

解题思路

每次将每个人的抢到的红包加上 当然了 被抢的人要减去红包
还有每次每个人抢到的红包个数也要加上

最后对象排序一下即可

注: java 最后一个 数据有亿点多 T 了

代码

import java.io.*;
import java.math.*;
import java.util.*;

public class Main
{
	static class edge implements Comparable<edge>
	{
		int sum, cnt, pos;

		public edge(int sum, int cnt, int pos)
		{
			this.sum = sum;
			this.cnt = cnt;
			this.pos = pos;
		}

		@Override
		public int compareTo(edge other)
		{
			if (this.sum != other.sum)
				return other.sum - this.sum;
			if (this.cnt != other.cnt)
				return other.cnt - this.cnt;
			return this.pos - other.pos;
		}

	}

	public static void main(String[] args)
	{
		int n = sc.nextInt();
		edge shu[] = new edge[n + 10];
		for (int i = 1; i <= n; i++)
			shu[i] = new edge(0, 0, i);
		for (int i = 1; i <= n; i++)
		{
			int k = sc.nextInt();
			while (k-- > 0)
			{
				int N = sc.nextInt();
				int P = sc.nextInt();
				shu[i].sum -= P;
				shu[N].sum += P;
				shu[N].cnt++;
			}
		}
		Arrays.sort(shu, 1, n + 1);

		for (int i = 1; i <= n; i++)
			out.printf("%d %.2f\n", shu[i].pos, shu[i].sum / 100.0);

		out.flush();
		out.close();
	}

	static Scanner sc = new Scanner(System.in);
	static PrintWriter out = new PrintWriter(System.out);
}

c++

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1e4;

struct edge
{
    int sum, cnt, pos;
    
    bool operator <(const edge &other) const
    {
        if(sum != other.sum)
            return sum > other.sum;
        if(cnt != other.cnt)
            return cnt > other.cnt;
        return pos < other.pos;
    }
} shu[N + 10];

int n;
int k;
int m, p;

int main()
{
    scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
	    shu[i].pos = i;
	    scanf("%d", &k);
		while (k-- > 0)
		{
		    scanf("%d%d", &m, &p);
			shu[i].sum -= p;
			shu[m].sum += p;
			shu[m].cnt ++;
		}
	}
	sort(shu + 1, shu + n + 1);

	for (int i = 1; i <= n; i++)
		printf("%d %.2f\n", shu[i].pos, shu[i].sum / 100.0);
    
    return 0;
}

对象数组排序

对象排序

对象排序


团体程序设计天梯赛-练习集-java

赞赏