poj 1716 Integer Intervals (差分约束)

来源:互联网 发布:网络维护人员工作总结 编辑:程序博客网 时间:2024/06/05 15:59

Description

An integer interval [a,b], a < b, is a set of all consecutive integers beginning with a and ending with b.
Write a program that: finds the minimal number of elements in a set containing at least two different integers from each interval.

Input

The first line of the input contains the number of intervals n, 1 <= n <= 10000. Each of the following n lines contains two integers a, b separated by a single space, 0 <= a < b <= 10000. They are the beginning and the end of an interval.

Output

Output the minimal number of elements in a set containing at least two different integers from each interval.
Sample Input

4
3 6
2 4
0 2
4 7

Sample Output

4

题解

这题比考试题简单。。。轻松混过!跟着大佬的步伐水水水(不大佬几乎不做水题,只有这几道我能勉强做出来。。)

代码

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;struct Edge {    int v, w, next;} e[200010];int n = 0, t = 0x3fffff, m, num = 0, a[100010], h[200010];void add(int u, int v, int w) {    num ++;    e[num].v = v;    e[num].w = w;    e[num].next = h[u];    h[u] = num;}int head = 0, tail = 1, vis[100010], dis[100010], queue[500010];void spfa(int s) {    memset(dis, -63, sizeof(dis));    queue[1] = s; vis[s] = 1; dis[s] = 0;    while(head < tail) {        int u = queue[++ head]; vis[u] = false;        for(int i = h[u]; i; i = e[i].next) {            int v = e[i].v;            if(dis[v] < dis[u] + e[i].w) {                dis[v] = dis[u] + e[i].w;                if(! vis[v]) {                    vis[v] = true;                    queue[++ tail] = v;                }            }        }    }}int main() {    scanf("%d", &m);    for(int i = 1; i <= m; i ++) {        int l, r;        scanf("%d %d", &l, &r);        n = max(n, r + 1); t = min(t, l); add(l, r + 1, 2);    }    for(int i = t; i < n; i ++)        add(i + 1, i, -1), add(i, i + 1, 0);    spfa(t);    printf("%d", dis[n]);    return 0;}
原创粉丝点击