CodeChef is a non-commercial competitive programming community
Login
Username (New User? Signup) Password (Forgot Password?)
Signup
Login or
Signup with
Connect
Note
  • Publicize your achievements on your Facebook Wall.
  • Challenge your friends or ask them for help.

Site Navigation

  • PRACTICE
    • Easy
    • Medium
    • Hard
    • Challenge
    • Peer
  • COMPETE
    • February CookOff
    • February Long Contest
    • January CookOff
  • DISCUSS
    • Wiki
    • Forums
    • Blog
    • Twitter
  • COMMUNITY
    • CodeChef Meetups
    • Campus Chapters
    • Host your Contest
    • User Groups
    • CodeChef TechTalks
    • All Educational Initiatives
    • Event Calendar
  • HELP
    • Frequently Asked Questions
    • FAQ for problem setters
    • Problem Setting
    • Ranks
    • Tutorials
  • ABOUT
    • About CodeChef
    • Team CodeChef
    • Press Room
    • CodeChef Financials
    • CodeChef Sponsorships
    • CEO's Corner
    • Contact Us
    • About Directi
Home » Compete » February 2010 Contest » Motorbike Racing

Motorbike Racing

Problem code: M2

  • All Submissions

All submissions for this problem are available.

It's time for the annual exciting Motorbike Race in Byteland.

There are N motorcyclists taking part in the competition. Johnny is watching the race. At the present moment (time 0), Johnny has taken note of the current velocity and position of each motorcyclist.

Johnny wants to know at a given point of time, which motorcyclist is in a specific place in the rank list. Please help him!

If at any given time two motorcyclists are in same position, the motorcyclist with the smaller index will be placed before the one with the larger index.

To make the problem simple, Johnny assumes that each motorcyclist is moving at a constant velocity.

Input

The first line contains a number t (about 10) which is the number of test cases. Then t test cases follow. Each test case has the following form.

The first line of the test case contains a number N (1 <= N <= 20000), the number of motorcyclists.

The i-th line in the next N lines contains two numbers, v and x, which are the velocity and the current position of the i-th motorcyclist (1 <= v, x <= 100,000).

The next line contains a number Q (1 <= Q <= 20000), the number of time queries.

Each line in the next Q lines contains two numbers, t (1 <= t <= 1,000,000,000) and k (1 <= k <= n), representing the query: "at time t, which motorcyclist is positioned k-th in the rank list?"

Output

For each test case, print Q lines, with each line containing the index of the motorcyclist for the corresponding query.

Remember to print a new line after each test case.

Example

Input:
1
4
2 100
3 50
4 60
5 1
4
1 1
50 2
60 4
100 1

Output:
1
4
1
4

Date: 2010-01-15
Time limit: 2.5s
Source limit: 50000
Languages: C C99 strict C++ 4.0.0-8 C++ 4.3.2 PAS gpc PAS fpc JAVA NICE JAR C# NEM ST ASM D FORT ADA BASH PERL PYTH RUBY LUA ICON PIKE PHP SCM guile SCM qobi LISP sbcl LISP clisp SCALA HASK ERL CAML CLPS PRLG WSPC BF ICK TEXT JS


  • Submit

Comments

  • Login or Register to post a comment.

i didn't get the difference

neeraj_km @ 1 Feb 2010 04:22 PM

i didn't get the difference between index number and ranking list.

Initially the motorcyclist is arranged through index wise or ranking wise ??

 

i don't understand how to

rahul999 @ 1 Feb 2010 04:33 PM

i don't understand how to resolve, when 2 r at same position

If two are the same position,

triplem @ 1 Feb 2010 04:36 PM

If two are the same position, the one that comes first in the input is earlier in the rank list.

example shows 4 motorcyclists

cooltodinesh @ 1 Feb 2010 04:39 PM

example shows 4 motorcyclists but ranks are given as 2 3 4 5 .

why not as 1 2 3 4?

i guess index no is the order

ankit_kheria @ 1 Feb 2010 04:39 PM

i guess

index no is the order in which motorcyclists are given in the input

and rank is calculated with respect to their position ie higher the position lower(numerically) the rank and when positions are same lower the index lower(numerically) is the rank.

current position means

anurag_aggarwal @ 1 Feb 2010 04:39 PM

current position means ranking or coordinate of the biker

@ Dinesh Salve 2,3,4,5 are

ankit_kheria @ 1 Feb 2010 04:40 PM

@ Dinesh Salve

2,3,4,5 are the speeds not the ranks

@ankit wat is meaning of

cooltodinesh @ 1 Feb 2010 04:45 PM

@ankit

wat is meaning of current position ith m.cyclist  .

2 100

hw is this for 4 mcyclists?

 

current position can be said

