-1
Well I’m in trouble on one issue
Enunciation
Given an integer vector, your task is to find the k-th occurrence (left to right) of an integer v in the vector. To make the problem more difficult (and more interesting!), you should answer m queries of this type.
Input of the test cases
8 4
1 3 2 2 4 3 2 1
1 3
2 4
3 2
4 2
In this case 1.3 I am looking for the number 3, in its first occurrence in my vector, so I use the number as Indice, the result and 2, as my code does
Logic I used in the question
to solve this problem I used the following logic, I created the element struct that will receive the value and the Indice, then I created the Map struct in it will have an element struct matrix, and an array of size that will have the size of the Indice of my struct, so when I call the function creates() I use the calloc that Zera my vector, in the insert function, I check if the Indice I’m entering and 0, why if it means there are no elements in that Indice, and fill the data normally, when it is in Else, I use realloc, to add the element, in my matrix.
My code
#include <stdio.h>
#include <stdlib.h>
typedef struct elemento
{
int valor, chave;
} Elemento;
typedef struct map
{
Elemento **dados;
int *tamanho;
} Map;
Map *cria(int tam);
int insere(Map *mp, int valor, int i);
Map *libera(Map *mp, int tam);
int main(int argc, char** argv)
{
int tam, teste;
int numero, indice;
int i;
while(scanf("%d %d", &tam, &teste) != EOF)
{
Map *matriz = cria(tam);
for(i = 0; i < tam; i++)
{
scanf("%d", &numero);
insere(matriz, numero, i + 1);
}
for(i = 0; i < teste; i++)
{
scanf("%d %d", &indice, &numero);
if(indice <= matriz->tamanho[numero])
{
printf("%d\n", matriz->dados[numero][indice - 1].chave);
}
else
{
printf("0");
}
}
matriz = libera(matriz, tam);
}
return 0;
}
Map *cria(int tam)
{
Map *mp = malloc(sizeof(Map));
if(!mp) return NULL;
mp->tamanho = calloc(tam, sizeof(int));
mp->dados = malloc(sizeof(Elemento*) * tam);
return mp;
}
int insere(Map *mp, int valor, int i)
{
if(mp->tamanho[valor] == 0)
{
mp->dados[valor] = malloc(sizeof(Elemento));
mp->dados[valor][0].valor = valor;
mp->dados[valor][0].chave = i;
mp->tamanho[valor]++;
}
else
{
int size = mp->tamanho[valor];
mp->dados[valor] = realloc(mp->dados[valor], (size + 1) * sizeof(Elemento));
mp->dados[valor][size].valor = valor;
mp->dados[valor][size].chave = i;
mp->tamanho[valor]++;
}
return 1;
}
Map *libera(Map *mp, int tam)
{
int i;
for(i = 0; i < tam; i++)
{
free(mp->dados[i]);
}
free(mp);
return NULL;
}
I honestly did not understand your interpretation of the problem and much less the logic of your solution.
– anonimo
I edited the question, in the Logic section that I used in the question, I speak the logic that I used, gave to understand better ?
– teste-90
No, in function
insereyou use the value provided as an index. What is the meaning of this?– anonimo
put the test cases in the description now, thanks for trying to help me
– teste-90