题目:
方法:因为没有限制最小步骤数。而且数据量也不大。直接模拟即可。方法就是,先把最后一列换成不存在1的一列,再把最后一行换成存在1的一行。这样那个小的(n-1)*(n-1)的矩阵就能保证,最多存在(n-2)个1,方法也就一样了。
代码如下:
<pre name="code" class="cpp">#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <string>
using namespace std;
#define MAXN 1010
#define INF 1e9+7
#define MODE 1000000
struct res{
int op;
int x;
int y;
};
vector <res> r;
int a[MAXN][MAXN];
int cnt=0;
void solve(int n)
{
if(n==0)
return;
for(int j=n;j>=1;j--)
{
int ok=1;
for(int i=1;i<=n;i++)
{
if(a[i][j]==1)
{
ok=0;
break;
}
}
if(ok&&j!=n)
{
for(int i=1;i<=n;i++)
{
swap(a[i][j],a[i][n]);
}
res temp;
temp.op=2;
temp.x=j;
temp.y=n;
r.push_back(temp);
break;
}
if(ok&&j==n)
break;
}
for(int i=n;i>=1;i--)
{
int ok=0;
for(int j=1;j<=n;j++)
{
if(a[i][j]){
ok=1;
break;
}
}
if(ok&&n!=i){
for(int j=1;j<=n;j++)
swap(a[i][j],a[n][j]);
res temp;
temp.op=1;
temp.x=i;
temp.y=n;
r.push_back(temp);
break;
}
if(ok&&n==i)
break;
}
solve(n-1);
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
a[i][j]=0;
}
for(int i=0;i<n-1;i++)
{
int x,y;
scanf("%d%d",&x,&y);
a[x][y]=1;
}
solve(n);
cout<<r.size()<<endl;
for(int i=0;i<r.size();i++)
{
printf("%d %d %d\n",r[i].op,r[i].x,r[i].y);
}
}