TOJ4483: Common Digit Pairs

4483: Common Digit Pairs 分享至QQ空间

Time Limit(Common/Java):3000MS/9000MS     Memory Limit:65536KByte
Total Submit: 90            Accepted:14

Description

 

Given N integers,  output the number of different pairs that two numbers have common digits. For example, given 3 integers: 1 11 21, there are 3 common digit pairs: <1, 11>, <1, 21>, <11, 21>.

 

Input

 

The first line has a positive integer N (1 ≤ N ≤ 1,000,000), then follow N different positive integers in the next N lines, each integer is no more than 1018.

 

Output

 

Output the numbers of different common digit pairs.

 

Sample Input

3
1
11
21

Sample Output

 3

有相同字符就视为一对,问你有多少对,以下为n^2的超时代码

#include <stdio.h>
char s[1000006][20]; 
int main()
{int n;
scanf("%d",&n);
getchar();
for(int i=0;i<n;i++)
scanf("%s",s[i]);
int e=0,f;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++){
    f=0;
    for(int k=0;s[i][k];k++){
    for(int l=0;s[j][l];l++)
    if(s[i][k]==s[j][l]){
        e++;f=1;
        break;
    }
    if(f)break;}
}
    printf("%d",e);
    return 0;
}

 

位运算状态压缩就可以了的很短时间的代码

#include <stdio.h>
__int64 s[1024];
int a[10];
int main()
{
    int n;
    a[0]=1;
    for(int i=1; i<10; i++)
        a[i]=a[i-1]*2;
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        char c;
        bool b[10]= {0};
        while(c=getchar(),c!='\n')
        {
            b[c-48]=1;
        }
        int e=0;
        for(int k=0; k<10; k++)
            if(b[k])
                e+=a[k];
        s[e]++;
    }
    __int64 f=0;
    for(int i=1; i<1024; i++)
    {
        f+=s[i]*(s[i]-1)/2;
        for(int j=1; j<i; j++)
            if(i&j)
                f+=s[i]*s[j];
    }
    printf("%I64d",f);
    return 0;
}

 

posted @ 2017-12-15 10:15  暴力都不会的蒟蒻  阅读(456)  评论(0编辑  收藏  举报