i am getting 0xc0000005 error(access violation error), where am i wrong in this code?
i couldnt debug this error. please help me.
question is this
Formally, given a wall of infinite height, initially unpainted. There occur N operations, and in ith operation, the wall is painted upto height Hi with color Ci. Suppose in jth operation (j>i) wall is painted upto height Hj with color Cj such that Hj >= Hi, the Cith color on the wall is hidden. At the end of N operations, you have to find the number of distinct colors(>=1) visible on the wall.
#include<iostream>
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main()
{
int t;
cin>>t;
for(int tt= 0;tt<t;tt++)
{
int h,c;
int temp = 0;
cin>>h>>c;
int A[h], B[c];
vector<int> fc;
for(int i = 0;i<h;i++)
{
cin>>A[i];
}
for(int j =0;j<h;j++)
{
cin>>B[j];
}
if(is_sorted(A,A+h))
{
return 1;
}
if(count(A,A+h,B[0]) == h)
{
return 1;
}
for(int i = 0;i<h;i++)
{
if(A[i]>=temp)
{
temp = A[i];
}
else
{
if(temp == fc[fc.size()-1])
{
fc[fc.size()-1] = B[i];
}
else
{
fc.push_back(B[i]);
}
}
}
}
}
There are several issues.
When reading values into B, your loop check is j<h. How many elements are in B?
You later look at fc[fc.size()-1]. This is Undefined Behavior if fc is empty, and is the likely source of your problem.
Other issues:
Don't use #include <bits/stdc++.h>
Avoid using namespace std;
Variable declarations like int A[h], where h is a variable, are not standard C++. Some compilers support them as an extension.
Related
Which is more efficient in terms of memory and time complexity hashing using int array or unordered_map in STL?
By hashing I mean storing elements formed by the combination of a key value and a mapped value, and fast retrieval of individual elements based on their keys.
Actually I was trying to solve this question.
Here's my solution:-
#include <bits/stdc++.h>
#define MAX 15000005
using namespace std;
/*
* author: vivekcrux
*/
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int c[MAX];
int n;
int sieve()
{
bitset<MAX> m;
m.set();
int ans = 0;
for(int i=2;i<MAX;i++)
{
if(m[i])
{
int mans = 0;
for(int j=i;j<MAX;j+=i)
{
m[j]=0;
mans += c[j];
}
if(mans<n)
ans = max(ans,mans);
}
}
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int i,j;
cin>>n;
int a[n+1];
for(i=0;i<n;i++)
{
cin>>a[i];
}
int g = a[0];
for(i=1;i<n;i++)
{
g = gcd(g,a[i]);
}
for(i=0;i<n;i++)
{
a[i] /= g;
if(a[i]!=1) c[a[i]]++;
}
int m = sieve();
if(m==0)
cout<<"-1";
else
cout<<n - m<<endl;
return 0;
}
In this code if I use
unordered_map<int,int> c;
instead of
int c[MAX];
I get a Memory limit exceeded verdict.I have found here that unordered_map has a constant average time complexity on average, but no details about space complexity is mentioned here.I wonder why am I getting MLE with unordered_map.
unordered_map uses bucket to store values. A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash value of their key. Lets see the following code in C++17.
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int,int> mp;
mp[4] = 1;
mp[41] = 5;
mp[67] = 6;
cout<<mp.bucket_count();
}
The output comes out be 7 (depends on compiler). This is the number of buckets used in the above code. But if we use an array of size 67, it will obviously take more memory. Another case would be that if we would had numbers 1, 2 and 3 instead of 4, 41 and 67, the output would have been 7. Here using array was the way to go for saving space. So it depends on the keys you are storing in the hash table. For time complexity, both performs equally same. There is a collision condition in unordered_map which would blow the overall time complexity of the code. Here is the codeforces link of the blog.
My implementation of selection sort does not work in case of j < n-2 or n-1 or n. What am I doing wrong?
Is there an online IDE that lets us put a watch for the control loops?
#include <stdio.h>
#define n 4
int main(void) {
int a[n]={4,3,2,1};
int j,min;
for(int i=0;i<n;i++){
min=i;
for(j=i+1;j<n-3;j++)
if(a[j]>a[j+1])
min=j+1;
if(min!=i){
int t=a[min];
a[min]=a[i];
a[i]=a[t];
}
}
for(int i=0;i<n;i++)
printf("%d",a[i]);
return 0;
}
I tried it here
Your code has indeed a strange limit on n-3, but it has also some other flaws:
To find a minimum you should compare with the current minimum (a[min]), not the next/previous element in the array
The code to swap is not correct: the last assignment should not be from a[t], but t itself.
Here is the corrected code:
int main(void) {
int a[n]={4,3,2,1};
int j,min;
for(int i=0;i<n;i++){
min=i;
for(j=i+1;j<n;j++)
if(a[min]>a[j])
min=j;
if(min!=i){
int t=a[min];
a[min]=a[i];
a[i]=t;
}
}
for(int i=0;i<n;i++)
printf("%d",a[i]);
return 0;
}
https://ideone.com/AGJDPS
NB: To see intermediate results in an online IDE, why not add printf calls inside the loop? Of course, for larger code projects you'd better use a locally installed IDE with all the debugging features, and step through the code.
I am trying to solve this Problem on UVA.The question is about finding the max-flow in the graph.I used Edmond-karp algorithm but I am continuously getting wrong answer.Can any one tell me what's wrong in my code ?
My code :
#include<bits/stdc++.h>
using namespace std;
#define MX 1000000007
#define LL long long
#define ri(x) scanf("%d",&x)
#define rl(x) scanf("%lld",&x)
#define len(x) x.length()
#define FOR(i,a,n) for(int i=a;i<n;i++)
#define FORE(i,a,n) for(int i=a;i<=n;i++)
template<class T1> inline T1 maxi(T1 a,T1 b){return a>b?a:b;}
template<class T2> inline T2 mini(T2 a,T2 b){return a<b?a:b;}
int parent[101],G[101][101],rG[101][101];
bool bfs(int s,int t,int n)
{
bool vis[n+2];
memset(parent,0,sizeof parent);
memset(vis,0,sizeof vis);
queue<int>Q;
Q.push(s);
vis[s]=true;
while(!Q.empty())
{
int fnt=Q.front();
Q.pop();
for(int v=1;v<=n;v++)
{
if(!vis[v] and G[fnt][v]>0)
{
vis[v]=true;
parent[v]=fnt;
Q.push(v);
}
}
}
return vis[t];
}
int main()
{
int n,tst=1;
ri(n);
while(n)
{
int s,t,c,flow=0;
ri(s),ri(t),ri(c);
FORE(i,1,c)
{
int x,y,z;
ri(x),ri(y),ri(z);
G[x][y]+=z;
G[y][x]+=z;
}
while(bfs(s,t,n))
{
int path=9999999;
for(int v=t;v!=s;v=parent[v])
{
int u=parent[v];
path=mini(path,G[u][v]);
}
for(int v=t;v!=s;v=parent[v])
{
int u=parent[v];
G[u][v]-=path;
G[v][u]+=path;
}
flow+=path;
}
printf("Network %d\nThe bandwidth is %d.\n\n", tst++, flow);
ri(n);
}
}
You push flow the other way around:
G[u][v]-=path;
G[v][u]+=path;
This should be:
G[u][v] += path;
G[v][u] -= path;
Also, I'm not sure about this part:
if(!vis[v] and G[fnt][v]>0)
[...]
path=mini(path,G[u][v]);
Because you are also allowed to take paths on which the flow is negative. You should not change G, which seems to be your capacities graph. Instead, you should have a matrix F that stores how much flow you send. Then your two conditions should be changed to:
if (!vis[v] && G[fnt][v] != F[fnt][v])
[...]
path = mini(path, G[u][v] - F[u][v])
And push flow on F, not G.
You seem to have thought about this since you declared a matrix rG, but you're never using it.
There might be other issues too. It's hard to tell without knowing what problems you're seeing.
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
int firstMissingPositive(vector<int> A) {
sort(A.begin() , A.end());
int i,start=-1,j;
for(i=0; i<A.size(); i++)//to find the least positive number
{
if(A.at(i)>=0)
{
start=i;
break;
}
}
if(start==-1)
return 1; //when the vector has no positive number
else
{
for(j=start; j<=A.at(A.size()); j++)//to find the least positive missing number
{
if ( find(A.begin(), A.end(), i)!=A.end() )
continue;
else
return i;
}
}
}
int main()
{
vector<int> b;
int myarray [] = { 501,504,503 };
b.insert (b.begin(), myarray, myarray+3);
firstMissingPositive(b);
}
The error shown is: terminate called after throwing an instance of
'std::out_of_range' what<>: vector::_M_range_check
I have been dealing with this since long but can not detect the err in it.
Here, you are stuck at this statement:
for(j=start; j<=A.at(A.size()); j++) //to find the least positive missing number
It should be:
for(j=start; j<=A.at(A.size()-1); j++)
because you are trying to access A.size()th element which is throwing out_of_range error.
You are developing a smartphone app. You have a list of potential
customers for your app. Each customer has a budget and will buy the app at
your declared price if and only if the price is less than or equal to the
customer's budget.
You want to fix a price so that the revenue you earn from the app is
maximized. Find this maximum possible revenue.
For instance, suppose you have 4 potential customers and their budgets are
30, 20, 53 and 14. In this case, the maximum revenue you can get is 60.
**Input format**
Line 1 : N, the total number of potential customers.
Lines 2 to N+1: Each line has the budget of a potential customer.
**Output format**
The output consists of a single integer, the maximum possible revenue you
can earn from selling your app.
Also, upper bound on N is 5*(10^5) and upper bound on each customer's budget is 10^8.
This is a problem I'm trying to solve . My strategy was to sort the list of budgets and then multiply each of those with its position-index in the sequence - and then print the max of the resulting sequence. However this seems to be quite time-inefficient (at least in the way I'm implementing it - I've attached the code for reference). My upper bound on time is 2 seconds. Can anyone help me find a
more time-efficient algorithm (or possibly a more efficient way to implement my algorithm) ?
Here is my solution :
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
using namespace std;
long long max(long long[],long long);
void quickSortIterative(long long[],long long,long long);
long long partition(long long[],long long,long long);
void swap(long long*,long long*);
int main(){
long long n,k=1;
scanf("%lld",&n);
if(n<1 || n > 5*((long long)pow(10,5))){
exit(0);
}
long long budget[n],aux[n];
for(long long i=0;i<n;i++){
scanf("%lld",&budget[i]);
if(budget[i]<1 || budget[i] > (long long)pow(10,8)){
exit(0);
}
}
quickSortIterative(budget,0,n-1);
for(long long j=n-1;j>=0;j--){
aux[j] = budget[j]*k;
k++;
}
cout<<max(aux,n);
return 0;
}
long long partition (long long arr[], long long l, long long h){
long long x = arr[h];
long long i = (l - 1);
for (long long j = l; j <= h- 1; j++)
{
if (arr[j] <= x)
{
i++;
swap (&arr[i], &arr[j]);
}
}
swap (&arr[i + 1], &arr[h]);
return (i + 1);
}
void swap ( long long* a, long long* b ){
long long t = *a;
*a = *b;
*b = t;
}
void quickSortIterative(long long arr[], long long l, long long h){
long long stack[ h - l + 1 ];
long long top = -1;
stack[ ++top ] = l;
stack[ ++top ] = h;
while ( top >= 0 ){
h = stack[ top-- ];
l = stack[ top-- ];
long long p = partition( arr, l, h );
if ( p-1 > l ){
stack[ ++top ] = l;
stack[ ++top ] = p - 1;
}
if ( p+1 < h ){
stack[ ++top ] = p + 1;
stack[ ++top ] = h;
}
}
}
long long max(long long arr[],long long length){
long long max = arr[0];
for(long long i=1;i<length;i++){
if(arr[i]>max){
max=arr[i];
}
}
return max;
}
Quicksort can take O(n^2) time for certain sequences (often already sorted sequences are bad).
I would recommend you try using a sorting approach with guaranteed O(nlogn) performance (e.g. heapsort or mergesort). Alternatively, you may well find that using the sort routines in the standard library will give better performance than your version.
You might use qsort in C or std::sort in C++, which is most likely faster than your own code.
Also, your "stack" array will cause you trouble if the difference h - l is large.
I have used STL library function sort() of C++. It's time complexity is O(nlogn). Here, you just need to sort the given array and check from maximum value to minimum value for given solution. It is O(n) after sorting.
My code which cleared all the test cases :
#include <algorithm>
#include <stdio.h>
#include <cmath>
#include <iostream>
using namespace std;
int main(){
long long n, a[1000000], max;
int i, j;
cin>>n;
for(i = 0; i < n; i++){
cin>>a[i];
}
sort(a, a + n);
max = a[n - 1];
for(i = n - 2; i >= 0; i--){
//printf("%lld ", a[i]);
if(max < (a[i] * (n - i)))
max = a[i] * (n - i);
}
cout<<max<<endl;
return 0;
}
I dont know if my answer is right or wrong please point out mistakes if there is any
#include<stdio.h>
void main()
{
register int i,j;
long long int n,revenue;
scanf("%Ld",&n);
long long int a[n];
for(i=0;i<n;i++)
scanf("%Ld",&a[i]);
for (i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
}
for(i=0;i<n;i++)
a[i]=(n-i)*a[i];
revenue=0;
for(i=0;i<n;i++)
{
if(revenue<a[i])
revenue=a[i];
}
printf("%Ld\n",revenue);
}
passed all the test cases
n=int(input())
r=[]
for _ in range(n):
m=int(input())
r.append(m)
m=[]
r.sort()
l=len(r)
for i in range(l):
m.append((l-i)*r[i])
print(max(m))
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
long long n;
std::cin >> n;
long long a[n];
for(long long i=0;i<n;i++)
{
std::cin >> a[i];
}
sort(a,a+n);
long long max=LONG_MIN,count;
for(long long i=0;i<n;i++)
{
if(a[i]*(n-i)>max)
{
max=a[i]*(n-i);
}
}
std::cout << max << std::endl;
return 0;
}
The following solution is in C programming Language.
The Approach is:
Input the number of customers.
Input the budgets of customers.
Sort the budget.
Assign revenue=0
Iterate through the budget and Multiply the particular budget with the remaining budget values.
If the previous-revenue < new-revenue. assign the new-revenue to revenue variable.
The code is as follows:
#include <stdio.h>
int main(void) {
int i,j,noOfCustomer;
scanf("%d",&noOfCustomer);
long long int budgetOfCustomer[noOfCustomer],maximumRevenue=0;
for(i=0;i<noOfCustomer;i++)
{
scanf("%Ld",&budgetOfCustomer[i]);
}
for(i=0;i<noOfCustomer;i++)
{
for(j=i+1;j<noOfCustomer;j++)
{
if(budgetOfCustomer[i]>budgetOfCustomer[j])
{
budgetOfCustomer[i]=budgetOfCustomer[i] + budgetOfCustomer[j];
budgetOfCustomer[j]=budgetOfCustomer[i] - budgetOfCustomer[j];
budgetOfCustomer[i]=budgetOfCustomer[i] - budgetOfCustomer[j];
}
}
}
for(i=0;i<noOfCustomer;i++)
{
budgetOfCustomer[i]=budgetOfCustomer[i]*(noOfCustomer-i);
}
for(i=0;i<noOfCustomer;i++)
{
if(maximumRevenue<budgetOfCustomer[i])
maximumRevenue=budgetOfCustomer[i];
}
printf("%Ld\n",maximumRevenue);
return 0;
}