andmej / acm

My solutions for problems from the UVa Online Judge (Valladolid).

This URL has Read+Write access

acm / 10003 - Cutting sticks / 10003.cpp
100644 65 lines (56 sloc) 1.32 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <map>
#include <algorithm>
#include <climits>
#include <vector>
 
using namespace std;
 
typedef pair<int,int> point;
 
vector<int> p;
map<point, int> cache;
 
int f(point n){
  // cout << "n: " << n.first << " " << n.second << endl;
  if (cache.count(n) > 0){
    //cout << "Retornando " << cache[n] << endl;
    return cache[n];
  }
  //first < second
  if (n.second < n.first) swap(n.first, n.second);
  
  for (int k=0; k<p.size()-1; ++k){
    if (p[k]<=n.first && n.first<=p[k+1] &&
p[k]<=n.second && n.second<=p[k+1]){
      cache[n] = 0;
      //cout << "Retornando 0" << endl;
      return 0;
    }
  }
 
  int min=INT_MAX;
  for (int k=0; k<p.size(); ++k){
    if (n.first<p[k] && p[k]<n.second){
      int q = n.second - n.first + f(point(n.first, p[k])) + f(point(p[k], n.second));
      //cout << "q es: " << q << endl;
      if (q < min){
min = q;
      }
    }
  }
  //cout << "min es: " << min << endl;
  cache[n] = min;
  //cout << "Retornando " << min << endl;
  return min;
  
}
 
int main(){
  int l;
  while (cin >> l && l > 0){
    int n;
    cin >> n;
    cache.clear();
    p = vector<int>(n+2);
    p[0] = 0;
    p[n+1] = l;
    for (int i=1; i<=n; ++i){
      cin >> p[i];
    }
    cout << "The minimum cutting is " << f(point(0, l)) << ".\n";
  }
  return 0;
}