Copyright (C) IOI日本委員会 1996. All rights reserved.


問題3.

 下記のプログラムは、昇順に並んだ整数のデータと対象となる整数(target)を読み、 それが何番目にあるかを求める。
 空欄に文あるいは式を入れて、プログラムを完成させよ。 [2点]


QuickBASICプログラム(3)

DEFINT A-Z
DECLARE FUNCTION search (d() AS INTEGER, s AS INTEGER)
CONST n = 100
OPTION BASE 1
DIM a(n) AS INTEGER

    FOR i = 1 TO n: INPUT a(i): NEXT i
    PRINT "target="; : INPUT target
    i = search(a(), target)
    IF i = 0 THEN PRINT "存在しない" ELSE PRINT i; "番目"
END

FUNCTION search (d() AS INTEGER, s AS INTEGER)
    left = 1: right = n
    DO
        k = INT((left + right) / 2)
        IF s = d(k) THEN
            search = k: EXIT FUNCTION
        ELSEIF s < d(k) THEN
             -----------------
            |     (a)       |
             -----------------
        ELSE
             -----------------
            |     (b)       |
             -----------------
        END IF
    LOOP WHILE left <= right
    search = 0
END FUNCTION


Cプログラム(3)

#include <stdio.h>

#define n 100
typedef int vector[n+1];

int search(vector d, int s)
{
    int left,right,k;

    left = 1; right = n;
    do {
        k = (left+right)/2;
        if (s==d[k]) return k;
        else {
                            -----------------
            if (s<d[k]) |      (a)      |;
                            -----------------
                  -----------------
            else |      (b)      |;
                  -----------------
        }
    } while (left<=right);
    return 0;
}

void main()
{
    int i,target; vector a;

    for (i=1; i<=n; i++) scanf("%d", &a[i]);
    printf("target="); scanf("%d", &target);
    i = search(a,target);
    if (i==0) printf("存在しない\n"); else printf("%d番目\n", i);
}


Pascalプログラム(3)

program problem3;
const n=100;
type vector=array[1..n] of integer;

    function search(d:vector; s:integer):integer;
    var left,right,k:integer;
    begin
        left := 1; right := n;
        repeat
            k := (left+right) div 2;
            if s=d[k] then begin search := k; exit end else
                                -----------------
            if s<d[k]) then |      (a)      |
                                -----------------
                  -----------------
            else |      (b)      |
                  -----------------
        until left>right;
        search := 0
    end; {search}

var i,target:integer; a:vector;
begin
    for i:=1 to n do read(a[i]);
    write('target='); readln(target);
    i := search(a,target);
    if i=0 then writeln('存在しない') else writeln(i,'番目')
end.


JOI'96へ戻る

JOIホームページへ戻る