数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。 提示: 0 <= index <= 11111111 1 <= value <= 100000
区块链毕设网qklbishe.com为您提供问题的解答
#include <string.h>
int main()
{
struct data
{
int index;
int value;
};
int temp1,temp2;
struct data indata[500];
int N =0;
while(EOF != scanf("%d",&N))
{
temp1 = 0;
temp2 = 0;
for(int i= 0;i<N;i++)
{
scanf("%d %d",&indata[i].index,&indata[i].value);
}
for(int i= 0;i<N-1;i++)
{
for(int j=i+1; j<N;j++)
{
if(indata[i].index >= indata[j].index)
{
temp1 = indata[i].index;
indata[i].index = indata[j].index;
indata[j].index = temp1;
temp2 = indata[i].value;
indata[i].value = indata[j].value;
indata[j].value = temp2;
}
}
}
int i=0;
for(i= 0;i<N-1;i++)
{
if(indata[i].index == indata[i+1].index)
{
indata[i+1].value += indata[i].value;
}
else
{
printf("%d %dn",indata[i].index,indata[i].value);
}
}
printf("%d %dn",indata[i].index,indata[i].value);
}
}
from collections import defaultdict while True: try: n=int(input()) d=defaultdict(int) for i in range(n): key,val=map(int,input().split()) d[key]+=val for i in sorted(d.keys()): print(str(i)+" "+str(d[i])) except: break
注意这里要用defaultdict,我最开始用的dict不对,在看了id 华科平凡大佬的代码之后才知道,如果只用dict的话,当对字典中不存在的key赋值时,会报错 而用defaultdict时,当调用不在字典中的key赋值时,返回的是默认值0(本例中defaultdict返回值为int)list对应[ ],str对应的是空字符串,set对应set( )。综上所述本题中使用正常的dict会报错而应该使用defaultdict,,其就相当于C++中的map集合
#include <stdio.h> #include <string.h> int main() { int i, n, tmp1, tmp2; scanf("%d", &n); int arr[1000]; memset(arr, 0, sizeof(arr)); while(n > 0) { n--; scanf("%d %d", &tmp1, &tmp2); arr[tmp1] += tmp2; } for(i = 0; i < 1000; ++i) if(arr[i] > 0) printf("%d %dn", i, arr[i]); return 0; }
巧妙的使用数组下标来排序 #include <stdio.h> int main(void) { int array[500] = { 0 }; for(int i=0;i<500;i++){ array[i]=-1; // 防止有输入value为0的情况 } int num1, num2, length; scanf("%d", &length); for (int i = 0; i < length; i++) { scanf("%d %d", &num1, &num2); if(array[num1]==-1){ array[num1] ++; } array[num1] += num2; } for (int i = 0; i < 500; i++) if(array[i]!=-1) printf("%d %drn", i, array[i]); return 0; }
#include <stdio.h> #define SIZE 10000 int main(void) { int a = 0, b = 0; int n = 0, i = 0; int sum = 0; int arr[SIZE] = {0}; while (scanf("%d", &n) != EOF) { for (i = 0; i < n; i++) { if (scanf("%d%d", &a, &b) != EOF) { arr[a] += b; } } for (i = 0; i < n; i++) if (arr[i] != 0) printf("%d %dn", i, arr[i]); } return 0; }
num_dict = {} for _ in range(int(input().strip())): nums = list(map(int, input().strip().split(" "))) if nums[0] in num_dict.keys(): num_dict[nums[0]] += nums[1] else: num_dict[nums[0]] = nums[1] for key in sorted(num_dict.keys()): print(key, num_dict[key], sep = " ")
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const arrs1 = [];
const obj = {};
rl.on(‘line’, function (line) {
const tokens = line.split(‘ ‘);
if (arrs1.length > 0) {
if (obj[tokens[0]]) {
obj[tokens[0]] = Number(obj[tokens[0]]) + Number(tokens[1])
} else {
obj[tokens[0]] = tokens[1]
}
}
arrs1.push(tokens[0])
if (arrs1.length > arrs1[0]) {
for (item in obj) {
console.log(item, obj[item])
}
}
});
const num = parseInt(readline()) const obj = {} for(let i = 0;i < num; i++){ const arr = readline().split(' ') const key = arr[0] const value = arr[1] if(key in obj){ obj[key] += value*1 }else{ obj[key] = value*1 } } for(let k in obj){ console.log(`${k} ${obj[k]}`) }
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = Integer.valueOf(sc.nextLine());
Map<Integer,Integer> hash = new TreeMap<>();
for(int i=0;i<num;i++){
String[] arr = sc.nextLine().split(" ");
int key = Integer.valueOf(arr[0]);
int value = Integer.valueOf(arr[1]);
hash.put(key,hash.getOrDefault(key,0)+value);
}
Iterator it = hash.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj = (Map.Entry) it.next();
System.out.println(obj.getKey() + " " + obj.getValue());
}
}
}
import java.util.*; import java.lang.*; import java.text.*; import java.math.*; import java.util.stream.Collectors; import static java.util.Map.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()) { int num = sc.nextInt(); Map<Integer,Integer> map=new HashMap(); for(int i=0;i<num;i++){ int key = sc.nextInt(); int value = sc.nextInt(); map.put(key,map.getOrDefault(key,0)+value); } List<Entry<Integer, Integer>> collect = map.entrySet().stream().sorted((o1, o2)->{ return o1.getKey() - o2.getKey(); } ).collect(Collectors.toList()); for (Entry<Integer, Integer> entry : collect) { System.out.println(entry.getKey()+" "+entry.getValue()); } } sc.close(); } }
const map = {}; const count = Number(readline()); for (let i = 0; i < count; i++) { const [key, value] = readline().split(" "); map[key] ? (map[key] += Number(value)) : (map[key] = Number(value)); } Object.keys(map) .sort((a, b) => Number(a) - Number(b)) .forEach((item) => { console.log(item, map[item]); });
import java.util.HashMap; import java.util.Scanner; import java.util.TreeSet; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); HashMap<Integer,Integer> data = new HashMap<Integer,Integer>(); int num = sc.nextInt(); for(int i=0; i<num; i++){ Integer a = new Integer(sc.nextInt()); Integer b = new Integer(sc.nextInt()); if(data.get(a) == null){ data.put(a,b); } else{ data.put(a,b+data.get(a)); } } TreeSet<Integer> keyset = new TreeSet<Integer>(data.keySet()); for(Integer key : keyset){ System.out.println(key + " " + data.get(key)); } } }
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map<Integer, Integer> map = new TreeMap<>();
for (int i=0; i<n; i++) {
int key = sc.nextInt();
int value = sc.nextInt();
if (!map.containsKey(key)) {
map.put(key, value);
} else {
map.put(key, map.get(key) + value);
}
}
map.forEach((k, v)-> {
System.out.println(k + " " + v);
});
}
}
#include<stdio.h> struct data{ //构造结构体类型 int index; int value; }; int main(void) { struct data temp[500]; //创建结构体数组 int n; scanf("%d",&n);//输入个数n for(int i=0;i<n;i++) { scanf("%d %d",&temp[i].index,&temp[i].value);//输入下标值与内容值 } //选择排序,将具有相同下标值的结构体数组元素变为相邻的 for(int i=0;i<n-1;i++) { int min=i,j; for(j=i+1;j<n;j++) { if(temp[min].index>temp[j].index) { min=j; } } if(min!=j) { struct data ll=temp[i]; temp[i]=temp[min]; temp[min]=ll; } } /*将相邻的结构体数组元素的下标值进行比较,若相同则将下标大的内容值加到小标小 的元素中,再将下标大的元素的下标值置为 -1*/ for(int k=n-1;k>0;k--) { if(temp[k].index==temp[k-1].index) { temp[k-1].value+=temp[k].value; for(int j=k;j<n-1;j++) { temp[k]=temp[k+1]; } temp[k].index=-1; } } //遍历输出数组元素,注意判断其下标值是否为 -1,不是就输出,否则不输出 for(int i=0;i<n;i++) { if(temp[i].index!=-1) printf("%d %dn",temp[i].index,temp[i].value); } return 0; }
我不能理解 extracted的方法不行而排行前100的代码可以,以及不知道为什么bestMethod方法可以。有大佬可以指点一下吗?求教
package com.ds.nowcoder.hj8; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.Scanner; import java.util.TreeMap; /** * @author: SunJunMing * @date: Created in 9:18 上午 2022/3/18 * @desc: HJ8 合并表记录 */ public class Main { private static Scanner sc = new Scanner(System.in); private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { // int num = Integer.parseInt(br.readLine()); extracted(); // myMethod(num); // bestMethod(); } private static void bestMethod() throws IOException { StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); st.nextToken(); // 分隔符 // 强转 int n = (int)st.nval; int[] arr = new int[n]; for (int i = 0; i < n; i++) { st.nextToken(); int key = (int)st.nval; st.nextToken(); int value = (int)st.nval; arr[key] = arr[key] + value; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (arr[i] != 0) { sb.append(i).append(" ").append(arr[i]).append("n"); } } System.out.println(sb.toString()); } private static void myMethod(int num) throws IOException { TreeMap<Integer, Integer> map = new TreeMap<>(); int[] arr = new int[2]; for (int i = 0; i < num; i++) { String readLine = br.readLine(); int index = readLine.indexOf(" "); arr[0] = Integer.parseInt(readLine.substring(0, index)); arr[1] = Integer.parseInt(readLine.substring(index + 1)); if (map.containsKey(arr[0])) { Integer integer = map.get(arr[0]); map.put(arr[0], arr[1] + integer); } else { map.put(arr[0], arr[1]); } } for (Integer integer : map.keySet()) { System.out.println(integer + " " + map.get(integer)); } } private static void extracted() { int num = sc.nextInt(); int[] keys = new int[num]; int[] values = new int[num]; int max = 0; for (int i = 0; i < num; i++) { keys[i] = sc.nextInt(); values[i] = sc.nextInt(); if (keys[i] > max) { max = keys[i]; } } int[] indexs = new int[max + 1]; for (int i = 0; i < num; i++) { indexs[keys[i]] = indexs[keys[i]] + values[i]; } for (int i = 0; i < max + 1; i++) { if (indexs[i] > 0) { System.out.println(i + " " + indexs[i]); } } } }
#include<string.h>
#include<math.h>
#define MAXSIZE 500
typedef enum{OK=0,ERROR}Status;
typedef struct
{
int key;
int value;
}key_value;
void swap(int array[],int i,int j)
{
int temp=array[i];
array[i] = array[j];
array[j]=temp;
}
void Sort(int array[],int count)
{
int i=0,j=0;
for(i=0;i<count-1;i++)
{
for(j = i+1;j<count;j++)
if(array[i]>array[j])
swap(array,i,j);
}
/*
for(i=0;i<count-1;i++)
{
for(j = 0;j<count-1-i;j++)
if(array[j]>array[j+1])
swap(array,j+1,j);
}
*/
}
/*
* index 0->11111111
*return 0->499
*
*/
int hash(key_value Table[],key_value* kv)
{
int i,temp,temp2,temp3;
temp = kv->key*499/500;
if(kv->key>=500)temp = kv->key*499/11111111;
i=0;
if(Table[temp].key==-1||Table[temp].key==kv->key)
{
return temp;
}
i=1;
while(1)
{
temp2 = temp + i;
temp3 = temp – i;
// temp2 = temp + pow(2,i);
// temp3 = temp – pow(2,i);
if(temp2>=500&&temp3<0)return -1;
if(Table[temp2].key==-1||Table[temp2].key==kv->key)
{
temp=temp2;
break;
}
if(Table[temp3].key==-1||Table[temp3].key==kv->key)
{
temp=temp3;
break;
}
i++;
}
return temp;
}
Status TableInsert(key_value Table[],key_value* kv)
{
int i,temp;
temp = hash(Table,kv);
if(temp == -1)return ERROR;
Table[temp].key = kv->key;
Table[temp].value += kv->value;
return OK;
}
Status TableGet(key_value Table[],key_value* kv)
{
int i,temp;
temp = hash(Table,kv);
if(temp == -1)return ERROR;
if(Table[temp].key==-1)return ERROR;
kv->key=Table[temp].key;
kv->value = Table[temp].value;
return OK;
}
int main()
{
int count=0;
int i=0,j,index,value;
key_value kv[500],kvt;
int sort[500];
memset(sort,0,sizeof(sort));
while(i<500)
{
kv[i].key=-1;
kv[i].value=0;
i++;
}
scanf("%d",&count);
i=0;
while(i<count)
{
scanf("%d",&kvt.key);
sort[i]=kvt.key;
scanf("%d",&kvt.value);
if(TableInsert(kv,&kvt)==ERROR)return 1;
i++;
}
Sort(sort,count);
i=0;
while(i<count)
{
if(sort[i]!=sort[i+1])
{
kvt.key=sort[i];
if(TableGet(kv,&kvt)==ERROR)return 1;
printf("%d %dn",kvt.key,kvt.value);
}
i++;
}
return 0;
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
Map<Integer,Integer> map = new TreeMap();
for(int i = 0 ; i< num; i++){
Integer key = sc.nextInt();
Integer value = sc.nextInt();
Integer oldValue = map.get(key);
if(oldValue!=null){
map.put(key,oldValue+value);
}else{
map.put(key,value);
}
}
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
for (Map.Entry<Integer, Integer> entry : entries) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
以上就是关于问题数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。
提示: 0 <= index <= 11111111 1 <= value <= 100000的答案
欢迎关注区块链毕设网-
专业区块链毕业设计成品源码,定制。
区块链NFT链游项目方科学家脚本开发培训