A - Inverse Pairs of Binary Strings Gym - 104397A

Given a set of n binary strings, each containing only the digits 00 and 11, you need to find an arrangement of these strings that minimizes the total number of inverse pairs in the final concatenated string. You may rearrange the strings in any order to achieve the minimum number of inverse pairs in the concatenated string.

Let's denote the i-th digit of the final concatenated string as si​. An inverse pair is defined as a pair of indices (i,j) such that isj​.

Input

The first line contains an integer n (1≤n≤106), indicating the number of binary strings.

Each of the next n lines contains a binary string. The sum of the lengths of all binary strings does not exceed 106106.

Output

Output a single integer representing the minimum number of inverse pairs.

Sample 1

Inputcopy Outputcopy
3
1
11
101
1

Note

For the sample, the final concatenated string with the minimum number of inverse pairs is 101111101111.

题意大概就是求合成字符串中的10的最小数量,意义0一定要尽量的靠前,按0的占比排序即可

官方题解

答案是按 0101 占比排序即可。
单个字符串内形成的逆序对个数是不随字符串顺序改变的,因此我们只需要最小化字符串间形成的逆序对。
考虑两个字符串 A, B 间的贡献,其中 A 包含 1 0 1  1 B 包含 x2 0 2  1
A B 前面,形成的逆序对数为 y1 x2 ,否则为 1 2
1 2  −  2 1  > 0  A 在前 B 在后形成逆序对少,否则 B 在前 A 在后形成逆序对少。
#include
#define int long long
using namespace std;
const int N=1e6+10;
int n;
struct node
{
    string s;
    double sum0;
}a[N];
bool cmp(node a,node b)
{
    return a.sum0>b.sum0;
}
int cnt;
signed main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i].s;
        cnt=0;
        for(int j=0;j

你可能感兴趣的:(数学建模)