ankit_kheria @ 1 Feb 2010 04:56 PM
current position can be said to distance from a fixed point(starting point say)..if position1 = 100 and position2 = 50 means the mcyclist1 is ahed of mcyclist2 by 50 units..

what is current position, can

code easy @ 1 Feb 2010 06:07 PM

what is current position, can somoone help me.

for velocity and position,

eng_mustafa @ 1 Feb 2010 08:44 PM

for velocity and position, are they real numbers or integers?

Submissions aren't appearing

g0wda @ 1 Feb 2010 10:26 PM

Submissions aren't appearing in recent activity... anyone else submitted yet?

@shashi..same here..

aansu @ 2 Feb 2010 12:55 AM

@shashi..same here..

same here!!

thesane @ 2 Feb 2010 08:43 AM

same here!!

can somebody explain the

arun chauhan @ 2 Feb 2010 11:18 AM

can somebody explain the condition when both the motor cyclist are at same position........... what is meant by the word "Placed"..... does it mean ranked ?????

Is there any limit on max

pj810 @ 2 Feb 2010 12:50 PM

Is there any limit on max value of v? the conditions says v >=1 but no upper limit?

@pawan When v, x appears in

Brian Drake @ 2 Feb 2010 01:22 PM

@pawan When v, x appears in the middle of a bound like that, it means that the bounds apply to both v and x, i.e. 1 <= v <= 100,000 and 1 <= x <= 100,000.

I have some questions

boxer @ 2 Feb 2010 02:17 PM

I have some questions regarding the input:

1) "The i-th line in the next N lines contains two numbers, v and x, which are the velocity and the current position of the i-th motorcyclist (1 <= v, x <= 100,000)."

The inputs given in the test case are :

2 100
3 50
4 60
5 1

Is the first number x and the second number v? This would be contrary to the statement mentioned above.

2) If there are only 4 motorcyclists, why is no one placed first and why is at least one placed fifth?

3) Does position mean rank of the motorcyclist or does it refer to distance/displacement form the starting line ?

It says it will be v followed

triplem @ 2 Feb 2010 03:11 PM

It says it will be v followed by x. Therefore it will be v followed by x.

The person at position 100 is in first place. Nobody is in 5th place.

Position means position, not rank.

@Abhijit In this case, if you

Brian Drake @ 2 Feb 2010 03:57 PM

@Abhijit In this case, if you swap v and x, the output changes. If your output does not match the sample output, you are doing something wrong! Why would you think the first number was x anyway?

Can we get Mustafa and

Brian Drake @ 2 Feb 2010 04:00 PM

Can we get Mustafa and Shashi's questions answered (particularly Mustafa's question about whether the inputs are integers or real numbers)? I'm not seeing any rankings, recent activity or successful submissions in the sidebar, but I am seeing updates in the problem list on the main contest page.

can you give some idea of how

rampage @ 2 Feb 2010 04:52 PM

can you give some idea of how many calculations the judge performs per second?

encountered a problem for the

arun chauhan @ 2 Feb 2010 06:39 PM

encountered a problem for the first time........

i am using gcc of ubuntu..... have written a code for the above problem..... in order to troubleshoot my code i wrote some printf statements to see the control flow..... now i am getting the output but there is this mysterious printf("n") statement which i inserted to have line gap between the output.... now whenever i comment out this statement, the program crashes and it shows segmentation fault..... and if i don't there is unwanted gap between the given input and produced output, which is what i suspect is the reason of getting a WA every time i submit the code......

Can anybody suggest something why commenting a printf("n") is causing program to fail.........

@admins I have a question. If

bairathirahul @ 2 Feb 2010 07:45 PM

@admins

I have a question.

If the submission gives error "Time Limit Exceeded".

Then is it confirm that it is giving correct output for all the test cases but only the time limit is exceeding.

@Rahul No.

admin @ 2 Feb 2010 09:12 PM

@Rahul No.

@Stephen Thanks for the

boxer @ 3 Feb 2010 12:44 AM
@Stephen Thanks for the clarification. I misinterpreted the data set and hence the question.

ADMIN, Solutions in C#2 are

boxer @ 3 Feb 2010 12:45 AM
ADMIN, Solutions in C#2 are not being accepted. Why?

@Rahul The FAQ says that the

Brian Drake @ 3 Feb 2010 11:32 AM

@Rahul The FAQ says that the answer is "no", as confirmed by Aniruddha above. I believe the way it works is, once the time limit is up, the judge stops running your program.

with 20000 motorcyclists ,it

vinu76jsr @ 3 Feb 2010 11:43 AM

with 20000 motorcyclists ,it sure will be one hell of a race.

Hi Admin, will the value of

legilimen @ 3 Feb 2010 02:10 PM

Hi Admin,

will the value of time t in the query be unique?

@legilimen There is nothing

Brian Drake @ 3 Feb 2010 04:43 PM

@legilimen There is nothing to suggest that the time values will be unique. I think we should assume that they may or may not be unique.

