2019 cattle off the National Day buy one get one training party day3

Topic links:

The meaning of problems: there are n points, n-1 sides of unidirectional, each point selling a commodity

Q began to walk from point 1, the first to buy the same type of goods as x, buy a second kind of commodity type y, and asked different ordered pair <x, y> number

 

solution:

col [i] represents the point of this product type

last [col [i]] represents the father from the time point 1 to point i process, the type of goods last occurrence point i

vis [col [i]] indicates the point i from a process, product type number of passes of point i

NUM [i] represents the process from a point i and the number of different types of goods

Each time a new sweep point v, (u and v's father) num [u] - num [last [col [v]]] is the number of needs to be updated

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M = 1e5 + 10;
const int mod = 1e9 + 7;
int num[M], vis[M], anss[M], ans, cnt, col[M], head[M], last[M];
struct node{
    int next, to;
}edge[M];
void add_edge(int u, int v) {
    edge[++cnt].next = head[u];
    edge[cnt].to = v;
    head[u] = cnt;
}
void dfs(int u, int sum, int ans) {
    for(int i = head[u]; i; i = edge[i].next) {
        int v = edge[i].to;
        int t = 0;
        int lastt = last[col[v]];
        vis[col[v]]++;
        if(vis[col[v]] == 1) num[v] = num[u] + 1;
        else num[v] = num[u];
        t = num[u] - num[last[col[v]]];
        last[col[v]] = u;
        //printf("%d %d %d\n", v, col[v], last[col[v]]);
        anss[v] = ans + t;
        if(vis[col[v]] == 1) dfs(v, sum + 1, ans + t);
        else dfs(v, sum + 1, ans + t);
        vis[col[v]]--;
        last[col[v]] = lastt;
    }
}
int main(){
    int n;
    while(~scanf("%d", &n)){
        cnt = 0;
        memset(head, 0, sizeof(head));
        for(int i = 1; i <= n; i++) num[i] = 0, last[i] = 0, vis[i] = 0, anss[i] = 0;
        for(int i = 2; i <= n; i++) {
            int u;
            scanf("%d", &u);
            add_edge(u, i);
        }
        for(int i = 1; i <= n; i++)
            scanf("%d", &col[i]);
        vis[col[1]]++;
        num[1] = 1;
        dfs(1, 1, 0);
//        for(int i = 1; i <= n; i++) {
//            printf("%d ", num[i]);
//        }
//        printf("\n");
        for(int i = 2; i <= n; i++) {
            printf("%d\n", anss[i]);
        }
    }
    return 0;
}
/*
3
1 2
1 2 3
3
1 1
1 2 3
4
1 2 3
1 3 2 3
7
1 1 3 2 4 2
3 3 3 4 5 3 3
7
1 1 3 2 4 2
2 3 3 4 5 3 3
*/
View Code

Guess you like

Origin www.cnblogs.com/linglinga/p/12077145.html