【bzoj1607】 [Usaco2008 Dec]Patting Heads 輕拍牛頭

Description

  今天是貝茜的生日,爲了慶祝自己的生日,貝茜邀你來玩一個遊戲.
    貝茜讓N(1≤N≤100000)頭奶牛坐成一個圈.除了1號與N號奶牛外,i號奶牛與i-l號和i+l號奶牛相鄰.N號奶牛與1號奶牛相鄰.農夫約翰用很多紙條裝滿了一個桶,每一張包含了一個獨一無二的1到1,000,000的數字.
    接着每一頭奶牛i從柄中取出一張紙條Ai.每頭奶牛輪流走上一圈,同時拍打所有編號能整除在紙條上的數字的牛的頭,然後做回到原來的位置.牛們希望你幫助他們確定,每一頭奶牛需要拍打的牛.

Input

    第1行包含一個整數N,接下來第2到N+1行每行包含一個整數Ai.

Output

 
    第1到N行,每行的輸出表示第i頭奶牛要拍打的牛數量.

Sample Input

5 //有五個數,對於任一個數來說,其它的數有多少個是它的約數
2
1
2
3
4

INPUT DETAILS:

The 5 cows are given the numbers 2, 1, 2, 3, and 4, respectively.

Sample Output

2
0
2
1
3

OUTPUT DETAILS:

The first cow pats the second and third cows; the second cows pats no cows;
etc.

【解析】

直接看代碼吧……

(這是暴力^_^)

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[110000],b[110000],s[110000];
int cmp(const void*xx,const void*yy)
{
    int n1=*(int *)xx;
    int n2=*(int *)yy;
    if(n1>n2) return 1;
    if(n1<n2) return -1;
    return 0;
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){scanf("%d",&a[i]);b[i]=a[i];}
    qsort(b+1,n,sizeof(int ),cmp);
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(b[j]>a[i]) break;
            if(a[i]%b[j]==0) s[i]++;
        }
    }
    for(int i=1;i<=n;i++) printf("%d\n",s[i]-1);
    return 0;
}

(這是正解)

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[110000],s[1100000],v[1100000];
int main()
{
	int n,maxx=-1;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		v[a[i]]++;
		maxx=max(maxx,a[i]);
	}
	for(int i=1;i<=maxx;i++)
	{
		if(v[i]!=0)//有i這個數 
		{
			for(int j=i;j<=maxx;j+=i)
			{
				s[j]+=v[i];//j能除i就累計j的答案 
			}
		}
	}
	for(int i=1;i<=n;i++) printf("%d\n",s[a[i]]-1);//自己也能除自己,把自己減掉 
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章