专题测试三 贪心与动态规划 L - Priest John's Busiest Day

  1. 题目
    John is the only priest in his town. October 26th is the John’s busiest day in a year because there is
    an old legend in the town that the couple who get married on that day will be forever blessed by the
    God of Love. This year N couples plan to get married on the blessed day. The i-th couple plan to hold
    their wedding from time Si to time Ti
    . According to the traditions in the town, there must be a special
    ceremony on which the couple stand before the priest and accept blessings. Moreover, this ceremony
    must be longer than half of the wedding time and can’t be interrupted. Could you tell John how to
    arrange his schedule so that he can hold all special ceremonies of all weddings?
    Please note that:
    John can not hold two ceremonies at the same time.
    John can only join or leave the weddings at integral time.
    John can show up at another ceremony immediately after he finishes the previous one.
    Input
    The input consists of several test cases and ends with a line containing a zero. In each test case, the
    first line contains a integer N (1 ≤ N ≤ 100, 000) indicating the total number of the weddings. In the
    next N lines, each line contains two integers Si and Ti (0 ≤ Si < Ti ≤ 2147483647).
    Output
    For each test, if John can hold all special ceremonies, print ‘YES’; otherwise, print ‘NO’.
    Sample Input
    3
    1 5
    2 4
    3 6
    2
    1 5
    4 6
    0
    Sample Output
    NO
    YES
  2. 思路
    对于每场婚礼,如果都能举行仪式,那么每场婚礼的中点一定处于举行仪式的时间内(因为举行仪式至少举行一半)。将中点求出来排个序,每次尽可能早地安排时间,如果保证每个中点都能被对应仪式覆盖就是YES,否则就是NO
  3. 代码
    #include<cstdio>
    #include<iostream>
    #include<string>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    
    int n;
    
    struct node
    {
        int S, T;
    }Node[100005];
    
    bool cmp(node a,node b)
    {
    	return (a.S + a.T) / 2 < (b.S + b.T) / 2;
    }
    
    int main()
    {
    	while(scanf("%d",&n)&&n!=0)
    	{
    		for(int i=0;i<n;i++){
    			scanf("%d%d",&Node[i].S,&Node[i].T);
    		}
    		sort(Node,Node+n,cmp);
    		int t = 0;
    		bool f = 1;
    		for(int i=0;i<n;i++)
    		{
    			t = max(t,Node[i].S)+(Node[i].T-Node[i].S)/2 + 1;
    			if (t > Node[i].T)
    			{
    				f = 0;break;
    			}
    		}
    		if(f)
    		{
    			printf("YES\n");
    		}
    		else
    		{
    			printf("NO\n");
    		}
    	}
    	return 0;
    }
posted @ 2022-02-17 12:35  Benincasa  阅读(31)  评论(0编辑  收藏  举报