## 10310 - Dog and Gopher

All about problems in Volume 103. If there is a thread about your problem, please use it. If not, create one with its number in the subject.

Moderator: Board moderators

crystaltanvir
New poster
Posts: 6
Joined: Mon Oct 18, 2010 8:13 pm

### Re: 10310 - Dog and Gopher

I got TLE with my code.... Can someone help????

Code: Select all

``````#include<cmath>
#include<iostream>
#include<cstdio>

using namespace std;

int main()
{
int N, i, c = 0;
while(1)
{
if(c != 0) cout << endl;
cin >> N;
c++;
int res = 0;
float dogx, dogy, gopx, gopy, escapex, escapey;
float holex[N], holey[N];
cin >> gopx >> gopy >> dogx >> dogy;
for(i = 0; i < N; i++)
{
cin >> holex[i] >> holey[i];
if(res != 1)
{
float dogdis, gopdis;
dogdis = sqrt(pow((dogx - holex[i]), 2) + pow((dogy - holey[i]), 2));
gopdis = sqrt(pow((gopx - holex[i]), 2) + pow((gopy - holey[i]), 2));
if(dogdis >= (2 * gopdis))
{
res = 1;
escapex = holex[i];
escapey = holey[i];
}
}
}
if(res == 0) cout << "The gopher cannot escape." << endl;
else printf("The gopher can escape through the hole at (%.3f,%.3f).\n", escapex, escapey);
}
return 0;
}

``````
TANVIR

ShaunOfTheLive
New poster
Posts: 1
Joined: Mon Apr 25, 2011 4:55 am

### Re: 10310 - Dog and Gopher

crystaltanvir wrote:I got TLE with my code.... Can someone help????

Code: Select all

``````#include<cmath>
#include<iostream>
#include<cstdio>

using namespace std;

int main()
{
int N, i, c = 0;
while(1)
{
if(c != 0) cout << endl;
cin >> N;
c++;
int res = 0;
float dogx, dogy, gopx, gopy, escapex, escapey;
float holex[N], holey[N];
cin >> gopx >> gopy >> dogx >> dogy;
for(i = 0; i < N; i++)
{
cin >> holex[i] >> holey[i];
if(res != 1)
{
float dogdis, gopdis;
dogdis = sqrt(pow((dogx - holex[i]), 2) + pow((dogy - holey[i]), 2));
gopdis = sqrt(pow((gopx - holex[i]), 2) + pow((gopy - holey[i]), 2));
if(dogdis >= (2 * gopdis))
{
res = 1;
escapex = holex[i];
escapey = holey[i];
}
}
}
if(res == 0) cout << "The gopher cannot escape." << endl;
else printf("The gopher can escape through the hole at (%.3f,%.3f).\n", escapex, escapey);
}
return 0;
}

``````
A little too late to reply to this, I guess, but I will anyway.

If you run your code on the command line and then press Ctrl+Z after you're done entering input, you'll see what the problem is. Your code doesn't properly handle EOF (end-of-file), and in fact it has no way to exit. It keeps running indefinitely after end-of-file. To handle this, instead of while(1) you'll want to do something like while(!cin.fail()).

Pro.metal
New poster
Posts: 9
Joined: Fri Dec 17, 2010 8:13 pm

### Re: 10310 - Dog and Gopher

using scanf is a better option since scanf is said to faster than cin !

and reading until EOF is a factor...while(scanf("%d",&N)!=EOF) can help