C ++, another variable is influenced by the scanf operator
The value of t becomes equal to 0 after the scanf instruction, I can't understand why t is affected by this operator, even if t = 100, the program only runs for 1 iteration! PS first question is here! and it took 100 minutes to write it! there is always some problem!: @
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#define MOD 1000000009
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m;
scanf("%d%d",&n,&m);
vector< pair<long long int,char> > a(m);
long long int x;
int i;
char d[1];
for(i=0;i<m;i++)
{
scanf("%s%lld",d,&x);// t becomes zero after this
a[i]=make_pair(x,d[0]);
}
sort(a.begin(),a.end());
long long int ans=1;
for(i=0;i<m-1;i++)
{
if(a[i].second!=a[i+1].second)
{
ans=ans*(a[i+1].first-a[i].first);
ans=ans%MOD;
}
}
ans=ans%MOD;
printf("%lld\n",ans);
}
return 0;
}
source to share
You are causing a buffer overflow on call scanf("%s%lld",d,&x)
. d
takes place only for 1 char
, but %s
is read until a space character is encountered. Even if the user only enters 1 character before the space, it still overflows because it %s
writes a null terminator at the end of the buffer he is writing. This is why it t
changes.
If you really only want to read 1 char
, you need to either:
-
declare
d
as just achar
and use%c
:char d; scanf("%c%lld",&d,&x);
-
declare
d
aschar d[2]
so that it takes place for a null terminator and use%1s
:char d[2]; scanf("%1s%lld",d,&x);
By the way, you have to be careful with things like scanf("%d%d",&n,&m)
. Think about what happens if the user types "123456"
and you would like to read it as 123
and 456
separately. The user will have to enter "123 456"
. So just be aware of it.
source to share