[2020 winter gmoj1671] [] [Friendly Number of inclusion and exclusion]

Title Description

After successful completion of homework, Mirko feel very tired. So, he lists the number N, these numbers are some of his favorite number, some number was not like him.

He likes to be called the number on the number of friendship, if at least one of the two numbers the same number (not required in the same location), then these two numbers is the number of friendship right. Please help Mirko in this N-friendly find out how many count the number of pairs.

Entry

The first line of a positive integer N (1 <= N <= 1000000).

Next N rows, each row a positive integer in the range of between 1-1018. The number N of any two numbers are different.

Export

Only one line an integer number represents the number of pairs of friendship.
Here Insert Picture Description

analysis

Friendly Number for that is not friendly. .
This problem did not have violence. . By explaining that this problem is the inclusion-exclusion principle (the last Friends of the chain). Because up to more than 1,023 ((1 << 10) -1), an array of 1024 opened. Then the corresponding stored bit. Cycle a bit, do not do is 0, then determine i, j equal relationship, not equal direct ride. And on the last layer of the cycle, up high.
Note: When the final output to metaphysics ans / 2, I do not know why. . .

The Code

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
long long num[1024],n,s,f[1024],ans,sum;
int main()
{
	freopen("kompici.in","r",stdin);
	freopen("kompici.out","w",stdout);
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    	long long x,y,z; 
    	cin>>x;
    	z=0;
    	while(x>0)
    	{
    		y=x%10;
    		x=x/10;
    		z=z|(1<<y);
		}
		num[z]++;
	}
	for(int i=1;i<=1023;i++)
	{
		if(num[i]==0) continue;
		for(int j=1;j<=1023;j++)
		{
			if((i&j)!=0&&num[j]>0&&i!=j)
			{
				ans+=num[i]*num[j];
			}
		}
		ans+=num[i]*(num[i]-1);
	}
	cout<<ans/2;
	fclose(stdin);
	fclose(stdout);
    return 0;
}

Published 63 original articles · won praise 61 · views 5434

Guess you like

Origin blog.csdn.net/dglyr/article/details/104440610