Intervals
Time Limit: 2000MS | | Memory Limit: 65536K |
Total Submissions: 23934 | | Accepted: 9075 |
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
思路:
首先第一个转化,是找到一个合理的表示。用ti表示每一个数,如果有用就是1,否则是0。吧S(i+1)定义成S(i+1)=sigma(tj)(1<=j<=i)也就是。S[i+1]表示从0到i有多少个数是需要的。
因此,题目中的条件可以表示成S[bi+1]>=S[ai]+Ci//至少要Ci个
这与bellman中的松弛操作时很像的。因此可以看成一些点
有D[v]>=D[u]+w(u,v)
上式对任何u成立,所以v应该是里面最大的,若D[v]<D[u]+w(u,v)则D[v]=D[u]+w(u,v)
于是。可以从ai和bi+1连一条线,它的长度是ci
这里只有这些条件还是不够的,还要加上两个使其满足整数性质的条件
1>=s[i+1]-s[i]>=0
有了这么多条件,使其自然构成了一个差分约束系统。
用spfa算法得到一个最长路,第一个到最后一个节点的最长路即是需要求的值。
AC:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 50005;
const int inf = 0x7f7f7f;
struct Edge
{
int k,c,next;
}edge[maxn*10];
int n,pre[maxn],cnt,s,t,dis[maxn];
bool vis[maxn];
void addedge(int a,int b,int c)
{
edge[cnt].k = b;
edge[cnt].c = c;
edge[cnt].next = pre[a];
pre[a] = cnt++;
}
void SPFA()
{
queue<int> que;
memset(vis,false,sizeof(vis));
for(int i = s; i <= t+1; i++)
dis[i] = -inf;
dis[s] = 0; vis[s] = true;
que.push(s);
while(!que.empty())
{
int u = que.front();
que.pop();
vis[u] = false;
for(int i = pre[u]; i != -1; i = edge[i].next)
{
int k = edge[i].k;
if(dis[k] < dis[u] + edge[i].c)
{
dis[k] = dis[u] + edge[i].c;
if(vis[k] == false)
{
vis[k] = true;
que.push(k);
}
}
}
}
printf("%d\n",dis[t+1]);
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
s = inf,t = -inf;
memset(pre,-1,sizeof(pre));
cnt = 0;
for(int i = 1; i <= n; i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
s = min(a,s); t = max(b,t);
addedge(a,b+1,c);
}
for(int i = s; i <= t; i++)
{
addedge(i,i+1,0);
addedge(i+1,i,-1);
}
SPFA();
}
return 0;
}