USACO 2.4 Bessie Come Home (comehome)
2014-02-25 13:58
363 查看
//Main idea //Calculate the shortest path from 'Z' to ohter pastures by Dijkstra algorithm; //And then choose shortest path among 'A' to 'Y'; /* ID: haolink1 PROG: comehome LANG: C++ */ //#include <iostream> #include <fstream> const int INF = 52 * 1000 + 1; int min_path[52]; bool is_remove[52]; int dist[52][52]; using namespace std; bool IsCapital(char x){ if(x >= 'A' && x <= 'Z') return true; else return false; } int ExtractMin(){ int min_index = -1; int min = INF; for(int i = 0; i < 52; i++){ if(min > min_path[i] && is_remove[i] == 0){ min = min_path[i]; min_index = i; } } if(min_index >= 0) is_remove[min_index] =1; return min_index; } void Relax(int x,int y){ if(min_path[y] > min_path[x] + dist[x][y]) min_path[y] = min_path[x] + dist[x][y]; } void Dijkstra(){ for(short i = 0; i < 52; i++){ min_path[i] = INF; } min_path[25] = 0; while(1){ int index = ExtractMin(); if(index < 0) break; for(int i = 0; i < 52; i++){ if(dist[index][i] < INF ){ Relax(index,i); } } } } int main(){ for(short i = 0; i < 52; i++ ){ for(short j = 0; j < 52; j++){ dist[i][j] = INF;//Note dist[i][i] is also INF and it will be used in Dijkstra; } } int num = 0; ifstream fin("comehome.in"); fin >> num; for(int i = 0; i < num; i++){ int x, y; char x_char,y_char; int dis; fin >> x_char >> y_char >> dis; if(IsCapital(x_char)){ x = x_char-'A'; }else x = x_char - 'a' + 26; if(IsCapital(y_char)) y = y_char-'A'; else y = y_char- 'a' + 26; if(dis < dist[x][y] && x != y)//For each path between two pastures, we only take the shortest; dist[x][y] = dist[y][x] = dis; } Dijkstra(); int min = INF; int index = -1; for(int i = 0; i < 25; i++){ if(min_path[i] < min){ min = min_path[i]; index = i; } } char cow = 'A' + index; ofstream fout("comehome.out"); fout << cow <<" "<< min << endl; return 0; }
相关文章推荐
- Javascript SHA-1:Secure Hash Algorithm
- [转]可视化的数据结构和算法
- 统计文件中不小于某一长度的单词的个数(泛型算法实现)
- 使用他人的MD5编码类,修改形成密码串
- Extracting Structured Data from Web Pages
- (译)Cocos2d_for_iPhone_1_Game_Development_Cookbook:1.13使用CCTexture2DMutable调换调色盘
- Java中3DES加密
- Refactoring Notes-Refactoring Methods(3)
- 图书馆管理程序~~不过貌似功能!!有空再修修
- trainging contest#2(2011成都现场赛)I BY Hyoga
- C/C++头文件包含内容概览
- 堆栈的应用(1) 平衡符号 C++实现
- 程序员编程艺术第一章、左旋转字符串
- 程序员编程艺术:第三章续、Top K算法问题的实现
- 程序员编程艺术:第四章、现场编写类似strstr/strcpy/strpbrk的函数
- 十四、第三章再续:快速选择SELECT算法的深入分析与实现
- 程序员编程艺术:第七章、求连续子数组的最大和
- 程序员编程艺术:第八章、从头至尾漫谈虚函数
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第十章、如何给10^7个数据量的磁盘文件排序