题目:

Aps Island has many cities. In the summer, many travellers will come to the island and attend festive events in different cities. The festive events in Aps Island are crazy. Once it starts, it will never end. In the following sentences, the cities which have festive events are called festive cities.
At the beginning, only city No. 1 is festive city. If a new city becomes festive city, the government will tellthe information center about this news.
Everyday, the information center will receive many inquiries from travellers from different cities of this land. They want to know the closest festive city, and calculate the distance (If current city has festive event, the distance is 0).
Due to the growing number of the travellers, the information center is overloaded. The government wants to fix the problem by developing a system to handle the inquiries automatically.
As a fact, cities in Aps Island are connected with highways(bidirectional, length of every highway is 1). Any two cities are connected directly or indirectly, and there is ONLY one path between any 2 cities.

Input:
 There are two integers in the first line, n (2<=n<=10^5) and m (1<=m<=10^5), n is the number of cities in the Aps Island and m is the number of queries.

The coming n-1 lines are the highways which connect two cities. In the line, there are two integers ai and bi (1<=ai,bi<=n,ai!=bi), representing two cities.  Each line means the highway connecting the two cities.
 Next m lines are inquiries from travellers or news from government. Each line has two integers qi andci (1<=qi<=2,1<=ci<=n). If qi=1, the government announces a new festive city ci. If qi=2, you have  to find and print the shortest distance from the city ci to the closest festive city.

Output:
  Results from each (qi = 2) Questions. Print every result with a new line.

C++
int main(){
// TODO: Implement your program
}

Sample Test
input
5 5

1 2

1 3

3 4

3 5

2 5

2 3

1 3

2 3

2 4
output
2

1

0

1

思路:

1、DFS

2、算法优化

代码:

1、DFS

#include<iostream>
#include<vector> using namespace std; struct Node{
vector<int> adjList;
}; void dfs(const vector<Node> &cities,vector<int> &dis,int x,int p){
vector<int> adj=cities[x].adjList;
for(int i=;i<adj.size();i++){
if(adj[i]==p)
continue;
if(dis[adj[i]]==- || dis[adj[i]]>dis[x]+){
dis[adj[i]]=dis[x]+;
dfs(cities,dis,adj[i],x);
}
}
} int main(){
int city_num;
int query_num;
int city_1,city_2; //input: two connected cities
int query,city; //input: query type and city
while(cin>>city_num && cin>>query_num){
if(city_num> && query_num>){
vector<Node> cities(city_num+);
vector<int> distances(city_num+,-);
// input information
for(int i=;i<city_num-;i++){
if(cin>>city_1 && cin>>city_2){
if(city_1> && city_1<=city_num && city_2> && city_2<=city_num){
cities[city_1].adjList.push_back(city_2);
cities[city_2].adjList.push_back(city_1);
}
else
return ;
}
} distances[]=;
dfs(cities,distances,,); for(int i=;i<query_num;i++){
cin>>query>>city;
if(query==){
distances[city]=;
dfs(cities,distances,city,);
}
else
cout<<distances[city]<<endl;
}
}
} return ;
}

2、算法优化

