NC24392. Cow Crossings
描述
输入描述
* Line 1: The number of cows, N.
* Lines 2..1+N: Line i contains the integers a_i and b_i, describing
the path taken by cow i.
输出描述
* Line 1: The number of safe cows.
示例1
输入:
4 -3 4 7 8 10 16 3 9
输出:
2
说明:
INPUT DETAILS:Java(javac 1.8) 解法, 执行用时: 1171ms, 内存消耗: 46040K, 提交时间: 2020-05-30 13:01:25
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { int N[][] = new int[sc.nextInt()][], max[] = new int[N.length], min[] = new int[N.length], count = 0; for (int i = 0; i < N.length; i++) { N[i] = new int[] { sc.nextInt(), sc.nextInt() }; } Arrays.sort(N, (a, b) -> a[0] - b[0]); for (int i = 0; i < N.length; i++) { max[i] = i > 0 ? Math.max(max[i - 1], N[i][1]) : N[i][1]; } for (int i = N.length - 1; i >= 0; i--) { min[i] = i < N.length - 1 ? Math.min(min[i + 1], N[i][1]) : N[i][1]; } for (int i = 0; i < N.length; i++) { if ((i == 0 || max[i - 1] < N[i][1]) && (i == N.length - 1 || min[i + 1] > N[i][1])) { count++; } } System.out.println(count); } } }
C++14(g++5.4) 解法, 执行用时: 49ms, 内存消耗: 2028K, 提交时间: 2020-07-05 15:27:48
#include <bits/stdc++.h> using namespace std; const int N = 100005; const int oo = 0x3f3f3f3f; int n, mxpre[N], mnsuf[N], ans, i; struct Rana { int a, b; } p[N]; int main() { scanf("%d", &n); for (i = 1; i <= n; ++i) scanf("%d%d", &p[i].a, &p[i].b); sort(p + 1, p + n + 1, [](const Rana u, const Rana v) { return u.a < v.a; }); mxpre[0] = -oo; for (i = 1; i <= n; ++i) mxpre[i] = max(mxpre[i - 1], p[i].b); mnsuf[n + 1] = oo; for (i = n; i > 0; --i) mnsuf[i] = min(mnsuf[i + 1], p[i].b); for (i = 1; i <= n; ++i) if (mxpre[i - 1] < p[i].b && p[i].b < mnsuf[i + 1]) ++ans; printf("%d", ans); }
C++11(clang++ 3.9) 解法, 执行用时: 53ms, 内存消耗: 1260K, 提交时间: 2020-05-30 09:47:37
#include<algorithm> #include<cstdio> using namespace std; struct node{int x,y;}a[100010]; bool cmp(node a,node b){return a.x<b.x;} int maxx=-1000000000,ans=0,n;bool h[100010]; int main(){ scanf("%d",&n); for(int i=1;i<=n;++i)scanf("%d%d",&a[i].x,&a[i].y); sort(a+1,a+n+1,cmp); for(int i=1;i<=n;++i)if(maxx>a[i].y)h[i]=1;else maxx=a[i].y; for(int i=n;i>=1;--i)if(maxx<a[i].y)h[i]=1;else maxx=a[i].y; for(int i=1;i<=n;++i)if(!h[i])ans++; printf("%d\n",ans); return 0; }