算法 合並表記錄


題目描述

數據表記錄包含表索引和數值(int范圍的整數),請對表索引相同的記錄進行合並,即將相同索引的數值進行求和運算,輸出按照key值升序進行輸出。

輸入描述:

先輸入鍵值對的個數
然后輸入成對的index和value值,以空格隔開

輸出描述:

輸出合並后的鍵值對(多行)

示例1

輸入

復制
4
0 1
0 2
1 2
3 4

輸出

復制
0 3
1 2
3 4

思路:使用hash表

#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <map>
using namespace std;

int main()
{
  int Sum[1024] = {0};
  int n = 0;
  int x = 0,y = 0;
  cin >>n;

  for(int i = 0; i < n; i++)
  {
    cin>>x>>y;
    Sum[x]+=y;
  }

  for(int i = 0; i < 1024; i++){
    if(Sum[i]>0){
      cout << i <<" "<< Sum[i] << endl;
    }
  }
  return 0;
}

 

注意如果這里長度太長就不能用int,並且注意最后不能用ends代替" "


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM