Description
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.
Input
Output
Sample Input
Sample Output
解題思路
用的靜態數組寫的,出現NO的情況有兩,一是輸入的字符串先短後長,長字符串會經過,之前字符串的終止節點;
二是輸入的字符串先長後短,短字符串不會產生新的節點。
AC代碼(1)
#include <cstdio>
#include <cstring>
int ch[100000][27], finish[100000][27]; //ch[][]記錄節點編號,第幾個節點經某個元素到第幾個節點,finish[][]記錄結束節點
int num_jd; //num_id 節點的個數
int val[100000]; //val[]記錄了每個節點的分支數,本題中沒用
int flag1, flag2;
void init()
{
num_jd = 1;
memset(ch, 0, sizeof(ch));
memset(val, 0, sizeof(val));
memset(finish, 0, sizeof(finish));
}
void insert(char *s)
{
int u = 0, i, c, len = strlen(s);
for(i = 0; i < len; i++)
{
c = s[i] - '0';
if(!ch[u][c])
{
ch[u][c] = num_jd++;
flag1 = 1;
}
if(finish[u][c])
flag2 = 1;
if(i == len - 1)
finish[u][c] = 1;
u = ch[u][c];
val[u]++;
}
}
int main()
{
int T, h, N;
char str[15];
scanf("%d", &T);
while(T--)
{
init();
scanf("%d", &N);
flag1 = 0, flag2 =0;
for(h = 0; h < N; h++)
{
scanf("%s", str);
if(h > 0 && !flag1 || flag2)
continue;
flag1 = 0, flag2 =0;
insert(str);
}
if(!flag1 || flag2)
{
printf("NO\n");
continue;
}
else
printf("YES\n");
}
return 0;
}
AC代碼(2)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char phone[10000][15];
int cmp(const void* a,const void* b)
{
return strcmp((char*)a, (char*)b);
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int i, n;
bool flag = false;
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%s", phone[i]);
}
qsort(phone, n, sizeof(phone[0]), cmp);
for(i = 0; i < n - 1; i++)
{
if(strncmp(phone[i], phone[i+1], strlen(phone[i])) == 0)
{
flag = true;
break;
}
}
if(flag == false)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}