题解:P15572 [USACO26FEB] Swap to Win B

· · 题解

P15572 [USACO26FEB] Swap to Win B 题解

一道简单的贪心+模拟。

目标就是把第一个字符串变成 t,打个比方:

t = "abc"
s[0] = "aaa"
s[1] = "bca"
- 先把 $s_1$ 的第一位和第二位交换,变成 `bca`, - 再把 $s_0$ 和 $s_1$ 的第二位交换,$s_0$ 变为 `aba`, - 接着把 $s_1$ 的第一位和最后一位交换,变成 `aac`, - 然后把 $s_1$ 的最后一位搬到 $s_0$,完成了。 换成输出: ``` 1 2 1 2 2 1 2 2 1 1 1 3 2 1 2 3 ``` 这表示: `1 x y z` 在第 $x$ 字符串中,把第 $y$ 个字符和第 $z$ 个字符的位置交换位置。 `2 x y z` 把第 $x$ 个字符串的第 $z$ 个字符和第 $y$ 个字符串的第 $z$ 个字符交换位置。 [AC代码](https://www.luogu.com.cn/record/270375619) ```c++ #include <bits/stdc++.h> using namespace std; #define N 1001 string s[N]; int ct[N][30]; struct cmd{ int type; int x; int y; int z; }; vector <cmd> op; void move(int type,int x,int y,int z){ op.push_back({type,x+1,y+1,z+1}); if(type==1) swap(s[x][y],s[x][z]); else{ ct[x][s[x][z]-'a']--; ct[y][s[y][z]-'a']--; swap(s[x][z],s[y][z]); ct[x][s[x][z]-'a']++; ct[y][s[y][z]-'a']++; } } void solve(){ int n,m; string t; cin>>n>>m>>t; for (int i=0;i<n;i++){ cin>>s[i]; } op.clear(); memset(ct,0,sizeof(ct)); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ ct[i][s[i][j]-'a']++; } } for(int i=0;i<m;i++){ if(s[0][i]!=t[i]){ for(int j=0;j<m;j++){ if(s[0][j]==t[i]&&s[0][j]!=t[j]){ move(1,0,i,j); break; } } } } for(int i=0;i<m;i++){ if(s[0][i]!=t[i]){ for(int j=1;j<n;j++){ if(ct[j][t[i]-'a']){ int c=int(find(s[j].begin(),s[j].end(),t[i])-s[j].begin()); move(1,j,i,c); move(2,0,j,i); break; } } } } int num=(int)op.size(); cout<<num<<'\n'; for(int i=0;i<num;i++){ cout<<op[i].type<<" "<<op[i].x<<" "<<op[i].y<<" "<<op[i].z<<endl; } } int main(){ ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); int t; cin>>t; while(t--) solve(); return 0; } ```