【NOIP2010】【贪心】【覆盖问题】T4 引水入城 题解

【NOIP2010】【贪心】【覆盖问题】T4 引水入城 题解_第1张图片
【NOIP2010】【贪心】【覆盖问题】T4 引水入城 题解_第2张图片

第一行贪心选点,最后一行判断覆盖,中间BFS

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define clr(x) memset(x,0,sizeof(x))
#define ms(a,x) memset(x,a,sizeof(x))
#define LL long long
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif

using namespace std;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int n,m;
int a[505][505],mp[505][505],l[505][505],r[505][505];
int qx[250005],qy[250005];

struct data { int l,r; } c[505];

inline bool operator < (data a,data b) { return a.l == b.l ? a.r < b.r : a.l < b.l; }

void bfs(int b[505][505], int x, int y, int v, bool f) {
    int head = 0, tail = 1;
    qx[0] = x; qy[0] = y; b[x][y] = v;
    while(head != tail) {
        int x = qx[head], y = qy[head++];
        for(int k = 0; k < 4; k++) {
            int nowx = x+dx[k], nowy = y+dy[k];
            if(nowx < 1 || nowy < 1 || nowx > n || nowy > m || b[nowx][nowy]) continue;
            if(!f && a[nowx][nowy] >= a[x][y]) continue;
            if(f == 1 && a[nowx][nowy] <= a[x][y]) continue;
            b[nowx][nowy] = b[x][y];
            qx[tail] = nowx;
            qy[tail++] = nowy;
        }
    }
}

int main() {
    freopen("flow.in","r",stdin);
    freopen("flow.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) scanf("%d",&a[i][j]);
    for(int i = 1; i <= m; i++) bfs(mp, 1, i, 1, 0);
    int tot = 0;
    for(int i = 1; i <= m; i++) if(!mp[n][i])tot++;
    if(tot) { printf("0\n%d\n",tot); return 0; }
    for(int i = 1; i <= m; i++) if(!l[n][i]) bfs(l, n ,i, i, 1);
    for(int i = m; i ; i--) if(!r[n][i]) bfs(r, n, i, i, 1);
    for(int i = 1; i <= m; i++) {
        if(!l[1][i]) l[1][i] = r[1][i];
        if(!r[1][i]) r[1][i] = l[1][i];
        c[i].l = l[1][i]; c[i].r = r[1][i];
    }
    int now = 0,to = 0;
    sort(c+1, c+m+1);
    for(int i = 1; i <= m; i++)
        if(now+1 >= c[i].l) to = max(to, c[i].r);
        else now = to, to = max(to, c[i].r), tot++;
    if(now != m) tot++;
    printf("1\n%d\n",tot);
    return 0;
}

你可能感兴趣的:(NOIP)