Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
晒代码 纪念第一道线段树#include <iostream> #include <string.h> #include <stdio.h> #define MAXN 300000 using namespace std; void BuildTree (int a, int b); void Paint (int a, int b, int color, int index); void Calc (int a, int b, int index); void Combine (int index); void Combine (int index); void Down (int index); void GetRes (int x); int Begin[MAXN]; int End[MAXN]; int Left[MAXN]; int Right[MAXN]; int Count[MAXN]; int pos = 0; int total; int l, t, n; int main() { char cmd[3]; int ls, rs, color, tmp; cin>>l>>t>>n; BuildTree (1, l); while (n--) { scanf ("%s", cmd); scanf ("%d%d", &ls, &rs); if (ls > rs) { tmp = ls; ls = rs; rs = tmp; } if (cmd[0] == 'C') { scanf ("%d", &color); Paint (ls, rs, color, 1); } else { total = 0; Calc (ls, rs, 1); GetRes (total); } } return 0; } void BuildTree (int a, int b) { pos++; int v = pos; Begin[v] = a; End[v] = b; Count[v] = 1; if (b != a) { int mid = (b + a) / 2; Left[v] = pos + 1; BuildTree (a, mid); Right[v] = pos + 1; BuildTree (mid + 1, b); } } void Paint (int a, int b, int color, int index) { Down (index); int mid = (Begin[index] + End[index]) / 2; if (a <= Begin[index] && b >= End[index]) { Count[index] = color; } else { if (Count[index] != color) { if (Count[index] != -1) { Count[Left[index]] = Count[index]; Count[Right[index]] = Count[index]; Count[index] = -1; //mixed color } } if (a <= mid) { Paint (a, b, color, Left[index]); } if (b > mid) { Paint(a, b, color, Right[index]); } Combine (index); } } void Calc (int a, int b, int index) { Down (index); int mid = (Begin[index] + End[index]) / 2; if (a <= Begin[index] && b >= End[index] && Count[index] != -1) { total = (total | (1<<(Count[index] - 1))); } else { if (a <= mid) { Calc (a, b, Left[index]); } if (b > mid) { Calc (a, b, Right[index]); } Combine (index); } } void GetRes (int x) { int res = 0; while (x > 0) { res += (x % 2); x /= 2; } cout<<res<<endl; } void Down (int index) { if (Left[index] != 0) { if (Count[index] != -1) { Count[Left[index]] = Count[Right[index]] = Count[index]; } } } void Combine (int index) { if (Left[index] != 0) { if (Count[Left[index]] == Count[Right[index]] && Count[Left[index]]) { Count[index] = Count[Left[index]]; } else { Count[index] = -1; } } } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator