PAT (Advanced Level) Practice - 1029 Median(25 分)

简介: PAT (Advanced Level) Practice - 1029 Median(25 分)

题目链接:点击打开链接

题目大意:两个序列合并,并输出合并后的中位数。

解题思路:


long int 数据(超过 INT_MAX)就默认为 INT_MAX,根据测试用例,最终答案不会是 long long 类型,否则就报“段错误”了,因为用的是优先队列,弹出。

当插入的个数超过中间个数值时,可以做弹出操作,最小的弹出。

注意:有可能第1序列个数很小,第2序列个数很大;也有可能反过来。

内存超限卡两种情况:i、所有数据存完;ii、数据类型太大。



MLE 代码(15分,最后一个点 MLE)

#include<bits/stdc++.h>
#include<cmath>
#define mem(a,b) memset(a,b,sizeof a);
#define INF 0x3f3f3f3f
#define MOD 1000000007
using namespace std;
typedef long long ll;
const int maxn=4*1e5+10;
int a[maxn];
int main()
{
    int n,l=0; scanf("%d",&n);
    for(int i=0;i<n;i++) scanf("%d",&a[l++]);
    scanf("%d",&n);
    for(int i=0;i<n;i++) scanf("%d",&a[l++]);
    sort(a,a+l);
    printf("%d\n",a[(l-1)/2]);
    return 0;
}

AC 代码

#include<bits/stdc++.h>
#include<cmath>
#define mem(a,b) memset(a,b,sizeof a);
#define INF 0x3f3f3f3f
#define MOD 1000000007
using namespace std;
typedef long long ll;
struct cmp
{
    bool operator()(int a,int b)
    {
        return a>b;
    }
};
priority_queue<int,vector<int>,cmp> pq;
int main()
{
    int n,mid,ans=0,sum=0,rs,st; scanf("%d",&n);
    ll a;
    ans=sum=n;
    for(int i=0;i<n;i++)
    {
        scanf("%lld",&a);
        if(a>INT_MAX) a=INT_MAX;
        pq.push(a);
    }
    scanf("%d",&n);
    sum+=n;
    mid=(sum-1)/2;
    st=sum-mid;
    while(ans>st)
    {
        ans--;
        pq.pop();
    }
    for(int i=0;i<n;i++)
    {
        scanf("%lld",&a);
        if(a>INT_MAX) a=INT_MAX;
        pq.push(a);
        ans++;
        if(ans>st) pq.pop();
    }
    printf("%d\n",pq.top());
    return 0;
}
目录
相关文章
|
存储 算法
PAT (Advanced Level) Practice 1046 Shortest Distance (20 分)
PAT (Advanced Level) Practice 1046 Shortest Distance (20 分)
99 0
PAT (Advanced Level) Practice 1046 Shortest Distance (20 分)
PAT (Advanced Level) Practice - 1122 Hamiltonian Cycle(25 分)
PAT (Advanced Level) Practice - 1122 Hamiltonian Cycle(25 分)
126 0
PAT (Advanced Level) Practice - 1012 The Best Rank(25 分)
PAT (Advanced Level) Practice - 1012 The Best Rank(25 分)
122 0
PAT (Advanced Level) Practice - 1118 Birds in Forest(25 分)
PAT (Advanced Level) Practice - 1118 Birds in Forest(25 分)
116 0
PAT (Advanced Level) Practice - 1060 Are They Equal(25 分)
PAT (Advanced Level) Practice - 1060 Are They Equal(25 分)
110 0
PAT (Advanced Level) Practice - 1095 Cars on Campus(30 分)
PAT (Advanced Level) Practice - 1095 Cars on Campus(30 分)
139 0
PAT (Advanced Level) Practice - 1147 Heaps(30 分)
PAT (Advanced Level) Practice - 1147 Heaps(30 分)
128 0
PAT (Advanced Level) Practice - 1087 All Roads Lead to Rome(30 分)
PAT (Advanced Level) Practice - 1087 All Roads Lead to Rome(30 分)
112 0
PAT (Advanced Level) Practice - 1145 Hashing - Average Search Time(25 分)
PAT (Advanced Level) Practice - 1145 Hashing - Average Search Time(25 分)
124 0
PAT (Advanced Level) Practice - 1130 Infix Expression(25 分)
PAT (Advanced Level) Practice - 1130 Infix Expression(25 分)
139 0