Hi Admin, I am getting a

sksamal @ 3 Feb 2010 05:45 PM

Hi Admin, I am getting a "time limit exceeded error" ( using C ).

The FAQ section doesnot mention in detail about it.  I feel my code is optimised and works well for large input sizes efficiently.

What is the time limit for C ?

C#2 solutions are now

i0exception @ 3 Feb 2010 06:23 PM

C#2 solutions are now accepted.

are the time queries in

haritosh @ 3 Feb 2010 07:19 PM

are the time queries in ascending order or any order?

I have tried several

thesane @ 3 Feb 2010 09:44 PM

I have tried several techniques for this problem and all of them give time limit exceeds !!

I even tried an empty loop just read the input and write -1 as output and also it gives time limit exceeds !!!!!

i solved motorbike race

abdus sattar bhuiyan @ 3 Feb 2010 10:04 PM

i solved motorbike race problem using the minimum data.but igot run time error. what is the problem???

I am getting a time limit

Trevoke @ 4 Feb 2010 01:12 AM

I am getting a time limit exceeded on my solutions in Ruby.. Shame because I'm pretty sure what I'm doing is correct. Is the time appropriately adjusted for the Ruby language?

@Admin c#2 is working now..

shrikant169 @ 4 Feb 2010 09:38 AM

@Admin

c#2 is working now.. however my doubt is still not clear.. Does Visual C# 2008 Express Edition come under C# or C#2 ?? Kindly Reply.. Thanks..

I am getting a run time

awesomeness @ 4 Feb 2010 11:16 AM

I am getting a run time error. I have written my code in Python. And its working fine on my system. Strange. I dont really see an error in my code

How can i get input? i am

kbalavignesh @ 4 Feb 2010 11:53 AM

How can i get input? i am using php.. and assigning all values using randomn values (as per the given scope)... Is it ok? .. If the N & Q get max value on randomn, it takes more time.

Whats the memory limit on

awesomeness @ 4 Feb 2010 12:09 PM

Whats the memory limit on this one? I think I am running out of memory. My code looks error free but it gives runtime error. I am consuming 4.5M on each run. Please help

@Sandip The FAQ says that 64

Brian Drake @ 4 Feb 2010 12:35 PM

@Sandip The FAQ says that 64 MB is guaranteed, so unless you are allocating a huge amount of memory in a single operation, your idea is probably wrong.

@ balavignesh - read the FAQ.

triplem @ 4 Feb 2010 12:42 PM

@ balavignesh - read the FAQ.

Admin kindly clarify whether

shrikant169 @ 4 Feb 2010 05:16 PM

Admin kindly clarify whether the values of V and X are integers or numbers.. thanks..

Even after so much optimizing

shrikant169 @ 4 Feb 2010 05:51 PM

Even after so much optimizing Time Exceeded error.. :(

Any chance of there being given an extension?? :)

Also recent activity thingy isnt working...

What recent activity are you

admin @ 4 Feb 2010 05:54 PM

What recent activity are you talking about? click the all submissions button on the top of the page. The sidebar shows the successful submissions.

oh yes.. sorry.. there are 0

shrikant169 @ 4 Feb 2010 06:08 PM

oh yes.. sorry.. there are 0 successful submissions for this question hence the "no recent activity".

Sorry..

I am getting wrong answer as

kbalavignesh @ 4 Feb 2010 06:18 PM

I am getting wrong answer as a result. I dont know what is wrong in my logic. Following are my inputs and outputs.. Please someone tell me, whether my input are correct.. (also the output..)

input

2
4
2 100
3 50
4 60
5 1
4
1 1
50 2
60 4
100 1
5
6 34
7 5
5 1
3 10
2 23
2
50 1
500 1

output

1
4
1
4

2
2

I solved the problem but

arun26oct @ 4 Feb 2010 07:18 PM

I solved the problem but getting time exceeded. My logic is really simple and it wroks fine. Will the judge increase the time limit for this program ???

I am getting the output on

sandyridgeracer @ 4 Feb 2010 07:34 PM

I am getting the output on my system.But here it shows run-time error(sigsegv).I am using double-dimensional array in my program.Does it any how effect the program.thnx in advance

@balavignesh Anyone

Brian Drake @ 5 Feb 2010 06:59 AM

@balavignesh Anyone discussing test cases here risks disqualification, as this is a contest. There have been numerous comments at Soccer League about this.

@admin Ahmed said above that

Brian Drake @ 5 Feb 2010 01:16 PM

@admin Ahmed said above that they tried submitting a program that just reads the input and it still gives Time Limit Exceeded! I also notice that there have not been any successful submissions yet. Can you confirm that the time limit is correct?

@

maximus1988 @ 5 Feb 2010 02:42 PM

@ admin

 

since1<=x<=100000

