2012 Asia Tianjin Regional Contest - charge-station 贪心

  注意到对于如果要在第i个城市建oil station,那么他的费用一定会比前面1~i-1个城市都建oil station的费用高。这就可以用来贪心,如果前i-1个城市全部建oil station就已经满足条件了,那么第i个城市就不用建。
  于是就从后往前枚举一下,然后跑个spfa什么的判断一下是否成立即可。
  时间复杂度 O(n3)
  写spfa居然写错了什么鬼啊!!!重写了一发差点又写错了T_T

#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
#define fore(i,u) for(int i=head[u];i;i=nxt[i])
#define cr(x) memset(x , 0 , sizeof x)
#define maxn 256
#define maxm 65536

typedef int arr[maxn];
typedef int adj[maxm];

inline int rd() {
    char c = getchar();
    while (!isdigit(c)) c = getchar() ; int x = c - '0';
    while (isdigit(c = getchar())) x = x * 10 + c - '0';
    return x;
}

arr fa , x , y , dis , vis , st;
adj to , nxt , val , head;

int n , ett , D;

queue<int> q;

inline int sqr(int x) { return x * x ; }

inline void ins(int u , int v , int w) {
    to[++ ett] = v , val[ett] = w , nxt[ett] = head[u] , head[u] = ett;
}

int find(int u) { return u == fa[u] ? u : fa[u] = find(fa[u]) ; }

void input() {
    ett = 0 , cr(head);
    rep (i , 1 , n) fa[i] = i;
    rep (i , 1 , n) {
        x[i] = rd() , y[i] = rd();
        rep (j , 1 , i - 1) {
            int w = ceil(sqrt(sqr(x[i] - x[j]) + sqr(y[i] - y[j])));
            if (w > D) continue;
            ins(i , j , w) , ins(j , i , w);
            fa[find(i)] = find(j);
        }
    }
}

bool spfa() {
    memset(dis , 0x7f , sizeof dis);
    memset(vis , 0 , sizeof vis);
    dis[1] = 0;
    vis[1] = 1;
    q.push(1);
    while (!q.empty()) {
        int u = q.front() ; q.pop();
        fore (i , u) {
            int v = to[i] , w = val[i];
            if (dis[v] > dis[u] + w) {
                dis[v] = dis[u] + w;
                if (st[v]) {
                    dis[v] = 0;
                    if (!vis[v]) {
                        q.push(v);
                        vis[v] = 1;
                    }
                }
            }
        }
    }
    rep (i , 1 , n) if (dis[i] > D / 2) return 0;
    return 1;
}

void solve() {
    rep (i , 2 , n) if (find(i) != find(1)) {
        puts("-1");
        return;
    }
    rep (i , 1 , n) st[i] = 1;
    int tot = n;
    per (i , n , 2) {
        st[i] = 0;
        if (spfa())
            tot --;
        else
            st[i] = 1;
    }
    if (tot == n && !spfa()) {
        puts("-1");
        return;
    }
    int r = n;
    per (i , n , 1) if (st[i]) {
        r = i;
        break;
    }
    per (i , r , 1) putchar(st[i] + '0');
    puts("");
}

int main() {
    #ifndef ONLINE_JUDGE
        freopen("data.txt" , "r" , stdin);
    #endif
    while (scanf("%d%d" , &n , &D) == 2) {
        input();
        solve();
    }
    return 0;
}

你可能感兴趣的:(2012 Asia Tianjin Regional Contest - charge-station 贪心)