Introduction

This is my blog of programming, I take notes and leave codes of computer science problems I solved here. Be my guest to comment :)

Sunday, October 28, 2012

uva 957 - Popes


Problem link
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
const int maxp=100010;
//------------------------------
int a[maxp];
int y,p;
//------------------------------
bool readfile() {
 if (cin.eof()) return(false);
 cin >> y;
 cin >> p;
 if (cin.eof()) return(false);
 memset(a,0,sizeof(a));
 for (int i=1; i<=p; i++) cin >> a[i];
 return(true);
}
//------------------------------
// Search for the value less than or equal to x that have the largest index.
int BSearch(int i, int j, int x) {  
 int l,r,m;
 l=i; r=j;
 do
 {
  m=(l+r)/2;
  if (a[m]<=x) l=m;  // If a[m] satisfy, search for the upper bound for larger index
  else r=m;    // The result must in the lower bound
 } while (r-l>1);   // Until l is next to r
 if (a[r]<=x) return(r);  // Check r first for larger index
 else return(l);    // if no then l is the result
}
//------------------------------
void solve() {
 int result=0,d,c;
 for (int i=1; i<=p; i++)
 {
  int dd=i;      // For each position
  // Search for the largest index which value not exceed a[i]+y-1
  int cc=BSearch(i,p,a[i]+y-1); 
  if (cc-dd+1>result)    // Update
  {
   result=cc-dd+1;
   d=dd; c=cc;
  }
 }
 cout << result << " " << a[d] << " " << a[c] << endl;
}
//------------------------------
int main() {
 while (readfile()) solve();
 return 0;
}

No comments:

Post a Comment