問題 B: Moderate Differences--------------------思維(數學)

題目描述
There are N squares in a row. The leftmost square contains the integer A, and the rightmost contains the integer B. The other squares are empty.

Aohashi would like to fill the empty squares with integers so that the following condition is satisfied:

For any two adjacent squares, the (absolute) difference of the two integers in those squares is between C and D (inclusive).
As long as the condition is satisfied, it is allowed to use arbitrarily large or small integers to fill the squares. Determine whether it is possible to fill the squares under the condition.

Constraints
3≤N≤500000
0≤A≤109
0≤B≤109
0≤C≤D≤109
All input values are integers.
輸入
Input is given from Standard Input in the following format:

N A B C D
輸出
Print YES if it is possible to fill the squares under the condition; print NO otherwise.
樣例輸入 Copy
5 1 5 2 4
樣例輸出 Copy
YES
提示
For example, fill the squares with the following integers: 1, −1, 3, 7, 5, from left to right.

題意:
有N個格子排成一排,最左邊的裏面寫了數字A,最右邊的寫了數字B,中間的 格子都是空的。 你需要在中間的每個格子裏填上一個數字,使得這個序列中,任意相鄰兩個數 的差的絕對值在[C,D]之間。 問是否存在這樣一種可行的填數方案,輸出YES或者NO。

解析:

假設現在存在K個 C≤xi+1-xi≤D 因爲要滿足n-1個連續,所以一定有n-1-k個 -D≤xi+1-xi≤-C
又因爲 ∑(xi+1-xi)=xn-x1  即B-A 。我們把這些式子加起來求和
得到
左區間: K*C-(n-1-k)*d
右區間: K*D-(n-1-k)*C;

那麼就得到了  K*C-(n-1-k)*d≤B-A≤K*D-(n-1-k)*C

枚舉k就完事了

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n;
ll a,b,c,d;
int main()
{
    while(scanf("%lld",&n)==1)
    {
        scanf("%lld %lld %lld %lld",&a,&b,&c,&d);
        for(ll i=0;i<=n-1;i++)//因爲有可能存在0個C≤xi+1−xi≤D的式子
        {
            if((b-a)>=(i*c-(n-i-1)*d)&&(b-a)<=(i*d-(n-i-1)*c))
            {
                printf("YES");
                return 0;
            }
        }
    }
    printf("NO");
    return 0;
}
發佈了430 篇原創文章 · 獲贊 8 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章