POJ - 1201 AcWing 362. Intervals(差分约束)(贪心+线段树)

题干:

You are given n closed, integer intervals [ai, bi] and n integers c1, …, cn.
Write a program that:
reads the number of intervals, their end points and integers c1, …, cn from the standard input,
computes the minimal size of a set Z of integers which has at least ci common elements with interval [ai, bi], for each i=1,2,…,n,
writes the answer to the standard output.

Input
The first line of the input contains an integer n (1 <= n <= 50000) – the number of intervals. The following n lines describe the intervals. The (i+1)-th line of the input contains three integers ai, bi and ci separated by single spaces and such that 0 <= ai <= bi <= 50000 and 1 <= ci <= bi - ai+1.
Output
The output contains exactly one integer equal to the minimal size of set Z sharing at least ci elements with interval [ai, bi], for each i=1,2,…,n.

Sample Input
5
3 7 3
8 10 3
6 8 1
1 3 1
10 11 1
Sample Output
6

思路:

总结下题意:给定 n 个区间 [ai,bi]和 n 个整数 ci。
你需要构造一个整数集合 Z,使得∀i∈[1,n],Z 中满足ai≤x≤bi的整数 x 不少于 ci 个。
求这样的整数集合 Z 最少包含多少个数。
例如样例的集合Z可能为:3,6,7,8,9,10
(1)因为是不等式关系,所以我们可以用差分约束来做,设Si为从1~i中杯选出数的个数,S0=0;则我们可以得出以下关系式:
S i S_i Si>= S i − 1 S_{i-1} Si1
S i − S i − 1 S_i-S_{i-1} SiSi1<=1即 S i − 1 S_{i-1} Si1>= S i S_i Si-1
S b − S a − 1 S_b-S_{a-1} SbSa1>=C即 S b S_b Sb >= S a − 1 S_{a-1} Sa1+C
将数轴右移一格,移出0的位置(即a->a+1)
因为题目保证有解,这样我们要求的就是 S 50001 S_{50001} S50001的最小值,即最长路。

//ACWING上能过POJ上超时
#include 
#include 
#include 
#include 

using namespace std;

const int N = 50010, M = 150010;

int n;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
int q[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

void spfa()
{
    memset(dist, -0x3f, sizeof dist);
    dist[0] = 0;
    st[0] = true;
    int hh = 0, tt = 1;
    q[0] = 0;

    while (hh != tt)
    {
        int t = q[hh ++ ];
        if (hh == N) hh = 0;
        st[t] = false;

        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] < dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                if (!st[j])
                {
                    q[tt ++ ] = j;
                    if (tt == N) tt = 0;
                    st[j] = true;
                }
            }
        }
    }
}

int main()
{
    scanf("%d", &n);

    memset(h, -1, sizeof h);
    for (int i = 1; i < N; i ++ )
    {
        add(i - 1, i, 0);
        add(i, i - 1, -1);
    }

    for (int i = 0; i < n; i ++ )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        a ++, b ++ ;
        add(a - 1, b, c);
    }

    spfa();

    printf("%d\n", dist[50001]);

    return 0;
}

(2)贪心+线段树

你可能感兴趣的:(图论,差分约束,线段树)