【线段树】tyvj1038 & tyvj1039

读英语题读烦了于是去tyvj等做了几道中文题

这两道都是裸的线段树……没什么要说的,用来入门还是挺好的……


 tyvj1038:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
long n, m;
long tree[800100];
long a[100100];

long min(long a, long b)
{
    return (a > b ? b : a);
}
void build(long p, long l, long r)
{
    if (l == r) {tree[p] = a[l];return;}
    long mid = (l + r) / 2;
    build(p * 2, l, mid);
    build(p * 2 + 1, mid + 1, r);
    tree[p] = min(tree[p * 2], tree[p * 2 + 1]);
}
long find (long p, long l, long r, long x, long y)
{
    if ((x <= l) && (r <= y)) return tree[p];
    long mid = (l + r) / 2;
    if (mid >= y) return (find (p * 2, l, mid, x, y));
    if (x > mid ) return (find (p * 2 + 1, mid +1, r, x, y));
    long tl = find (p * 2, l, mid, x, y);
    long t2 = find (p * 2 + 1, mid +1, r, x, y);
    return (min(tl, t2));
}
int main()
{
    freopen("tyvj1038.in", "r", stdin);
    scanf("%d%d", &m, &n);
    for (long i = 1; i <= m; i++)
    {
        long t;
        scanf("%d", &a[i]);
    }
    build(1, 1, m);

    for (long j = 1; j <= n; j++)
    {
        long x, y;
        scanf("%d%d", &x, &y);
        printf("%d ",find(1, 1, m, x, y));
    }
    return 0;
}

tyvj1039:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
long n, m;
long tree[800100];
long a[100100];

long min(long a, long b)
{
    return (a > b ? b : a);
}
void build(long p, long l, long r)
{
    if (l == r) {tree[p] = a[l];return;}
    long mid = (l + r) / 2;
    build(p * 2, l, mid);
    build(p * 2 + 1, mid + 1, r);
    tree[p] = min(tree[p * 2], tree[p * 2 + 1]);
}
long find (long p, long l, long r, long x, long y)
{
    if ((x <= l) && (r <= y)) return tree[p];
    long mid = (l + r) / 2;
    if (mid >= y) return (find (p * 2, l, mid, x, y));
    if (x > mid ) return (find (p * 2 + 1, mid +1, r, x, y));
    long tl = find (p * 2, l, mid, x, y);
    long t2 = find (p * 2 + 1, mid +1, r, x, y);
    return (min(tl, t2));
}

void change(long p, long l, long r, long k, long x)
{
    if (l == r) {tree[p] = x;return;}
    long mid = (l + r) / 2;
    if (k <= mid) change(p * 2, l, mid, k, x);
        else change(p * 2 + 1, mid + 1, r, k, x);
    tree[p] = min(tree[p * 2], tree[p * 2 + 1]);

}
int main()
{
    freopen("tyvj1039.in", "r", stdin);
    scanf("%d%d", &m, &n);
    for (long i = 1; i <= m; i++)
    {
        long t;
        scanf("%d", &a[i]);
    }
    build(1, 1, m);

    for (long j = 1; j <= n; j++)
    {
        long t,x, y;
        scanf("%d%d%d", &t, &x, &y);
        if (t == 1) printf("%d ",find(1, 1, m, x, y));
            else change(1, 1, m, x, y);
    }
    return 0;
}


你可能感兴趣的:(【线段树】tyvj1038 & tyvj1039)