WY63. 丰收
描述
又到了丰收的季节,恰逢小易去牛牛的果园里游玩。输入描述
第一行一个数n(1 <= n <= 105)。输出描述
m行,第i行输出第qi个苹果属于哪一堆。示例1
输入:
5 2 7 3 4 9 3 1 25 11
输出:
1 5 3
C++ 解法, 执行用时: 30ms, 内存消耗: 3752KB, 提交时间: 2020-10-29
#include <stdio.h> #include <vector> #include <string> #include <cstring> #include<algorithm> #include <iostream> #include <math.h> using namespace std; int main() { int n, m; std::iostream::sync_with_stdio(0); cin.tie(0); cin >> n; int app[100000] = { 0 }; for (int i = 0; i < n; i++) { cin >> app[i]; } cin >> m; vector<pair<int, int>> vec(m); for (int i = 0; i < m; i++) { cin >>vec[i].first; vec[i].second = i; } for (int i = 1; i < n; i++) { app[i] += app[i - 1]; } sort(vec.begin(), vec.end()); int j = 0; vector<int> display(m); for (int i = 0; i<m; i++) { while (vec[i].first>app[j]) j++; display[vec[i].second] = j+1; } for (int i = 0; i<m; i++) printf("%d\n",display[i] ); //二分查找! /*cin >> m; for (int i = 0; i != m; ++i) { cin >> q; cout<< lower_bound(appsum.begin(), appsum.end(), make_pair(q,0))->second<< endl; }*/ return 0; }
C++ 解法, 执行用时: 31ms, 内存消耗: 3780KB, 提交时间: 2020-10-29
#include <stdio.h> #include <vector> #include <string> #include <cstring> #include<algorithm> #include <iostream> #include <math.h> using namespace std; int main() { int n, m; std::iostream::sync_with_stdio(0); cin.tie(0); cin >> n; int app[100000] = { 0 }; for (int i = 0; i < n; i++) { cin >> app[i]; } cin >> m; vector<pair<int, int>> vec(m); for (int i = 0; i < m; i++) { cin >>vec[i].first; vec[i].second = i; } for (int i = 1; i < n; i++) { app[i] += app[i - 1]; } sort(vec.begin(), vec.end()); int j = 0; vector<int> display(m); for (int i = 0; i<m; i++) { while (vec[i].first>app[j]) j++; display[vec[i].second] = j+1; } for (int i = 0; i<m; i++) printf("%d\n",display[i] ); //二分查找! /*cin >> m; for (int i = 0; i != m; ++i) { cin >> q; cout<< lower_bound(appsum.begin(), appsum.end(), make_pair(q,0))->second<< endl; }*/ return 0; }