标签:src close closed 语言 ict equals sub F12 个人
注意到 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; }
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; }
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(); } }
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)
请思考时间上更优的方法
HZNU 19级短学期 7.3 HZNUOJ1842 天天向上
标签:src close closed 语言 ict equals sub F12 个人
原文地址:https://www.cnblogs.com/hznumqf/p/13220953.html