zoukankan      html  css  js  c++  java
  • 寻找发帖“水王”的扩展问题

    #include<stdio.h>
    #include<stdlib.h>
    /*
      在一个论坛,发现有三个发帖很多的Id ,他们发帖的总数都超过了总数的1/4 ,编程快速的找到这三个id 
      算法: 每次删除是个不同的Id ,那么最后剩下的 三个Id 就是所求的id 
    */
    void findThreeK(int* p,int length)
    {
         int candidate[3],nTimes[3]={0,0,0},i;
         
         for(i=0;i<length; i++)
         {
           if(p[i]==candidate[0])  
           {
             nTimes[0]++;
           }
           else if(p[i]==candidate[1])
           {
             nTimes[1]++;
           }
           else if(p[i]==candidate[2])
           {
             nTimes[2]++;
           }
           else if(nTimes[0]==0)
              {
                 candidate[0]=p[i];
                 nTimes[0] = 1;
              }
            else if(nTimes[1]==0)
              {
                 candidate[1]=p[i];
                 nTimes[1] = 1;
              }
            else if(nTimes[2]==0)
             {
                 candidate[2] = p[i];
                 nTimes[2] = 1;
             }
             else {
                    nTimes[0]--;
                    nTimes[1]--;
                    nTimes[2]--;
                  }
         }
       for(int i = 0 ; i < 3;i++)
       printf("%d " ,candidate[i]);
    } 
    int main()
    {
        FILE *fread = fopen("Id.txt","r");
        
        if(fread==NULL)
        {
           printf("can't open the file!\n");
           exit(0);
        }
        int current = 0;
        // 动态初始化数组 p ,如果不初始化会出现错误 
        int *p = (int*)malloc(sizeof(int)*10);   
        
        // id数组的长度 
        int length = 0 ; 
        // 将 数据读入内存,存入数组P 
        while(fscanf(fread,"%d",¤t)!=EOF)
        {
           if(length%10==0)
           p = (int*)realloc(p , sizeof(int)*(length+10));
           p[length] = current;
           length++;
        }
        
        findThreeK(p,length);
        /*
        for(int i = 0 ;i < length ;i++)
        printf("%d ",p[i]);
        */
        system("pause"); 
        return 0;
    } 
    


  • 相关阅读:
    「CH6801」棋盘覆盖
    「POJ3613」Cow Relays
    「Luogu4556」Vani有约会-雨天的尾巴
    The Proof of Fibonacci GCD
    Ubuntu flatabulous 主题
    CSP-S 2019 复赛游记
    「Luogu1402」酒店之王
    HDU/5499/模拟
    cfedu/A/求和
    HDU<1372>/bfs
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3109168.html
Copyright © 2011-2022 走看看