P3531 [POI2012]LIT-Letters
很容易想到冒泡排序的交换次数为逆序对数,考虑此题如何定义“排序”,显然 $a$ 中第 $k$ 个某字母一定和 $b$ 中第 $k$ 个某字母对齐,然后直接求逆序对数。
查看代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <cstdio> #include <vector> using namespace std; typedef long long LL; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write(Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar(x % 10 + '0'); } const int N = 1e6 + 10; int n, w[N], tr[N]; char s[N], t[N]; void modify (int x) { for (; x <= n; x += x & -x) tr[x]++; } int query (int x) { int res = 0; for (; x; x -= x & -x) res += tr[x]; return res; } int main () { read(n); scanf("%s%s", s + 1, t + 1); static int cnt[26]; vector <int> p[26]; for (int i = 1; i <= n; i++) p[t[i] - 'A'].push_back(i); for (int i = 1; i <= n; i++) w[i] = p[s[i] - 'A'][cnt[s[i] - 'A']++]; LL res = 0; for (int i = n; i; i--) { res += query(w[i]); modify(w[i]); } write(res); return 0; }
|