HDOJ1004

最近才有意识地开始刷HDOJ上的题目,先从水题开始练手,比如说1004

该题目的意思很简单,第一行输入气球的个数n,以下n行输入n个气球的颜色,n为0时输入结束,要求输出哪种颜色的气球颜色最多。

这题是很简单,也用不到什么算法的东西,就是对输入的字符串进行比较和统计。

看到题的第一想法很简单,先抛开问题,先对输入的格式做一个尝试,就是对输入的结果进行遍历输出,呵呵,最初的尝试就折腾了很久,也是比较无语。

#include<iostream>
#include<string.h>
using namespace std;
int main(){
    int n;
    char *balloon[1000];
    memset(balloon,0,1000);
    char temp[15];
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>temp;
        strcpy(balloon[i],temp);
    }
    for(int i=0;i<n;i++)
      cout<<balloon[i]<<endl;
    return 0;
}

以上,编译没任何问题,输入一个整数以后,再输入一个字符串,但是,再按回车就开始报错,程序直接崩了,Process exited with return value 3221225477,很明显,有点经验的就知道,这是一个常规的初始化报错的问题,仔细想了一下程序崩溃的原因,

char* balloon[1000]里面放的是未初始化的char*指针,其并没有指向任何有意义的内容,再对其使用strcpy进行赋值,对一个未定义的结果赋值,程序肯定会异常崩溃。其实解决的办法很简单,两种方案,一种是在使用strcpy进行赋值之前,使用malloc对对balloon[i]进行内存分配。

balloon[i] = (char*)malloc(15);
strcpy(balloon[i], temp);

另一种方案更简单,直接将balloon声明为一个二维数组,char balloon[1000][15];就OK

看来,C中的指针就是容易出问题,这方面还需要加强修炼。呵呵。

下面贴出AC的代码[一道水题折腾了将近一个半小时,看来自己也是水得一笔]:

#include<iostream>
#include<string.h>

using namespace std;
int main()
{
    int count[1000],color,n,i,j;
    char ball[1000][15],temp[15];
    bool flag;
    while(cin>>n&&n)
    {
        memset(count,0,1000);
        color=0;
        for(i=0;i<n;i++)
        {
            cin>>temp;
            flag=false;
            for(j=0;j<i;j++)
            {
                if(strcmp(ball[j],temp)==0)
                {
                    count[j]++;
                    flag=true;
                }
            }
            if(!flag)
            {
                strcpy(ball[i],temp);
                count[i]++;
                color++;
            }
        }
        int max=0;
        for(i=0,j=0;i<color;i++)
        {
            if(max<count[i])
            {
                max=count[i];
                j=i;
            }
        }
        cout<<ball[j]<<endl;
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-07-31 10:17:08

HDOJ1004的相关文章

hdoj1004 简单string应用

1 #include <iostream> 2 #include <string> 3 #include <string.h> 4 using namespace std; 5 6 string str[1000]; 7 8 int main() 9 { 10 int a[1000]; 11 int n,i,j,max; 12 while (cin>>n,n) 13 { 14 memset(a,0,sizeof(a)); 15 for (i=0;i<n

HDOJ-1004 Let the Balloon Rise

http://acm.hdu.edu.cn/showproblem.php?pid=1004 输入N个字符串  输出出现频率最高的字符串 # include <stdio.h> # include <string.h> # define MAX 1005 struct BALLOON { char Color[20]; int Times;//同颜色气球出现次数 }Balloon[MAX]; int n, Count; void Set_Balloon(char Color[])

HDOJ-1004

Let the Balloon Rise Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 103000    Accepted Submission(s): 39524 Problem Description Contest time again! How excited it is to see balloons floating ar