C++版
#include<iostream>
#include<algorithm>
#include<stack>
#include<unordered_map>
using namespace std;
int main(){
int n,k;
scanf("%d%d",&n,&k);
unordered_map<int,int> m;
m[0] = 0;
int count = 0;
while(k--){
int x,y;
scanf("%d%d",&x,&y);
if(m.count(y)==0){
count++;
}
m[x] = y;
}
cout<<count<<endl;
}
Java版
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
map.put(0,0);
int count = 0;
while (k!=0){
int x = sc.nextInt();
int y = sc.nextInt();
if(!map.containsKey(y)){
count++;
}
map.put(x,y);
k--;
}
System.out.println(count);
}
}
这篇博客展示了使用C++和Java编程语言实现的一个简单算法,该算法读取一系列整数对,并计算在这些整数对中不重复的第二个元素的数量。程序通过维护一个哈希映射来跟踪已出现的元素,从而达到计数目的。
3194

被折叠的 条评论
为什么被折叠?