so it means that at 100000 the race ends?

so after that riders will stop instead of going farther

@ adminsince1<=x<=100000so it

maximus1988 @ 5 Feb 2010 02:42 PM

@ admin


since1<=x<=100000

so it means that at 100000 the race ends?

so after that riders will stop instead of going farther

Please read the problem

admin @ 5 Feb 2010 02:44 PM

Please read the problem statement. Those are the constraints for the value of 'x'.

@Aashish The important point

Brian Drake @ 5 Feb 2010 03:03 PM

@Aashish The important point is the definition of x. This variable is carefully defined in the problem statement.

Does judge's compiler use

Shyamendra Solanki @ 5 Feb 2010 03:10 PM

Does judge's compiler use optimization flags?

@admin :I am getting the

sandyridgeracer @ 5 Feb 2010 09:52 PM

@admin :I am getting the output on my system.But here it shows run-time error(sigsegv).PLS HELP

The wording is very

Trevoke @ 5 Feb 2010 10:08 PM

The wording is very confusing.

Velocity, "distance traveled" and "position" would be better. Position is too ambiguous.

Is it possible to access the

jcomeau_ictx @ 6 Feb 2010 06:59 AM

Is it possible to access the ONLINE_JUDGE property from Python? I tried accessing it as an environment variable using os.getenv(), but no joy.

@ admin please clarify

sai4anand @ 6 Feb 2010 08:36 AM

@ admin please clarify whether the input velocity will be given in sorted manner or not????

and also about the time for which we have to find the rank will be given in sorted manner??????

It clearly doesn't say they

triplem @ 6 Feb 2010 12:50 PM

It clearly doesn't say they will be sorted, so you have no reason to believe so.

The time limit on this

omkardanke @ 6 Feb 2010 06:30 PM

The time limit on this problem is pretty hard. I doubt whether anyone can solve 10 test cases of 20000 queries of 20000 racers within 2.5 seconds.

 

My solution took 25 seconds for 1 test case of 20000 racers with 1000 queries.

 

And I can't seem to improve it other than optimising the data storage.

":( internal error occurred

I @ 6 Feb 2010 09:46 PM
":( internal error occurred in the system"what does this mean?

I brought the time down to 17

omkardanke @ 7 Feb 2010 12:35 AM

I brought the time down to 17 seconds by using a dynamic new techinue to store and process data. But to no avail.... :(

Even my quantum

Flopsy @ 7 Feb 2010 03:21 AM

Even my quantum computing solution got Time Limit Exceeded... :)

Hey guys.. I have a doubt..

srini_chilli @ 7 Feb 2010 07:54 AM

Hey guys.. I have a doubt.. The position 'x' was noted for all bikes at time0 right. (i.e.) Position = velocity*time0.

 

But if you go by the above formula and calculate time0, it is different for each bike. How?

Is there a flaw in the question?

 

For example

2 100 -- > time0 = 100/2 = 50
3 50 -- > time0 = 50/3

x is the position at time 0.

triplem @ 7 Feb 2010 08:02 AM

x is the position at time 0. So for v=2 and x=100, at time 0 the bike is at 100, at time 1 the bike is at 102, and so on. I don't know where you get 50 from.

Yes, But the time0 should be

srini_chilli @ 7 Feb 2010 08:15 AM

Yes, But the time0 should be unique for all bikes..

time is essentialy distance/velocity..

so if u put this formula for each bike in the testcase u should get the same value..

which is not the case right now isn't it.. Or have a missed something here

@Srinivasan, @Stephen It

Brian Drake @ 7 Feb 2010 08:48 AM

@Srinivasan, @Stephen It seems like Srinivasan thinks that there is a variable called "time0" and the positions for each bike was noted at time = time0, where position = 0 at time = 0. If that were the case, then Srinivasan's calculations would make sense. In fact, the position for each bike was noted at time = 0.

How come CodeChef's site keep

alok @ 7 Feb 2010 08:17 PM

How come CodeChef's site keep showing this message when I open the contest page :

warning: ksort() expects parameter 1 to be array, null given in /var/www/codechef/sites/all/modules/contest_page/contest_page.module on line 279.

 

Well... 0.15 sec for 2.9 Mb

alok @ 8 Feb 2010 11:54 AM

Well... 0.15 sec for 2.9 Mb mem. So it's possible.

hi, all the number are

liubiaoyong @ 8 Feb 2010 11:57 AM

hi, all the number are integer?

is v and x are

gauravgaba @ 8 Feb 2010 05:40 PM

is v and x are integers????????????

m newbie hereits my first

anant4coding @ 10 Feb 2010 04:46 PM

m newbie here

its my first time

can u please tell me how to take input

whether as .txt file or somhw else???

I am starting to give up on

sohilgupta @ 10 Feb 2010 11:50 PM

