【CF1015B】Obtaining the String(模拟)
题意:
给定两个字符串,每次可以交换相邻两个字符,给出任意一组交换次数小于1e4的方案使得a串成为b串,输出交换的次数与位置,无解输出-1
n<=50
思路:每次找到第一个不相同的字符,从后面找到一个相同的换上来
若找不到相同的则输出-1
1 #include<cstdio> 2 #include<cstring> 3 #include<string> 4 #include<cmath> 5 #include<iostream> 6 #include<algorithm> 7 #include<map> 8 #include<set> 9 #include<queue> 10 #include<vector> 11 using namespace std; 12 typedef long long ll; 13 typedef unsigned int uint; 14 typedef unsigned long long ull; 15 typedef pair<int,int> PII; 16 typedef vector<int> VI; 17 #define fi first 18 #define se second 19 #define MP make_pair 20 21 const int N=1100; 22 int c[N]; 23 char a[N],b[N]; 24 int n; 25 26 int read() 27 { 28 int v=0,f=1; 29 char c=getchar(); 30 while(c<48||57<c) {if(c=='-') f=-1; c=getchar();} 31 while(48<=c&&c<=57) v=(v<<3)+v+v+c-48,c=getchar(); 32 return v*f; 33 } 34 35 int main() 36 { 37 //freopen("1.in","r",stdin); 38 //freopen("1.out","w",stdout); 39 scanf("%d",&n); 40 scanf("%s",b+1); 41 scanf("%s",a+1); 42 int flag=0; 43 for(int i=1;i<=n;i++) 44 if(a[i]!=b[i]) {flag=1; break;} 45 int ans=0; 46 int noans=0; 47 while(flag) 48 { 49 int k=0; 50 flag=0; 51 for(int i=1;i<=n;i++) 52 if(a[i]!=b[i]){k=i; flag=1; break;} 53 if(!k) break; 54 int f=0; 55 for(int i=k+1;i<=n;i++) 56 if(b[i]==a[k]){f=i; break;} 57 if((k)&&(!f)) {noans=1; break;} 58 else 59 { 60 for(int j=f-1;j>=k;j--) 61 { 62 c[++ans]=j; 63 char t=b[j+1]; 64 b[j+1]=b[j]; 65 b[j]=t; 66 } 67 } 68 } 69 if(noans) printf("-1"); 70 else 71 { 72 printf("%d\n",ans); 73 for(int i=1;i<=ans;i++) printf("%d ",c[i]); 74 } 75 return 0; 76 } 77
null