1. 程式人生 > 實用技巧 >牛客多校9-K.The Flee Plan of Groundhog

牛客多校9-K.The Flee Plan of Groundhog

題意:

  a的速度是一秒走一格,b的速度是一秒走兩格,前t秒a沿著a->b的最短路去找b,t秒的時候b反過來抓a,問a最長多少秒才會被抓住

做法:

  先dfs處理出b從n走到圖上任意一點所需要的時間。再在t時a所處的位置bfs處理出a從t時位置到圖上各點的時間,如果a和b同時到某點或比b晚到某點,則會被b抓住,維護一個被抓時間的最大值即可

CODE

  1 #include <bits/stdc++.h>
  2 #define dbug(x) cout << #x << "=" << x << endl
  3 #define
eps 1e-8 4 #define pi acos(-1.0) 5 6 using namespace std; 7 typedef long long LL; 8 9 const int inf = 0x3f3f3f3f; 10 11 template<class T>inline void read(T &res) 12 { 13 char c;T flag=1; 14 while((c=getchar())<'0'||c>'9')if(c=='-')flag=-1;res=c-'0'; 15 while
((c=getchar())>='0'&&c<='9')res=res*10+c-'0';res*=flag; 16 } 17 18 const int maxn = 1e5 + 7; 19 20 int n, t; 21 22 vector<int> g[maxn]; 23 int fa[maxn]; 24 int depth[maxn], vis_time[maxn]; 25 26 int ans; 27 28 void dfs(int x, int pre){ 29 int d = g[x].size();
30 for ( int i = 0; i <= d - 1; ++i ) { 31 int v = g[x][i]; 32 if(v == pre) { 33 continue; 34 } 35 fa[v] = x; 36 depth[v] = depth[x] + 1; 37 vis_time[v] = depth[v] / 2 + depth[v] % 2; 38 dfs(v, x); 39 } 40 } 41 42 bool vis[maxn]; 43 int vis_time2[maxn]; 44 45 void bfs(int x) { 46 queue<int> q; 47 q.push(x); 48 while(!q.empty()) { 49 int temp = q.front(); 50 q.pop(); 51 if(vis[temp]) 52 continue; 53 vis[temp] = 1; 54 // dbug(temp); 55 // printf("::vis[%d]:%d vis2[%d]:%d\n",temp, vis_time[temp], temp, vis_time2[temp]); 56 if(vis_time2[temp] <= vis_time[temp]) { 57 ans = max(ans, vis_time[temp]); 58 } 59 // dbug(ans); 60 if(vis_time2[temp] >= vis_time[temp]) { 61 continue; 62 } 63 int d = g[temp].size(); 64 // dbug(d); 65 for ( int i = 0; i < d; ++i ) { 66 int v = g[temp][i]; 67 // dbug(v); 68 if(vis[v]) { 69 continue; 70 } 71 vis_time2[v] = vis_time2[temp] + 1; 72 q.push(v); 73 } 74 } 75 } 76 77 int main() 78 { 79 read(n); read(t); 80 for ( int i = 1; i <= n - 1; ++i ) { 81 int x, y; 82 read(x); read(y); 83 g[x].push_back(y); 84 g[y].push_back(x); 85 } 86 dfs(n, n); 87 int node = 1; 88 while(t--) { 89 node = fa[node]; 90 } 91 bfs(node); 92 // for ( int i = 1; i <= n; ++i ) { 93 // printf("time[%d]:%d time2[%d]:%d\n",i, vis_time[i], i, vis_time2[i]); 94 // } 95 cout << ans << endl; 96 return 0; 97 } 98 /* 99 7 100 1 101 1 2 102 2 4 103 4 5 104 5 6 105 6 3 106 5 7 107 108 6 1 109 1 2 110 1 3 111 1 4 112 1 5 113 1 6 114 115 10 2 116 1 2 117 2 5 118 5 7 119 5 6 120 3 6 121 3 4 122 7 8 123 8 9 124 9 10 125 126 */
View Code