Here are my two codes for the Spoj problem BATTLESHIP, both give WA one at 0.13s and other at 0.73 sec. the only difference in both the codes is i changed everything from int to double. Is the time difference cz double arithmetic is slower or cz changing it makes answer right for more test cases?
CODE WITH DOUBLE
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
double min(double a, double b)
{
return (a < b) ? a : b;
}
int main()
{
double M, N, S, i, j, rows, columns;
double area, answer, ships = 0, l = 0, n = 1, k;
char c;
int flag = 0, conflag = 0;
scanf("%lf %lf %lf\n", &M, &N, &S);
i = 0;
j = 0;
while(i < M)
{
scanf("%c", &c);
// printf("%d\n", i);
if(j == N)
{
i++;
j = 0;
continue;
}
if(c == 'X')
{
k = 0;
if(j < S - 1)
{
//printf("..%d..", flag);
if(flag == 1)
k = k + min(l, j + 1);
else if(j + (S) == N)
{
flag = 1;
l = j + 1;
k = k + l;
}
else if(flag == 0)
k = k + j + 1;
// printf("..%d %.0lf %d..\n", flag, k, l);
}
else if(j > N - S)
{
k = k + (N - j);
}
else
{
k = k + S;
}
if(i < S - 1)
{
if(conflag == 1)
k = k*min(n, i + 1);
else if(i + (S) == M)
{
conflag = 1;
n = i + 1;
k = k*n;
}
else if(conflag == 0)
k = k*(i + 1);
}
else if (i > M - S)
{
k = k*(M - i);
}
else
{
k = k*S;
}
//printf("%d %d %.0lf...\n", i, j, k);
ships = ships + k;
}
j++;
}
rows = M - (S - 1), columns = N - (S - 1);
area = rows*columns;
answer = ships/area;
printf("%.6lf\n", answer);
return 0;
}
CODE WITH INT
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int min(int a, int b)
{
return (a < b) ? a : b;
}
int main()
{
int M, N, S, i, j, rows, columns;
double area, answer, ships = 0, l = 0, n = 1, k;
char c;
int flag = 0, conflag = 0;
scanf("%d %d %d\n", &M, &N, &S);
i = 0;
j = 0;
while(i < M)
{
scanf("%c", &c);
// printf("%d\n", i);
if(j == N)
{
i++;
j = 0;
continue;
}
if(c == 'X')
{
k = 0;
if(j < S - 1)
{
//printf("..%d..", flag);
if(flag == 1)
k = k + min(l, j + 1);
else if(j + (S) == N)
{
flag = 1;
l = j + 1;
k = k + l;
}
else if(flag == 0)
k = k + j + 1;
// printf("..%d %.0lf %d..\n", flag, k, l);
}
else if(j > N - S)
{
k = k + (N - j);
}
else
{
k = k + S;
}
if(i < S - 1)
{
if(conflag == 1)
k = k*min(n, i + 1);
else if(i + (S) == M)
{
conflag = 1;
n = i + 1;
k = k*n;
}
else if(conflag == 0)
k = k*(i + 1);
}
else if (i > M - S)
{
k = k*(M - i);
}
else
{
k = k*S;
}
//printf("%d %d %.0lf...\n", i, j, k);
ships = ships + k;
}
j++;
}
rows = M - (S - 1), columns = N - (S - 1);
area = rows*columns;
answer = ships/area;
printf("%.6lf\n", answer);
return 0;
}