#include<iostream>
#include<vector> using namespace std; #define MIN_DISTANCE 1000000
typedef struct Node CityNode; /***** definition of data structure about each city *****/
struct Node{
int parent;
int depth;
bool isFestival;
vector<int> adjList;
Node():parent(-),depth(),isFestival(false){}
}; /***** function declaration *****/
// compute parent and depth of each node on the tree
void getParentAndDepth(vector<CityNode> &citites,int city_num);
// compute distance from the festival city by finding the nearear common parents
int getDistFromFesCity(vector<CityNode> &cities,int cur_city,int fes_city,vector<vector<int> > &distances); /***** main function *****/
int main(){
int city_num;
int query_num;
int city_1,city_2; //input: two connected cities
int query,city; //input: query type and city
while(cin>>city_num && cin>>query_num){
if(city_num> && query_num>){
vector<CityNode> cities(city_num);
vector<vector<int> > distances(city_num,vector<int>(city_num,));
// input information
for(int i=;i<city_num-;i++){
if(cin>>city_1 && cin>>city_2){
if(city_1> && city_1<=city_num && city_2> && city_2<=city_num){
cities[city_1-].adjList.push_back(city_2-);
cities[city_2-].adjList.push_back(city_1-);
}
else
return ;
}
} // compute parent,depth of each node on the tree
getParentAndDepth(cities,city_num); vector<int> festivalCity; //city who announced as festival city
vector<int> miniDist; // minimum distance of each query
festivalCity.push_back();
cities[].isFestival=true;
int dist; // find the nearest path from all festival cities
for(int i=;i<query_num;i++){
if(cin>>query && cin>>city){
int nearest=MIN_DISTANCE;
// if query==1, add to festival cities
if(query== && city> && city<=city_num){
festivalCity.push_back(city-);
cities[city].isFestival=true;
}
// if query==2, find the nearest festival city
else if(query== && city> && city<=city_num){
for(int k=;k<festivalCity.size();k++){
if(distances[city-][festivalCity[k]]!=)
dist=distances[city-][festivalCity[k]];
else
dist=getDistFromFesCity(cities,city-,festivalCity[k],distances);
if(dist<nearest)
nearest=dist;
}
miniDist.push_back(nearest);
}
else
return ;
}
} for(int i=;i<miniDist.size();i++)
cout<<miniDist[i]<<endl;
}
}
return ;
} void getParentAndDepth(vector<CityNode> &cities,int city_num){
vector<int> stk;
stk.push_back();
int node;
int v;
int count=;
while(!stk.empty() && count<city_num){
node=stk.back();
stk.pop_back();
for(int i=;i<cities[node].adjList.size();i++){
v=cities[node].adjList[i];
if(v== ||cities[v].parent!=-)
continue;
cities[v].parent=node;
cities[v].depth=cities[node].depth+;
stk.push_back(v);
count++;
}
}
} int getDistFromFesCity(vector<CityNode> &cities,int cur_city,int fes_city,vector<vector<int> > &distances){
int a=cur_city;
int b=fes_city; if(a==b)
return ;
int dist=;
while(cities[a].depth>cities[b].depth){
a=cities[a].parent;
dist++;
}
while(cities[a].depth<cities[b].depth){
b=cities[b].parent;
dist++;
}
while(a!=b){
a=cities[a].parent;
dist++;
b=cities[b].parent;
dist++;
} distances[cur_city][fes_city]=dist; return dist;
}

