题目描述
数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照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;
}