【线段树】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;
}


全部评论

相关推荐

Yushuu:你的确很厉害,但是有一个小问题:谁问你了?我的意思是,谁在意?我告诉你,根本没人问你,在我们之中0人问了你,我把所有问你的人都请来 party 了,到场人数是0个人,誰问你了?WHO ASKED?谁问汝矣?誰があなたに聞きましたか?누가 물어봤어?我爬上了珠穆朗玛峰也没找到谁问你了,我刚刚潜入了世界上最大的射电望远镜也没开到那个问你的人的盒,在找到谁问你之前我连癌症的解药都发明了出来,我开了最大距离渲染也没找到谁问你了我活在这个被辐射蹂躏了多年的破碎世界的坟墓里目睹全球核战争把人类文明毁灭也没见到谁问你了😆
点赞 评论 收藏
分享
想去夏威夷的小哥哥在度假:5和6才是重点
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务