(算法)Travel Information Center的更多相关文章

  1. Oracle E-Business Suite Release 12.2 Information Center - Manage

    Oracle E-Business Suite Maintenance Guide Release 12.2 Part No. E22954-14     PDF: http://docs.oracl ...

  2. 机器学习sklearn19.0聚类算法——Kmeans算法

    一.关于聚类及相似度.距离的知识点 二.k-means算法思想与流程 三.sklearn中对于kmeans算法的参数 四.代码示例以及应用的知识点简介 (1)make_blobs:聚类数据生成器 sk ...

  3. ISP路由表分发中的AS与BGP

    ➠更多技术干货请戳:听云博客 摘要 本文面向,初级网络工程师,数据挖掘工程师,涉及EGP(外部网关协议; Exterior Gateway Protocol),IGP(内部网关协议; Interior ...

  4. Landsat 8 OLI_TIRS 卫星数字产品

      产品描述           2013 年2月11日,美国航空航天局(NASA) 成功发射Landsat-8卫星.Landsat-8卫星上携带两个传感器,分别是OLI陆地成像仪(Operation ...

  5. “你什么意思”之基于RNN的语义槽填充(Pytorch实现)

    1. 概况 1.1 任务 口语理解(Spoken Language Understanding, SLU)作为语音识别与自然语言处理之间的一个新兴领域,其目的是为了让计算机从用户的讲话中理解他们的意图 ...

  6. TCP/IP 详解常用术语

    业务需要,最近看TCP/IP 这本书,专业名词太多了,总结一下,给后来着参考,直接使用. 后续会在读书时慢慢添加. ACK:(ACKnowledgment)TCP首部中的确认标志. ARP:地址解析协 ...

  7. Nginx学习笔记(反向代理&搭建集群)

    一.前言 1.1 大型互联网架构演变历程 1.1.1 淘宝技术 淘宝的核心技术(国内乃至国际的 Top,这还是2011年的数据) 拥有全国最大的分布式 Hadoop 集群(云梯,2000左右节点,24 ...

  8. DHTML---HTML5

    1. HTML概述 网页是网站的表现层,各种编程语言(如Java)构成后台的逻辑,我们将后台逻辑做好然后通过页面表达.同时通过网页来与后台进行交互.而Html是我们做网页的基础,由浏览器来解析. 1. ...

  9. Video for Linux Two API Specification Revision 2.6.32【转】

    转自:https://www.linuxtv.org/downloads/legacy/video4linux/API/V4L2_API/spec-single/v4l2.html Video for ...

随机推荐

  1. 推荐13个.Net开源的网络爬虫

    1:.Net开源的跨平台爬虫框架 DotnetSpider Star:430 DotnetSpider这是国人开源的一个跨平台.高性能.轻量级的爬虫软件,采用 C# 开发.目前是.Net开源爬虫最为优 ...

  2. mac 刻录ISO系统盘

    今天本本系统坏了,手头上又没有U盘PE工具,只有MAC和光驱,只好在MAC上下载系统ISO刻录,我是直接点ISO文件,右键刻录到光盘,刻录好之后放到本本上发现不能引导,再把光盘放回MAC上一看,光盘里 ...

  3. 内存映射函数remap_pfn_range学习——示例分析(2)

    li {list-style-type:decimal;}ol.wiz-list-level2 > li {list-style-type:lower-latin;}ol.wiz-list-le ...

  4. 前端使用AngularJS的$resource,后端ASP.NET Web API,实现增删改查

    AngularJS中的$resource服务相比$http服务更适合与RESTful服务进行交互.本篇后端使用ASP.NET Web API, 前端使用$resource,实现增删改查. 本系列包括: ...

  5. error CS0234: 命名空间“XXX”中不存在类型或命名空间名称“UserInfoVm”(是否缺少程序集引用?)

    □ 背景 UserInfoVm是在MVC的Models文件夹中的一个view model,这个view model是某部分视图的的页面Model.当加载这个部分视图的时候报了错. □ 思考 UserI ...

  6. TMS WEB CORE直接从HTML&CSS设计的页面布局

    TMS WEB CORE直接从HTML&CSS设计的页面布局 TMS WEB CORE支持DELPHI IDE中拖放控件,生成HTML UI.这种方式适合DELPHI和C++ BUILDER的 ...

  7. runOnUiThread更新主线程

    更新UI采用Handle+Thread,需要发送消息,接受处理消息(在回调方法中处理),比较繁琐.除此之外,还可以使用runOnUiThread方法.   利用Activity.runOnUiThre ...

  8. PHP读写INI文件

    读INI文件 public function readini($name) { if (file_exists(SEM_PATH.'init/'.$name)){ $data = parse_ini_ ...

  9. 整合 Ext JS 和第三方类库

    介绍 ExtJS提供了许多高度可定制化内置组件.如果它不在框架(framework)里面,你可以很容易的扩展这些类,或者浏览Sencha市场(Sencha Market) 寻找你可能需要的任何东西.那 ...

  10. python文档生成工具:pydoc、sphinx;django如何使用sphinx?

    文档生成工具: 自带的pydoc,比较差 建议使用sphinx 安装: pip install sphinx 安装主题: 由各种主题,我选择常用的sphinx_rtd_theme pip instal ...