【CSU 1756】Prime

http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1756

直接暴力O(n^2logn)过不了 两两算gcd

考虑每个数的范围[1,1000]统计一下即可O(1000^2*log(1000))

Notice:1与任何数互质,需要特判(自己与自己互质)

Code1 统计

// <1756.cpp> - Wed Oct 19 08:25:53 2016
// This file is made by YJinpeng,created by XuYike's black technology automatically.
// Copyright (C) 2016 ChangJun High School, Inc.
// I don't know what this program is.
 
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN=1001;
inline int gi() {
    register int w=0,q=0;register char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    if(ch=='-')q=1,ch=getchar();
    while(ch>='0'&&ch<='9')w=w*10+ch-'0',ch=getchar();
    return q?-w:w;
}
int a[MAXN];
int main()
{
    int T=gi();
    while(T--){
        int n=gi(),ans=0;
        memset(a,0,sizeof(a));
        for(int i=1;i<=n;i++)
            a[gi()]++; 
        for(int i=1;i<MAXN;i++)
            if(a[i])
                for(int j=i+1;j<MAXN;j++)
                    if(__gcd(i,j)==1)ans+=a[i]*a[j];
        ans+=a[1]>1?(a[1]-1)*a[1]/2:0;//this
        printf("%d\n",ans);
    }
    return 0;
}
 
View Code

Code2 vector 本以为记录一下哪些数出现过(结果发现数据水,还跑得慢一点)

// <1756.cpp> - Wed Oct 19 08:25:53 2016
// This file is made by YJinpeng,created by XuYike's black technology automatically.
// Copyright (C) 2016 ChangJun High School, Inc.
// I don't know what this program is.

#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN=1001;
inline int gi() {
    register int w=0,q=0;register char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    if(ch=='-')q=1,ch=getchar();
    while(ch>='0'&&ch<='9')w=w*10+ch-'0',ch=getchar();
    return q?-w:w;
}
int a[MAXN];vector<int>b;
inline int gcd(register int a,register int b){
    return b==0?a:gcd(b,a%b);
}
int main()
{
    freopen("1756.in","r",stdin);
    freopen("1756.out","w",stdout);
    int T=gi();
    while(T--){
        int n=gi(),ans=0,to;
        memset(a,0,sizeof(a));
        for(int i=1;i<=n;i++)
            a[gi()]++;b.clear();
        for(int i=1;i<MAXN;i++)
            if(a[i])b.push_back(i);to=b.size();
        for(int i,o=0;i=b[o],o<to;o++)
            if(a[i])
                for(int j,k=o+1;j=b[k],k<to;k++)
                    if(gcd(i,j)==1)ans+=a[i]*a[j];
        if(b[0]==1)ans+=a[1]>1?(a[1]-1)*a[1]/2:0;//this
        printf("%d\n",ans);
    }
    return 0;
}
View Code

 

posted @ 2016-10-19 20:29  _Mashiro  阅读(134)  评论(0编辑  收藏  举报