2020 Southeast USA Regional 部分题解

A-Ant Typing

一开始我就想到用枚举,但是估算错了枚举的规模,算成了9^9,觉得枚举规模过大就放弃了。实际上只有9!种情况,大概三十多万种,也就是A(9,9)。stl中提供了一个生成字典序的函数next_permutation(),可以用这个函数来简化代码量。对于计算结果,无需每次遍历输入的字符串,只要记录从一个数字到另一个数字的次数即可,也就是cnt[i][j]表示从i到j的次数,然后根据生成的字典序列计算就好。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int cnt[10][10] = {0}; //cnt[i][j]记录蚂蚁从i+1到j+1的次数
    int ans = 100000000, temp;
    string str;
    vector<int> perm(10,0);
    cin >> str;

    for (int i = 1; i < str.size(); i++)//统计cnt
    {
        cnt[str[i - 1] - '0'][str[i] - '0']++;
    }

    for (int i = 1; i <= 9; i++) //perm[i]表示数字i在第perm[i]个位置
    {
        perm[i]=i;
    }

    do
    {
        temp = perm[str[0]-'0']-1;//蚂蚁一开始位于最左边,加上从最左边到第一个数字的距离
        for (int i = 1; i <= 9; i++)
        {
            for (int j = i + 1; j <= 9; j++)
            {
                temp += (cnt[i][j] + cnt[j][i]) * abs(perm[i]-perm[j]);
            }
        }
        if (temp < ans)
        {
            ans = temp;
        }
    } while (next_permutation(perm.begin()+1, perm.end()));
    ans += str.size();//每个位置都要停留一秒来敲击键盘
    cout << ans ;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值