1. 程式人生 > 其它 >codeforces--以自我為中心的子陣列

codeforces--以自我為中心的子陣列

技術標籤:codeforces

  1. Egocentric Subarrays

inputstandard input
outputstandard output
You have an array a consisting of n positive integers, and an integer k.

You call a subarray an egocentric subarray if the difference between the maximum and minimum elements of the subarray is equal to k.

Recall that a subarray is a contiguous segment of elements of the original array, in order.

For example, if a=[5,4,1,2,3,6] and k=3, then [4,1], [4,1,2,3], and [3,6] are egocentric subarrays, while [5,4,1,2], [4,1,2,3,6], and [5] are not.

Your task is to find the number of egocentric subarrays in the array.

Input
The first line of input contains two space-separated integers n (1<=n<=100) and k (1<=k<=109): the length of the array, and the number to find if the difference is equal to, respectively.

The next line consists of n space-separated integers: the array elements (1<=ai<=109).

Output
Output the number of egocentric subarrays of the array.

Scoring
Full problem: 7 points
翻譯:

  1. 自我中心的子串 每test1秒的時間限制 每test256兆位元組的記憶體限制 inputstandard輸入 outputstandard輸出 你有一個數組a由n個正整數和一個整數k組成。
    如果一個子陣列的最大和最小元素之差等於k你就可以稱它為以自我為中心的子陣列。 回想一下,子陣列是原陣列元素的連續段。
    例如,如果a=[5,4,1,2,3,6],
    k=3,那麼[4,1,2,3],和[3,6]是自我中心子陣列,而[5,4,1,2,6],和[5]不是。
    您的任務是找到陣列中以自我為中心的子陣列的數量。 輸入 輸入的第一行包含兩個用空格分隔的整數n (1<=n<=100)和k
    (1<=k<=109):陣列的長度,以及查詢差值是否等於的數字。
    下一行由n個以空格分隔的整陣列成:陣列元素(1<=ai<=109)。 輸出 輸出陣列中以自我為中心的子陣列的數量。 得分
    完整題:7分

思路:

這個有點用三層迴圈,外層用size控制問題規模,第二層控制起始,第三層找當前子問題max與min,第三層迴圈結束就判斷max-min是否==k,是就ans++;
最終輸出ans!

ac code(7points):

#include<stdio.h>

int main()
{
    int n,k;
    scanf("%d %d",&n,&k);
    int a[n];

    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    int ans=0;
    int size;
    for(size=2;size<=n;size++){
        for(int i=0;i<=n-size;i++){
            int min=a[i];
            int max=a[i];
            for(int j=i;j<i+size;j++){
                if(max<a[j])max=a[j];
                if(min>a[j])min=a[j];
            }
            if(max-min==k)ans++;
        }
    }
    printf("%d\n",ans);
    return 0;
}