hdu_6095_思维题_贪心题

来源:互联网 发布:日本浴衣短款淘宝 编辑:程序博客网 时间:2024/06/03 16:59

Rikka with Competition

As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:

A wrestling match will be held tomorrow. n players will take part in it. The ith player’s strength point is ai.

If there is a match between the ith player plays and the jth player, the result will be related to |ai−aj|. If |ai−aj|>K, the player with the higher strength point will win. Otherwise each player will have a chance to win.

The competition rules is a little strange. Each time, the referee will choose two players from all remaining players randomly and hold a match between them. The loser will be be eliminated. After n−1 matches, the last player will be the winner.

Now, Yuta shows the numbers n,K and the array a and he wants to know how many players have a chance to win the competition.

It is too difficult for Rikka. Can you help her?
Input
The first line contains a number t(1≤t≤100), the number of the testcases. And there are no more than 2 testcases with n>1000.

For each testcase, the first line contains two numbers n,K(1≤n≤105,0≤K<109).

The second line contains n numbers ai(1≤ai≤109).
Output
For each testcase, print a single line with a single number – the answer.
Sample Input
2
5 3
1 5 9 6 3
5 2
1 5 9 6 3
Sample Output
5
1
Source
2017 Multi-University Training Contest - Team 5

任意两个人相比,相差大于K,分低的淘汰,否则两人都有可能赢,剩下的继续比,问有最多多少人可能赢?

从反面求,从小到大排,相差<=k,就有机会赢,否则剩下的人都会被淘汰;

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;typedef long long ll;ll num[(int)1e5+10];int main(){    int t;    while(cin>>t)    {        while(t--)        {            ll n,k,i;            cin>>n>>k;            for(i=0; i<n; i++)                scanf("%lld",num+i);            sort(num,num+n);           // for(i=0;i<n;i++)          //      cout<<num[i]<<endl;            ll ans=1;            for(i=n-1; i>0; i--)            {               //  puts("1111");                if(num[i]-num[i-1]<=k)                {                   // puts("%%%%%");                    ans++;                }                else                    break;            }           cout<<ans<<endl;        }    }    return 0;}