题目1112:拦截导弹

来源:互联网 发布:网络粑粑什么意思 编辑:程序博客网 时间:2024/05/24 07:24

java实现:

import java.io.IOException;import java.io.FileReader;import java.util.Scanner;import java.util.Arrays;class Main{public static final boolean DEBUG = false;public static void main(String[] args) throws IOException{Scanner cin;int n;if (DEBUG) {cin = new Scanner(new FileReader("d:\\OJ\\uva_in.txt"));} else {cin = new Scanner(System.in);}while (cin.hasNext()) {n = cin.nextInt();int[] arr = new int[n];for (int i = 0; i < n; i++) {arr[i] = cin.nextInt();}int[] dp = new int[n];Arrays.fill(dp, 1);int ans = 1;for (int i = 1; i < n; i++) {for (int j = 0; j < i; j++) {if (arr[i] <= arr[j]) {dp[i] = Math.max(dp[j] + 1, dp[i]);ans = Math.max(ans, dp[i]);}}}System.out.println(ans);}}}


C++实现:

#include <iostream>#include <fstream>#include <vector>#include <algorithm>using namespace std;int main(){    int n;    #ifndef ONLINE_JUDGE        ifstream cin("d:\\OJ\\uva_in.txt");    #endif // ONLINE_JUDGE    while (cin >> n) {        vector<int> v(n);        for (int i = 0; i < n; i++) {            cin >> v[i];        }        reverse(v.begin(), v.end());        vector<int> ans;        for (size_t i = 0; i < v.size(); i++) {            if (ans.size() == 0) {                ans.push_back(v[i]);            } else {                int len = ans.size();                if (v[i] >= ans[len - 1]) ans.push_back(v[i]);                else {                    vector<int>::iterator it = lower_bound(ans.begin(), ans.end(), v[i]);                    *it = v[i];                }            }        }        cout << ans.size() << endl;    }    return 0;}


0 0
原创粉丝点击