@ Решение Бена довольно сладкое. Он не обрабатывает следующие случаи:
# all these return numeric(0):
x <- c(1,2,9,9,2,1,1,5,5,1) # duplicated points at maxima
which(diff(sign(diff(x)))==-2)+1
x <- c(2,2,9,9,2,1,1,5,5,1) # duplicated points at start
which(diff(sign(diff(x)))==-2)+1
x <- c(3,2,9,9,2,1,1,5,5,1) # start is maxima
which(diff(sign(diff(x)))==-2)+1
Вот более надежная (и медленная, уродливая) версия:
localMaxima <- function(x) {
# Use -Inf instead if x is numeric (non-integer)
y <- diff(c(-.Machine$integer.max, x)) > 0L
rle(y)$lengths
y <- cumsum(rle(y)$lengths)
y <- y[seq.int(1L, length(y), 2L)]
if (x[[1]] == x[[2]]) {
y <- y[-1]
}
y
}
x <- c(1,2,9,9,2,1,1,5,5,1)
localMaxima(x) # 3, 8
x <- c(2,2,9,9,2,1,1,5,5,1)
localMaxima(x) # 3, 8
x <- c(3,2,9,9,2,1,1,5,5,1)
localMaxima(x) # 1, 3, 8
Проблема в том, что в строке 32, 33 вместо массива 'weight' есть индексная переменная 'w'. И еще одна вещь, если вы используете 'j' для индексации, чем объявляете ее 'int', а не float.
Я не уверен, что ваш алгоритм будет работать. Но это будет работать сейчас. Если вам нужна помощь в algo, вы можете прокомментировать.
//maximum value of loot
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int maxi(int a , int b)
{
if(a>b) return a;
else return b;
}
int main()
{
int n,W,V=0,j;// line i have changed
float v,w;
vector<int> values;
vector<int> weights;
vector<float> vbyw;
cin>>n>>W;
for(int i = 0 ; i<n; i++)
{
cin>>v>>w;
values.push_back(v);
weights.push_back(w);
vbyw.push_back(float(v/w));
}
sort(vbyw.begin(),vbyw.end());
j = vbyw.size()-1;
while(W>0 && j>0)
{
W = W - maxi(weights[j],W); // line i have changed
V = V + maxi(weights[j],W)*vbyw[j]; // line i have changed
j--;
}
cout<<V;
return 0;
}