Intervals
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 31007 | Accepted: 11999 |
Description
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
Source
问题链接:POJ1201 Intervals
问题描述:给定n(n <= 50000)组数,ai bi ci。问在[0, 50000]区间中至少需要选择多少个整数,才能使得在被选择的数中,至少有ci个整数在[ai,bi]中。其中0 <= ai <= bi <= 50000,。
解题思路:差分约束,求最小值,使用最长路,可将所有的边的权值变为相反数,然后求最短路径,最后取结果的相反数,这就是最长路了。dist[i]表示[0,...,i]这个区间需要出现的数,因此ai,bi,ci,可以转换为dist[bi]-dist[ai-1]>=ci。对于dist[i]和dist[i-1]其实是有自身限制的,考虑到每个点有选和不选两种状态,所以dist[i]和dist[i-1]需要满足以下不等式: 0 <= dist[i] - dist[i-1] <= 1 (即第i个数选还是不选)。由于-1不能映射到小标,所以可以将所有点都向x轴正方向偏移1个单位(即所有数+1)。
AC的C++程序:
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int N=50050;
const int INF=0x3f3f3f3f;
struct Edge{
int v,w;
Edge(int v,int w):v(v),w(w){}
};
vector<Edge>g[N];
int dist[N];
bool vis[N];
void spfa(int s,int e)
{
memset(vis,false,sizeof(vis));
fill(dist,dist+e+1,INF);
queue<int>q;
q.push(s);
dist[s]=0;
vis[s]=true;
while(!q.empty())
{
int u=q.front();
vis[u]=false;
q.pop();
for(int i=0;i<g[u].size();i++)
{
int v=g[u][i].v;
int w=g[u][i].w;
if(dist[v]>dist[u]+w)
{
dist[v]=dist[u]+w;
if(!vis[v])
{
q.push(v);
vis[v]=true;
}
}
}
}
}
int main()
{
int n,a,b,c;
while(~scanf("%d",&n))
{
for(int i=0;i<N;i++)
g[i].clear();
int s=N,e=0;//s记录出现过的最小的端点,e记录出现过的最大的端点
for(int i=1;i<=n;i++)
{
scanf("%d%d%d",&a,&b,&c);//区间[a,b]中的数至少有c个
a++,b++;
s=min(s,a);
e=max(e,b);
//dist[b]-dist[a-1]>=c 建立一条从a-1到b的权值为-c的有向边
g[a-1].push_back(Edge(b,-c));
}
//隐含条件区间[i,i]中的数至多出现1次,最少出现0次
// 1>=dist[i]-dist[i-1]>=0
for(int i=s;i<=e;i++)
{
//dist[i]-dist[i-1]>=0 建立一条从i-1到i的权值为0的有向边
g[i-1].push_back(Edge(i,0));
//dist[i-1]-dist[i]>=-1 建立一条从i到i-1的权值为-1的有向边
g[i].push_back(Edge(i-1,1));
}
spfa(s-1,e);//开始结点是s-1
printf("%d\n",-dist[e]);
}
return 0;
}