您的位置:首页 > 其它

poj 1716 Integer Intervals(差分约束系统)

2016-01-28 17:29 302 查看
Integer Intervals

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 13437 Accepted: 5711
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 <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <list>
#include <vector>
#include <algorithm>
#include <iomanip>
#define RR freopen("in.txt","r"m,stdin)
#define WW freopen("out.txt","w",stdout)
#define LL long long
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 100010;
const double eps = 1e-9;
typedef struct node
{
int v,w,next;
}Edge;
Edge edge[MAXN];
int Dis[MAXN*3], head[MAXN], Left, Right,top;
bool vis[MAXN];

void Add(int u, int v, int w)
{
edge[top].v = v;
edge[top].w = w;
edge[top].next = head[u];
head[u] = top++;
}

void SPFA()
{
for(int i=Left; i<=Right; i++)
Dis[i] = -INF;
queue<int >Q;
Dis[Left] = 0;
Q.push(Left);
while(!Q.empty())
{
int u = Q.front();
Q.pop();
vis[u] = false;
for(int i=head[u]; i!=-1; i=edge[i].next)
{
int v = edge[i].v;
int w = edge[i].w;
if(Dis[v] < Dis[u] + w)
{
Dis[v] = Dis[u] + w;
if(!vis[v])
{
Q.push(v);
vis[v] = true;
}
}
}
}
}

int main()
{
int n,u,v;
while(~scanf("%d",&n))
{
top = 0;
memset(head, -1, sizeof(head));
memset(vis, false, sizeof(vis));
memset(edge, 0, sizeof(edge));
Left = INF, Right = -INF;
for(int i=0;i<n;i++)
{
scanf("%d %d",&u, &v);
Add(u,v+1,2);
Left = min(Left, u);
Right = max(Right, v+1);
}
for(int i=Left; i<Right; i++)
{
Add(i, i+1, 0);
Add(i+1, i, -1);
}
SPFA();
printf("%d\n",Dis[Right]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: