A - 区间选点 II
题目描述
给定一个数轴上的 n 个区间,要求在数轴上选取最少的点使得第 i 个区间 [ai, bi] 里至少有 ci 个点
使用差分约束系统的解法解决这道题
使用差分约束系统的解法解决这道题
使用差分约束系统的解法解决这道题
使用差分约束系统的解法解决这道题
使用差分约束系统的解法解决这道题
Input
输入第一行一个整数 n 表示区间的个数,接下来的 n 行,每一行两个用空格隔开的整数 a,b 表示区间的左右端点。1 <= n <= 50000, 0 <= ai <= bi <= 50000 并且 1 <= ci <= bi - ai+1。
Output
输出一个整数表示最少选取的点的个数
Sample Input
5
3 7 3
8 10 3
6 8 1
1 3 1
10 11 1
Sample Output
6
题目思路
在这里根据题目要求,我们需要使用差分约束系统来解决这个问题。对于这个问题,我们可以转化为图论问题来求解。
其中区间的左右端点a,b是图中的点,其中选点的个数c就是权重。这样我们就可以添加边(a,b+1,c)(注意:这里是b+1,因为区间是闭区间,并且要保证图中的点是正数)。然后使用dis数组记录距离,即表示需要选点的个数。对于每个区间[a,b]需要满足dis[b] - dis[a-1] >= c 。又需要对每个dis都有意义,所以需要满足0 <= dis[i] - dis[i-1] <= 1,由于我们需要求最长路所以需要转化为>=,应该转化为dis[i] - dis[i-1] >= 0,dis[i-1] - dis[i] >= -1;所以我们还需要再在整个大区间里面新加上边。最后用spfa跑最长路就可以了。
代码实现
#include <iostream>
#include <cmath>
#include <queue>
#include <cstring>
using namespace std;
#define _for(i,a,b) for(int i = (a); i < (b); i++)
#define _rep(i,a,b) for(int i = (a); i <= (b); i++)
const int N = 5e4 + 100;
int n,a,b,c;
const int inf = -1e8;
//链式前向星
struct edge
{
int to,next,w;
};
edge e[4*N];
int head[N],tot;
int dis[N];
bool vis[N];
int maxb,mina;
void addedge(int x,int y,int w)
{
e[tot].to=y,e[tot].next=head[x];
e[tot].w=w,head[x]=tot;
tot++;
}
void spfa(int s)
{
dis[s] = 0;
queue<int> q;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
vis[u] = false;
for(int i = head[u];i != -1;i = e[i].next)
{
int v = e[i].to;
if(dis[v] < dis[u] + e[i].w)
{
dis[v] = dis[u] + e[i].w;
if(!vis[v])
{
q.push(v);
vis[v] = true;
}
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin >> n;
_rep(i,0,N)
{
head[i] = -1;
vis[i] = false;
dis[i] = inf;
}
tot = 0;
maxb = 0,mina = 4*N;
_for(i,0,n)
{
cin >> a >> b >> c;
maxb = max(maxb,b+1);
mina = min(mina,a);
addedge(a,b+1,c);
}
_rep(i,mina,maxb)
{
addedge(i,i+1,0);
addedge(i+1,i,-1);
}
spfa(mina);
cout<<dis[maxb]<<endl;
}
总结
在这个题目里面我有一个点没有注意到,导致了一直re,就是边的个数,我开的空间是和点数是一样的,这样肯定是不对的。