歡迎加入我的 Discord 群組與我討論程式相關的問題!

Posted on 

 by 

 in ,

CSES – Sum of Two Values

評分:1 分,滿分為 5。

題意

給 n 個整數,兩個數字加起來剛好等於 x

解題方法

利用 C++ 內建的 map <int,int> 來紀錄每個元素的位置。

#include <bits/stdc++.h>
using namespace std;
int main(){
    map <int,int> mp;
    int n, x;
    cin >> n >> x;
    vector <int> a(n);
    for(int i = 0;i < n;i++){
        cin >> a[i];
    }
    for(int i = 0;i < n;i++){
        if(mp.count(x-a[i])){
            cout << i+1 << ' ' << mp[x-a[i]]+1 << '\n';
            return 0;
        }
        mp[a[i]] = i;
    }
    cout << "IMPOSSIBLE\n";
}

主要知識:基礎資料結構 (basic data structures)

發表迴響

Blog at WordPress.com.

%d 位部落客按了讚: