HZNU 19級短學期 7.3 HZNUOJ1842 天天向上


注意到 n名同學 n<=1000 m個詢問 m<=1000

因此思路可以是:

將n名同學的信息存儲在一個數組中,對於每個詢問,向這個數組查找這名同學。 至於題目要求的“”他們與第一名相差多少名次“ 實際上就是前面有幾個人比他分數高。

於是相當於循環里面套兩個循環。

請注意讀入字符串的時候讀入了”:“請思考如何處理

復雜度O(n*m) ,可以接受

 

C語言:

#include<stdio.h>
#include<string.h>

struct Student {
    char s[105];
    int score;
};

int main() {
    int n, m;
    struct Student s[1005];
    char name[105];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf(" %s%d", s[i].s,&s[i].score);
        s[i].s[strlen(s[i].s) - 1] = '\0';
    }
    scanf("%d", &m);
    for (int i = 0; i < m; i++) {
        scanf("%s", name);
        int sc;
        int rank = 0;
        for (int j = 0; j < n; j++) {
            if (strcmp(name, s[j].s) == 0) {
                sc = s[j].score; break;
            }
        }
        for (int j = 0; j < n; j++) {
            if (s[j].score > sc) rank++;
        }
        printf("%d\n", rank);
    }
    return 0;
}
View Code

 

C++:

#include<iostream>
#include<unordered_map>
#include<string>

std::unordered_map<std::string, int> stu;


int main() {
    int n, m;
    std::cin >> n;
    std::string name;
    int score;
    for (int i = 0; i < n; i++) {
        std::cin >> name >> score;
        stu[name] = score;
    }
    std::cin >> m;
    for (int i = 0; i < m; i++) {
        std::cin >> name;
        name += ":";
        int tmp = stu[name];
        int rank = 0;
        for (auto it = stu.begin(); it != stu.end(); it++) {
            if (it->second > tmp) rank++;
        }
        printf("%d\n", rank);
    }
    return 0;
}
View Code

 

Java:

import java.util.Scanner;

public class Main{
    static String[] a = new String[1005];
    static int[] b = new int [1005];
    public static void main(String[] args){
        Scanner in = new Scanner (System.in);
        int n,m;
        n = in.nextInt();
        for(int i = 0 ;i < n; i++){
            a[i]=in.next();
            b[i]=in.nextInt();
        }
        m = in.nextInt();
        for(int i=0; i < m; i++){
            String name = new String();
            int tmp = 0;
            name=in.next();
            for(int j = 0;j < n; j++){
                if(name.equals(a[j].substring(0, a[j].length() - 1)))  {
                    tmp=b[j];
                    break;
                }
            }
            int rank = 0;
            for(int j = 0;j < n; j++){
                if(b[j] > tmp) rank++;
            }
            System.out.println(rank);
        }
        in.close();
    }
}
View Code

 

Python:

d = dict()
n = int(input())
for i in range(n):
    name, score = map(str, input().split(": "))
    d[name] = int(score)
m = int(input())
for i in range(m):
    name = input()
    tmp = d[name]
    rank = 0
    for num in d.values():
        if num > tmp:
            rank += 1
    print(rank)
View Code

 

 

請思考時間上更優的方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM