【点击获取原题链接】](http://www.sdutacm.org/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2023/pid/1960.html)
共用体练习
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
给定n和m,接下来有n个描述,每个描述包含一个类型标志和一组相应的数据。类型标志共3种:INT DOUBLE STRING,然后对应一组相应的数据。紧接着有m个询问,每个询问仅包含一个整数x,要求输出第x个描述对应的数据(STRING类型保证不含空格,每组对应STRING数据不会超过19个字符)。
Input
输入的第一行为两个整数,n和m (n<=100000, m<=100000),分别代表描述的个数和询问的个数。接下来为 n 行描述,最后为m行询问,具体格式见样例输入输出。
Output
对于每个询问,输出对应的结果,注意:浮点数保留两位小数。
Example Input
5 4
INT 456
DOUBLE 123.56
DOUBLE 0.476
STRING welcomeToC
STRING LemonTree
0
1
2
4
Example Output
456
123.56
0.48
LemonTree
Hint
必须使用共用体完成。
Author
/****题目设定只能用共用体特别烦人。。。。。。****/
////公用体类型
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
union node
{
int a;
double b;
char c[100];
} a[100000+10];
char b[100000][10];/// 储存每次输入的类型名
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
{
scanf("%s",b[i]);
if(strcmp(b[i],"INT")==0)/// int类型
{
int t;
scanf("%d",&t);
a[i].a=t;
}
else if(strcmp("DOUBLE",b[i])==0)///double 类型
{
double t;
scanf("%lf",&t);
a[i].b=t;
}
else if(strcmp("STRING",b[i])==0)/// char 类型
{
char t[300];
scanf("%s",t);
strcpy(a[i].c,t);/// 把t的内容复制给A[i].c
}
}
while(m--)/// 进行m次询问
{
int t;
scanf("%d",&t);
if(strcmp(b[t],"INT")==0)/// 先判断共用体对象的类型
{
printf("%d\n",a[t].a);
}
else if(strcmp(b[t],"DOUBLE")==0)
{
printf("%.2lf\n",a[t].b);
}
else if(strcmp(b[t],"STRING")==0)
{
printf("%s\n",a[t].c);
}
}
return 0;
}