其他分享
首页 > 其他分享> > 洛谷P2846 [USACO08NOV]光开关Light Switching

洛谷P2846 [USACO08NOV]光开关Light Switching

作者:互联网


洛谷P2846 [USACO08NOV]光开关Light Switching


标签


简明题意


思路


注意事项


总结


AC代码

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;

const int maxn = 1e5 + 10;

int n, m;

struct Node
{
   int l, r, num;
   bool on;
};

Node tree[maxn * 4];

void build(int o, int l, int r)
{
   tree[o].l = l, tree[o].r = r;
   if (l == r)
   	return;

   int mid = (l + r) / 2;
   build(o * 2, l, mid);
   build(o * 2 + 1, mid + 1, r);
}

void spread(int o)
{
   if (tree[o].on == 1)
   {
   	if (tree[o].l != tree[o].r)
   		tree[o * 2].on ^= tree[o].on, tree[o * 2 + 1].on ^= tree[o].on;
   		
   	tree[o].on = 0;
   	tree[o].num = tree[o].r - tree[o].l + 1 - tree[o].num;
   }
}

void update(int o)
{
   spread(o * 2), spread(o * 2 + 1);
   if (tree[o].l != tree[o].r)
   	tree[o].num = tree[o * 2].num + tree[o * 2 + 1].num;
}

void change(int o, int l, int r)
{
   spread(o);
   if (tree[o].l == l && tree[o].r == r)
   {
   	tree[o].on = 1;
   	return;
   }
   
   int mid = (tree[o].l + tree[o].r) / 2;
   if (r <= mid)
   	change(o * 2, l, r);
   else if (l > mid)
   	change(o * 2 + 1, l, r);
   else
   	change(o * 2, l, mid), change(o * 2 + 1, mid + 1, r);

   update(o);
}

int ask(int o, int l, int r)
{
   spread(o);
   if (tree[o].l == l && tree[o].r == r)
   	return tree[o].num;

   int mid = (tree[o].l + tree[o].r) / 2;
   if (r <= mid)
   	return ask(o * 2, l, r);
   else if (l > mid)
   	return ask(o * 2 + 1, l, r);
   return ask(o * 2, l, mid) + ask(o * 2 + 1, mid + 1, r);
}

void solve()
{
   scanf("%d%d", &n, &m);
   build(1, 1, n);

   while (m--)
   {
   	int opt, l, r;
   	scanf("%d%d%d", &opt, &l, &r);

   	if (opt == 0)
   		change(1, l, r);
   	else
   		printf("%d\n", ask(1, l, r));
   }
}

int main()
{
   //freopen("Testin.txt", "r", stdin);
   solve();
   return 0;
}

双倍经验

标签:洛谷,int,Light,tree,mid,return,spread,num,P2846
来源: https://blog.csdn.net/weixin_42431507/article/details/95004792