百练OJ:4151:电影节
生活随笔
收集整理的這篇文章主要介紹了
百练OJ:4151:电影节
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:
4151電影節
描述
大學生電影節在北大舉辦! 這天,在北大各地放了多部電影,給定每部電影的放映時間區間,區間重疊的電影不可能同時看(端點可以重合),問李雷最多可以看多少部電影。
輸入
多組數據。每組數據開頭是n(n<=100),表示共n場電影。
接下來n行,每行兩個整數(0到1000之間),表示一場電影的放映區間
n=0則數據結束
輸出
對每組數據輸出最多能看幾部電影
樣例輸入
8 3 4 0 7 3 8 15 19 15 20 10 15 8 18 6 12 0樣例輸出
3解題分析:
本題采用貪心算法:
首先對輸入的數據按照結束時間從小到大排序,然后進行貪心選擇。
解題代碼:
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner input = new Scanner(System.in);while (true) {int n = input.nextInt();int length = n;if (n == 0)break;int[] starts = new int[n];int[] ends = new int[n];while (n > 0) {n--;int start = input.nextInt();int end = input.nextInt();starts[n] = start;ends[n] = end;}// 按照結束時間從早到晚排序for (int i = length - 1; i > 0; i--) {for (int j = i; j >= 0; j--) {if (ends[i] < ends[j]) {// 交換int tempStart = starts[i];starts[i] = starts[j];starts[j] = tempStart;int tempEnd = ends[i];ends[i] = ends[j];ends[j] = tempEnd;}}}// 開始貪心int tmpStart = 0;int index = 0;int count = 0;while (index < length) {if (starts[index] >= tmpStart) {count++;tmpStart = ends[index];}index++;}System.out.println(count);}} }結果:?Accepted
總結
以上是生活随笔為你收集整理的百练OJ:4151:电影节的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java将字符串逻辑表达式转成布尔值
- 下一篇: 威佐夫博弈:百练OJ:1067:取石子游