Chaos Strings BIT类似求逆序数

来源:互联网 发布:nginx lua 修改header 编辑:程序博客网 时间:2024/06/11 03:01

Runing on judge 1 5 9 28……Accepted

处理字符串,根据字符串的字典序对其进行赋予权值,接近a的权值大些,然后在按转置的字符串X' 对 X(原串)进行排序,再然后就是很裸的树状数组模板求逆序数了。



Little Lovro likes to play games with words. During the last few weeks he realized that some words don't like each other.


The words A and B don't like each other if the word A is lexicographically before the word B, but the word B' is lexicographically before the word A', where X' stands for the word X reversed (if X="kamen" then X'="nemak"). For example, the words "lova" and "novac" like each other, but the words "aron" and "sunce" don't like each other.

Given some set of the words, we define  the degree of chaos of the set as  the number of pairs of different words that don't like each other.

Write a program that, given a set of words, finds the chaos degree for the set.

 

Input

 

The first line of input contains an integer N, 2 ≤ N ≤ 100 000.

Each of the following N lines contains one word – a sequence of at most 10 lowercase letters of the English alphabet ('a'-'z'). There will be no two identical words in the set.

 

Output

 

The first and only line of output should contain a single integer – the chaos degree of the given set of words.


Note: use 64-bit signed integer type (int64 in Pascal, long long in C/C++).

 

Sample

input  2 lopta kugla  output  0input  4 lova novac aron sunce  output  3input  14 branimir vladimir tom kruz bred pit zemlja nije ravna ploca ko je zapalio zito  output  48


#define _CRT_SECURE_NO_WARNINGS#include <cstdio>#include <iostream>#include <cstring>#include <string>#include <algorithm> #define N 100007using namespace std;long long bit[N];int n;struct Str {char str[12];int p; //权重bool operator < (const Str rhs) const { //两字符串的逆串比较大小, z->aint len1 = strlen(str), len2 = strlen(rhs.str);while (len1 >= 0 && len2 >= 0) {if (str[len1] == rhs.str[len2])len1--, len2--;elsereturn (str[len1] > rhs.str[len2]); }return len1 >= len2;}}a[N];bool cmp(Str lhs, Str rhs) {return strcmp(lhs.str, rhs.str) > 0; //从大到小排序z->a}inline int lowbit(int x) {return x & (-x);}void add(int pos, int val) {while (pos <= n) {bit[pos] += val;pos += lowbit(pos);}}long long sum(int pos) {long long res = 0;while (pos > 0) {res += bit[pos];pos -= lowbit(pos);}return res;}int main(){while (~scanf("%d", &n)) {memset(bit, 0, sizeof bit);memset(a, 0, sizeof a);for (int i = 1; i <= n; ++i) {scanf("%s", a[i].str);}sort(a + 1, a + n + 1, cmp);for (int i = 1; i <= n; ++i)a[i].p = i;sort(a + 1, a + n + 1);long long ans = 0;for (int i = 1; i <= n; ++i) {ans += (i - sum(a[i].p) - 1);add(a[i].p, 1);}printf("%lld\n", ans);}return 0;}



原创粉丝点击