题目链接:登录—专业IT笔试面试备考平台_牛客网

|
| 3 |

暴力枚举,全部变成对应的26个字母字符需要的操作步数,取最少的一个操作步数,
这里的操作步数,是 环形 26 字母数组中 两个字符之间最短距离。
环形数组的两个元素之间的最短距离关系是
|
这里环形数组的大小是 26 。
- #include
- #include
- #include
- #include
- #include
- #define endl '\n'
- #define x first
- #define y second
- #define mk make_pair
- #define int long long
- #define NO puts("NO")
- #define YES puts("YES")
- #define umap unordered_map
- #define INF 0x3f3f3f3f3f3f3f3f
- #define All(x) (x).begin(),(x).end()
- #pragma GCC optimize(3,"Ofast","inline")
- #define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
- using namespace std;
- const int N = 2e6 + 10;
- using PII = pair<int,int>;
- inline void solve()
- {
- string s;
- int ans = INF; // ans 取正无穷,方便取 min
- cin >> s;
-
- // 遍历 26 个字母
- for(int i = 0;i < 26;++i)
- {
- int tem = 0; // 临时存储总距离
- // 全部字符变成 对应的字母
- for(char j : s)
- {
- int c = j - 'a'; // 对应字母
- int mid = abs(i - c); // 中间的距离
- int out = 26 - abs(i - c); // 全部距离 - 中间距离 == 外边距离
- int dis = min(mid,out);
- tem += dis;
- }
- ans = min(ans,tem); // 取最少总距离,即最少操作数
- }
- cout << ans << endl;
- }
- signed main()
- {
- // freopen("a.txt", "r", stdin);
- ___G;
- int _t = 1;
- // cin >> _t;
- while (_t--)
- {
- solve();
- }
-
- return 0;
- }
