Milking Cows
第一种方法 标记一下开始和结束时间 然后扫一遍 就能得出答案了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include<cstdio> #include<cstring> const int maxn=1000000+5; int vis[maxn]; int main() { int n,x,y; scanf ( "%d" ,&n); memset (vis,0, sizeof (vis)); int up=0; for ( int i=0;i<n;i++) { scanf ( "%d%d" ,&x,&y); if (y>up) up=y; vis[x]++; vis[y]--; } int ans1=0,ans2=0; int cur=0,cnt1=0,cnt2=0; bool start= false ; for ( int i=0;i<=up;i++) { if (vis[i]) start= true ; cur+=vis[i]; if (cur>0) { cnt1++; if (cnt2>ans2) ans2=cnt2; cnt2=0; } else if (cur==0) { if (start) cnt2++; if (cnt1>ans1) ans1=cnt1; cnt1=0; } } printf ( "%d %d\n" ,ans1,ans2); return 0; } |
第二种方法 按开始时间排序 然后
从左到右扫一遍,记录一个当前区间,[tmp.begin , tmp.end]
如果下一组数据的begin比tmp.end的小(或相等),则是连接起来的,检查这组数据的end,取max{end , tmp.end}。
如果下一组数据的begin比tmp.end的大,则是相互断开的,整理本区间,ans1取max{tmp.end - tmp.begin , ans1}。ans2取max{begin - tmp.end , ans2}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include<cstdio> #include<algorithm> using namespace std; const int maxn=5000+5; struct farmer { int begin; int end; bool operator <( const farmer &a) const { return begin<a.begin; } }a[maxn]; int main() { int n; scanf ( "%d" ,&n); for ( int i=0;i<n;i++) scanf ( "%d%d" ,&a[i].begin,&a[i].end); sort(a,a+n); farmer tmp=a[0]; int ans1=a[0].end-a[0].begin,ans2=0; for ( int i=1;i<n;i++) { if (a[i].begin<=tmp.end) tmp.end=max(tmp.end,a[i].end); else { ans1=max(ans1,tmp.end-tmp.begin); ans2=max(ans2,a[i].begin-tmp.end); tmp=a[i]; } } printf ( "%d %d\n" ,ans1,ans2); return 0; } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步