牛客 - Pass Through With One Breath(中位数)
生活随笔
收集整理的這篇文章主要介紹了
牛客 - Pass Through With One Breath(中位数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個環,初始時每個數為 aia_iai?,現在可以對每個數執行加一或者減一的操作,問最少進行多少次操作可以使得整個環存在著一個起點,開始逐漸遞增
題目分析:因為 nnn 不算大,可以考慮枚舉起點,當起點確定后,又因為每個位置的偏移量都是確定的,所以不難求出對于每個位置而言最優的起點的取值,取這 nnn 位置的中位數作為最終的起點顯然是最優的,每次維護一下最小值作為答案就好了
代碼:
// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<unordered_map> using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e6+100; int a[N]; int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--){int n;read(n);for(int i=1;i<=n;i++) read(a[i]),a[i+n]=a[i];LL ans=1e18;for(int st=1;st<=n;st++)//枚舉起點{vector<int>node;for(int i=1;i<=n;i++) node.push_back(a[i+st-1]-i);nth_element(node.begin(),node.begin()+(n+1)/2-1,node.end());int num=node[(n+1)/2-1];LL res=0;for(auto it:node) res+=abs(it-num);ans=min(ans,res);}write(ans),putchar('\n');}return 0; }總結
以上是生活随笔為你收集整理的牛客 - Pass Through With One Breath(中位数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 897E Wi
- 下一篇: CodeForces - 724C Ra