I am starting to give up on this. I dont know where I am going wrong but the following solution runs perfectly fine for any imaginable test case possible on mine but gives wrong answer here. Please show me some ight and tell me is it because of the compiler difference because I am working on Turbo c and here it is gcc or something wrong in my code

Here's my soln : http://www.codechef.com/viewsolution/185888

Just tell me this: Are all

awesomeness @ 11 Feb 2010 11:58 AM

Just tell me this: Are all the x and v integers or should I expect floating point? I dont see anything in the question that suggests that they should be integers. I wrote my code for integers and its giving me a runtime error which I think is because a floating point value is being sent as input. Please clarify

I agree this really should

triplem @ 11 Feb 2010 12:12 PM

I agree this really should have been clarified a long time ago. I'm guessing they are always integers.

Admin, Why cant problem

sppraveen @ 11 Feb 2010 01:04 PM

Admin, Why cant problem statement be more clear. It always has some issues. We all know that if v and x are real numbers , that would have been mentioned. So I find they are integers as nothing is mentioned.

Why cant this datatype information be specified explicitly. There is fun involved in guessing corner test cases and its a part of the competition , but there is no fun in finding the datatype. Why do you guys still dont explicitly make somethings clear. Everybody who have seen this problem must have got this doubt once. It made me write some sample program to really find the datatype. This is unnecessary.

What does it take to mention

sppraveen @ 11 Feb 2010 01:07 PM

What does it take to mention that it is integer. May be I should not ask this question , as efforts were not taken to assert the problem statement, test cases and even timings for all problems. Why should you worry about explicitly specifying the datatype :)

Can somebody please put me

triplem @ 11 Feb 2010 03:16 PM

Can somebody please put me out of my misery and give me some hint as to the approach? Can't think of anything better than O(N) per query (quickselect).

My approach was pretty messy,

gmark @ 11 Feb 2010 03:33 PM

My approach was pretty messy, but the basic idea was to partition the competitors into m groups, where you can pick m as you like. Inside each group we keep track of a sorted list of these competitors according to their rank within this group as the race proceeds. This is done by precomputing all events inside a group (i.e. the times when two riders change rank). When we come to a query at time t, we first process all events that have happened since the time of the last query (queries are processed in order of time), so that the sorted list of ranks inside each group is correct.

Given a query, the problem is now to select the k'th overall smallest (or largest) from these sorted lists. This has been solved by Frederickson and Johnson in 1982 in their paper The Complexity of Selection and Ranking in X+Y and Matrices with Sorted Columns in time O(m + plog(k/p)) with p = min(k,m) per query. I didn't implement this approach, since I found it to be a bit too complicated. Instead I answered queries using something very similar to quickselect. Pick a random element from these lists, and compute using a binary search in each list the rank of the element we picked. From this we can decide exactly as in quickselect which part to recurse in. Once we are down to only a few competitors left as candidates for the k'th element, just do a standard quickselect on these.

Great win, congratulations

tomek @ 11 Feb 2010 04:03 PM

Great win, congratulations Mark!

These were good problems.

@Mark Greve: That was

alok @ 11 Feb 2010 04:28 PM

@Mark Greve: That was interesting approach.Better than finding product of time velocity of order 1000000000.

 

I would really like to know what other approaches were used.

Thanks Tomek! I had the

gmark @ 11 Feb 2010 04:50 PM

Thanks Tomek! I had the network for n = 20 with 93 gates ready for a few days. I knew this would improve my score by maybe 3-5 points, but I didn't want to submit it until the very last moment. When you hit 149, I knew I could beat it, but when you got 146.9 I wasn't sure at all. So with 20 minutes to go and my first submission using this network not beating your score, I was a bit disappointed. Luckily the optimization I had just tried out shortly before, which didn't give anything turned out to work very well with the new network for n = 20...

//{{{ #include

