不知不觉这已经是第100篇随笔了……
Intervals
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1532 Accepted Submission(s): 569
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
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.
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
题意:在每个区间[ai,bi]上至少选择ci个元素,构成一个集合S,使集合S中的元素最少;
分析:f(a) 表示在区间 [0,a] 上选择了一些元素;
则:f(b)-f(a-1)>=ci;
0<=f(a)-f(a-1)<=1;
View Code
1 #include<iostream> 2 #include<string.h> 3 #include<queue> 4 #define MAX 50010 5 6 using namespace std; 7 8 struct edge 9 { 10 int x,value,next; 11 }e[4*MAX]; 12 int head[MAX],d[MAX],a,b,cnt; 13 bool visited[MAX]; 14 15 void add(int u,int v,int w) 16 { 17 e[cnt].x=v; 18 e[cnt].value=w; 19 e[cnt].next=head[u]; 20 head[u]=cnt++; 21 } 22 23 void SPFA() 24 { 25 int temp,tnext,tx; 26 memset(visited,false,sizeof(visited)); 27 memset(d,-50000,sizeof(d)); 28 queue<int>Q; 29 while(!Q.empty()) Q.pop(); 30 Q.push(a); 31 d[a]=0;visited[a]=true; 32 while(!Q.empty()) 33 { 34 temp=Q.front();Q.pop(); 35 tnext=head[temp]; 36 while(tnext!=-1) 37 { 38 tx=e[tnext].x; 39 if(d[tx]<d[temp]+e[tnext].value) 40 { 41 d[tx]=d[temp]+e[tnext].value; 42 if(!visited[tx]) 43 { 44 Q.push(tx); 45 visited[tx]=true; 46 } 47 } 48 tnext=e[tnext].next; 49 } 50 visited[temp]=false; 51 } 52 } 53 54 int main() 55 { 56 int n,u,v,w,i; 57 while(cin>>n) 58 { 59 a=MAX;b=0;cnt=0; 60 for(i=0;i<MAX;i++) head[i]=-1; 61 for(i=0;i<n;i++) 62 { 63 cin>>u>>v>>w; 64 if(a>u) a=u; 65 if(b<v+1) b=v+1; 66 add(u,v+1,w); 67 } 68 for(i=a;i<=b;i++) 69 { 70 add(i,i-1,-1); 71 add(i-1,i,0); 72 } 73 SPFA(); 74 cout<<d[b]<<endl; 75 } 76 return 0; 77 }