fork download
  1. #include <iostream>
  2. #include <map>
  3. using namespace std;
  4.  
  5. struct node
  6. {
  7. int x,y;
  8. node(int x1,int y1)
  9. {
  10. x=x1;
  11. y=y1;
  12. }
  13. };
  14.  
  15. int main() {
  16.  
  17. int n,m;
  18. cin>>n>>m;
  19.  
  20. int a[n];
  21. int indices[n+1];
  22. for(int i=0;i<n;i++)
  23. {
  24. cin>>a[i];
  25. indices[a[i]]=i;
  26. }
  27.  
  28. int ans=1;
  29. for(int j=1;j<n;j++)
  30. {
  31. if(indices[j] > indices[j+1])
  32. {
  33. ans++;
  34. }
  35. }
  36. //cout<<"ans="<<ans<<endl;
  37.  
  38. for(int i=0;i<m;i++)
  39. {
  40. int x,y;
  41. cin>>x>>y;
  42.  
  43. x--;
  44. y--;
  45.  
  46. map<int,map<int,int> > updatedPairs;
  47. if(a[x]+1 <=n)
  48. {
  49. updatedPairs[a[x]][a[x]+1]=1;
  50. }
  51. if(a[x]-1 >=0)
  52. {
  53. updatedPairs[a[x]-1][a[x]]=1;
  54. }
  55. if(a[y]+1 <=n)
  56. {
  57. updatedPairs[a[y]][a[y]+1]=1;
  58. }
  59. if(a[y]-1 >=0)
  60. {
  61. updatedPairs[a[y]-1][a[y]]=1;
  62. }
  63.  
  64.  
  65. for(auto it=updatedPairs.begin();it!=updatedPairs.end();it++)
  66. {
  67. map<int,int> Map = it->second;
  68. for(auto it2=Map.begin();it2!=Map.end();it2++)
  69. {
  70. ans-=(indices[it->first] > indices[it2->first]);
  71. }
  72. }
  73.  
  74. //cout<<"ans="<<ans<<endl;
  75.  
  76. int temp = a[x];
  77. a[x] = a[y];
  78. a[y] = temp;
  79.  
  80. indices[a[x]]=x;
  81. indices[a[y]]=y;
  82.  
  83. for(auto it=updatedPairs.begin();it!=updatedPairs.end();it++)
  84. {
  85. map<int,int> Map = it->second;
  86. for(auto it2=Map.begin();it2!=Map.end();it2++)
  87. {
  88. ans+=(indices[it->first] > indices[it2->first]);
  89. }
  90. }
  91.  
  92. cout<<ans<<endl;
  93. }
  94.  
  95.  
  96.  
  97. return 0;
  98. }
Success #stdin #stdout 0.01s 5288KB
stdin
5 3
4 2 1 5 3
2 3
1 5
2 3
stdout
2
3
4