標籤:
血的教訓:
1. 盡信題解,不如無題解!
2. C++ STL很坑爹。。
測試結果分析與比較:
#1是我自己寫的,使用priority_queue,超記憶體:
#include <cstdio>#include <cstring>#include <algorithm>#include <queue>using namespace std;priority_queue <unsigned int> pq;int main(){ unsigned int n,i,x,s1,s2; scanf("%d",&n); if(n % 2 != 0){ for(i=1;i<=n;i++){ scanf("%d",&x); pq.push(x); if(pq.size() == n/2+2){ pq.pop(); } } printf("%.1lf\n",(double)pq.top()); } else{ for(i=1;i<=n;i++){ scanf("%d",&x); pq.push(x); if(pq.size() == n/2+2){ pq.pop(); } } s1 = pq.top(); pq.pop(); s2 = pq.top(); printf("%.1lf\n",(double)(s1+s2)/2); } return 0;}
#2 from PegasusWang http://www.cnblogs.com/PegasusWang/archive/2013/03/23/2977597.html
使用priority_queue,同樣超記憶體
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue> //for priority_queue
using namespace std;
int main()
{
priority_queue<unsigned int> ipq;
int n;
scanf("%d", &n);
unsigned int t;
for (int i = 1; i <= n / 2 + 1; ++i)
{
scanf("%u", &t);
ipq.push(t);
}
int tn = n / 2 + 2;
while (tn <= n)
{
scanf("%u", &t);
ipq.push(t);
++tn;
ipq.pop();
}
if (n & 1) //if n is odd
printf("%u.0\n", ipq.top());
else
{
int t1 = ipq.top();
ipq.pop();
printf("%.1f", (double)(t1 + ipq.top()) / 2);
}
return 0;
}
#3 from 不許偷懶啦小鬼 http://blog.csdn.net/yujuan_mao/article/details/7985424
使用priorty_queue,還是超記憶體
#include<cstdio>#include<iostream>#include<queue>#include<vector>#include<algorithm>using namespace std;int main(){ unsigned int n,temp,i,j,k,m,x,y; priority_queue<unsigned int,vector<unsigned int>,greater<unsigned int> > Q; cin>>n; for(i=0;i<n;i++){ scanf("%u",&m); Q.push(m); if(Q.size()>(n/2+1)) Q.pop(); } if(n%2) printf("%.1lf\n",1.0*Q.top()); else{ x=Q.top(); Q.pop(); y=Q.top(); printf("%.1lf\n",1.0*(x+y)/2); } return 0;}
#4 from http://www.zgxue.com/163/1639818.html
使用數組和堆,AC
#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <vector>#include <queue>using namespace std;const int maxn=250000;int a[maxn/2+10];int main(){ int n;double ans; while(scanf("%d",&n)!=EOF) { int num=0,x; for(int i=0;i<n/2+1;i++) scanf("%d",&a[i]); make_heap(a,a+n/2+1); for(int i=n/2+1;i<n;i++) { scanf("%d",&x); if(x<a[0]) { pop_heap(a,a+n/2+1); a[n/2]=x; push_heap(a,a+n/2+1); } } if(n%2) { ans=(double)a[0]; printf("%.1lf\n",ans); } else { ans=(double)a[0]; pop_heap(a,a+n/2+1); ans+=(double)a[0]; printf("%.1lf\n",ans/2.0); } } return 0;}
The standard container adaptor priority_queue calls make_heap, push_heap and pop_heap automatically to maintain heap properties for a container.
[Ural1306] Sequence Median(網上很多題解騙人,這才是對的!業界良心!)