Optimal Subsequences (Easy Version)
题目:给一个序列从中抽出一部分数放在另一序列中,要求顺序仍是原序列的高低。给定数字K和pos求抽出K的序列使得:
1、序列的和最大
2、字典序最小(就是第一数尽可能小,相同则比较第二个,依次递推)
求满足这样的序列第pos个数是多少。
Input
The first line contains an integer nn (1≤n≤1001≤n≤100) — the length of the sequence aa.
The second line contains elements of the sequence aa: integer numbers a1,a2,…,an (1≤ai≤109).
The third line contains an integer m (1≤m≤100) — the number of requests.
The following mm lines contain pairs of integers kj and pos~j ~(1≤k≤n, 1≤posj≤kj) — the requests.
Output
输入m组pos的值,用换行间隔。
Examples
inputCopy
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
outputCopy
20
10
20
10
20
10
inputCopy
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
outputCopy
2
3
2
3
2
3
1
1
3
Note
In the first example, for a=[10,20,10]a=[10,20,10] the optimal subsequences are:
for k=1k=1: [20][20],
for k=2k=2: [10,20][10,20],
for k=3k=3: [10,20,10][10,20,10].
思路:原本以为是个动态规划的题目,本着暴力的原则去做。。。然后就没有然后了。
后来才知道是贪心思想:
对于一个序列从中取K个数使其和最大,在最大的前提下使得字典序最小,那么这k个数字一定是前K大个数字,所以我们就找到了这K个数的取值。但是为了字典序最小,我们必须当值越小时尽可能地应该放在越靠前。
#include<bits/stdc++.h>
#define x first
#define y second
using namespace std;
int n,pos,k,m;
pair<int,int>a[101],b[101];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++){
int tmp;
scanf("%d",&tmp);
a[i].x=-tmp;//将值按其相反数放入,使得值越大,越优先
a[i].y=i;//在值相同的情况下,下标越小越优先。
}
sort(a+1,a+1+n);
scanf("%d",&m);
for(int i=1;i<=m;i++){
scanf("%d%d",&k,&pos);
for(int i=1;i<=k;i++){
b[i].x=a[i].y;
b[i].y=-a[i].x;//恢复其值
}
sort(b+1,b+1+k);//恢复其在坐标轴的位置
printf("%d\n",b[pos].y);
}
}