强烈推荐,刷PTA的朋友都认识一下柳神–PTA解法大佬
本文由参考于柳神博客写成
还有就是非常非常有用的 算法笔记 全名是
算法笔记 上级训练实战指南 //这本都是PTA的题解
算法笔记
PS 今天也要加油鸭
题目原文
Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian – return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤105). Then N lines follow, each contains a command in one of the following 3 formats:
Push key
Pop
PeekMedian
where key
is a positive integer no more than 105.
Output Specification:
For each Push
command, insert key
into the stack and output nothing. For each Pop
or PeekMedian
command, print in a line the corresponding returned value. If the command is invalid, print Invalid
instead.
Sample Input:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
Sample Output:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
题目大意:
给一个栈
然后还有它的入栈和出栈操作.
还有一个PeekMedian命令要你算出当前的中位数.
如果栈中没有元素,那么就输出Invalid
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 10010;
const int maxv = 110;
int w[maxn], dp[maxv] = { 0 }; //w[i]为钱币的价值
bool choice[maxn][maxv], flag[maxn];
bool cmp(int a, int b) {
return a > b;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <=n; ++i) {
scanf("%d", &w[i]);
}
sort(w + 1, w + n + 1, cmp);
for (int i = 1; i <= n; ++i) {
for (int v = m; v >= w[i]; v--) {
//状态转移方程
if (dp[v] <= dp[v - w[i]] + w[i]) { //等于时也要饭
dp[v] = dp[v - w[i]] + w[i];
choice[i][v] = 1; //放入第i件物品
}
else
choice[i][v] = 0; //不放入第i件物品
}
}
if (dp[m] != m) printf("No Solution"); //无解
else {
//记录最优路径
int k = n, num = 0, v = m;
while (k >= 0) {
if (choice[k][v] == 1) {
flag[k] = true;
v -= w[k];
num++;
}
else
flag[k] = false;
k--;
}
for (int i = n; i >= 1; i--) {
if (flag[i] == true) {
printf("%d", w[i]);
num--;
if (num > 0)printf(" ");
}
}
}
return 0;
}