pat乙级1003,第一个测试点过不去?


#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
struct
{
    string str;
    bool flag=1;
}s[15];
int main()
{
    int a_front = 0, a_mid = 0, a_rear = 0;
    int n = 0;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> s[i].str;
        a_front = s[i].str.find('P'); a_mid = s[i].str.find('T') - a_front - 1; a_rear = s[i].str.size() - s[i].str.find('T') - 1;
        
        int p_n = 0, t_n = 0 ,a_n=0;
        for (int j = 0; j < s[i].str.size(); j++)
        {        
            if (s[i].str[j] != 'P' && s[i].str[j] != 'A' && s[i].str[j] != 'T')
            {
                s[i].flag = 0;
                break;
            }
            if (s[i].str[j] == 'P')
                p_n++;
            if (s[i].str[j] == 'A')
                a_n++;
            if (s[i].str[j] == 'T')
                t_n++;
        }
        
        if(a_n ==0 || t_n != 1 || p_n != 1 || a_front * a_mid != a_rear|| s[i].str.find('P') >= s[i].str.find('T'))
             s[i].flag = 0;
    }
    for (int i = 0; i < n; i++)
    {
        if (s[i].flag == 1)
            printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:

问题可能出在字符串查找函数find上。在C++中,string类型的find函数返回的是字符串中第一个匹配字符的位置,而不是字符的下标。因此,在查找P和T的位置时,应该使用find_first_of函数,而不是find函数。

修改代码如下所示:

#include <iostream>
#include <string>
using namespace std;

struct {
    string str;
    bool flag = true;
}s[15];

int main() {
    int n = 0;
    cin >> n;

    for (int i = 0; i < n; i++) {
        cin >> s[i].str;

        int p_pos = s[i].str.find_first_of('P');
        int t_pos = s[i].str.find_first_of('T', p_pos + 1);

        if (p_pos < t_pos && t_pos == s[i].str.size() - 1) {
            int a_cnt = t_pos - p_pos - 1;
            int p_cnt = p_pos;
            int t_cnt = s[i].str.size() - t_pos - 1;
            if (a_cnt == 0 || p_cnt * (a_cnt - 1) != t_cnt) {
                s[i].flag = false;
            }
        }
        else {
            s[i].flag = false;
        }
    }

    for (int i = 0; i < n; i++) {
        if (s[i].flag) {
            cout << "YES" << endl;
        }
        else {
            cout << "NO" << endl;
        }
    }

    return 0;
}

在上述代码中,我们使用find_first_of函数来查找P和T的位置,并根据题目要求进行判断。注意,我们在结构体中将标志位的初始值设置为true,表示默认情况下所有的字符串都是符合要求的,只有在判断过程中发现不符合要求的情况才将标志位设置为false


如果以上回答对您有所帮助,点击一下采纳该答案~谢谢