2037-No AC this summer (java)

Insert picture description here
Insert picture description here
Idea : You can sort the end time of all programs, and then start from the first program, compare the end time of the first program with the start time of the next program, if the start time of the next program is greater than the first The end time of each program indicates that the first program can be played completely, and the comparison can be done in order.

import java.util.*;
public class Main{
    
                         //简单的贪心算法,归类练习更有效
public static void main(String[] args) {
    
    
	Scanner a=new Scanner(System.in);
	while(a.hasNext())
	{
    
    
		int n=a.nextInt();
		if(n==0)
			break;
		else if(n<=100)
		{
    
    
			int[][] arr=new int[n][2];		//建立一个二维数组,将时间点开始与终点放进去
			for(int i=0;i<n;i++)
			{
    
    
				arr[i][0]=a.nextInt();
				arr[i][1]=a.nextInt();
			}
			for(int i=0;i<n-1;i++)          //n-1的原因是确保j小于n
			{
    
    
				for(int j=i+1;j<n;j++)		//这两个for是将所有节目的终点时间从小打到进行排序遍历
				{
    
    
					if(arr[i][1]>arr[j][1])
					{
    
    
						int t=arr[i][1];	//将小的终点节目的那一对时间放到前面
						arr[i][1]=arr[j][1];
						arr[j][1]=t;
						int m=arr[i][0];
						arr[i][0]=arr[j][0];
						arr[j][0]=m;
					}
				}
			}
			int count=1;
			int s=arr[0][1];				//这一步是将第一个节目的开始时间赋予S。
			for(int i=1;i<n;i++)
			{
    
    
				if(arr[i][0]>=s)			//每一对节目的开始时间有序的与第一个节目的开始时间进行比较
				{
    
    
					count++;
					s=arr[i][1];			//如果时间合适可以看完上一个节目时,将下一个节目的终点时间赋予S
				}
			}
			System.out.println(count);		//输出即可
		}
	}
}
}

If there is an error, please correct me.

Guess you like

Origin blog.csdn.net/weixin_45956604/article/details/114603372
ac