【华为机试】合并表查询

题目描述

数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。


输入描述:

先输入键值对的个数 然后输入成对的index和value值,以空格隔开



输出描述:

输出合并后的键值对(多行)


输入例子:
4
0 1
0 2
1 2
3 4

输出例子:
0 3
1 2
3 4

解题思路


模板题,考察结构体排序,使用vector容器和sort方法。。

注:“题目描述”中的“key值”其实就是指 index值。


sort用法1:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct note{
    int index;
    int value;

    /*定义结构体排序方式(index升序)*/
    bool operator < (const note &x) const{
        return index < x.index;
    }
};

int main(){
    int n;
    while( cin>>n ){
        vector<note> p;

        note temp;
        while( n-- ){
            cin>>temp.index>>temp.value;
            p.push_back( temp );
        }

        sort( p.begin(),p.end() );

        vector<note>::iterator itr1,itr2;
        for( itr1=p.begin(); itr1<p.end(); ++itr1 ){
            for( itr2=itr1+1; itr2<p.end(); ++itr2 ){//查找后方索引重复的项
                if( itr2->index == itr1->index ){
                    itr1->value += itr2->value;
                    itr2->index = 999999;//重复项特殊标记,便于控制输出
                }
                else{
                    break;
                }
            }

            if( itr1->index!=999999 ){
                cout<<(itr1->index)<<" "<<(itr1->value)<<endl;
            }
        }
    }
    return 0;
}

sort用法2:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct note{
    int index;
    int value;
};

bool cmp( note a,note b ){
    return a.index<b.index;
}

int main(){
    int n;
    while( cin>>n ){
        vector<note> p;

        note temp;
        while( n-- ){
            cin>>temp.index>>temp.value;
            p.push_back( temp );
        }

        sort( p.begin(),p.end(),cmp );

        vector<note>::iterator itr1,itr2;
        for( itr1=p.begin(); itr1<p.end(); ++itr1 ){
            for( itr2=itr1+1; itr2<p.end(); ++itr2 ){//查找后方索引重复的项
                if( itr2->index == itr1->index ){
                    itr1->value += itr2->value;
                    itr2->index = 999999;//重复项特殊标记,便于控制输出
                }
                else{
                    break;
                }
            }

            if( itr1->index!=999999 ){
                cout<<(itr1->index)<<" "<<(itr1->value)<<endl;
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coder Ben

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值