I n t e r v a l s Intervals Intervals
Time Limit: 10000/5000 MS (Java/Others) | Memory Limit: 65536/32768 K (Java/Others) |
---|---|
Total Submission(s): 5495 | Accepted Submission(s): 2002 |
Problem 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 endpoints 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 <= 50 000) - 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 <= 50 000 and 1 <= ci <= bi - ai + 1.
Process to the end of file.
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
Author
1384
题目大意:
给出若干个闭区间[ai , bi]和整数ci,要求得到一个集合S,使得其对于区间[ai , bi],集合S中至少存在ci个数在区间[ai , bi]里,要求输出集合S的元素最少个数。
题意分析:
我们可以把每个数看成一个点,这个点选的话就是1,不选的话就是0,[0 , R]之间选取数的个数就可以用前缀和来得到(记为X[R]),则[L , R]之间选取的元素个数为X[R]-X[L-1],这样我们就可以把上述约束条件转化成不等式:X[bi] - X[ai-1] >= ci,一个元素只有选与不选两种选择,所以可以得到 0 <= X[k+1] - X[k] <= 1,根据这一约束条件可以得到不等式:X[k+1] - X[k] >= 0,X[k] - X[k+1] >= -1,根据上述不等式进行连边建图:
X[ai-1] -> X[bi]---------边权为ci
X[k] ->X[k+1]-----------边权为0
X[k+1]->X[k]------------边权为-1
建完图之后跑一遍Bellman-Ford(SPFA)找出最长路径就可以了。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 5e4+7;
const int INF = 0x3f3f3f3f;
struct EDGE{
int to,cost;
};
vector<EDGE> G[maxn];
int n,maxx;
void add_edge(int u,int v,int w){
G[u].push_back((EDGE){v,w});
}
void build(){
for(int i=0;i<maxn;i++) G[i].clear();
maxx = -1;
for(int i=1;i<=n;i++){
int pa,pb,pc;
scanf("%d %d %d",&pa,&pb,&pc);
add_edge(pa-1,pb,pc);
maxx = max(maxx,pb);
}
for(int i=0;i<maxx;i++){
add_edge(i,i+1,0);
add_edge(i+1,i,-1);
}
}
int SPFA(){
int dist[maxn],vis[maxn];
fill(dist,dist+maxn,-INF);
memset(vis,0,sizeof(vis));
dist[0] = 0;
queue<int> que;
que.push(0); vis[0] = 1;
while(!que.empty()){
int now = que.front();
que.pop(); vis[now] = 0;
for(int i=0;i<G[now].size();i++){
EDGE e = G[now][i];
if(dist[now]+e.cost>dist[e.to]){
dist[e.to] = dist[now] + e.cost;
que.push(e.to); vis[e.to] = 1;
}
}
}
return dist[maxx];
}
int main(){
while(scanf("%d",&n)!=EOF){
build();
printf("%d\n",SPFA());
}
return 0;
}