天天看点

POJ 3683 - Priest John's Busiest Day(2-SAT)

题目;

http://poj.org/problem?id=3683

<挑战326-327>

当模版.

AC.

#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
#include <cstring>

using namespace std;
const int maxn = 1005;
int n, m;
int S[maxn], T[maxn], D[maxn];

int V;
vector<int> G[2005];
vector<int> rG[2005];
vector<int> vs;
bool used[2005];
int cmp[2005];

void add_edge(int from, int to)
{
    G[from].push_back(to);
    rG[to].push_back(from);
}
void dfs(int v)
{
    used[v] = true;
    for(int i = 0; i < G[v].size(); ++i) {
        if(!used[G[v][i]]) dfs(G[v][i]);
    }
    vs.push_back(v);
}
void rdfs(int v, int k)
{

    used[v] = 1;
    cmp[v] = k;
    for(int i = 0; i < rG[v].size(); ++i) {
        if(!used[rG[v][i]]) rdfs(rG[v][i], k);
    }
}
void scc()
{
    memset(used, 0, sizeof(used));
    vs.clear();
    for(int v = 0; v < V; ++v) {
        if(!used[v]) dfs(v);
    }
    memset(used, 0, sizeof(used));
    int k = 0;
    for(int i = vs.size()-1; i >= 0; --i) {
        if(!used[vs[i]]) rdfs(vs[i], k++);
    }
    //return k;
}

void solve()
{
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < i; ++j) {
            if(min(S[i]+D[i], S[j]+D[j]) > max(S[i], S[j])) {
                add_edge(i, n+j);
                add_edge(j, n+i);
            }
            if(min(S[i]+D[i], T[j]) > max(S[i], T[j]-D[j])) {
                add_edge(i, j);
                add_edge(n+j, n+i);
            }
            if(min(T[i], S[j]+D[j]) > max(T[i]-D[i], S[j])) {
                add_edge(n+i, n+j);
                add_edge(j, i);
            }
            if(min(T[i], T[j]) > max(T[i]-D[i], T[j]-D[j])) {
                add_edge(n+i, j);
                add_edge(n+j, i);
            }
        }
    }

    scc();

    for(int i = 0; i < n; ++i) {
        //if(sccno[i] == sccno[n+i]) {
        if(cmp[i] == cmp[n+i]) {
            printf("NO\n");
            return ;
        }
    }

    printf("YES\n");
    for(int i = 0; i < n; ++i) {
        //if(sccno[i] > sccno[n+i]) {
        if(cmp[i] > cmp[n+i]) {
            printf("%02d:%02d %02d:%02d\n",
                    S[i]/60, S[i]%60, (S[i]+D[i])/60, (S[i]+D[i])%60);
        }
        else {
            printf("%02d:%02d %02d:%02d\n",
                    (T[i]-D[i])/60, (T[i]-D[i])%60, T[i]/60, T[i]%60);
        }
    }
//    for(int i = 0; i < 2*n; ++i) {
//        printf("%d ", cmp[i]);
//    }
//    printf("\n");
}
int main()
{
//freopen("in", "r", stdin);
    while(~scanf("%d", &n)) {

        int hour1, min1, hour2, min2, d;
        for(int i = 0; i < n; ++i) {
            scanf("%d:%d %d:%d %d", &hour1, &min1, &hour2, &min2, &d);
            S[i] = hour1*60+min1;
            T[i] = hour2*60+min2;
            D[i] = d;
        }

        V= 2*n;
        for(int i = 0; i < V; ++i)  {
            G[i].clear();
            rG[i].clear();
        }
        solve();

    }

    return 0;
}