Hey USACO, I was wondering about this problem, my terminal outputs 3, but the test server tells me my code outputted 4. I was wondering where I might have gone wrong.
Thanks
P
Read the instructions here on how to ask for help on a problem…
You didn’t send your formatted code, so we can’t help you…
Sorry, this might be hard to read.
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
using namespace::std;
int main()
{
ifstream fin ("measurement.in");
ofstream fout ("measurement.out");
int n,i,j,k,counter;
counter=0;
bool flag;
flag=false;
int date[n];
string name[101]={""};
int change[101]={0};
int cows[3];
cows[0]=cows[1]=cows[2]=3;
int fame[3];
fame[0]=0;
fame[1]=1;
fame[2]=2;
int temp[3];
fin>>n;
for(i=0;i<n;i++)
{
fin>>date[i];
fin>>name[date[i]];
fin>>change[date[i]];
}
sort(date,date+n);
for(i=0;i<n;i++)
{
if(name[date[i]]=="Bessie")
{
cows[0]=cows[0]+change[date[i]];
temp[0]=cows[0];
}
else if(name[date[i]]=="Elsie")
{
cows[1]=cows[1]+change[date[i]];
temp[1]=cows[1];
}
else if(name[date[i]]=="Mildred")
{
cows[2]=cows[2]+change[date[i]];
temp[2]=cows[2];
}
sort(temp,temp+3);
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
if(temp[2]==cows[j])
{
if(cows[j]!=fame[k])
{
flag=true;
}
}
else if(temp[2]!=cows[j])
{
if(cows[j]==fame[k])
{
flag=true;
}
}
}
}
if(flag==true)
{
counter++;
}
flag=false;
}
fout<<counter<<endl;
}
Just throwing darts here- what if you’re referencing an index that’s out of bounds? C++ doesn’t do bounds checking when getting an element, so it may not throw an error and silently return something weird instead.
@above Thanks for the advice I compiled with the terminal so I’m pretty I didn’t access any memory I didn’t have
I don’t see why compiling with the terminal would avoid illegal memory access.
Sorry, I should have clarified, it usually returns “segmentation fault.”
Try running this code here:
#include <iostream>
#include <vector>
using namespace std; // only a quick run so this should be ok
int main() {
vector<int> arr{0, 10, 6, 7, 8};
cout << arr[0] << endl;
cout << arr[100] << endl;
}
Thanks! That doesn’t put out segmentation fault so I’m probably mistaken. I did find out the reason: I changed the string array to a regular array, and it no longer has that mistake. I am wondering why that happens though.
please put fin and fout outside of int main lol. It doesn’t matter in this code but it will once you need functions. btw, try defining less variable next time as i don’t think this is necessary lol.
see
compiling with -fsanitize=undefined
should give you an error
The following also works as file input…
freopen("file.in", "r", stdin);
freopen("file.out", "w", stdout);
// Make sure you know that "file.in" and "file.out" are just random file names I made...