当前位置:网站首页>[Jiudu OJ 09] two points to find student information

[Jiudu OJ 09] two points to find student information

2022-07-06 01:27:00 CodeLinghu

【 Nine degrees OJ 09】 Two points to find student information

One 、 The question

Two 、 The answer process

Ideas :

Two points search

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct student// Used to represent the structure of students 
{
    
    char sno[100];// Student number 
    char name[100];// full name 
    char sex[10];// Gender 
    int age;// Age 

    // The comparison function embedded in the structure 
    bool operator < (const student &b) const// Comparison function , Make it possible to sort Function order 
    {
    
        return strcmp(sno,b.sno)<0;
    }
}buf[1000];
int main()
{
    
    int n,m;
    char x[100];
    while(scanf("%d",&n)!=EOF)
    {
    
        for(int i=0;i<n;i++)
        {
    
            scanf("%s %s %s %d",&buf[i].sno,&buf[i].name,&buf[i].sex,&buf[i].age);
        }
        sort(buf,buf+n);// Sort the array , Make it sort in ascending order by student number 
        scanf("%d",&m);
        while(m--!=0)
        {
    
            int ans=-1;
            scanf("%s",&x);// Enter the student number to be searched 
            int top=n-1,base=0;// The starting subscript is 0, The ending subscript is n-1, Find the entire array 
            int cnt=1;
            while(top>=base)
            {
    
                int mid=(top+base)/2;// Calculate the middle point subscript 
                int tmp=strcmp(buf[mid].sno,x);// Compare the intermediate student number with the target student number 
                if(tmp==0)
                {
    
                    ans=mid;
                    break;// If equal, then complete the jump out of the binary search 
                }
                else if(tmp<0)base=mid+1;// If less than , Then the starting subscript becomes the coordinate of the point after the intermediate node 
                else top=mid-1;// If more than , Then the end subscript becomes the subscript before the intermediate node 
                printf("%d\t",mid);
                printf("%d\t",cnt++);
            }
            if(ans==-1)printf(" not find");// To find the failure 
            else printf("%s %s %s %d\n",buf[ans].sno,buf[ans].name,buf[ans].sex,buf[ans].age);
        }
    }
}
原网站

版权声明
本文为[CodeLinghu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140124531682.html