You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1 ≤ i, j ≤ n). In other words, let's consider all n2 pairs of numbers, picked from the given array.
For example, in sequence a = {3, 1, 5} are 9 pairs of numbers: (3, 3), (3, 1), (3, 5), (1, 3), (1, 1), (1, 5), (5, 3), (5, 1), (5, 5).
Let's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair (p1, q1) is lexicographically less than pair (p2, q2) only if either p1 < p2, or p1 = p2 and q1 < q2.
Then the sequence, mentioned above, will be sorted like that: (1, 1), (1, 3), (1, 5), (3, 1), (3, 3), (3, 5), (5, 1), (5, 3), (5, 5)
Let's number all the pair in the sorted list from 1 to n2. Your task is formulated like this: you should find the k-th pair in the ordered list of all possible pairs of the array you've been given.
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ n2). The second line contains the array containing n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). The numbers in the array can coincide. All numbers are separated with spaces.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout, streams or the %I64dspecificator instead.
In the single line print two numbers — the sought k-th pair.
2 4 2 1
2 2
3 2 3 1 5
1 3
In the first sample the sorted sequence for the given array looks as: (1, 1), (1, 2), (2, 1), (2, 2). The 4-th of them is pair (2, 2).
The sorted sequence for the array from the second sample is given in the statement. The 2-nd pair there is (1, 3).
题目大意:
给出长度为N的序列,每次从序列中取出两个位子的数,那么能够组成n^2个数对,我们将其按照字典序排序后,输出第K个数对。
思路:
①既然是组成n^2个数对,那么我们在操作之前,将序列排序是不会影响结果的。
②拍完序之后我们发现,如果整个序列没有重复的数字的话,我们第k个数对很好找,问题就在于有重复的数字的解决方法。
我们这里可以离散化一下,然后乱搞搞就行。
注意数据要用LL。
Ac代码:
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<map>
using namespace std;
#define ll __int64
int a[150000];
int have[150000];
int main()
{
ll n;
ll k;
while(~scanf("%I64d%I64d",&n,&k))
{
int cnt=0;
map<int,int>rs;
map<int,int>s;
memset(have,0,sizeof(have));
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
sort(a+1,a+1+n);
for(int i=1;i<=n;i++)
{
if(s[a[i]]==0)s[a[i]]=++cnt;
have[s[a[i]]]++;
rs[s[a[i]]]=a[i];
}
ll sum=0;
for(ll i=1;i<=n;i++)
{
if(have[i]==0)continue;
ll pre=sum;
sum+=have[i];
if(pre*n<=k&&sum*n>=k)
{
printf("%d ",rs[i]);
ll pos=0;
ll now=pre*n;
while(1)
{
pos++;
now+=have[i];
if(now>=k)
{
printf("%d\n",a[pos]);
break;
}
}
break;
}
}
}
}