zoukankan      html  css  js  c++  java
  • Project Euler:Problem 42 Coded triangle numbers

    The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:

    1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

    By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.

    Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?



    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <string>
    #include <map>
    using namespace std;
    
    map<int, int>mp;
    void triangle()
    {
    	for (int i = 1; i < 10000; i++)
    	{
    		mp[i*(i + 1) / 2] = 1;
    	}
    }
    
    int main()
    {
    	triangle();
    	ifstream input;
    	input.open("words.txt");
    	char s[16347];
    	while (!input.eof())
    		input >> s;
    	input.close();
    	vector<string> name;
    	string tm;
    	for (int i = 1; i <= 16346; i++)
    	{
    		if (s[i] >= 65 && s[i] <= 90 && s[i + 1] == '"')
    		{
    			tm = tm + s[i];
    			name.push_back(tm);
    			tm.clear();
    		}
    		else if (s[i] == ',' || s[i] == '"')
    			continue;
    		else
    			tm = tm + s[i];
    	}
    	int ans = 0;
    	for (int i = 0; i < name.size(); i++)
    	{
    		int sum = 0;
    		for (int j = 0; j < name[i].length(); j++)
    		{
    			sum = sum + name[i][j] - 'A' + 1;
    		}
    		if (mp[sum] == 1)
    			ans++;
    	}
    	cout << ans << endl;
    	system("pause");
    	return 0;
    }
    


  • 相关阅读:
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    72. Edit Distance
    583. Delete Operation for Two Strings
    582. Kill Process
    indexDB基本用法
    浏览器的渲染原理
    js实现txt/excel文件下载
    git 常用命令
    nginx进入 配置目录时
  • 原文地址:https://www.cnblogs.com/llguanli/p/6919726.html
Copyright © 2011-2022 走看看