• 通知邻居问题


    这是百度校招的一道编程题:

    题目意思如下:有一个人,他通知了邻居参加晚宴,临时有事晚宴取消,由于事情紧急,他只能通知一个邻居,而邻居中有合作的邻居和没有合作的邻居,

    有合作的邻居若知道会议取消,他会告诉左边挨着的两个邻居,和右边挨着的两个邻居,会议取消的消息。不合作的邻居知道会议取消,不会告诉其他邻居这个消息。

    问这个人能通知到的最多人数情况。

    输入:

    两个参数,一个是邻居数,一个是字符串 ,c表示合作的邻居,n表示不合作的邻居。

    输出:

    最多通知的人数情况,I标记通知到的人数,U标记未通知到的人数。

    例如:

    输入:

    10  ncnncncncn

    输出:

    UUIIIIIIII

    思路:暴力求解。求出通知每个人的情况下,通知的情况,让后求出最大的一种输出。

    代码如下:

    #include <iostream>
    #include <string>
    #include <iomanip>
    using namespace std;
    string annoncement(int numOfNeighbours, string characteristic);
    int main(){
        int n;
        string str;
        while(1){
            cin>>n>>str;
            cout<<annoncement(n, str)<<endl;
        }
        return 0;
    }
    
    string annoncement(int numOfNeighbours, string characteristic)
    {
        //WRITE YOUR CODE HERE
        int* jilu=new int[numOfNeighbours];
        int* left1=new int[numOfNeighbours];
        int* right=new int[numOfNeighbours];
        memset(jilu,0,numOfNeighbours);
        memset(left1,0,numOfNeighbours);
        memset(right,0,numOfNeighbours);
        int n=characteristic.size();
        cout<<setw(8)<<"i"<<setw(16)<<"jilu[i]"<<setw(16)<<"left1[i]"<<setw(16)<<"right[i]"<<endl;
        for(int i=0;i<n;i++)
        {
            int num=1,j=i-1,m=i+1;
            if(characteristic[i]=='c'){
                int k=2;
                while(k--&&j>=0){
                    num++;
                    if(characteristic[j--]=='c'){
                        k=2;
                    }
                }
                 k=2;
                while(k--&&m<n){
                    num++;
                    if(characteristic[m++]=='c'){
                        k=2;
                    }
                }
            }
            jilu[i]=num;
            left1[i]=j+1;
            right[i]=m-1;
            cout<<setw(8)<<i<<setw(16)<<jilu[i]<<setw(16)<<left1[i]<<setw(16)<<right[i]<<endl;
        }
    
        int nmax=0,kk=0;
        for(int i=0;i<n;i++)
            if(nmax<jilu[i]){
                nmax=jilu[i];
                kk=i;
            }
            string str;
        for(int i=0;i<n;i++){
            if(left1[kk]<=i&&i<=right[kk])
                str+='I';
            else
                str+='U';
        }
        delete []jilu;
        delete []left1;
        delete []right;
        return str;
    }
  • 相关阅读:
    C语言-10-位域与共用体
    python-并发编程
    计算机操作系统
    网络编程-Socket
    网络编程-基础
    python-面向对象进阶
    python-面向对象
    python-模块分类与导入
    python-函数进阶
    python-函数内置方法
  • 原文地址:https://www.cnblogs.com/lqwh/p/7554873.html
Copyright © 2020-2023  润新知