简体   繁体   中英

Trouble finding maximum values for every column in 2 dimensional array

Problem- http://codeforces.com/problemset/problem/152/A

I have tried to find the maximum grade per subject and then find all the students who have obtained maximum grade for every subject.If a student has scored maximum marks in atleast 1 subject,the value of corresponding element in best is assigned 1. Finding number of elements having value 1 in the array best,we can determine number of successful students. I am having trouble in determining maximum grade per subject.The maximum grade per subject for test case 7(given below) is coming out wrong.What is wrong with my code?

Judge's log for test case giving wrong output:

Time: 0 ms, memory: 0 KB
Verdict: WRONG_ANSWER
Input
3 4
2553
6856
5133
Output
3
Answer
2
Checker comment
wrong answer expected 2, found 3

My code:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    int n,m,temp;
    string grade[101];
    int best[101],maxgrade[101];

    cin>>n>>m;
    for(int i=0;i<n;i++)
    {
        cin>>grade[i];
    }

    for(int j=0;j<m;j++) //Finding maximum grade per subject.
    {
        int maximum=grade[0][j];
        maximum-=48; //Marks are stored as characters.Subtracting 48 gives integral value of the ASCII value of number.

        for(int i=0;i<n;i++)
        {
            temp=grade[i][j];
            temp-=48;
            maxgrade[j]=max(maximum,temp);                      
        }
    }

    int successful=0;

    for(int i=0;i<n;i++) //Finding number of students having obtained maximum grade in atleast 1 subject.
    {
        for(int j=0;j<m;j++)
        {
            temp=grade[i][j];
            temp-=48;

            if(temp==maxgrade[j])
            {
                best[i]=1;
                successful++;
                break;
            }
        }
    }

    cout<<successful;
}

The problem is in the first for loop, you could correct it as a follows (please note maxgrade[j]=max(...) expression):

for(int j=0;j<m;j++) //Finding maximum grade per subject.
{
    maxgrade[j] = 0;

    for(int i=0;i<n;i++)
    {
        temp=grade[i][j] - 48;
        maxgrade[j]=max(maxgrade[j], temp);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM