luogu 1514

来源:互联网 发布:查看java heap size 编辑:程序博客网 时间:2024/06/09 22:12

引水入城
调了一天, 时间一不小心就超了, 在bfs中就可以找出他的区间(还有不用每一次都循环找)在bfs中就可以o(1)维护.

#include <cstdio>//因为已经先bfs一遍了, 所以能保证这样找到的一定是一段区间中的#include <cstring>#include <algorithm>#include <iostream>#define MAXN 510 // 从上往下灌水找到第一问, 从下往上灌找到区间然后线段覆盖.   using namespace std;int a[MAXN][MAXN];int vis[MAXN][MAXN];bool ok[MAXN];int n, m;int ans, p, tot;struct L {    int l, r;} ls[MAXN];int read() {    int f = 1, k = 0;    char c = getchar();    while (c < '0' || c > '9') {        if(c == '-') {            f = -1;        }        c = getchar();    }    while (c >= '0' && c <= '9') {        k = k * 10 + c - '0';        c = getchar();    }    return f * k;}void bfs(int x, int y) {    vis[x][y] = tot;    if(a[x][y] > a[x][y + 1] && y + 1 <= m && vis[x][y + 1] != tot) {        bfs(x, y + 1);    }    if(a[x][y] > a[x][y - 1] && y - 1 >= 1 && vis[x][y - 1] != tot) {        bfs(x, y - 1);    }    if(a[x][y] > a[x - 1][y] && x - 1 >= 1 && vis[x - 1][y] != tot) {        bfs(x - 1, y);    }    if(a[x][y] > a[x + 1][y] && x + 1 <= n && vis[x + 1][y] != tot) {        bfs(x + 1, y);    }    if(x == n) {        ok[y] = true;        if(!ls[tot].l) ls[tot].l = y, ls[tot].r = y;        else if(ls[tot].l > y) ls[tot].l = y;        else if(ls[tot].r < y) ls[tot].r = y;     }}bool cmp (const L &a, const L &b) {    if(a.l == b.l) {        return a.r < b.r;    }    return a.l < b.l;}int main() {    n = read(), m = read();    for(int i = 1; i <= n; i ++) {        for(int j = 1; j <= m; j ++) {            a[i][j] = read();        }    }    for(int i = 1; i <= m; i ++) {        if(!vis[1][i]) tot = i, bfs(1, i);    }    p = 1;    for(int i = 1; i <= m; i ++) {        if(!ok[i]) {            p = 0;            ans ++;        }    }    if(p == 0) {        printf("0\n%d", ans);        return 0;    }    printf("1\n");    sort(ls + 1, ls + m + 1,cmp);    p = 0;    ans = 0;    while (p < m) {        int maxx = 0;        for(int i = 1; i <= m; i ++) {            if(ls[i].l <= p + 1 && ls[i].r > maxx ) {                maxx = ls[i].r;            }        }        p = maxx;        ans ++;    }    printf("%d", ans);    return 0;}
原创粉丝点击