# Bzoj 4371: [IOI2015]sorting排序 二分

 1 #include<cstdio>
2 #include<algorithm>
3 #define maxn 200050
4 using namespace std;
5 int n;
6 int v[maxn],now[maxn];
7 int a[maxn],b[maxn],x[maxn*3],y[maxn*3];
8 struct qnode{
9     int x,y;
10 }q[maxn*3];
11 int check(int m){
12     for (int i=0;i<n;i++)
13     b[i]=a[i],v[i]=0;
14     for (int i=1;i<=m;i++)
15     swap(b[x[i]],b[y[i]]);
16     int need=0;
17     for (int i=0;i<n;i++)
18     if (!v[i]){
19         int x=i;
20         while (!v[x]){
21             v[x]=1;
22             if (!v[b[x]]) {
23                 q[++need].x=b[x];
24                 q[need].y=b[b[x]];
25             }
26             x=b[x];
27         }
28     }
29     return need;
30 }
31 int main(){
32 //    freopen("game.in","r",stdin);
33 //    freopen("game.out","w",stdout);
34     scanf("%d",&n);
35     for (int i=0;i<n;i++)
36     scanf("%d",&a[i]),now[a[i]]=i;
37     int Q;
38     scanf("%d",&Q);
39     for (int i=1;i<=Q;i++)
40     scanf("%d%d",&x[i],&y[i]);
41     int l=0,r=Q;
42     while (l<=r){
43         int m=(l+r)>>1;
44         if (check(m)>m) l=m+1;else r=m-1;
45     }
46     int need=check(l);
47     printf("%d\n",l);
48     for (int i=1;i<=need;i++){
49         swap(a[x[i]],a[y[i]]);
50         now[a[x[i]]]=x[i];
51         now[a[y[i]]]=y[i];
52         printf("%d %d\n",now[q[i].x],now[q[i].y]);
53         swap(a[now[q[i].x]],a[now[q[i].y]]);
54         now[a[now[q[i].x]]]=now[q[i].x];
55         now[a[now[q[i].y]]]=now[q[i].y];
56     }
57     for (int i=need+1;i<=l;i++)
58     printf("0 0\n");
59     return 0;
60 }
4371

posted @ 2019-04-11 20:38  Bunnycxk  阅读(142)  评论(0编辑  收藏