Author : Anwar Jahid Ruman Hossain
CSE, Batch - 6
BRUR.
Problem Statement : [ SPOJ ] MULTQ3 - Multiples of 3
Source : Light OJ
Category : Segment Tree
Algorithm : Segment Tree
Verdict : Time Limit Exceeded
- #include<bits/stdc++.h>
- using namespace std;
- #define ll long long int
- #define mx 100005
- int tree[mx*3][3];
- int arr[mx];
- void build_segment(int node,int left,int right){
- if(left==right){
- tree[node][0] = 1;
- tree[node][1] = 0;
- tree[node][2] = 0;
- return;
- }
- int mid=(left+right)/2;
- build_segment(node*2, left, mid);
- build_segment(node*2 + 1, mid+1, right);
- tree[node][0] = tree[node*2][0] + tree[node*2+1][0];
- tree[node][1] = tree[node*2][1] + tree[node*2+1][1];
- tree[node][2] = tree[node*2][2] + tree[node*2+1][2];
- }
-
- int query_seqment(int node,int left,int right,int ia,int ib){
- if(right < ia || left > ib)return 0;
- if(ia <= left && right <= ib){
- return tree[node][0];
- }
- int mid=(left+right)/2;
- int cnt = 0;
- cnt += query_seqment(node*2 + 1, mid+1, right, ia, ib);
- cnt += query_seqment(node*2, left, mid, ia, ib);
- return cnt;
- }
- void update_segment(int node,int left,int right, int ia,int ib){
- if(ia>right || ib<left)
- return;
- if(left==right){
- int tmp = tree[node][0];
- tree[node][0] = tree[node][1];
- tree[node][1] = tree[node][2];
- tree[node][2] = tmp;
- return;
- }
- int mid=(left+right)/2;
- update_segment(node*2,left,mid,ia,ib);
- update_segment(node*2+1,mid+1,right,ia,ib);
- tree[node][0] = tree[node*2][0] + tree[node*2+1][0];
- tree[node][1] = tree[node*2][1] + tree[node*2+1][1];
- tree[node][2] = tree[node*2][2] + tree[node*2+1][2];
- }
- int main(){
- ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
-
-
- int n,q;
- while(scanf("%d%d",&n,&q)!=EOF){
- build_segment(1,1,n);
- int op,ia,ib;
- for(int i=1;i<=q;i++){
- scanf("%d%d%d",&op,&ia,&ib);
- if(op==1)
- printf("%d\n",query_seqment(1,1,n,ia+1,ib+1));
- else if(op==0){
- update_segment(1,1,n,ia+1,ib+1);
- }
- }
- }
- return 0;
- }
No comments:
Post a Comment