Codeforces 160C(腦洞)
問題描述:
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
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.
Input
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 %I64d specificator instead.
OutputIn the single line print two numbers — the sought k-th pair.
Example
2 4 2 1Output
2 2Input
3 2 3 1 5Output
1 3題目題意:給我們n個數,形成n*n個數對,按照字典序排序後第k個數是哪一個數對
題目分析:這道題目的關鍵是如果倆個數相等的時候,怎麼去找,所以我們需要記錄一下每一個數出現的個數,通過k的值我們可以找到第一個數,如果第一個數的個數不止一個,我們就需要(舉個例子)
1 1 3 k為5
首先k/3+1等於2那麼為1,但是1的個數有倆個,我們需要以倆個倆個的來找,因為(1,1) (1,1)一定是這樣往下面排的
程式碼如下:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const int maxn=1e5+100;
ll a[maxn],num[maxn];
int main()
{
ll n,k;
while (scanf("%lld%lld",&n,&k)!=EOF) {
for (int i=1;i<=n;i++) {
scanf("%lld",&a[i]);
}
sort (a+1,a+n+1);
for (int i=1;i<=n;i++) {
ll sum=0;
for (int j=i;j<=n;j++) {
if (a[i]==a[j]) sum++;
else break;
}
for (int j=i;j<=i+sum;j++) num[j]=sum;
i=i+sum-1;
}
ll pos;
if (k%n==0) pos=k/n;
else pos=k/n+1;
if (num[pos]==1) {
ll res=k-(pos-1)*n;
printf("%lld %lld\n",a[pos],a[res]);
}
else {
while (num[pos]==num[pos-1]&&a[pos]==a[pos-1]) pos=pos-1;
ll res=k-(pos-1)*n;
if (res%num[pos]==0) {
printf("%lld %lld\n",a[pos],a[res/num[pos]]);
}
else {
int cnt=1;
while (res-cnt*num[pos]>=0) cnt++;
printf("%lld %lld",a[pos],a[cnt]);
}
}
}
return 0;
}