2013/08/09

SPOJ: Шулуун будах




http://www.spoj.com/CSMS/problems/TIM1019/



#include <stdio.h>
#include <stdlib.h>

// Toon shuluun
struct Axis {
 long    x;
 char   color;

 struct Axis* pre;
 struct Axis* next;

} *current = NULL, *start = NULL, *temp, *end = NULL;

//Shuluun budah: x1-ees x2 hurtel color unguur budna
void insert(int x1, int x2, char color){
 // Gants tseg budahgui
 if(x1 == x2) return;
 //Toon shuluun hooson bol
 if (start == NULL) {
  start = (struct Axis*) malloc(sizeof(struct Axis));
  temp  = (struct Axis*) malloc(sizeof(struct Axis));

  start->x   = x1;
  start->color  = color;
  start->pre   = NULL;
  start->next  = temp;

  temp->x   = x2;
  temp->color  = 'b';
  temp->next   = NULL;
  temp->pre   = start;

  end = temp;

  return;
 }
 //Budaj ehleh tseg 0 uyd ungiig ni solino
 if (x1 == 0) {
  start->color = color;
 }
 else
  //Ehnees ni tugsgul hurtel
  for(current = start; ; current = current->next) {
   // x1 tseg hamgiin baga, uuruusuu ih tsegiin umnu baina
   if (current->x > x1) {
    //Tseg davhatsval
    if (current->pre->x == x1) {
     if(current->pre->color != color) {
      temp = current->pre;
      temp->pre->next = current;
      current->pre = temp->pre;
      free(temp);
     }
     break;
    }
    // Ijil unguur budahgui
    if (current->pre->color == color) {
     break;
    }
    //Budaj ehleh tseg
    temp = (struct Axis*) malloc(sizeof(struct Axis));

    temp->x     = x1;
    temp->color    = color;
    temp->next     = current;
    temp->pre    = current->pre;

    current->pre->next  = temp;
    current->pre     = temp;

    break;
   }
  }
 // Tugsgul tseg eseh
 if(x2 == 1000000000) {
   end->color = (color == 'b') ? 'w' : 'b';
 } else
 for(; current != NULL; current = current->next) {
  //Budah buyu interval dotorh buh tsegiig ustgah
  if(current->x <= x2) {
   current->pre->next = current->next;
   current->next->pre = current->pre;
   free(current);
  } else {
   //Budaj duusan tseg
   if (current->color == color) {
    temp = (struct Axis*) malloc(sizeof(struct Axis));
    temp->color   = (current->color == 'w') ? 'b' : 'w';
    temp->x    = x2;
    temp->pre   = current->pre;
    temp->next   = current;
    current->pre->next = temp;
    current->pre  = temp;
   }
   break;
  }
 }
}

int main(){
 int n;
 long a, b, c;
 long max = 0;
 long temp;
 insert(0, 1000000000, 'w');

 scanf("%d", &n);

 for(;n > 0; n--) {
  scanf("%ld %ld %c", &a, &b, &c);
  insert(a, b, c);
 }

 for(current = start; current->next != NULL; current = current->next) {
  if(current->color == 'w') {
   temp = current->next->x - current->x;
   if(temp > max) {
    max = temp;
    a = current->x;
    b = current->next->x;
   }
  }
 }
 if(max > 0)
 printf("%ld %ld", a, b);
 return 0;
}

No comments:

Post a Comment