模拟 Minimum Distance in a Star Graph


转自http://www.mamicode.com/info-detail-2019082.html


#include<bits/stdc++.h>
using namespace std;
map<char, int> pos;
char st[11], en[11];
int n;
bool OK()
{
    for(int i=0; i<n; i++){
        if(st[i] != en[i])
            return false;
    }return true;
}
int main(void)
{
    scanf("%d", &n);
    for(int t=1; t<=5; t++){
        pos.clear();
        scanf("%s %s", st, en);
        for(int i=0; i<n; i++){
            pos[en[i]] = i;///记录每一个数字的在en的位置
        }
        int ans = 0;
        int p = 0;
        while(!OK()){///每一次检查一下序列是否已经变成了最终序列
            if(en[0] != st[0]){    //如果不相等,则肯定要先交换第一个,通过pos,把st第一个放回与en对应的位置
                swap(st[0], st[pos[st[0]]]);
                ans++;
            }else{//即使第一个相等了,后面也不一定相等,就又要和第一个交换,这样才符合规则
                for(int i=1; i<n; i++){
                    if(en[i] != st[i]){
                        swap(st[0], st[i]);
                        ans++;
                        break;
                    }
                }
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

posted @ 2018-04-08 21:37  LandingGuys  阅读(122)  评论(0)    收藏  举报