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