1. 程式人生 > >洛谷 P2926 [USACO08DEC]拍頭Patting Heads

洛谷 P2926 [USACO08DEC]拍頭Patting Heads

tdi -o etc lines time rmi cow ace birt

P2926 [USACO08DEC]拍頭Patting Heads

題目描述

It‘s Bessie‘s birthday and time for party games! Bessie has instructed the N (1 <= N <= 100,000) cows conveniently numbered 1..N to sit in a circle (so that cow i [except at the ends] sits next to cows i-1 and i+1; cow N sits next to cow 1). Meanwhile, Farmer John fills a barrel with one billion slips of paper, each containing some integer in the range 1..1,000,000.

Each cow i then draws a number A_i (1 <= A_i <= 1,000,000) (which is not necessarily unique, of course) from the giant barrel. Taking turns, each cow i then takes a walk around the circle and pats the heads of all other cows j such that her number A_i is exactly

divisible by cow j‘s number A_j; she then sits again back in her original position.

The cows would like you to help them determine, for each cow, the number of other cows she should pat.

今天是貝茜的生日,為了慶祝自己的生日,貝茜邀你來玩一個遊戲.

貝茜讓N(1≤N≤100000)頭奶牛坐成一個圈.除了1號與N號奶牛外,i號奶牛與i-l號和i+l號奶牛相鄰.N號奶牛與1號奶牛相鄰.農夫約翰用很多紙條裝滿了一個桶,每一張包含了一個不一定是獨一無二的1到1,000,000的數字.

接著每一頭奶牛i從柄中取出一張紙條Ai.每頭奶牛輪流走上一圈,同時拍打所有手上數字能整除在自己紙條上的數字的牛的頭,然後做回到原來的位置.牛們希望你幫助他們確定,每一頭奶牛需要拍打的牛.

輸入輸出格式

輸入格式:

  • Line 1: A single integer: N

  • Lines 2..N+1: Line i+1 contains a single integer: A_i

輸出格式:

  • Lines 1..N: On line i, print a single integer that is the number of other cows patted by cow i.

輸入輸出樣例

輸入樣例#1: 復制
5 
2 
1 
2 
3 
4 
輸出樣例#1: 復制
2 
0 
2 
1 
3 

說明

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

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

思路:用類似於歐拉篩法的東西去解決。刷表法就可以了。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,maxn;
int a[100010];
int ma[1000010],ans[1000100]; 
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        ma[a[i]]++;maxn=max(a[i],maxn);
    }
    for(int i=1;i<=maxn;i++){
        if(!ma[i])    continue;
        for(int j=i;j<=maxn;j+=i)
            ans[j]+=ma[i];
    }
    for(int i=1;i<=n;i++)
        cout<<ans[a[i]]-1<<endl;
} 

洛谷 P2926 [USACO08DEC]拍頭Patting Heads