当前位置: 首页 > news >正文

(算法)Travel Information Center

题目:

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=0;i<adj.size();i++){
        if(adj[i]==p)
            continue;
        if(dis[adj[i]]==-1 || dis[adj[i]]>dis[x]+1){
            dis[adj[i]]=dis[x]+1;
            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>0 && query_num>0){
            vector<Node> cities(city_num+1);
            vector<int> distances(city_num+1,-1);
            // input information
            for(int i=0;i<city_num-1;i++){
                if(cin>>city_1 && cin>>city_2){
                    if(city_1>0 && city_1<=city_num && city_2>0 && city_2<=city_num){
                        cities[city_1].adjList.push_back(city_2);
                        cities[city_2].adjList.push_back(city_1);
                    }
                    else
                        return 0;
                }    
            }

            distances[1]=0;
            dfs(cities,distances,1,0);

            for(int i=0;i<query_num;i++){
                cin>>query>>city;
                if(query==1){
                    distances[city]=0;
                    dfs(cities,distances,city,0);
                }
                else
                    cout<<distances[city]<<endl;
            }
        }
    }

    return 0;
}

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(-1),depth(0),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>0 && query_num>0){
            vector<CityNode> cities(city_num);
            vector<vector<int> > distances(city_num,vector<int>(city_num,0));
            // input information
            for(int i=0;i<city_num-1;i++){
                if(cin>>city_1 && cin>>city_2){
                    if(city_1>0 && city_1<=city_num && city_2>0 && city_2<=city_num){
                        cities[city_1-1].adjList.push_back(city_2-1);
                        cities[city_2-1].adjList.push_back(city_1-1);
                    }
                    else
                        return 0;
                }    
            }

            // 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(0);
            cities[0].isFestival=true;
            int dist;

            // find the nearest path from all festival cities
            for(int i=0;i<query_num;i++){
                if(cin>>query && cin>>city){
                    int nearest=MIN_DISTANCE;
                    // if query==1, add to festival cities
                    if(query==1 && city>0 && city<=city_num){
                        festivalCity.push_back(city-1);
                        cities[city].isFestival=true;
                    }
                    // if query==2, find the nearest festival city
                    else if(query==2 && city>0 && city<=city_num){
                        for(int k=0;k<festivalCity.size();k++){
                            if(distances[city-1][festivalCity[k]]!=0)
                                dist=distances[city-1][festivalCity[k]];
                            else
                                dist=getDistFromFesCity(cities,city-1,festivalCity[k],distances);
                            if(dist<nearest)
                                nearest=dist;
                        }
                        miniDist.push_back(nearest);
                    }
                    else
                        return 0;
                }
            }

            for(int i=0;i<miniDist.size();i++)
                cout<<miniDist[i]<<endl;
        }
    }
    return 0;
}


void getParentAndDepth(vector<CityNode> &cities,int city_num){
    vector<int> stk;
    stk.push_back(0);
    int node;
    int v;
    int count=0;
    while(!stk.empty() && count<city_num){
        node=stk.back();
        stk.pop_back();
        for(int i=0;i<cities[node].adjList.size();i++){
            v=cities[node].adjList[i];
            if(v==0 ||cities[v].parent!=-1)
                continue;
            cities[v].parent=node;
            cities[v].depth=cities[node].depth+1;
            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 0;
    int dist=0;
    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;        
}

转载于:https://www.cnblogs.com/AndyJee/p/4887034.html

相关文章:

  • 带进度条的文件批量上传插件uploadify
  • Bootstrap 下拉菜单
  • jQuery的Ajax提交
  • linux命令ps aux|grep xxx详解
  • EXCEL数据导入SQL表的方法
  • 研究:我们的宇宙至少四次进入其它宇宙
  • js获取元素样式
  • Adobe:下一代Flash Player效率将提高10倍
  • 九度OJ 1054:字符串内排序 (排序)
  • [CareerCup] 12.3 Test Move Method in a Chess Game 测试象棋游戏中的移动方法
  • Java常量池解析与字符串intern简介
  • Flash开发利器IntelliJ IDEA - 安装
  • 微软出页游用flash技术
  • 具体的了解“gt;/dev/null 2gt;amp;1”
  • 2.C#的输入、输出与运算符、数据类型
  • 【node学习】协程
  • Git学习与使用心得(1)—— 初始化
  • httpie使用详解
  • MYSQL如何对数据进行自动化升级--以如果某数据表存在并且某字段不存在时则执行更新操作为例...
  • MySQL用户中的%到底包不包括localhost?
  • Netty 4.1 源代码学习:线程模型
  • open-falcon 开发笔记(一):从零开始搭建虚拟服务器和监测环境
  • Sublime text 3 3103 注册码
  • WordPress 获取当前文章下的所有附件/获取指定ID文章的附件(图片、文件、视频)...
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 第十八天-企业应用架构模式-基本模式
  • 给github项目添加CI badge
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 讲清楚之javascript作用域
  • 力扣(LeetCode)56
  • 马上搞懂 GeoJSON
  • 实战|智能家居行业移动应用性能分析
  • 说说动画卡顿的解决方案
  • 想晋级高级工程师只知道表面是不够的!Git内部原理介绍
  • 一个项目push到多个远程Git仓库
  • 用 Swift 编写面向协议的视图
  • 掌握面试——弹出框的实现(一道题中包含布局/js设计模式)
  • 如何用纯 CSS 创作一个货车 loader
  • #NOIP 2014# day.1 生活大爆炸版 石头剪刀布
  • #QT(TCP网络编程-服务端)
  • $refs 、$nextTic、动态组件、name的使用
  • (C++)栈的链式存储结构(出栈、入栈、判空、遍历、销毁)(数据结构与算法)
  • (二十三)Flask之高频面试点
  • (九)One-Wire总线-DS18B20
  • ***利用Ms05002溢出找“肉鸡
  • **PyTorch月学习计划 - 第一周;第6-7天: 自动梯度(Autograd)**
  • **登录+JWT+异常处理+拦截器+ThreadLocal-开发思想与代码实现**
  • .gitattributes 文件
  • .htaccess 强制https 单独排除某个目录
  • .NET CF命令行调试器MDbg入门(三) 进程控制
  • .Net6 Api Swagger配置
  • .NET多线程执行函数
  • .Net高阶异常处理第二篇~~ dump进阶之MiniDumpWriter
  • .net通用权限框架B/S (三)--MODEL层(2)