sravanya14 @ 11 Feb 2010 07:28 PM

  1. //{{{
  2. #include <algorithm>
  3. #include <cassert>
  4. #include <cstdio>
  5. #include <cstdlib>
  6. #include <cctype>
  7. #include <cmath>
  8. #include <iostream>
  9. #include <sstream>
  10. #include <string>
  11. #include <utility>
  12. #include <vector>
  13. #include <cassert>
  14. #include <ctime>
  15. #include <queue>
  16. using namespace std;
  17. #define VAR(a,b) __typeof(b) a=(b)
  18. #define REP(i,n) for(int _n=n, i=0;i<_n;++i)
  19. #define FOR(i,a,b) for(int i=(a),_b=(b);i<=_b;++i)
  20. #define FORD(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
  21. #define FOREACH(it,c) for(VAR(it,(c).begin());it!=(c).end();++it)
  22. #define ALL(c) (c).begin(),(c).end()
  23. #define TRACE(x) cerr << "TRACE(" #x ")" << endl;
  24. #define DEBUG(x) cerr << #x << " = " << x << endl;
  25. template<class T>
  26. ostream& operator<<(ostream&o, const vector<T>&v) {
  27. o<<'{';
  28. FOREACH(it,v) o<<*it<<',';
  29. return o<<'}';
  30. }
  31. typedef long long LL;
  32. const int INF = 1000000000; const LL INFLL = LL(INF) * LL(INF);
  33. typedef vector<int> VI; typedef vector<string> VS; typedef vector<VI> VVI;
  34. template<class T> inline int size(const T&c) { return c.size(); }
  35. class INPUT {
  36. static const int BUFSIZE = 1<<16;
  37. static char buffer[];
  38. char *bufpos;
  39. char *bufend;
  40. void grabBuffer();
  41. public:
  42. INPUT() { grabBuffer(); }
  43. bool eof() { return bufend==buffer; }
  44. char nextChar() { return *bufpos; }
  45. inline char readChar();
  46. inline void skipWS();
  47. inline unsigned readUnsigned();
  48. inline int readInt();
  49. };
  50. char INPUT::buffer[INPUT::BUFSIZE];
  51. void INPUT::grabBuffer() {
  52. bufpos = buffer;
  53. bufend = buffer + read(0, buffer, BUFSIZE);
  54. }
  55. char INPUT::readChar() {
  56. char res = *bufpos++;
  57. if(bufpos==bufend) grabBuffer();
  58. return res;
  59. }
  60. inline bool myisspace(char c) { return c<=' '; }
  61. void INPUT::skipWS() {
  62. while(!eof() && myisspace(nextChar())) readChar();
  63. }
  64. unsigned INPUT::readUnsigned() {
  65. skipWS();
  66. unsigned res = 0;
  67. while(!eof() && isdigit(nextChar())) {
  68. res = 10u * res + (readChar()-'0');
  69. }
  70. return res;
  71. }
  72. int INPUT::readInt() {
  73. skipWS();
  74. bool neg = false;
  75. if(!eof() && nextChar()=='-') { neg=true; readChar(); }
  76. int res = static_cast<int>(readUnsigned());
  77. if(neg) res = -res;
  78. return res;
  79. }
  80. class OUTPUT {
  81. static const int BUFSIZE = 1<<16;
  82. static char buffer[];
  83. char *bufpos;
  84. char *BUFLIMIT;
  85. public:
  86. void flushBuffer();
  87. OUTPUT():bufpos(buffer),BUFLIMIT(buffer+BUFSIZE-100) {}
  88. ~OUTPUT() { flushBuffer(); }
  89. inline void operator()(char c);
  90. inline void operator()(unsigned x);
  91. inline void operator()(int x);
  92. inline void operator()(const char*s);
  93. void operator()(const string&s) { operator()(s.c_str()); }
  94. template<class A,class B>
  95. void operator()(const A& a,const B& b) {
  96. operator()(a); operator()(b);
  97. }
  98. template<class A,class B,class C>
  99. void operator()(const A& a,const B& b,const C&c) {
  100. operator()(a); operator()(b); operator()(c);
  101. }
  102. template<class A,class B,class C,class D>
  103. void operator()(const A& a,const B& b,const C&c,const D&d) {
  104. operator()(a); operator()(b); operator()(c); operator()(d);
  105. }
  106. template<class A,class B,class C,class D,class E>
  107. void operator()(const A& a,const B& b,const C&c,const D&d,const E&e) {
  108. operator()(a); operator()(b); operator()(c); operator()(d); operator()(e);
  109. }
  110. template<class A,class B,class C,class D,class E,class F>
  111. void operator()(const A& a,const B& b,const C&c,const D&d,const E&e,const F&f) {
  112. operator()(a); operator()(b); operator()(c); operator()(d); operator()(e); operator()(f);
  113. }
  114. };
  115. char OUTPUT::buffer[OUTPUT::BUFSIZE];
  116. void OUTPUT::flushBuffer() {
  117. char *p = buffer;
  118. while(p < bufpos) {
  119. p += write(1, p, bufpos-p);
  120. }
  121. bufpos = buffer;
  122. }
  123. void OUTPUT::operator()(char c) {
  124. *bufpos = c;
  125. ++bufpos;
  126. if(bufpos >= BUFLIMIT) flushBuffer();
  127. }
  128. void OUTPUT::operator()(unsigned x) {
  129. char *old = bufpos;
  130. do {
  131. *bufpos = char('0' + x % 10u);
  132. x /= 10u;
  133. ++bufpos;
  134. } while(x);
  135. reverse(old, bufpos);
  136. if(bufpos >= BUFLIMIT) flushBuffer();
  137. }
  138. void OUTPUT::operator()(int x) {
  139. if(x<0) { operator()('-'); x = -x; }
  140. operator()(static_cast<unsigned>(x));
  141. }
  142. void OUTPUT::operator()(const char*s) {
  143. while(*s) operator()(*s++);
  144. }
  145. INPUT input;
  146. OUTPUT output;
  147. //}}}
  148. const int TIME_SWITCH = 50;
  149. const int SORT_THRESHOLD = 6;
  150. const int MAX_DISTANCE = 100000;
  151. struct Player {
  152. int id;
  153. int x0,v;
  154. LL curPos;
  155. };
  156. struct Query {
  157. int id;
  158. int t,pos;
  159. int answer;
  160. };
  161. vector<Player> players;
  162. vector<Query> queries;
  163. int nextQueryNr;
  164. inline bool operator<(const Player &a, const Player &b) {
  165. if(a.curPos != b.curPos) return a.curPos > b.curPos;
  166. return a.id < b.id;
  167. }
  168. void readInput() {
  169. int n = input.readInt();
  170. players.resize(n);
  171. REP(i,n) {
  172. Player &p = players[i];
  173. p.id = i;
  174. p.v = input.readInt();
  175. p.x0 = input.readInt();
  176. }
  177. int nq = input.readInt();
  178. queries.resize(nq);
  179. REP(i,nq) {
  180. Query &q = queries[i];
  181. q.id = i;
  182. q.t = input.readInt();
  183. q.pos = input.readInt()-1;
  184. q.answer = -1;
  185. }
  186. }
  187. struct cmpQueryTime {
  188. inline bool operator()(const Query&a, const Query&b) const {
  189. return a.t < b.t;
  190. }
  191. };
  192. void sortQueries() {
  193. sort(queries.begin(), queries.end(), cmpQueryTime());
  194. nextQueryNr = 0;
  195. }
  196. void positionPlayers(int t) {
  197. FOREACH(it, players) {
  198. Player &p = *it;
  199. p.curPos = p.x0 + LL(t) * LL(p.v);
  200. }
  201. }
  202. void phase0() {
  203. while(nextQueryNr < size(queries)) {
  204. int t = queries[nextQueryNr].t;
  205. if(t >= TIME_SWITCH) break;
  206. int p = nextQueryNr+1;
  207. while(p<size(queries) && queries[p].t == t) ++p;
  208. positionPlayers(t);
  209. if(p-nextQueryNr >= SORT_THRESHOLD) {
  210. sort(players.begin(), players.end());
  211. FOR(i,nextQueryNr,p-1) {
  212. Query &q = queries[i];
  213. q.answer = players[q.pos].id;
  214. }
  215. } else {
  216. FOR(i,nextQueryNr,p-1) {
  217. Query &q = queries[i];
  218. nth_element(players.begin(), players.begin()+q.pos, players.end());
  219. q.answer = players[q.pos].id;
  220. }
  221. }
  222. nextQueryNr = p;
  223. }
  224. }
  225. struct cmpVelocity {
  226. inline bool operator()(const Player&a, const Player&b) const {
  227. return a.v > b.v;
  228. }
  229. };
  230. struct Event {
  231. int t,a,b; // player with id a passes player b
  232. Event(int t,int a,int b):t(t),a(a),b(b) {}
  233. };
  234. inline bool operator<(const Event &a, const Event &b) {
  235. return a.t < b.t;
  236. }
  237. int nextEventNr;
  238. vector<Event> events;
  239. vector<int> playerAt; // id -> player position
  240. void processEvents(int t) {
  241. while(nextEventNr < size(events) && events[nextEventNr].t <= t) {
  242. int idA = events[nextEventNr].a;
  243. int idB = events[nextEventNr].b;
  244. ++nextEventNr;
  245. int posA = playerAt[idA];
  246. int posB = playerAt[idB];
  247. if(posA > posB) {
  248. playerAt[idA] = posB;
  249. playerAt[idB] = posA;
  250. swap(players[posA], players[posB]);
  251. }
  252. }
  253. }
  254. void phase1() {
  255. sort(players.begin(), players.end(), cmpVelocity());
  256. events.clear();
  257. REP(a,size(players)) {
  258. FOR(b,a+1,size(players)-1) {
  259. int dv = players[a].v - players[b].v;
  260. if(dv * TIME_SWITCH > MAX_DISTANCE) break;
  261. if(dv==0) continue;
  262. int dx = players[b].x0 - players[a].x0;
  263. int aid = players[a].id;
  264. int bid = players[b].id;
  265. if(aid > bid) ++dx;
  266. if(dx<=0) continue;
  267. int t = (dx+dv-1)/dv;
  268. if(t <= TIME_SWITCH) continue;
  269. events.push_back(Event(t,aid,bid));
  270. }
  271. }
  272. sort(events.begin(), events.end());
  273. positionPlayers(TIME_SWITCH);
  274. sort(players.begin(), players.end());
  275. playerAt.resize(size(players));
  276. REP(i,size(players)) {
  277. playerAt[players[i].id] = i;
  278. players[i].v = 0; // reuse as visited
  279. }
  280. nextEventNr=0;
  281. while(nextQueryNr < size(queries)) {
  282. Query &q = queries[nextQueryNr++];
  283. processEvents(q.t);
  284. q.answer = players[q.pos].id;
  285. }
  286. }
  287. void solve() {
  288. phase0();
  289. phase1();
  290. }
  291. void print() {
  292. vector<int> answers(size(queries),-1);
  293. FOREACH(it,queries) {
  294. Query &q = *it;
  295. answers[q.id] = q.answer;
  296. }
  297. FOREACH(it, answers) output(*it + 1, 'n');
  298. output('n');
  299. }
  300. int main() {
  301. int ntc = input.readInt();
  302. REP(tc,ntc) {
  303. readInput();
  304. sortQueries();
  305. solve();
  306. print();
  307. }
  308. }

