pipioj 1211: 小镇购物(bfs)
http://www.pipioj.online/problem.php?id=1211
1 #define IO std::ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); 2 #define bug(x) cout<<#x<<" is "<<x<<endl 3 #include <bits/stdc++.h> 4 #define iter ::iterator 5 using namespace std; 6 typedef long long ll; 7 typedef pair<int,ll>P; 8 #define pb push_back 9 #define mk make_pair 10 #define se second 11 #define fi first 12 #define rs o*2+1 13 #define ls o*2 14 const ll mod=1e9+7; 15 const int N=1e5+5; 16 int T,n,m,k,s; 17 18 int a[N],vis[N],b[N][105]; 19 20 vector<int>g[N]; 21 22 void bfs(int x){ 23 queue<int>q; 24 25 for(int i=1;i<=n;i++){ 26 if(a[i]==x){ 27 vis[i]=1; 28 b[i][x]=0; 29 q.push(i); 30 } 31 } 32 33 while(!q.empty()){ 34 int u=q.front(); 35 q.pop(); 36 for(int i=0;i<g[u].size();i++){ 37 int v=g[u][i]; 38 if(b[v][x]!=-1)continue; 39 b[v][x]=b[u][x]+1; 40 vis[v]=1; 41 q.push(v); 42 } 43 } 44 45 46 47 } 48 49 50 int main(){ 51 IO; 52 while(cin>>n>>m>>k>>s){ 53 for(int i=1;i<=n;i++){ 54 cin>>a[i]; 55 vis[i]=0; 56 g[i].clear(); 57 memset(b[i],-1,sizeof(b[i])); 58 } 59 for(int i=1;i<=m;i++){ 60 int u,v; 61 cin>>u>>v; 62 g[u].pb(v); 63 g[v].pb(u); 64 } 65 for(int i=1;i<=k;i++)bfs(i); 66 for(int i=1;i<=n;i++){ 67 ll ans=0; 68 sort(b[i]+1,b[i]+1+k); 69 for(int j=1;j<=s;j++)ans+=b[i][j]; 70 if(i==n)cout<<ans<<endl; 71 else cout<<ans<<" "; 72 } 73 } 74 }