#27999: (問)如何寫出時間複雜度小的程式呢? C++


910580@mail.pcsh.ntpc.edu.tw (29劉佳翰)

學校 : 新北市立板橋高級中學
編號 : 163586
來源 : [114.24.177.219]
最後登入時間 :
2022-01-08 17:16:18
c508. 去蟲 | From: [114.24.231.31] | 發表日期 : 2021-11-08 21:38

我的部分程式碼如下,我評分結果是

AC (0.1s, 712KB)

可是排名內有人只用13ms完成,我幾乎是他的10倍時間,請問該如何修正?

sort 時間複雜度是多少? 高手又是用時間複雜度多少的甚麼方法呢?

bool compare(int a, int b) {

  return a > b;

}

int main()

{

    int n,ch;

    cin>>n;

    int arr[n];

    for(int i=0;i<n;i++){

        cin>>arr[i];

    }

    sort(arr,arr+n);

    for(int i=0;i<n;i++){

        cout<<arr[i]<<" ";

    }

    cout<<endl;

    sort(arr,arr+n,compare);

    for(int i=0;i<n;i++){

        if(ch!=arr[i]){

        cout<<arr[i]<<" ";

        }

        ch=arr[i];

    }

 
#28000: Re:(問)如何寫出時間複雜度小的程式呢? C++


910580@mail.pcsh.ntpc.edu.tw (29劉佳翰)

學校 : 新北市立板橋高級中學
編號 : 163586
來源 : [114.24.177.219]
最後登入時間 :
2022-01-08 17:16:18
c508. 去蟲 | From: [114.24.231.31] | 發表日期 : 2021-11-08 21:46

用加速器

std::ios::sync_with_stdio(false);

cin.tie(NULL);

之後結果

AC (67ms, 724KB)

快了約1倍,但依然比不上排行榜上的大大們

 
#28003: Re:(問)如何寫出時間複雜度小的程式呢? C++


linlincaleb@gmail.com (臨末之頌)

學校 : 新北市立板橋高級中學
編號 : 132772
來源 : [111.248.111.135]
最後登入時間 :
2023-04-01 22:41:13
c508. 去蟲 | From: [111.248.111.61] | 發表日期 : 2021-11-08 23:13

用加速器

std::ios::sync_with_stdio(false);

cin.tie(NULL);

之後結果

AC (67ms, 724KB)

快了約1倍,但依然比不上排行榜上的大大們

理念是:每次輸入一個數字N後,就把ar[N]++,複雜度O(N),可是陣列不能開那麼大,所以要離散化(或者hash table?)。我不確定hash table是否可行,但離散化是可以的

 
#35495: Re: (問)如何寫出時間複雜度小的程式呢? C++


jeremydingeric@gmail.com (164253)

學校 : 臺北市立成功高級中學
編號 : 158900
來源 : [140.116.1.143]
最後登入時間 :
2024-04-02 13:37:11
c508. 去蟲 | From: [36.230.201.58] | 發表日期 : 2023-06-04 22:30

我的部分程式碼如下,我評分結果是

AC (0.1s, 712KB)

可是排名內有人只用13ms完成,我幾乎是他的10倍時間,請問該如何修正?

sort 時間複雜度是多少? 高手又是用時間複雜度多少的甚麼方法呢?

bool compare(int a, int b) {

  return a > b;

}

int main()

{

    int n,ch;

    cin>>n;

    int arr[n];

    for(int i=0;i

        cin>>arr[i];

    }

    sort(arr,arr+n);

    for(int i=0;i

        cout<

    }

    cout<

    sort(arr,arr+n,compare);

    for(int i=0;i

        if(ch!=arr[i]){

        cout<

        }

        ch=arr[i];

    }

sort一次就好 第二行輸出用for(i=n-1;i>=0;--i)倒著輸出

然後不要用scanf printf 我是用自製緩衝區fread跟puts 14ms

可以看看pi的教學 https://horikitacoding.blogspot.com/2019/07/how-to-optimize-your-code-in-c.html

 
ZeroJudge Forum