Topic links: https://vjudge.net/problem/CodeForces-266C
Title effect: a matrix of n * n, n-1 which has a '1', the rest is 0, there are two operations: a two-line exchange 1; 2 of a two-exchange. In both operations, all the transducer 1 to the main diagonal at all, i.e., i> j.
Analysis: Because there are the n-1 1, so there must be an all zero, to this column and the last column exchange, and then locate the line is present. 1, and the last line of the exchange, so put the problem is converted into a (n-1 ) * (n-1) among the matrix operations, can be resolved recursively.
Code:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 5, M = 1e5 + 5;
int n, cnt, mp[N][N];
struct node {
int op, x, y;
}ans[M];
void dfs(int num) {
if(num <= 1) return ;
int id, flag;
for(int j = 1; j <= num; j++) {
flag = 1;
for(int i = 1; i <= num; i++) {
if(mp[i][j]) {
flag = 0;
break;
}
}
if(flag) {
id = j;
break;
}
}
if(id != num) {
for(int i = 1; i <= num; i++) {
swap(mp[i][id], mp[i][num]);
}
ans[cnt].op = 2;
ans[cnt].x = id;
ans[cnt++].y = num;
}
for(int i = 1; i <= num; i++) {
flag = 0;
for(int j = 1; j <= num; j++) {
if(mp[i][j]) {
flag = 1;
break;
}
}
if(flag) {
id = i;
break;
}
}
if(id != num) {
for(int j = 1; j <= num; j++) {
swap(mp[id][j], mp[num][j]);
}
ans[cnt].op = 1;
ans[cnt].x = id;
ans[cnt++].y = num;
}
dfs(num - 1);
}
int main() {
int x, y;
scanf("%d", &n);
for(int i = 1; i < n; i++) {
scanf("%d %d", &x, &y);
mp[x][y] = 1;
}
cnt = 0;
dfs(n);
printf("%d\n", cnt);
for(int i = 0; i < cnt; i++)
printf("%d %d %d\n", ans[i].op, ans[i].x, ans[i].y);
return 0;
}