【偽模板】等差數列

來源:互聯網
上載者:User

標籤:一個   序列   代碼   namespace   code   ret   map   bit   cpp   

一個長度為 n 的序列,最少改變多少個數,使得其成為一個公差為 d 的等差序列。

題解:對於任意一個位置的數 a[ i ] ,如果這個數不變的話,那麼所有與它相差 \(k*d\) 的數都不需要改變。因此,有等式\(a[i]-a[j]=d*(i-j)\)成立時,這個數也不需要改變,左右移項整理得\(a[i]+i*d=a[j]+j*d\),可以用map記錄 \(a[i]-i*d\) 的數值,最後遍曆map取其最大值即可。
時間複雜度為\(O(n*logn)\)

代碼如下:

/*    這裡以公差等於1為例*/#include <bits/stdc++.h>using namespace std;const int maxn=1e5+10;int n;map<int,int> mp;int main(){    scanf("%d",&n);    for(int i=1;i<=n;i++){        int a;scanf("%d",&a);        mp[a-i]++;    }    int ans=0;    for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++)        ans=max(ans,it->second);    printf("%d\n",n-ans);    return 0;}

【偽模板】等差數列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.