Đề bài:
Thuật toán:
- Với C++ bạn có thể dùng sẵn CTDL Priority Queue (hàng đợi ưu tiên). Còn với Pascal thì bạn phải tự viết CTDL Heap
Code:
- C++ (xem)
#include
using namespace std;
const int MAXN = 20000;
string s;
priority_queue h;
char key;
int num, a[MAXN];
bool cmp(int a, int b) {
return (a > b);
}
int main() {
//freopen("test.inp","r",stdin);
//freopen("test.out","w",stdout);
// solve
getline(cin, s);
do {
key = s[0];
if (key == '+') {
s.erase(0,1);
num = atoi(s.c_str());
if (h.size()<15000) h.push(num);
} else if (!h.empty())
{
num = h.top();
while (!h.empty() && h.top()==num) h.pop();
}
getline(cin, s);
} while (s != "");
// pop
int res = 0;
while (!h.empty()) {
res++;
a[res] = h.top();
while (!h.empty() && h.top()==a[res]) h.pop();
}
// print
cout << res << endl;
for (int i = 1; i <= res; i++) cout << a[i] << endl;
return 0;
}
- Pascal (xem)
const fi='';
fo='';
maxn=15000+3;
var h:array[1..maxn] of longint;
i,j:longint;
res:array[0..maxn] of longint;
nh,n,ans:longint;
procedure swap(var x,y:longint);
var tg:longint;
begin
tg:=x;x:=y;y:=tg;
end;
procedure qs(l,r:longint);
var x,i,j:longint;
begin
i:=l;j:=r;
x:=res[(i+j) div 2];
repeat
while res[i]>x do inc(i);
while res[j]j;
if il then qs(l,j);
end;
procedure downheap(i:longint);
var j:longint;
begin
j:= i + i;
if j>nh then exit;
if (jh[i] then
begin
swap(h[i],h[j]);
downheap(j);
end;
end;
procedure upheap(i:longint);
var j:longint;
begin
j:=i div 2;
if i>1 then
if h[i]>h[j] then
begin
swap(h[i],h[j]);
upheap(j);
end;
end;
procedure push(x:longint);
begin
inc(nh);
h[nh]:=x;
upheap(nh);
end;
function pop:longint;
begin
pop:=h[1];
h[1]:=h[nh];
dec(nh);
downheap(1);
end;
procedure xuat;
begin
for i:=1 to n do
if res[i]<>res[i-1] then writeln(res[i]);
end;
procedure main;
var tam,s:string;
x,err:longint;
begin
assign(input,fi);reset(input);
assign(output,fo);rewrite(output);
while not seekeof(input) do
begin
readln(s);
if s[1]='+' then
begin
if nh<15000 then
begin
tam:=copy(s,2,length(s));
val(tam,x,err);
push(x);
end
end
ELSE
if nh>0 then
begin
if nh>0 then x:=pop;
while (nh>0) and (h[1]=x) do pop;
end;
end;
for i:=1 to nh do
begin
res[i]:=pop;
inc(n);
end;
qs(1,n);
res[0]:=-1;
for i:=1 to n do
if res[i]<>res[i-1] then inc(ans);
writeln(ans);
xuat;
close(input);close(output);
end;
begin
main;
end.
Speak Your Mind