[英]Binary search of a fixed point
I need to write a program that being 我需要写一个程序
S = x 1 , …, x n S = x 1 ,...,x n
A sequence of integer numbers such that 整数序列,使得
x 1 < … < x n x 1 <…<x n
For every integer number a and every index 对于每个整数a和每个索引
1 ≤ i ≤ n 1≤i≤n
Define 限定
f a(i) = x i + a. f a(i) = x i + a。
Given S
and a
, tells whether there is some i
such that 给定S
和a
,则判断是否存在这样的i
f a(i) = i. f a(i) = i。
I have implemented the following program: 我已经实现了以下程序:
#include <iostream>
#include <vector>
using namespace std;
int fixpoint(const vector<int>& v, int a, int esq, int dre) {
if(esq > dre) return -1;
int m = (esq+dre)/2;
if(v[m]+a == m+1) return m+1;
if(v[m]+a > m+1) return fixpoint(v, a, m+1, dre);
if(v[m]+a < m+1) return fixpoint(v, a, esq, m-1);
}
int main() {
int s;
while(cin >> s) {
vector<int> v(s);
for(int i = 0; i<s; ++i) cin >> v[i];
int n;
cin >> n;
for(int i = 0; i<n; ++i) {
int a;
cin >> a;
int fix = fixpoint(v, a, 0, v.size()-1);
if(fix == -1) cout << "no fixed point for " << a << endl;
else cout << "fixed point for " << a << ": " << fix << endl;
}
cout << endl;
}
}
The program must write the first i that satisfies the condition, but if i use the following input: 程序必须先写一个满足条件的i,但是如果我使用以下输入:
5
-7 -2 0 4 8
1
0
5
0 1 2 3 4
3
0 -1 1
The output is: 输出为:
Sequence #1
no fixed point for 0
Sequence #2
no fixed point for 0
no fixed point for -1
fixed point for 1: 3
And the fixed point for 1
in the second sequence should be 1
, because it is the first i
that satisfies the condition. 并且第二个序列中1
的不动点应该是1
,因为它是满足条件的第一个i
。
Could you help me? 你可以帮帮我吗?
I see two problems. 我看到两个问题。
First in your function you should invert the branches of the binary search, as being f monotone increasing (as i) if f > i
you have to search in the intervall with smaller i. 首先,在函数中,应反转二分查找的分支,因为f单调递增(如i),如果f > i
,则必须在具有较小i的区间中进行搜索。
int fixpoint(const vector<int>& v, int a, int esq, int dre) {
if ( esq > dre ) return -1;
int m = (esq + dre)/2;
int m1 = m + 1;
int f = v[m] + a;
if( f == m1)
return m1;
else if( f < m1)
return fixpoint(v, a, m1, dre);
else
return fixpoint(v, a, esq, m-1);
}
Second, your second example is ill formed, as f == i
for every i. 其次,您的第二个示例格式错误,因为每个i f == i
i。 Your function returns 3 only because it's the first index it checks and 3 is as correct an answer as 1. 您的函数仅返回3,因为它是它检查的第一个索引,并且3的正确答案是1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.