PTA——抢红包

L2-2 抢红包(25 分)
没有人没抢过红包吧…… 这里给出N个人之间互相发红包、抢红包的记录,请你统计一下他们抢红包的收获。

输入格式:

输入第一行给出一个正整数N(≤104),即参与发红包和抢红包的总人数,则这些人从1到N编号。随后N行,第i行给出编号为i的人发红包的记录,格式如下:

K    N1     P1    ⋯   NK    PK

其中K(0≤K≤20)是发出去的红包个数,Ni是抢到红包的人的编号,P​i(>0)是其抢到的红包金额(以分为单位)。注意:对于同一个人发出的红包,每人最多只能抢1次,不能重复抢。

输出格式:

按照收入金额从高到低的递减顺序输出每个人的编号和收入金额(以元为单位,输出小数点后2位)。每个人的信息占一行,两数字间有1个空格。如果收入金额有并列,则按抢到红包的个数递减输出;如果还有并列,则按个人编号递增输出。

输入样例:

10
3 2 22 10 58 8 125
5 1 345 3 211 5 233 7 13 8 101
1 7 8800
2 1 1000 2 1000
2 4 250 10 320
6 5 11 9 22 8 33 7 44 10 55 4 2
1 3 8800
2 1 23 2 123
1 8 250
4 2 121 4 516 7 112 9 10
输出样例:

1 11.63
2 3.63
8 3.63
3 2.11
7 1.69
6 -1.67
9 -2.18
10 -3.26
5 -3.26

4 -12.32


pta模拟赛进阶题第二题,当时排序用的冒泡,打了半天,sort函数只会最基本的

后来去看了下别人怎么打的,sort66666666666


第一次代码

#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
struct people
{
	int no;//编号
	int money=0;//拥有金额
	int geshu=0;//抢红包的个数
}a[10001];
int main()
{
	int n,k,bh,m,temp;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>k;
		int sum=0;
		for(int j=0;j<k;j++)
		{
			cin>>bh>>m;
			a[bh-1].money+=m;
			a[bh-1].geshu++;
			sum+=m;
		}
		a[i].money-=sum;
		a[i].no=i;
	}
	for(int i=0;i<n;i++)
	for(int j=1;j<n-i;j++)
	{
		if(a[j-1].money<a[j].money)
		{
			temp=a[j-1].money;
			a[j-1].money=a[j].money;
			a[j].money=temp;
			temp=a[j-1].geshu;
			a[j-1].geshu=a[j].geshu;
			a[j].geshu=temp;
			temp=a[j-1].no;
			a[j-1].no=a[j].no;
			a[j].no=temp;
			continue;
		}
		if(a[j-1].money==a[j].money)//如果收入金额有并列
		{
			if(a[j-1].geshu<a[j].geshu)//按抢到红包的个数递减输出
			{
			temp=a[j-1].geshu;
			a[j-1].geshu=a[j].geshu;
			a[j].geshu=temp;
			temp=a[j-1].no;
			a[j-1].no=a[j].no;
			a[j].no=temp;
			continue;
			}
			if(a[j-1].geshu==a[j].geshu)//如果还有并列,则按个人编号递增输出
			{
			if(a[j-1].no>a[j].no)
			{
			  temp=a[j-1].no;
			a[j-1].no=a[j].no;
			a[j].no=temp;
			}
			}
		}
	}
	for(int i=0;i<n;i++)
	{
		cout.precision(2);
		cout<<a[i].no+1<<" "<<fixed<<a[i].money*1.0/100<<endl;
	}
	
	return 0;
}

第二次代码

#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
struct people
{
	int no;//编号
	int money=0;//拥有金额
	int geshu=0;//抢红包的个数
}a[10001];
bool cmp(people a,people b)
{
    if(a.money!=b.money)
        {return a.money>b.money;}
    else if(a.geshu!=b.geshu)
        {return a.geshu>b.geshu;}
    else
    {return a.no<b.no;}
}
int main()
{
	int n,k,bh,m,temp;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>k;
		int sum=0;
		for(int j=0;j<k;j++)
		{
			cin>>bh>>m;
			a[bh-1].money+=m;
			a[bh-1].geshu++;
			sum+=m;
		}
		a[i].money-=sum;
		a[i].no=i;
	}
	sort(a,a+n,cmp);
	for(int i=0;i<n;i++)
	{
		cout.precision(2);
		cout<<a[i].no+1<<" "<<fixed<<a[i].money*1.0/100<<endl;
	}

	return 0;
}

嗯,看着简单了不少

多标准排序

STL中的仿函数

等于:equal_to<T>

不等于:not_equal_to<T>

大于:greater<T>

大于等于:greater_equal<T>

小于:less<T>

小于等于:less_equal<T>



猜你喜欢

转载自blog.csdn.net/qq_40729773/article/details/79690738