using namespace std;
typedef long long int ll;
typedef unsigned long long ull;
typedef double db;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int,int> PI;
typedef pair<ll,ll> PL;
#define w(n) while(n--)
#define f(i,n) for(ll i=1;i<=n;i++)
#define fr(i,n) for(int i=0;i<n;i++)
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
w(t)
{
ll n;
cin>>n;
ll ans=0;
ll a[n];
std::stack<int>st ;
ll mn=INT_MAX;
int index;
fr(i,n)
{
ll x;
cin>>x;
a[i]=x;
st.push(x);
mn=min(mn,x);
if(mn==x)
{
index=i;
}
}
ans=mn*n;
while(st.top()!=mn)
{st.pop();}
st.pop();
int cnt=0;
int k=index;
while(!st.empty())
{
cnt++;
k=index;
mn=*min_element(a,a+k);
while(st.top()!=mn)
{
st.pop();
index--;
}
ans=ans+(mn-cnt)*k;
st.pop();
}
cout<<ans<<"\n";
}
}
why this is showing a runtime error
Please Format your code and link the question first.
For reference, here’s my code
My Code
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin>>n;
long long int ans=0;
for(int i=0, value=1e9;i<n;i++){
int box;
cin>>box;
value=min(value, box);
ans+=value;
}
cout<<ans<<'\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >>t;
while(t--){
solve();
}
}
but why is that runtime error coming in my code
Okay a few fixes were needed.
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;
typedef double db;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int,int> PI;
typedef pair<ll,ll> PL;
#define w(n) while(n--)
#define f(i,n) for(ll i=1;i<=n;i++)
#define fr(i,n) for(int i=0;i<n;i++)
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
w(t)
{
ll n;
cin>>n;
ll ans=0;
ll a[n];
std::stack<int>st ;
ll mn=INT_MAX;
int index;
fr(i,n)
{
ll x;
cin>>x;
a[i]=x;
st.push(x);
mn=min(mn,x);
if(mn==x)
{
index=i;
}
}
//(ll) to prevent overflow
ans=(ll)mn*(n-index);//Only the ones you will pop
while(st.top()!=mn)
{st.pop();}
st.pop();
int cnt=0;
int k=index;
while(!st.empty())
{
cnt++;
k=index;
mn=*min_element(a,a+k);
while(st.top()!=mn)
{
st.pop();
index--;
}
st.pop();
index--;//You need to reduce index for this pop as well. this caused The RE
ans=ans+(ll)mn*(k-index);//Again only the ones you've popped
}
cout<<ans<<"\n";
}
}