時間限制: 2 Sec 內存限制: 256 MB
題目描述
There are N boxes arranged in a circle. The i-th box contains Ai stones.
Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:
Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-th box. Here, the (N+k)-th box is identified with the k-th box.
Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.
Constraints
1≤N≤105
1≤Ai≤109
輸入
The input is given from Standard Input in the following format:
N
A1 A2 … AN
輸出
If it is possible to remove all the stones from the boxes, print YES. Otherwise, print NO.
樣例輸入
5
4 5 1 2 3
樣例輸出
YES
提示
All the stones can be removed in one operation by selecting the second box.
題目大概是說有n個盒子連成一個環,每次從某一個盒子裏拿走1個石頭,從後一個盒子裏拿走2個石頭,以此類推,到從選定的盒子的前一個拿走n個石頭爲止,問有沒有方案能將所有石頭恰好拿走。
我的思路是考慮比較第i個盒子與第(i+1)個盒子,只有兩種可能,一種是從第i個盒子裏拿走j個石頭,並且從第(i+1)個盒子拿走(j+1)個石頭(j!=n),另一種是從第i個盒子裏拿走n個石頭,並且從第(i+1)個盒子拿走1個石頭。執行一次第一種操作,會使a(i+1)-ai==1;執行一次第二種操作,會使a(i+1)-ai==1-n。因爲每執行一次操作,會減少(n+1)*n/2個石子,所以我們可以算出執行操作的次數,設其爲m,設對第i個盒子執行了(m-k)次第一種操作,進行了k次第二種操作,那麼a(i+1)-ai==(m-k)*1+k*(1-n),化簡後得a(i+1)ai==m-nk,進一步求出k,k即爲從第ai個盒子拿走一個石頭的操作數,那麼將所有的k加在一起,即爲從某個盒子裏拿走一個石頭的操作數,即爲總操作數。如果滿足這些條件,則一定可以保證有恰好將所有石頭拿走的方案,如果不滿足,則一定沒有。
#include <bits/stdc++.h>
int main()
{
long long a[100005]={0};
long long i,k,n,m,sum=0;
int flag=1;
scanf("%lld",&n);
for (i=0;i<n;i++)
{
scanf("%lld",a+i);
sum+=a[i];
}
if (sum%(n*(n+1)/2))
flag=0;
else
{
m=2*sum/n/(n+1);
if ((m-a[0]+a[n-1])%n) //是環所以對第一個和最後一個進行單獨處理
flag=0;
else
{
k=(m-a[0]+a[n-1])/n;
for (i=1; i<n; i++)
{
if ((m-a[i]+a[i-1])%n||m<a[i]-a[i-1])
{
flag=0;
break;
}
k+=(m-a[i]+a[i-1])/n;
}
}
}
if (k!=m)
flag=0;
if (flag)
printf("YES\n");
else
printf("NO\n");
return 0;
}
|