题目链接:Minimum Distance in a Star Graph
思路:模拟,因为只能把后面的和第一个交换,所以当第一个不在其应在的位置时,把它放到应在的位置;当第一个已经在它应在的位置时,去后面一个不在正确位置的点和第一个交换……直到字符串完全匹配。
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#define Max(a,b) a>b?a:b
#define Min(a,b) a>b?b:a
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
const double eps = 1e-6;
const double Pi = acos(-1.0);
const int INF=0x3f3f3f3f;
int before[10];
int after[10];
map<int,int> mp;
map<int,int> mp2;
int n;
bool check(){
for(int i = 1; i <= n; i++){
if(before[i] != after[i]) return true;
}
return false;
}
int main(){
int a,b;
while(~scanf("%d",&n)){
int countt = 5;
while(countt--){
mem(before,0);
mem(after,0);
scanf("%d%d",&a,&b);
mp.clear();
mp2.clear();
for(int i = n; i >= 1; i--){
before[i] = a % 10;
mp[a%10] = i;
a /= 10;
after[i] = b % 10;
mp2[b%10] = i;
b /= 10;
}
int ans = 0;
int tmp;
int ind;
while(check()){
for(int i = 1; i <= n; i++){
if(before[i] != after[i]){
ans++;
if(i == 1) ind = mp2[before[1]];
else ind = i;
tmp = before[1];
mp[before[1]] = ind;
before[1] = before[ind];
mp[before[ind]] = 1;
before[ind] = tmp;
break;
}
}
}
printf("%d\n",ans);
}
}
return 0;
}