40分,TLE三个

P1168 中位数

Surpersolo @ 2019-08-15 16:49:20

#include<bits/stdc++.h>
using namespace std;
long long n,k,a[10000005];
int main() {
cin>>n; 
    k=(n+1)/2;
    for(long long i=1; i<=n; i++)
    cin>>a[i];
    for(long long i=1; i<=2*k-1; i+=2) {
        sort(a+1,a+i+1);
        printf("%lld\n",a[(i+1)/2]);
    }
    return 0;
}

by Surpersolo @ 2019-08-15 16:49:58

大佬求助,这种写法过于简单


by Computer1828 @ 2019-08-15 17:02:15

,每次都排个序,难道不会超时??


by 学而思李老师 @ 2019-08-15 17:03:20

把sort移到for循环外面


by Surpersolo @ 2019-08-15 17:13:09

@社会我猪酐 还是会错的

by 学而思李老师 @ 2019-08-15 17:15:16

抱歉,我看错题了,这题我的方法是这样的:

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> a;
using namespace std;
int main(){
    int n, tmp;
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++){
        scanf("%d", &tmp);
        a.insert(upper_bound(a.begin(), a.end(), tmp), tmp);
        if(i % 2 == 1){
            printf("%d\n", a[(i - 1) / 2]);
        }
    }
    return 0;
}

by 学而思李老师 @ 2019-08-15 17:15:40

STL大法好


by Surpersolo @ 2019-08-15 17:27:03

@社会我猪酐 谢谢了,我看懂了

by Surpersolo @ 2019-08-15 17:28:07

我这是枚举了n遍,时间复杂度O(n^n),超了

|