付忠慶的練習小筆記-Codeforces #277 Div2 C

原題連接ios

http://codeforces.com/contest/486/problem/Cspa

這個C題顯然更水一些指針

步數能夠分爲兩種 上下一種 左右一種code

總步數最小 = 上下最小+左右最小blog

先討論上下最小 就是從兩個方向去由字母1到字母2  min(dis(A,B),26-dis(A,B));ci

而後討論左右最小 pos是起始指針的位置io

1-統一在前半段操做,pos要是在後半段就「映射」到前半段,pos=n+1-pos;class

2-若上下操做爲0 那麼左右直接也是0test

3-找出左邊第一個操做l 右邊第一個操做rstream

      一, 如果 pos<l<r   返回 r-pos

  二,  如果 l<r<pos 返回 pos-l

  三,如果 l<pos<r  返回 min(r-pos,pos-l);

 

 

結束

附代碼:

 1 #include <iostream>
 2 #include <cmath>
 3 typedef long long LL;
 4 using namespace std;
 5 int a[110000],f[100000];
 6 
 7 int main()
 8 {
 9     int n,pos;
10     while (cin>>n>>pos)
11     {
12         if (pos>n/2) pos=n+1-pos;
13         LL ans=0;
14         char temp;
15         for (int i=1;i<=n;i++)
16         {
17             cin>>temp;
18             a[i]=temp-'a'+1;
19         }
20         for (int i=1;i<=n/2;i++)
21         {
22             int dis = abs(a[i]-a[n-i+1]);
23             f[i]=min(dis,26-dis);
24             ans+=f[i];
25         }
26         if (ans==0) {cout<<0<<endl;continue;}
27         int l=1,r=n/2;
28         while(!f[l++]&&l<=r);
29         l--;
30         while(!f[r--]&&l<=r);
31         r++;
32         if (pos>r) ans+=pos-l;
33         if (pos<l) ans+=r-pos;
34         if (pos<=r&&pos>=l) ans+=(r-l)+min(r-pos,pos-l);
35         cout<<ans<<endl;
36     }
37     return 0;
38 }
相關文章
相關標籤/搜索