My solution is actually quite

pieguy @ 12 Feb 2010 12:21 AM

My solution is actually quite similar to Mark's, but instead of keeping each individual group sorted, I keep the groups themselves in order (that is, every motorcycle in group i will be ahead of every motorcycle in group j if i<j).  Then for each query I can find the right group with binary search, then use nth_element to find the right motorcycle within the group.  Unfortunately, it's possible for every motorcycle to end up in the same group, but I got lucky and there weren't any test cases like this (I was quite surprised when my submission passed).

Ha, I was thinking you must

tomek @ 12 Feb 2010 12:38 AM

Ha, I was thinking you must have found a 92 comparators network. I also had a 93-gate network for n=20, but apparently wasn't optimizing it nearly that well.

I have to admit that my 0.15

tomek @ 12 Feb 2010 04:14 AM

I have to admit that my 0.15 solution could have probably been defeated with more difficult test cases - it's O(N^2 + Q log Q) in the worst case. I generate all pairwise position swaps after t=50, by looking at all pairs of bikers with the difference in velocities smaller than 2000. Apparently there weren't that many pairs of bikers with velocities that close.

Thanks guys. I suspected it

triplem @ 12 Feb 2010 05:24 AM

Thanks guys. I suspected it would be something along the lines of grouping, but was always put off by easy worst cases.

