Thursday, May 11, 2017

【UVa】Frogger

Problem here

Solution

自己的石子為點0,目標石子為1
生成MST直到點0點1連通
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory.h>
  4. #include <utility>
  5. #include <string>
  6. #include <math.h>
  7. #include <stdio.h>
  8. #include <algorithm>
  9. using namespace std;
  10. vector<pair<float, pair<int, int> > > edges;
  11. string spp;
  12. float cal(int x1, int x2, int y1, int y2){
  13. return (float)sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
  14. }
  15. bool cmp(pair<float, pair<int, int> > a, pair<float, pair<int, int> > b){
  16. return a.first < b.first;
  17. }
  18. int pre[1000];
  19. int find(int x){
  20. int r = x;
  21. while(pre[r] != r){
  22. r = pre[r];
  23. }
  24. int j = x, y;
  25. while(j != r){
  26. y = pre[j];
  27. pre[j] = r;
  28. j = y;
  29. }
  30. return r;
  31. }
  32. void join(int a, int b){
  33. int fa = find(a);
  34. int fb = find(b);
  35. if(fa != fb){
  36. pre[fa] = fb;
  37. }
  38. }
  39. int main(){
  40. int n;
  41. int count = 1;
  42. while(cin >> n){
  43. if(n==0)
  44. break;
  45. vector<pair<int , int > > point;
  46. for(int i = 0; i < n; i++){
  47. int x, y;
  48. cin >> x >> y;
  49. point.push_back(make_pair(x,y));
  50. for(int j = 0; j < i; j++){
  51. edges.push_back(make_pair(cal(point[i].first, point[j].first, point[i].second, point[j].second), make_pair(i, j)) );
  52. }
  53. }
  54. cout << "Scenario #" << count++ << endl;
  55. sort(edges.begin(), edges.end(), cmp);
  56. for(int i = 0; i < n; i++)
  57. pre[i] = i;
  58. for(int i = 0; i < edges.size(); i++){
  59. if(find(edges[i].second.first)==find(edges[i].second.second))
  60. continue;
  61. join(edges[i].second.first, edges[i].second.second);
  62. if(find(1) == find(0)){
  63. printf("Frog Distance = %.3lf\n", edges[i].first);
  64. break;
  65. }
  66. }
  67. edges.clear();
  68. cout << endl;
  69. getline(cin, spp);
  70. }
  71. return 0;
  72. }

No comments:

Post a Comment