北京師範大學上機題
題目一描述:
給出一系列字符串及其對應ID,要求找出某個字符串對應的ID。
輸入n+1行,第一行輸入字符串個數,接下來輸入n行,每行輸入字符串及其對應的ID。
最後輸入其中的一個字符串,輸出該字符串對應的ID。
#include<iostream>
using namespace std;
struct dic {
string str;
int id;
};
int main() {
int n;
cout << "輸入字符串個數:";
cin >> n;
dic* d = new dic[n];
cout << "輸入每條數據的字符串和對應ID:";
for (int i = 0;i < n;i++) {
cin >> d[i].str >> d[i].id;
}
string str;
cout << "輸入要查找的字符串:";
cin >> str;
int k = 0;
for (int i = 0;i < n;i++) {
if (d[i].str == str) {
k = d[i].id;
}
}
cout << str << "對應的ID是:" << k << endl;
return 0;
}
運行測試結果:
題目二描述:
輸入一組學生的成績,以及一個給定區間,輸出區間中成績最高的學生的排名和成績最低的學生排名。
#include<iostream>
using namespace std;
void sort(int num[], int n) {//先對成績從高到低排序
int temp;
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < n - i - 1;j++) {
if (num[j] < num[j + 1]) {
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
}
}
}
}
int main() {
int n;
cout << "輸入成績的個數:";
cin >> n;
int* num = new int[n];
cout << "輸入成績:";
for (int i = 0;i < n;i++)
cin >> num[i];
sort(num, n);
int a, b;
cout << "輸入查詢區間:";
cin >> a >> b;
for (int i = 0;i < n;i++) {//從高到低找到比範圍最大的數要小的第一個數
if (num[i] <= b) {
cout << "最高排名:" << i + 1 << endl;
break;
}
}
for (int i = n - 1;i >= 0;i--) {//從低到高找到比範圍最小的數要大的第一個數
if (num[i] >= a) {
cout << "最低排名:" << i + 1 << endl;
break;
}
}
return 0;
}
運行測試結果:
題目三描述:
輸入一堆要完成的任務,每個任務有開始時間和要完成的時間,求把這些任務做完最快要多久。
算法思路:
先找出各個任務中最早的開始時間,再找出最晚的結束時間,計算最晚結束時間和最早開始時間的差值。
#include<iostream>
using namespace std;
struct task {
int beg_time;
int spend_time;
};
int main() {
int n;
cout << "輸入任務數:";
cin >> n;
task* t = new task[n];
cout << "輸入每個任務的開始時間和所需時間:" << endl;
for (int i = 0;i < n;i++) {
cin >> t[i].beg_time >> t[i].spend_time;
}
int start = t[0].beg_time, end = t[0].beg_time + t[0].spend_time;
for (int i = 1;i < n;i++) {
if (t[i].beg_time < start)
start = t[i].beg_time;
if (end < (t[i].beg_time + t[i].spend_time))
end = t[i].beg_time + t[i].spend_time;
}
cout << "所需時間爲:" << end - start << endl;
return 0;
}
運行測試結果: