POJ 3253 Fence Repair

哈夫曼思想,优先队列解决

手打版

就把上一篇堆的代码做了点改动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*
poj 3253
368K 47MS
*/

#include<map>
#include<set>
#include<list>
#include<queue>
#include<stack>
#include<ctime>
#include<cmath>
#include<string>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>

#define MAXN 30005
#define MAX_INT 2147483647
#define FA(x) (x>>1)
#define LC(x) ((x<<1))
#define RC(x) ((x<<1)|1)
#define MID(x,y) ( (x + y) >> 1 )
#define TIME_BEGIN double t1 = clock()
#define TIME_END double t2 = clock();printf("\n%.2lfms\n",t2-t1)

using namespace std;

int size,top = 1;
__int64 heap[MAXN];

bool cmp(__int64 a,__int64 b)
{
return a < b;
}

void up(int id)
{
if(id == 1)
return ;
if(!cmp(heap[FA(id)] , heap[id]))
{
swap(heap[FA(id)] , heap[id]);
up(FA(id));
}
}

void down(int id)
{
if(RC(id) <= size)
{
if(cmp(heap[LC(id)] , heap[RC(id)]) && cmp(heap[LC(id)] , heap[id]))
{
swap(heap[LC(id)] , heap[id]);
down(LC(id));
}
else if(!cmp(heap[LC(id)] , heap[RC(id)]) && cmp(heap[RC(id)] , heap[id]))
{
swap(heap[RC(id)] , heap[id]);
down(RC(id));
}
}
else if(LC(id) <= size)
{
if(cmp(heap[LC(id)] , heap[id]))
{
swap(heap[LC(id)] , heap[id]);
down(LC(id));
}
}
}

void insert(__int64 t)
{
heap[++size] = t;
up(size);
}

__int64 dele()
{
__int64 tmp = heap[top];
if(RC(top) <= size)
{
if(heap[LC(top)] < heap[RC(top)])
{
tmp += heap[LC(top)];
heap[LC(top)] = heap[size--];
down(LC(top));
}
else
{
tmp += heap[RC(top)];
heap[RC(top)] = heap[size--];
down(RC(top));
}
heap[top] = tmp;
down(top);
}
else
{
size --;
tmp += heap[LC(top)];
}
return tmp;
}

void print(int num)
{
int k = 1,cnt = 0,kk = 0;
while(num)
{
num -= k;
while(kk < k)
{
cnt ++; kk ++;
cout<<heap[cnt]<<" ";
}
kk = 0;
cout<<endl;
k = min(k<<1, num);
}
}

int main()
{
__int64 sum = 0;
freopen("./3253.in" , "r" , stdin);
int n;
cin>>n;
if(n == 1)
{
cout<<0<<endl;
return 0;
}
while(n--)
{
int t;
scanf("%d",&t);
insert(t);
}
while(size > 1)
{
sum+= dele();
}
cout<<sum<<endl;
return 0;
}

STL偷懒版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
poj 3253
324K 32MS
*/
#include<queue>
#include<cstdio>
using namespace std;
priority_queue<int>myQueue;
int main()
{
int n,t;
__int64 ans = 0;
scanf("%d",&n);
for(int i = 1;i <= n;i ++)
{
scanf("%d",&t);t = -t;
myQueue.push(t);
}
while(myQueue.size() > 1)
{
__int64 t1 = myQueue.top();
myQueue.pop();
__int64 t2 = myQueue.top();
myQueue.pop();t1 += t2;ans += t1;
myQueue.push(t1);
}
printf("%I64d\n",-ans);
return 0;
}