I would be rather disappointed if the official solution had a worst-case quadratic running time.

Can somebody please post all

sohilgupta @ 12 Feb 2010 02:12 PM

Can somebody please post all the test cases used while evaluating the answers?? It will really help me to know what did I miss in this problem with my approach..

SUCCESSFUL SUBMISSIONS FOR THIS PROBLEM:

Programming Competition Fetching successful submissions
Directi Go for Gold
CodeChef is a global programming communityCodeChef hosts online programming competitions
CodeChef is a non-commercial competitive programming community
  • About CodeChef
  • About Directi
  • CEO's Corner
  • C-Programming
  • Programming Languages
  • Contact Us
© 2009 Directi Group. All Rights Reserved. CodeChef uses SPOJ © by Sphere Research Labs
In order to report copyright violations of any kind, send in an email to copyright@codechef.com
CodeChef a product of Directi
The time now is:
CodeChef - A Platform for Aspiring Programmers

CodeChef was created as a platform to help programmers make it big in the world of computer programming. At CodeChef we work hard to revive the geek in you by hosting programming contests on a monthly basis. We also aim to have training sessions and events related to online programming for programmers around the world. Apart from providing a platform for programming competitions, CodeChef also has various tutorials and forum discussions to help those who are new to the world of computer programming.

Practice Section - A Place to hone your 'Computer Programming Skills'

Try your hand at one of our many practice problems and submit your solution in a language of your choice. Our judge accepts solutions in over 35+ programming languages. Online programming was never this much fun! Receive points, and move up through the CodeChef ranks. Use our practice section to better prepare yourself for the multiple programming competitions that take place through-out the month on CodeChef.

Compete - Monthly Programming Contests and Cook-offs

Here is where you can show off your computer programming skills. Take part in our 10 day long monthly programming contests and the shorter format Cook-off programming contests. Put yourself up for recognition and win great prizes. Prizes worth up to Rs.20,000 and $700 are up for grabs every month along with lots more CodeChef goodies.

Discuss

Are you new to computer programming? Do you need help with algorithms? Then be part of CodeChefs Forums and interact with all our programmers love helping out other programmers and share their ideas.

CodeChef Community

As part of our Educational initiative, we give institutes the opportunity to associate with CodeChef in the form of Campus Chapters. Hosting online programming competitions is not the only feature on CodeChef. Be a part of the CodeChef community through CodeChef meetups and techtalks. You can also host a programming contest for your institute on CodeChef and be a guest author on our blog.

Domain Name Registration, Web hosting, and Website Design provided by BigRock.com