PageRenderTime 25ms CodeModel.GetById 12ms app.highlight 11ms RepoModel.GetById 0ms app.codeStats 0ms

/180A.cpp

https://bitbucket.org/alculquicondor/codeforces
C++ | 100 lines | 87 code | 11 blank | 2 comment | 14 complexity | 7a9b0c1be6dd075718759fa8fac8d441 MD5 | raw file
  1#include<vector>
  2#include<iostream>
  3
  4using namespace std;
  5
  6struct cluster {
  7    int id, pos;
  8    cluster(int id, int pos) {
  9        this->id = id;
 10        this->pos = pos;
 11    }
 12    cluster() {}
 13};
 14
 15bool operator != (cluster a, cluster b) {
 16    return a.id!=b.id or a.pos!=b.pos;
 17}
 18
 19int n;
 20typedef pair<int,int> pii;
 21vector<vector<int> > file;
 22vector<cluster> disk;
 23vector<pii> ans;
 24
 25int firstempty;
 26
 27void find1stempty(int ini=0) {
 28    for(firstempty=ini; disk[firstempty]!=cluster(-1,-1); firstempty++);
 29//    cout<<"#"<<firstempty<<"\n";
 30}
 31
 32void moveone(int x,int y) {
 33    ans.push_back(pii(x,y));
 34//    cout<<"$"<<x<<" "<<y<<"\n";
 35    cluster ant = disk[x];
 36    disk[y] = ant;
 37    disk[x] = cluster(-1,-1);
 38    file[ant.id][ant.pos] = y;
 39}
 40
 41void desp(int x,int y) {
 42    if(firstempty>x) {
 43        moveone(x,firstempty);
 44        swap(firstempty,x);
 45    }
 46    for(int i=firstempty-1; i>=y; i--) {
 47        moveone(i,i+1);
 48        firstempty = i;
 49    }
 50    moveone(x,firstempty);
 51    find1stempty(y+1);
 52}
 53
 54void desp2(int x,int y) {
 55    moveone(x,firstempty);
 56    swap(firstempty,x);
 57    for(int i=firstempty+1; i<=y; i++) {
 58        moveone(i,i-1);
 59        firstempty = i;
 60    }
 61    moveone(x,y);
 62    find1stempty(y+1);
 63}
 64
 65int main() {
 66    int m;
 67    cin >> n >> m;
 68    file.resize(m);
 69    disk.assign(n,cluster(-1,-1));
 70    for(int i=0,tam; i<m; i++) {
 71        cin >> tam;
 72        file[i].resize(tam);
 73        for(int j=0; j<tam; j++) {
 74            cin >> file[i][j];
 75            file[i][j] --;
 76            disk[file[i][j]] = cluster(i,j);
 77        }
 78    }
 79    find1stempty();
 80
 81    for(int i=0,tam; i<m; i++) {
 82        if(firstempty<file[i][0]) {
 83            moveone(file[i][0],firstempty);
 84            find1stempty(file[i][0]+1);
 85        }
 86        tam = file[i].size();
 87        for(int j=1; j<tam; j++) {
 88            int x = file[i][j];
 89            int y = file[i][j-1];
 90            if(x>y+1)
 91                desp(x,y+1);
 92            else if(x<y+1)
 93                desp2(x,y);
 94        }
 95    }
 96    cout<<ans.size()<<endl;
 97    for(auto x:ans) {
 98        cout << x.first+1 << " " << x.second+1 << "\n";
 99    }
100}