luogu P1966 matches Fenwick tree line up in reverse order of discrete

pass

Intuitively we hope ai and bi as similar as possible. We make a bold guess, is not a sequence ranked i and b i of the sequence ranked one place is the best yet. Try a few sets of data found to be so

Let us seek to exchange the title number. And we now only care about the relative ranking, so the original value is not important. We put the original sequence of two discrete look, turned into 1-n.

It now becomes a demand, the number of columns of two 1-n, how many need to be exchanged in order to become the same sequence. Seem to have a conclusion, we have a sequence remain intact, so that another sequence to move closer, and transform two together, in the best case strategy, the number is the same.

That put a sequence into another sequence, the best to be exchanged several times it? We think of the reverse order, it is to assume that there are x reverse order, as long as we exchange x times, will be able to become a serial order. So if we have another sequence when ordered standard, to seek another sequence in reverse order of what is not is the answer.

A merge sort in sequence to a standard case, it is inconvenient to do reverse order. There is another way we seek to reverse, the reverse seek Fenwick tree right. Front to back scan sequence, for the current x, see tree array, [x, MAXN] how many number. Then position +1 x's. That this question is the same, just outside the nest a loc [] only, so the standard sequence to seek another reverse right. Because of Fenwick tree, to reverse it.

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 const int MAXN = 110000,mo = 99999997;
 5 int n,a[MAXN],b[MAXN],tp[MAXN],loc[MAXN],tre[MAXN],ans;
 6 int lowbit(int x)
 7 {
 8     return x & -x;
 9 }
10 int query(int x)
11 {
12     int res = 0;
13     for(;x;x -= lowbit(x))
14     {
15         res += tre[x];
16         res %= mo;
17     }
18     return res;
19 }
20 void add(int x)
21 {
22     for(;x <= n;x += lowbit(x)) 
23         tre[x]++;
24 }
25 int main()
26 {
27     scanf("%d",&n);
28     for (int i = 1;i <= n;i++)
29     {
30         scanf("%d",&a[i]);
31         tp[i] = a[i];
32     }
33     sort(tp + 1,tp + n + 1);
34     for (int i = 1;i <= n;i++) 
35         a[i] = lower_bound(tp + 1,tp + n + 1,a[i]) - tp;
36     for (int i = 1;i <= n;i++) 
37     {
38         scanf("%d",&b[i]);
39         tp[i] = b[i];
40     }
41     sort(tp + 1,tp + n + 1);
42     for (int i = 1;i <= n;i++) 
43     {
44         b[i] = lower_bound(tp + 1,tp + n + 1,b[i]) - tp;
45         loc[b[i]] = i;
46     }
47     for (int i = 1;i <= n;i++)
48     {
49         ans += query(n - loc[a[i]] + 1);
50         ans %= mo;
51         add(n - loc[a[i]] + 1);
52     }
53     printf("%d\n",ans);
54     return 0;
55 }

 

 

Guess you like

Origin www.cnblogs.com/iat14/p/11520215.html