Asia Regional Contest, Tokyo,Problem C Shopping
2015-11-16 22:32
323 查看
贪心。
不难证明,如果两个区间有交集,那么最好的方法是走完这些区间的并再掉头。 也就是说,处理出所有相交的区间组成一个更大的区间,然后对于这些区间,答案要加上两倍的区间长度。 然后最后再加上整条街的长度即可。
细节参见代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 1000 + 5;
int T,n,m,u,v;
struct node {
int l, r;
node(int ll=0, int rr=0):l(ll), r(rr) {}
bool operator < (const node& rhs) const {
return l < rhs.l || (l == rhs.l && r < rhs.r);
}
}b[maxn],a[maxn];
int main() {
scanf("%d%d",&n,&m);
int cnt = 0, cnt2 = 0;
for(int i=0;i<m;i++) {
scanf("%d%d",&u,&v);
if(u > v) continue;
a[cnt++] = node(u,v);
}
sort(a,a+cnt);
int l = a[0].l, r = a[0].r, ans = 0;
for(int i=1;i<cnt;i++) {
if(r >= a[i].l) r = max(r, a[i].r);
else {
b[cnt2++] = node(l,r);
l = a[i].l;
r = a[i].r;
}
if(i == cnt-1) b[cnt2++] = node(l,r);
}
for(int i=0;i<cnt2;i++)
ans += (b[i].r - b[i].l) * 2;
ans += n+1;
printf("%d\n",ans);
return 0;
}
不难证明,如果两个区间有交集,那么最好的方法是走完这些区间的并再掉头。 也就是说,处理出所有相交的区间组成一个更大的区间,然后对于这些区间,答案要加上两倍的区间长度。 然后最后再加上整条街的长度即可。
细节参见代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 1000 + 5;
int T,n,m,u,v;
struct node {
int l, r;
node(int ll=0, int rr=0):l(ll), r(rr) {}
bool operator < (const node& rhs) const {
return l < rhs.l || (l == rhs.l && r < rhs.r);
}
}b[maxn],a[maxn];
int main() {
scanf("%d%d",&n,&m);
int cnt = 0, cnt2 = 0;
for(int i=0;i<m;i++) {
scanf("%d%d",&u,&v);
if(u > v) continue;
a[cnt++] = node(u,v);
}
sort(a,a+cnt);
int l = a[0].l, r = a[0].r, ans = 0;
for(int i=1;i<cnt;i++) {
if(r >= a[i].l) r = max(r, a[i].r);
else {
b[cnt2++] = node(l,r);
l = a[i].l;
r = a[i].r;
}
if(i == cnt-1) b[cnt2++] = node(l,r);
}
for(int i=0;i<cnt2;i++)
ans += (b[i].r - b[i].l) * 2;
ans += n+1;
printf("%d\n",ans);
return 0;
}
相关文章推荐
- 1.一些 贪心算法 的简单思维题:
- 贪心算法——字典序最小问题
- 贪心算法——区间调度问题
- Jump Game I,II 贪心
- Wildcard Matching
- 贪心题目循环和控制台折行
- HDOJ 1009
- hdu 4738 Caocao's Bridges 2013 ACM-ICPC杭州赛区网络赛 1001 双连通分量
- hdu 4750 2013 ACM/ICPC Asia Regional Nanjing Online 1003 并查集+离线操作
- hust 1626 Cutting rope
- 【解题报告】【USACO】酸奶工厂
- 【解题报告】【】交谊舞
- POJ 1328
- HDU5117
- Best Cow Line
- 1216: 斐波那契数列
- 1217: 打印沙漏
- 我的ACM-ICPC资源整理
- 贪心 hdu 1003
- 最大容器