JZOI1142 排队布局

#include <bits/stdc++.h>
using namespace std;
inline int read() {
    int x = 0,tmp = 1;char ch = getchar();
    while( ch < '0' || ch > '9' ) {if ( ch == '-' ) tmp = -1; ch = getchar();}
    while( ch >= '0' && ch <= '9'){x = x * 10 + ch - '0'; ch = getchar(); }
    return x * tmp;
}
int INF;
struct Point {
    int to, next, w;
} edge[410000];
int head[1100], idx = 0, dis[1100], in[1100];
bool vis[1100];
inline void ade( int u, int v, int w ) {
    edge[++ idx].to = v;
    edge[idx].w = w;
    edge[idx].next = head[u];
    head[u] = idx;
}
int spfa( int _sta, int _end ) {
    memset( in, 0, sizeof( in ) );
    memset( vis, 0, sizeof( vis ) );
    memset( dis, 127, sizeof( dis ) ); INF = dis[0];
    vis[_sta] = 1; dis[_sta] = 0;
    queue< int > Q;
    Q.push( _sta ); in[_sta] = 1;
    while( !Q.empty() ) {
        int now = Q.front();
        Q.pop();
        vis[now] = 0;
        for( int i = head[now] ; i != -1 ; i = edge[i].next ) {
            int son = edge[i].to, w = edge[i].w;
            if( dis[son] > dis[now] + w ) {
                dis[son] = dis[now] + w;
                if( !vis[son] ) {
                    in[son] ++;
                    if( in[son] > _end ) return -1;
                    vis[son] = 1;
                    Q.push( son );
                }
            }
        }
    }
    if( dis[_end] == INF ) return -2;
    return dis[_end];
     
}
int main() {
    memset( head, -1, sizeof( head ) );
    int N = read(), M1 = read(), M2 = read();
    for( int i = 1 ; i <= M1 ; ++ i ) {
        int u = read(), v = read(), w = read();
        ade( u, v, w );
    }
    for( int i = 1 ; i <= M2 ; ++ i ) {
        int u = read(), v = read(), w = read();
        ade( v, u, -w );
    }
    for( int i = 2 ; i <= N ; ++ i ) ade( i, i - 1, 0 );
    printf( "%d\n", spfa( 1, N ) );
     
 
    return 0;
}
 
/**************************************************************
    Problem: 1142
    User: ARZhu
    Language: C++
    Result: 正确
    Time:4 ms
    Memory:6364 kb
****************************************************************/
posted @ 2017-04-19 12:24  ARZhu  阅读(315)  评论(0编辑  收藏  举报