ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมที่หาต้นทุนในการทำให้สตริงเป็นพังกรัม
สำหรับสิ่งนี้ เราจะได้รับอาร์เรย์ของจำนวนเต็ม งานของเราคือแปลงสตริงที่กำหนดให้เป็นพังกรัมและคำนวณต้นทุนในการทำเช่นนั้นด้วยความช่วยเหลือของอาร์เรย์ที่ให้มาพร้อมกับต้นทุนของการเพิ่มตัวอักขระ
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
//calculating the total cost of
//making panagram
int calc_cost(int arr[], string str) {
int cost = 0;
bool occurred[26] = { false };
for (int i = 0; i < str.size(); i++)
occurred[str[i] - 'a'] = true;
for (int i = 0; i < 26; i++) {
if (!occurred[i])
cost += arr[i];
}
return cost;
}
int main(){
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 };
string str = "abcdefghijklmopqrstuvwz";
cout << calc_cost(arr, str);
return 0;
}
ผลลัพธ์
63