Va 1442: Cave (Greedy)

Source: Internet
Author: User

The length of a cave is N. It tells you the height of the ground and the height of the top of each position, so that you can fill the water in it, so that the water cannot touch the ceiling (but it can be infinitely close ). The maximum amount of water. (Both sides of the cave are regarded as closed)

Idea: If you know how high a position can look to the left, and how high it can be to the right, you can know the final height of this position. The method is to scan twice. Define a previous maximum value for each scan. If the previous maximum value is higher than the current top, it is dropped to the top. If it is lower than the bottom, it will rise to the bottom (because the height behind it can be blocked by the bottom ). If it is in the middle, you do not need to change it.

Code:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define N 1000010int p[N];int s[N];int main() {    int t;    scanf("%d", &t);    while (t--) {        int n;        scanf("%d", &n);        for (int i = 0; i < n; i++) {            scanf("%d", &p[i]);        }        for (int i = 0; i < n; i++) {            scanf("%d", &s[i]);        }        int tmp = 0x3f3f3f3f;        for (int i = 0; i < n; i++) {            tmp = min(tmp, s[i]);            tmp = max(tmp, p[i]);            s[i] = tmp;        }        tmp = 0x3f3f3f3f;        for (int i = n-1; i >= 0; i--) {            tmp = min(tmp, s[i]);            tmp = max(tmp, p[i]);            s[i] = tmp;        }        int ans = 0;        for (int i = 0; i < n; i++) {            ans += s[i]-p[i];        }        printf("%d\n", ans);    }    return 0;}

 

Va 1442: Cave (Greedy)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.