其他分享
首页 > 其他分享> > CF1307D Cow and Fields

CF1307D Cow and Fields

作者:互联网

思路:

排序,参考了https://codeforces.com/blog/entry/73953

实现:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 void bfs(int x,vector<int>& d,vector<vector<int>>&g){
 4     queue<int>q;
 5     q.push(x);
 6     int n=d.size();
 7     vector<bool>vis(n,false);
 8     vis[x]=true;
 9     while(!q.empty()){
10         int tmp=q.front();q.pop();
11         for(int i=0;i<g[tmp].size();i++){
12             int t=g[tmp][i]; 
13             if(!vis[t]){
14                 d[t]=d[tmp]+1;
15                 vis[t]=true;
16                 q.push(t);
17             }
18         }
19     }
20 }
21 int main(){
22     int n,m,k;
23     while(cin>>n>>m>>k){
24         set<int>sp;
25         vector<vector<int>>g(n+1,vector<int>());
26         for(int i=0;i<k;i++){
27             int x;cin>>x;
28             sp.insert(x);
29         }
30         for(int i=0;i<m;i++){
31             int a,b;
32             cin>>a>>b;
33             g[a].push_back(b);
34             g[b].push_back(a);
35         }
36         vector<int>d(n+1,0),dr(n+1,0);
37         bfs(1,d,g);
38         bfs(n,dr,g);
39         vector<int>t;
40         for(auto it:sp){
41             t.push_back(it);
42         }
43         sort(t.begin(),t.end(),[&](int x,int y){return d[x]-dr[x]<d[y]-dr[y];});
44         int res=1,maxn=dr[t.back()];
45         for(int i=t.size()-2;i>=0;i--){
46             int id=t[i];
47             res=max(res,d[id]+maxn);
48             maxn=max(maxn,dr[id]);
49         }
50         cout<<min(res+1,d[n])<<endl;
51     }
52     return 0;
53 }

标签:Cow,int,Fields,CF1307D,back,vector,push,dr,id
来源: https://www.cnblogs.com/wangyiming/p/16244197.html