Click here to Skip to main content
15,884,059 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need help with my code for CodeChef's Chef and Digits http://www.codechef.com/APRIL14/problems/ADIGIT/[^]

My code somehow gives WA, I tried every test case that came to my mind and don't know what is wrong. Can someone see the problem?

Algorithm is:

1. Sort a copy of the list of indices x given in the input in M vector.
2. Sweep through the string, counting the occurrences of each digit as I go along. Each time I hit one of the x, I compute the answer from the current counts and put the answer in a array indexed by x.
3.Output the answers in correct order by looping through the original list and looking up the value in answers massive.
Here is my code:

C++
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include<iostream>
#include<vector>
#include<fstream>
#include<algorithm>
#include<string>
#include<cmath>
#include<sstream>
using namespace std;
int n, m, t;
string temp;
int counter[10];
int answers[100002];

int answer(int mas[], int x) {
    int B = 0;
    for (int i = 0; i <= 9; i++)
        B += mas[i] * abs(x - i);
    return B;
}



int main() {
    cin>>n>>m;
    vector<int>M;
    vector<int>M2;
    cin >> temp;
    int B = 0;
    for (int i = 0; i < m; i++) {
        cin>>t;
        M.push_back(t);
        M2.push_back(t);
    }
    sort(M.begin(), M.end());

    int k = 0;

    for (int i = 1; i <= n; i++)
    {
        if (k == M.size()) break;
        if (i == M[k])
        {
            answers[M[k]] = answer(counter, temp[M[k]-1]-'0');
            k++;
        }
        counter[temp[i - 1] - '0']++;
    }

    for (int i = 0; i < m; i++)
        printf("%d\n", answers[M2[i]]);

    return 0;
}
Posted
Comments
OriginalGriff 10-Apr-14 12:24pm    
WA? What's 'At supposed to mean?
Richard MacCutchan 10-Apr-14 12:49pm    
Rhymes with anchor?
Richard MacCutchan 10-Apr-14 12:58pm    
Wouldn't it be more sensible to post your question in the forum connected to the article on CodeChef?
Member 10739783 10-Apr-14 13:00pm    
WA = Wrong Answer
OriginalGriff 10-Apr-14 13:59pm    
Well, that helps a lot as well!
There is, presumably, one "right answer" - which leaves us with an infinite surfeit of "wrong answer" values which it could be...

So, what value did you expect, and why? And what value did you get, and what have you done to find out why?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900