La3211 Now or Later(2-SAT判定+二分法)

题目: n 架飞机,每架飞机的降落时间有两个选择,一个为早点降落,另一个为晚点降落;求两架飞机降落时间差的最小值的最大值(就是怎么安排,使得所有飞机降落的时间差的最小值尽量大)

输入:一个n,代表飞机数目;接下来n行,表示每架飞机降落的两个时间

分析:最小值尽量大,用二分查找;对于查到一个最小值t,如果任意两个时间差小于t,那么这两架飞机就不能同时降落,由此产生了条件就是时间差<t的就不能同时满足

代码:

#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2010;

struct TwoSAT {
    int n, c, s[N*2];
    vector<int> G[N*2];
    bool mark[N*2];

    void init( int n ) {
        this->n = n;
        for ( int i = 0; i < n*2; ++i ) G[i].clear(); 
        memset( mark, 0, sizeof(mark) );
    }
    bool dfs( int x ) {
        if ( mark[x^1] ) return false;
        if ( mark[x] ) return true;
        mark[x] = true;
        s[c++] = x;
        for ( int i = 0; i < G[x].size(); ++i ) 
            if ( !dfs(G[x][i]) ) return false;
        return true;
    }
    void add ( int x, int xval, int y, int yval ) {
        x = x * 2 + xval;
        y = y * 2 + yval;
        G[x^1].push_back(y);
        G[y^1].push_back(x);
    }
    bool solve() {
        for ( int i = 0; i < n*2; i += 2 ) 
            if ( !mark[i] && !mark[i+1] ) {
                c = 0;
                if ( !dfs(i) ) {
                    while ( c > 0 ) mark[s[--c]] = false;
                    if ( !dfs(i+1) ) return false;
                }
            }
        return true;
    }
};

TwoSAT solver;
int t[N][2], n;

bool test ( int dif ) {
    solver.init(n);
    for ( int i = 0; i < n; ++i ) for ( int a = 0; a < 2; ++a ) 
        for ( int j = i+1; j < n; ++j ) for ( int b = 0; b < 2; ++b ) 
            if ( abs( t[i][a] - t[j][b] ) < dif )  solver.add( i, a^1, j, b^1 );
    return solver.solve();
}

int main()
{
    while ( scanf("%d", &n) != EOF && n ) {
        int L = 0, R = 0;
        for ( int i = 0; i < n; ++i ) for ( int a = 0; a < 2; ++a ) {
            scanf("%d", &t[i][a]);
            R = max( R, t[i][a] );
        }
        while ( L < R ) {
            int M = L + ( R - L + 1 ) / 2;
            if ( test(M) ) L = M; 
            else R = M - 1;
        }
        printf("%d\n", L );
    }
}


你可能感兴趣的:(La3211 Now or Later(2-SAT判定+二分法))