/180A.cpp
https://bitbucket.org/alculquicondor/codeforces · C++ · 100 lines · 87 code · 11 blank · 2 comment · 14 complexity · 7a9b0c1be6dd075718759fa8fac8d441 MD5 · raw file
- #include<vector>
- #include<iostream>
- using namespace std;
- struct cluster {
- int id, pos;
- cluster(int id, int pos) {
- this->id = id;
- this->pos = pos;
- }
- cluster() {}
- };
- bool operator != (cluster a, cluster b) {
- return a.id!=b.id or a.pos!=b.pos;
- }
- int n;
- typedef pair<int,int> pii;
- vector<vector<int> > file;
- vector<cluster> disk;
- vector<pii> ans;
- int firstempty;
- void find1stempty(int ini=0) {
- for(firstempty=ini; disk[firstempty]!=cluster(-1,-1); firstempty++);
- // cout<<"#"<<firstempty<<"\n";
- }
- void moveone(int x,int y) {
- ans.push_back(pii(x,y));
- // cout<<"$"<<x<<" "<<y<<"\n";
- cluster ant = disk[x];
- disk[y] = ant;
- disk[x] = cluster(-1,-1);
- file[ant.id][ant.pos] = y;
- }
- void desp(int x,int y) {
- if(firstempty>x) {
- moveone(x,firstempty);
- swap(firstempty,x);
- }
- for(int i=firstempty-1; i>=y; i--) {
- moveone(i,i+1);
- firstempty = i;
- }
- moveone(x,firstempty);
- find1stempty(y+1);
- }
- void desp2(int x,int y) {
- moveone(x,firstempty);
- swap(firstempty,x);
- for(int i=firstempty+1; i<=y; i++) {
- moveone(i,i-1);
- firstempty = i;
- }
- moveone(x,y);
- find1stempty(y+1);
- }
- int main() {
- int m;
- cin >> n >> m;
- file.resize(m);
- disk.assign(n,cluster(-1,-1));
- for(int i=0,tam; i<m; i++) {
- cin >> tam;
- file[i].resize(tam);
- for(int j=0; j<tam; j++) {
- cin >> file[i][j];
- file[i][j] --;
- disk[file[i][j]] = cluster(i,j);
- }
- }
- find1stempty();
- for(int i=0,tam; i<m; i++) {
- if(firstempty<file[i][0]) {
- moveone(file[i][0],firstempty);
- find1stempty(file[i][0]+1);
- }
- tam = file[i].size();
- for(int j=1; j<tam; j++) {
- int x = file[i][j];
- int y = file[i][j-1];
- if(x>y+1)
- desp(x,y+1);
- else if(x<y+1)
- desp2(x,y);
- }
- }
- cout<<ans.size()<<endl;
- for(auto x:ans) {
- cout << x.first+1 << " " << x.second+1 << "\n";
- }
- }