Codeforces 986A. Fair(对物品bfs暴力求解)

解题思路:

  1.对物品i bfs,更新每个小镇j获得每个物品i的最短距离。

  2.时间复杂度o(n*k),满足2s的要求。

 

代码:

#include <iostream>
#include <queue>
#include <list>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long ll;
#define MAX 2000000000 

int a[500050];
list <int> e[500050];
int d[500050][110];
bool used[500010];
queue <int> q;


int main(){
//    fill(d[0],d[0]+500050*110,MAX);
    int n,m,k,s;
    scanf("%d%d%d%d", &n, &m, &k, &s);
    for(int i = 1;i <= n; ++i){
        scanf("%d", &a[i]);
    }
    int u,v;
    for(int i = 1;i <= m; ++i){
        scanf("%d%d", &u, &v);
        e[u].push_back(v);
        e[v].push_back(u);
    }
    for(int i = 1;i <= k; ++i){
        memset(used,false,sizeof(used));
        for(int j = 1;j <= n; ++j){
            if(a[j] == i){
                d[j][i] = 0;
                q.push(j);
                used[j] = true;
            }
        }
        while(q.size()){
            int x = q.front();
            for(auto l:e[x]){
                if(!used[l]){
                    d[l][i] = d[x][i]+1;
                    used[l] = true;
                    q.push(l);
                }
            }
            q.pop();
        }
    }
    for(int i = 1;i <= n; ++i){
        sort(d[i]+1,d[i]+1+k);
        int ans = 0;
        for(int j = 1;j <= s; ++j){
            ans += d[i][j];
        }
        printf("%d ",ans);
    }
    printf("\n");
    return 0;
}

 

posted @ 2018-05-30 17:41  ninding  阅读(442)  评论(0编辑  收藏  举报